@@ -31,7 +31,8 @@ uint32_t F_CPU_CORRECTED = F_CPU;
31
31
#define PWM_TIMER_PERIOD 0xFF /* For frequency */
32
32
#define PWM_TIMER_COMPARE 0x80 /* For duty cycle */
33
33
34
- #define TIME_TRACKING_TICKS_PER_OVF 256 /* Timer ticks per overflow of TCB3 */
34
+ #define TIME_TRACKING_TIMER_PERIOD 0xFF
35
+ #define TIME_TRACKING_TICKS_PER_OVF (TIME_TRACKING_TIMER_PERIOD + 1) /* Timer ticks per overflow of TCB3 */
35
36
#define TIME_TRACKING_TIMER_DIVIDER 64 /* Clock divider for TCB3 */
36
37
#define TIME_TRACKING_CYCLES_PER_OVF (TIME_TRACKING_TICKS_PER_OVF * TIME_TRACKING_TIMER_DIVIDER)
37
38
@@ -104,7 +105,6 @@ unsigned long millis()
104
105
105
106
unsigned long micros () {
106
107
unsigned long overflows , microseconds ;
107
- //uint16_t overflows, microseconds;
108
108
uint8_t ticks ;
109
109
110
110
/* Save current state and disable interrupts */
@@ -403,25 +403,24 @@ void init()
403
403
/********************* TCB3 for system time tracking **************************/
404
404
405
405
/* Calculate relevant time tracking values */
406
- //microseconds_per_timerb3_overflow = clockCyclesToMicroseconds(TIME_TRACKING_CYCLES_PER_OVF, F_CPU_CORRECTED);
407
- microseconds_per_timerb3_overflow = clockCyclesToMicroseconds (TIME_TRACKING_CYCLES_PER_OVF , F_CPU );
406
+ microseconds_per_timerb3_overflow = clockCyclesToMicroseconds (TIME_TRACKING_CYCLES_PER_OVF , F_CPU_CORRECTED );
407
+ microseconds_per_timerb3_tick = microseconds_per_timerb3_overflow /TIME_TRACKING_TIMER_PERIOD ;
408
+
408
409
millis_inc = microseconds_per_timerb3_overflow / 1000 ;
409
410
fract_inc = ((microseconds_per_timerb3_overflow % 1000 ));
410
- microseconds_per_timerb3_tick = microseconds_per_timerb3_overflow /PWM_TIMER_PERIOD ;
411
411
412
412
/* Default Periodic Interrupt Mode */
413
413
/* TOP value for overflow every 1024 clock cycles */
414
- TCB3 .CCMP = PWM_TIMER_PERIOD ;
414
+ TCB3 .CCMP = TIME_TRACKING_TIMER_PERIOD ;
415
415
416
416
/* Enable TCB3 interrupt */
417
417
TCB3 .INTCTRL |= TCB_CAPT_bm ;
418
418
419
419
/* Clock selection -> same as TCA (F_CPU/64 -- 250kHz) */
420
420
TCB3 .CTRLA = TCB_CLKSEL_CLKTCA_gc ;
421
- //TCB3.CTRLA = TCB_CLKSEL_CLKDIV2_gc;
422
421
423
- // / * Enable & start */
424
- TCB3 .CTRLA |= TCB_ENABLE_bm ;
422
+ /* Enable & start */
423
+ TCB3 .CTRLA |= TCB_ENABLE_bm ; /* Keep this last before enabling interrupts to ensure tracking as accurate as possible */
425
424
426
425
/*************************** ENABLE GLOBAL INTERRUPTS *************************/
427
426
0 commit comments