simple key debounce

This commit is contained in:
2025-12-13 00:37:13 +01:00
parent 67fd176973
commit 66497ba1ce

View File

@@ -1,21 +1,53 @@
#![no_std]
#![no_main]
use defmt::info;
use embassy_executor::Spawner;
use embassy_rp::gpio::{Level, Output};
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_time::{Duration, Timer};
use {defmt_rtt as _, panic_probe as _};
pub struct Debouncer<'a> {
input: Input<'a>,
debounce: Duration,
}
impl<'a> Debouncer<'a> {
pub fn new(input: Input<'a>, debounce: Duration) -> Self {
Self { input, debounce }
}
pub async fn debounce(&mut self) -> Level {
loop {
let l1 = self.input.get_level();
self.input.wait_for_any_edge().await;
Timer::after(self.debounce).await;
let l2 = self.input.get_level();
if l1 != l2 {
break l2;
}
}
}
}
#[embassy_executor::main]
async fn main(_spawner: Spawner) -> ! {
let p = embassy_rp::init(Default::default());
let mut led = Output::new(p.PIN_25, Level::Low);
let mut switch_input = Debouncer::new(Input::new(p.PIN_0, Pull::Up), Duration::from_millis(20));
switch_input.input.set_schmitt(true);
loop {
defmt::info!("led on");
led.set_high();
Timer::after(Duration::from_millis(300)).await;
defmt::info!("led off");
defmt::info!("switch off");
led.set_low();
Timer::after(Duration::from_millis(300)).await;
switch_input.debounce().await;
info!("switch on");
led.set_high();
switch_input.debounce().await;
}
}