use B compare match register to trigger interrupt

This commit is contained in:
2025-07-18 20:31:23 +01:00
parent 7b524aaae2
commit 1f961964f0
2 changed files with 41 additions and 14 deletions

View File

@@ -1,12 +1,24 @@
use arduino_hal::pac::TC0;
use arduino_hal::{clock::Clock, pac::TC0, DefaultClock};
// Raises two interrupts: TIMER0_COMPA every period cycles/1024
// and TIMER0_COMPB compb_cocunt cycles/1024 after TIMER0_COMPA
pub fn segment_timer_init(tc0: TC0, seg_freq: u32, on_div: u32) {
// 16_000_000 / 1024 / 100 => 156 (100Hz|10ms)
let ocra = DefaultClock::FREQ / 1024 / seg_freq;
let ocrb: u32 = ocra / on_div;
pub fn segment_timer_init(tc0: TC0, counts: u8) {
// Use CTC mode: reset counter when matches compare value
tc0.tccr0a.write(|w| w.wgm0().ctc());
// Set the compare value
tc0.ocr0a.write(|w| w.bits(counts));
// Set the compare value for TOP (reset)
tc0.ocr0a
.write(|w| w.bits(ocra.try_into().expect("timer init seg_freq out of rage")));
// Set the compare value for B match
tc0.ocr0b
.write(|w| w.bits(ocrb.try_into().expect("timer init on_div out of rage")));
// Slow down the timer (CLK / prescale)
tc0.tccr0b.write(|w| w.cs0().prescale_1024());
// Raise interrupt on reset
tc0.timsk0.write(|w| w.ocie0a().set_bit());
// Raise interrupt on counter TOP (reset)
// Raise interrupt on B match
tc0.timsk0
.write(|w| w.ocie0a().set_bit().ocie0b().set_bit());
}