From 2eb2253571f1dd7f1e4ed07c7a46e24fd5c7bb39 Mon Sep 17 00:00:00 2001 From: jakeg00dwin Date: Mon, 5 Aug 2024 15:37:43 -0700 Subject: [PATCH] Fixed issue with not bitshifting the clock prescaler bitmap --- src/timer/timer.c | 70 +++++++++++++++++++++++++++++++++++++++-------- src/timer/timer.h | 13 +++++---- 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/src/timer/timer.c b/src/timer/timer.c index cee538a..f2a16e0 100644 --- a/src/timer/timer.c +++ b/src/timer/timer.c @@ -13,24 +13,72 @@ #endif #include "timer.h" -#include "avr/io.h" +#include +#include -void Timer_SelectClock(void) +#define FCLK_PER 3333333UL +#define DIV8 0x3 +#define PERIOD_VALUE 40 + +//These are expiremential found values that account for overhead +//for smaller durations. +#define OVERHEAD_ONE 226 +#define OVERHEAD_TWO 151 +#define OVERHEAD_THREE 75 + + +static uint16_t overflow_count = 0; + + +uint16_t Timer_GetOverflowCount(void) { - //set the timer to divde the clock by 256 - //Check datasheet page: 189 - TCA0.SINGLE.CTRLA |= 0x6; + return overflow_count; +} + +void Timer_Start(void) +{ + //clear the overflow event count + overflow_count = 0; + + sei(); + + //Enable the overflow Interrupt. + TCA0.SINGLE.INTCTRL = TCA_SINGLE_OVF_bm; + + //set Normal mode. + TCA0.SINGLE.CTRLB = TCA_SINGLE_WGMODE_NORMAL_gc; + + //Disable event counting. + TCA0.SINGLE.EVCTRL &= ~(TCA_SINGLE_CNTEI_bm); + + //Set the Period Value + TCA0.SINGLE.PER = PERIOD_VALUE; + + //set the Timer to divide FCLK_PER by 8. + TCA0.SINGLE.CTRLA |= (DIV8<<1); + //Enable the Timer + TCA0.SINGLE.CTRLA |= TCA_SINGLE_ENABLE_bm; } -void Timer_Enable(void) + +void Timer_Disable(void) { - TCA0.SINGLE.CTRLA |= (1<<0); + cli(); + TCA0.SINGLE.CTRLA &= ~(1<<0); + TCA0.SINGLE.CTRLESET |= ((0x3)<<2); } -void Timer_Period(void) +//Triggered on the overflow of the timer A's counter. +ISR(TCA0_OVF_vect) { - TCA0.SINGLE.PER = 10000; + cli(); + + //Increment the Overflow counter. + overflow_count += 1; + + // The interrupt flag has to be cleared manually + TCA0.SINGLE.INTFLAGS = TCA_SINGLE_OVF_bm; + + sei(); } - - diff --git a/src/timer/timer.h b/src/timer/timer.h index d38e468..b65eccd 100644 --- a/src/timer/timer.h +++ b/src/timer/timer.h @@ -10,6 +10,7 @@ #ifndef TIMER #define TIMER +#include "stdbool.h" #include "inttypes.h" /** @@ -17,11 +18,11 @@ * @param a The first argument */ -/** - * The timer select clock function sets the divider to 256 assuming a - * default clock diver of 6 is applied to the 20MHz crystal. This gives a - * 13020.8333 Hz or approximatly 13.02Khz tick rate. - */ -void Timer_SelectClock(void); + +void Timer_Start(void); + +void Timer_Disable(void); + +uint16_t Timer_GetOverflowCount(void); #endif // TIMER