esp-hal/examples/src/bin/timer_interrupt.rs
Jesse Braham 5facb759ae
[2/3] Timer abstraction: add OneShotTimer/PeriodicTimer drivers, Timer trait (#1570)
* Add the `Timer` trait, `OneShotTimer` and `PeriodicTimer` types

* `PeriodicTimer` now working for `TIMG`

* `OneShotTimer` now working for `TIMG`

* `OneShotTimer` now working for `SYSTIMER` (plus, some cleanup)

* SYSTIMER now mostly working for ESP32-S2 as well

* Update `timer_interrupt` example and fix clippy lint to make CI happy again

* Update `CHANGELOG.md`

* Make `SYSTIMER` work correctly with `PeriodicTimer`, address some review comments

* Make `Timer::now()` return a `fugit::Instant`
2024-05-23 06:21:12 +00:00

71 lines
1.8 KiB
Rust

//! This shows how to use the TIMG peripheral interrupts.
//!
//! There is TIMG0 which contains a general purpose timer and a watchdog timer.
//% CHIPS: esp32 esp32c2 esp32c3 esp32c6 esp32h2 esp32s2 esp32s3
#![no_std]
#![no_main]
use core::cell::RefCell;
use critical_section::Mutex;
use esp_backtrace as _;
use esp_hal::{
clock::ClockControl,
interrupt::{self, Priority},
peripherals::{Interrupt, Peripherals, TIMG0},
prelude::*,
system::SystemControl,
timer::timg::{Timer, Timer0, TimerGroup, TimerInterrupts},
};
static TIMER0: Mutex<RefCell<Option<Timer<Timer0<TIMG0>, esp_hal::Blocking>>>> =
Mutex::new(RefCell::new(None));
#[entry]
fn main() -> ! {
let peripherals = Peripherals::take();
let system = SystemControl::new(peripherals.SYSTEM);
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();
let timg0 = TimerGroup::new(
peripherals.TIMG0,
&clocks,
Some(TimerInterrupts {
timer0_t0: Some(tg0_t0_level),
..Default::default()
}),
);
let timer0 = timg0.timer0;
interrupt::enable(Interrupt::TG0_T0_LEVEL, Priority::Priority1).unwrap();
timer0.load_value(500u64.millis());
timer0.start();
timer0.listen();
critical_section::with(|cs| {
TIMER0.borrow_ref_mut(cs).replace(timer0);
});
loop {}
}
#[handler]
fn tg0_t0_level() {
critical_section::with(|cs| {
esp_println::println!(
"Interrupt at {} ms",
esp_hal::time::current_time()
.duration_since_epoch()
.to_millis()
);
let mut timer0 = TIMER0.borrow_ref_mut(cs);
let timer0 = timer0.as_mut().unwrap();
timer0.clear_interrupt();
timer0.start(500u64.millis());
});
}