Skip to content

Commit 4208bf1

Browse files
committed
Properly setup CTC mode for timer
The previous setup was out of spec, and overflowed at 255 instead of 195
1 parent e60fcce commit 4208bf1

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

sw/main.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,9 @@ const uint32_t V_REF_mV = 5000;
130130
* interval [s] = overflow [ticks] / (F_CPU [ticks/s] / prescaler [unit-less])
131131
* = 99.84 ms
132132
*/
133-
constexpr uint8_t TIMER_OVERFLOW = (uint8_t)(F_CPU / 1024 / 10);
134-
constexpr double TIMER_TICK_INTERVAL = (double)TIMER_OVERFLOW / ((double)F_CPU / 1024.0); // == 0.099840 s
135-
constexpr uint32_t TIMER_TICK_INTERVAL_US = (uint32_t)(TIMER_TICK_INTERVAL * 1000000.0);
133+
constexpr uint8_t TIMER_OVERFLOW = (uint8_t)(F_CPU / 1024 / 10); // 2e6 / 1024 / 10 = 195.3125
134+
constexpr double TIMER_TICK_INTERVAL = (double)TIMER_OVERFLOW / ((double)F_CPU / 1024.0); // 195 / (2e6 / 1024) = 99.84ms
135+
constexpr uint32_t TIMER_TICK_INTERVAL_US = (uint32_t)(TIMER_TICK_INTERVAL * 1e6);
136136

137137
/* Since this timer is updated in an ISR, care has to be taken
138138
* when reading it, because all operations involving variables
@@ -153,7 +153,7 @@ inline uint32_t As_to_mAh(uint32_t value)
153153
return lrintf(cap);
154154
}
155155

156-
ISR(TIMER0_OVF_vect)
156+
ISR(TIMER0_COMPA_vect)
157157
{
158158
system_timer += timer_t{0, TIMER_TICK_INTERVAL_US};
159159
}
@@ -440,8 +440,8 @@ int main()
440440
adc_state = adc_state_t::IDLE;
441441

442442
/* Enable timer and interrupts */
443-
TCCR0B |= _BV(WGM02); // Set timer mode to CTC (datasheet 15.7.2)
444-
TIMSK0 |= _BV(TOIE0); // enable overflow interrupt
443+
TCCR0A |= _BV(WGM01); // Set timer mode to CTC (datasheet 15.7.2)
444+
TIMSK0 |= _BV(OCIE0A); // enable overflow interrupt
445445
OCR0A = TIMER_OVERFLOW;
446446
TCCR0B |= _BV(CS02) | _BV(CS00); // Start timer at Fcpu/1024
447447
sei();

0 commit comments

Comments
 (0)