@@ -31,7 +31,8 @@ uint32_t F_CPU_CORRECTED = F_CPU;
3131#define PWM_TIMER_PERIOD 0xFF /* For frequency */
3232#define PWM_TIMER_COMPARE 0x80 /* For duty cycle */
3333
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 */
3536#define TIME_TRACKING_TIMER_DIVIDER 64 /* Clock divider for TCB3 */
3637#define TIME_TRACKING_CYCLES_PER_OVF (TIME_TRACKING_TICKS_PER_OVF * TIME_TRACKING_TIMER_DIVIDER)
3738
@@ -104,7 +105,6 @@ unsigned long millis()
104105
105106unsigned long micros () {
106107 unsigned long overflows , microseconds ;
107- //uint16_t overflows, microseconds;
108108 uint8_t ticks ;
109109
110110 /* Save current state and disable interrupts */
@@ -403,25 +403,24 @@ void init()
403403/********************* TCB3 for system time tracking **************************/
404404
405405 /* 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+
408409 millis_inc = microseconds_per_timerb3_overflow / 1000 ;
409410 fract_inc = ((microseconds_per_timerb3_overflow % 1000 ));
410- microseconds_per_timerb3_tick = microseconds_per_timerb3_overflow /PWM_TIMER_PERIOD ;
411411
412412 /* Default Periodic Interrupt Mode */
413413 /* TOP value for overflow every 1024 clock cycles */
414- TCB3 .CCMP = PWM_TIMER_PERIOD ;
414+ TCB3 .CCMP = TIME_TRACKING_TIMER_PERIOD ;
415415
416416 /* Enable TCB3 interrupt */
417417 TCB3 .INTCTRL |= TCB_CAPT_bm ;
418418
419419 /* Clock selection -> same as TCA (F_CPU/64 -- 250kHz) */
420420 TCB3 .CTRLA = TCB_CLKSEL_CLKTCA_gc ;
421- //TCB3.CTRLA = TCB_CLKSEL_CLKDIV2_gc;
422421
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 */
425424
426425/*************************** ENABLE GLOBAL INTERRUPTS *************************/
427426
0 commit comments