//! Button Interrupt
//!
//! Solution
// Reference: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/freertos.html
use anyhow::Result;
use std::thread;
use esp_idf_hal::{prelude::Peripherals};
use esp_idf_sys::{
gpio_config, gpio_config_t, gpio_install_isr_service,
gpio_int_type_t_GPIO_INTR_POSEDGE, gpio_isr_handler_add, gpio_mode_t_GPIO_MODE_INPUT,
gpio_int_type_t_GPIO_INTR_NEGEDGE
};
use std::time::Duration;
// This `static mut` holds the queue handle we are going to get from `xQueueGenericCreate`.
// This is unsafe, but we are careful not to enable our GPIO interrupt handler until after this value has been initialised, and then never modify it again
static mut counter:u32 = 10;
#[no_mangle]
#[inline(never)]
#[link_section = ".iram1"]
unsafe extern "C" fn button_interrupt(_: *mut core::ffi::c_void) {
unsafe{
counter+=1;
}
}
pub fn intr_counter() {
counter+=1;
}
fn main() -> Result<()> {
let peripherals = Peripherals::take().unwrap();
//let mut led = PinDriver::output(peripherals.pins.gpio2)?;
const GPIO_NUM: i32 = 9;
// Configures the button
let io_conf = gpio_config_t {
pin_bit_mask: 1 << GPIO_NUM,
mode: gpio_mode_t_GPIO_MODE_INPUT,
pull_up_en: true.into(),
pull_down_en: false.into(),
intr_type: gpio_int_type_t_GPIO_INTR_NEGEDGE, // Positive edge trigger = button down
};
unsafe {
// Writes the button configuration to the registers
/*esp!(gpio_config(&io_conf))?;
// Installs the generic GPIO interrupt handler
esp!(gpio_install_isr_service(0))?;
// Registers our function with the generic GPIO interrupt handler we installed earlier.
esp!(gpio_isr_handler_add(
GPIO_NUM,
Some(button_interrupt),
std::ptr::null_mut()
))?;*/
gpio_config(&io_conf);
// Installs the generic GPIO interrupt handler
gpio_install_isr_service(0);
// Registers our function with the generic GPIO interrupt handler we installed earlier.
gpio_isr_handler_add(
GPIO_NUM,
Some(button_interrupt),
std::ptr::null_mut()
);
}
// Reads the queue in a loop.
loop {
unsafe {
thread::sleep(Duration::from_millis(100));
println!("hello world {}", counter);
// If the event has the value 0, nothing happens. if it has a different value, the button was pressed.
// If the button was pressed, a function that changes the state of the LED is called.
//led.set_high()?;
}
}
}
Loading
esp32-c3-rust-1
esp32-c3-rust-1