From bdd5ae4dd66941e27128f3ad45d7452c33af716b Mon Sep 17 00:00:00 2001 From: Lars-Dominik Braun Date: Tue, 19 Aug 2014 15:50:26 +0200 Subject: timer: Support arbitrary timer values FIXME: large values do not work yet. --- timer.c | 42 +++++++++++++++++++++++++++++------------- timer.h | 6 +++--- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/timer.c b/timer.c index d2634f2..c4e5704 100644 --- a/timer.c +++ b/timer.c @@ -5,24 +5,28 @@ #include "timer.h" -/* counts one second, off by +1s per 2m - */ - -volatile uint16_t count = 0; -volatile unsigned char hit = 0; +volatile unsigned char hits, maxhits; ISR(TIMER1_COMPA_vect) { - ++hit; + ++hits; } -bool timerHit () { - bool ret = hit != 0; - hit = 0; - return ret; +/* Check if timer was hit, return time since last restart or 0 if not hit yet + */ +uint32_t timerHit () { + if (hits >= maxhits) { + const uint32_t ret = TCNT1 * (uint32_t) 128 + + (uint32_t) hits * OCR1A * (uint32_t) 128; + hits = 0; + return ret; + } else { + return 0; + } } -void timerStart () { - count = 0; +/* Start a timer that fires every t us + */ +void timerStart (const uint32_t t) { /* reset timer value */ TCNT1 = 0; /* set ctc (compare timer and clear) mode (part 1) */ @@ -31,12 +35,24 @@ void timerStart () { TIMSK1 = (1 << OCIE1A); /* set compare value */ #if F_CPU == 8000000 - OCR1A = 7812; + const uint32_t tdiv = t/128; + if (tdiv > UINT16_MAX) { +#warning "fix this" + assert (0); + } else { + /* with divider 1024 each clock tick is 128us with a rounding error of + * 64us per second/4ms per minute, since its a 16 bit timer we support + * up to 2**16-1 ticks, which is 8388480us (8s) */ + OCR1A = tdiv; + maxhits = 1; + } #else #error "cpu speed not supported" #endif /* io clock with 1024 prescaler; ctc (part 2) */ TCCR1B = (1 << CS12) | (1 << CS10) | (1 << WGM12); + + hits = 0; } void timerStop () { diff --git a/timer.h b/timer.h index c1b3511..6284be7 100644 --- a/timer.h +++ b/timer.h @@ -1,10 +1,10 @@ #ifndef TIMER_H #define TIMER_H -#include +#include -void timerStart (); -bool timerHit (); +void timerStart (const uint32_t t); +uint32_t timerHit (); void timerStop (); #endif /* TIMER_H */ -- cgit v1.2.3