/* * "THE BEER-WARE LICENSE" (Revision 42): * Martin Wenger and Stefan Rupp * wrote this file. As long as you retain this notice you can do whatever you want * with this stuff. If we meet some day, and you think this stuff is worth it, * you can buy me/us a beer in return. * (c) 2005-2010 Martin Wenger, Stefan Rupp * (c) 2013,2014 Stefan Rupp */ #include #include "timer.h" #include #include /* timer_time gets increased on every interrupt * those interrupts happen every 1ms */ static volatile uint32_t timer_time; ISR(TIMER0_COMPA_vect) { ++timer_time; return; } /** * Initialize the timer * This function has to be called first, before calling timer_wait and/or timer_get, * else timer_get will always return 0, and timer_wait will wait forever! */ void timer_init(void) { uint8_t sreg = SREG; // Stop all interrupts cli(); // Reset timer to zero timer_time = 0; // - Time accuracy: 1 millisecond (corresponding frequency: 1kHz) // ==> F_CPU = 20Mhz // ==> 20Mhz / 256 = 78.125 kHz // ==> let timer count to 77 to get (almost) 1kHz frequency // therefore: // - Set Timer/Counter0 prescaler to 256 ==> (1< (1< timer_get() ); return; } /** * Decode a integer timestamp (in microseconds) * into hours, minutes, seconds, microseconds * \param time the time in microseconds * \param hours will be filled in to contain the hours after return * \param minutes will be filled in to contain the minutes after return * \param seconds will be filled in to contain the seconds after return * \param ms be filled in to contain the microseconds after return */ void timer_decode(uint32_t time, uint8_t *hours, uint8_t *minutes, uint8_t *seconds, uint16_t *ms) { if (ms != NULL) { *ms = time % 1000; } time /= 1000; if (seconds != NULL) { *seconds = time % 60; } time /= 60; if (minutes != NULL) { *minutes = time % 60; } time /= 60; if (hours != NULL) { *hours = time; } return; } /** * Encode a time given as hours, minutes, seconds and microsecods into a integer storing micorseconds * \param time the variable to store the time into * \param hour the hours to store * \param hour the minutes to store * \param hour the seconds to store * \param hour the microseconds to store */ void timer_encode(uint32_t *time, uint8_t hours, uint8_t minutes, uint8_t seconds, uint16_t ms) { *time = hours; *time *= 60; *time += minutes; *time *= 60; *time += seconds; *time *= 1000U; *time += ms; return; } /* void timer_validate(uint8_t *hours, uint8_t *minutes, uint8_t *seconds, uint16_t *ms) { while (*ms >= 1000) { *ms -= 1000; (*seconds)++; } while (*seconds >= 60) { *ms -= 60; (*minutes)++; } while (*minutes >= 60) { *minutes -= 60; (*hours)++; } return; } */