working hard real time interrupt

This commit is contained in:
Priec
2025-10-15 18:03:17 +02:00
parent 31bc689c69
commit 4f21d03822

View File

@@ -17,6 +17,8 @@ use esp_hal::{
timer::timg::TimerGroup,
time::Duration,
};
use core::cell::RefCell;
use critical_section::Mutex;
use esp_hal::handler;
use log::info;
@@ -27,6 +29,7 @@ extern crate alloc;
esp_bootloader_esp_idf::esp_app_desc!();
static mut INTERRUPT_FIRED: bool = false;
static TIMER0: Mutex<RefCell<Option<esp_hal::timer::timg::Timer<'static>>>> = Mutex::new(RefCell::new(None));
#[esp_hal_embassy::main]
async fn main(spawner: Spawner) {
@@ -37,23 +40,27 @@ async fn main(spawner: Spawner) {
esp_alloc::heap_allocator!(size: 64 * 1024);
let mut timer_group1 = TimerGroup::new(peripherals.TIMG1);
let mut timer0 = timer_group1.timer0;
let timer_group1 = TimerGroup::new(peripherals.TIMG1);
let timer0 = timer_group1.timer0;
// make it periodic, 1 s per tick, enable interrupt
timer0.set_interrupt_handler(TG1_T0_LEVEL);
timer0.clear_interrupt();
timer0.load_value(Duration::from_secs(1)).unwrap();
timer0.enable_interrupt(true);
timer0.enable_auto_reload(true);
timer0.load_value(Duration::from_secs(1)).unwrap();
timer0.start();
// Store timer in the static safely
critical_section::with(|cs| {
TIMER0.borrow_ref_mut(cs).replace(timer0);
});
// enable NVIC entry for this timer
unsafe {
interrupt::enable(
peripherals::Interrupt::TG1_T0_LEVEL,
interrupt::Priority::Priority2, // medium priority for now
)
.unwrap();
}
interrupt::enable(
peripherals::Interrupt::TG1_T0_LEVEL,
interrupt::Priority::Priority2, // medium priority
)
.unwrap();
// Initialize GPIO4 as output (starts LOW)
let mut gpio4 = Output::new(peripherals.GPIO4, Level::Low, OutputConfig::default());
@@ -61,29 +68,27 @@ async fn main(spawner: Spawner) {
info!("Embassy initialized!");
loop {
let mut counter = 0;
while counter < 10000000 {
counter += 1;
}
unsafe {
if INTERRUPT_FIRED {
info!("Timer interrupt fired!");
INTERRUPT_FIRED = false;
}
info!("info!");
// let mut counter = 0;
// while counter < 10000000 {
// counter += 1;
// }
if unsafe { INTERRUPT_FIRED } {
gpio4.toggle();
info!("tick");
unsafe { INTERRUPT_FIRED = false; }
}
esp_hal::delay::Delay::new().delay_millis(100);
}
}
#[handler]
fn TG1_T0_LEVEL() {
// Clear the interrupt
critical_section::with(|_cs| {
unsafe {
let mut tg1 = TimerGroup::new(peripherals::TIMG1::steal());
tg1.timer0.clear_interrupt();
critical_section::with(|cs| {
if let Some(timer) = TIMER0.borrow_ref_mut(cs).as_mut() {
INTERRUPT_FIRED = true;
timer.clear_interrupt();
unsafe { INTERRUPT_FIRED = true; }
}
});
}