mirror of
https://github.com/mytechnotalent/Embedded-Hacking.git
synced 2026-05-26 17:28:25 +02:00
feat: add 0x03_button_rust driver with 8 unit tests
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
//! @file button.rs
|
||||
//! @brief Implementation of the push-button GPIO input driver with debounce
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
|
||||
use embedded_hal::digital::{InputPin, OutputPin, StatefulOutputPin};
|
||||
|
||||
/// Push-button GPIO input driver with debounce.
|
||||
pub struct ButtonDriver<B: InputPin, D: FnMut(u32)> {
|
||||
btn_pin: B,
|
||||
debounce_ms: u32,
|
||||
delay_fn: D,
|
||||
}
|
||||
|
||||
impl<B: InputPin, D: FnMut(u32)> ButtonDriver<B, D> {
|
||||
/// Initialize a GPIO pin as an active-low button input with pull-up.
|
||||
///
|
||||
/// The pin reads logic high when the button is open and logic low when
|
||||
/// the button connects the pin to GND.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `btn_pin` - GPIO pin configured as input with pull-up.
|
||||
/// * `debounce_ms` - Debounce settling time in milliseconds (e.g. 20).
|
||||
/// * `delay_fn` - Closure that sleeps for the given number of milliseconds.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A new ButtonDriver instance.
|
||||
pub fn init(btn_pin: B, debounce_ms: u32, delay_fn: D) -> Self {
|
||||
Self { btn_pin, debounce_ms, delay_fn }
|
||||
}
|
||||
|
||||
/// Confirm a raw active-low pin read by waiting for the debounce period.
|
||||
///
|
||||
/// After an initial low reading on the pin, this helper re-samples the pin
|
||||
/// after debounce_ms milliseconds to confirm the reading is stable.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if the pin is still low after the debounce delay.
|
||||
fn debounce_confirm(&mut self) -> bool {
|
||||
(self.delay_fn)(self.debounce_ms);
|
||||
self.btn_pin.is_low().unwrap()
|
||||
}
|
||||
|
||||
/// Read the debounced state of the button.
|
||||
///
|
||||
/// Returns true only when the pin reads low continuously for the debounce
|
||||
/// period configured in init(). This prevents mechanical contact bounce
|
||||
/// from registering as multiple rapid presses.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if the button is firmly pressed, `false` if released.
|
||||
pub fn is_pressed(&mut self) -> bool {
|
||||
if self.btn_pin.is_low().unwrap() {
|
||||
return self.debounce_confirm();
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Indicator LED driver that owns a single output pin.
|
||||
pub struct ButtonLed<L: OutputPin + StatefulOutputPin> {
|
||||
led_pin: L,
|
||||
}
|
||||
|
||||
impl<L: OutputPin + StatefulOutputPin> ButtonLed<L> {
|
||||
/// Initialize a GPIO pin as a push-pull digital output for an indicator LED.
|
||||
///
|
||||
/// Configures the output and drives it low (LED off).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `led_pin` - GPIO pin configured as a digital output.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A new ButtonLed instance.
|
||||
pub fn init(mut led_pin: L) -> Self {
|
||||
led_pin.set_low().unwrap();
|
||||
Self { led_pin }
|
||||
}
|
||||
|
||||
/// Set the indicator LED state.
|
||||
///
|
||||
/// Drives the output pin high (LED on) or low (LED off).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `on` - `true` to turn the LED on, `false` to turn it off.
|
||||
pub fn set(&mut self, on: bool) {
|
||||
if on {
|
||||
self.led_pin.set_high().unwrap();
|
||||
} else {
|
||||
self.led_pin.set_low().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core::convert::Infallible;
|
||||
use embedded_hal::digital::ErrorType;
|
||||
|
||||
struct MockInputPin {
|
||||
low: bool,
|
||||
}
|
||||
|
||||
impl MockInputPin {
|
||||
fn new(low: bool) -> Self {
|
||||
Self { low }
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorType for MockInputPin {
|
||||
type Error = Infallible;
|
||||
}
|
||||
|
||||
impl InputPin for MockInputPin {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(!self.low)
|
||||
}
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.low)
|
||||
}
|
||||
}
|
||||
|
||||
struct MockOutputPin {
|
||||
state: bool,
|
||||
}
|
||||
|
||||
impl MockOutputPin {
|
||||
fn new() -> Self {
|
||||
Self { state: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorType for MockOutputPin {
|
||||
type Error = Infallible;
|
||||
}
|
||||
|
||||
impl OutputPin for MockOutputPin {
|
||||
fn set_low(&mut self) -> Result<(), Self::Error> {
|
||||
self.state = false;
|
||||
Ok(())
|
||||
}
|
||||
fn set_high(&mut self) -> Result<(), Self::Error> {
|
||||
self.state = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl StatefulOutputPin for MockOutputPin {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.state)
|
||||
}
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(!self.state)
|
||||
}
|
||||
fn toggle(&mut self) -> Result<(), Self::Error> {
|
||||
self.state = !self.state;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn noop_delay(_ms: u32) {}
|
||||
|
||||
#[test]
|
||||
fn is_pressed_when_low_and_confirmed() {
|
||||
let pin = MockInputPin::new(true);
|
||||
let mut drv = ButtonDriver::init(pin, 20, noop_delay);
|
||||
assert!(drv.is_pressed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_not_pressed_when_high() {
|
||||
let pin = MockInputPin::new(false);
|
||||
let mut drv = ButtonDriver::init(pin, 20, noop_delay);
|
||||
assert!(!drv.is_pressed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debounce_ms_stored() {
|
||||
let pin = MockInputPin::new(false);
|
||||
let drv = ButtonDriver::init(pin, 50, noop_delay);
|
||||
assert_eq!(drv.debounce_ms, 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debounce_calls_delay() {
|
||||
let mut called_with: u32 = 0;
|
||||
let pin = MockInputPin::new(true);
|
||||
let mut drv = ButtonDriver::init(pin, 25, |ms| called_with = ms);
|
||||
drv.is_pressed();
|
||||
assert_eq!(called_with, 25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn led_init_starts_off() {
|
||||
let led = ButtonLed::init(MockOutputPin::new());
|
||||
assert!(!led.led_pin.state);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn led_set_on() {
|
||||
let mut led = ButtonLed::init(MockOutputPin::new());
|
||||
led.set(true);
|
||||
assert!(led.led_pin.state);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn led_set_off() {
|
||||
let mut led = ButtonLed::init(MockOutputPin::new());
|
||||
led.set(true);
|
||||
led.set(false);
|
||||
assert!(!led.led_pin.state);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn led_set_on_then_off_then_on() {
|
||||
let mut led = ButtonLed::init(MockOutputPin::new());
|
||||
led.set(true);
|
||||
led.set(false);
|
||||
led.set(true);
|
||||
assert!(led.led_pin.state);
|
||||
}
|
||||
}
|
||||
|
||||
// End of file
|
||||
@@ -0,0 +1,8 @@
|
||||
//! @file lib.rs
|
||||
//! @brief Library root for the button driver crate
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
|
||||
#![no_std]
|
||||
|
||||
pub mod button;
|
||||
@@ -0,0 +1,247 @@
|
||||
//! @file main.rs
|
||||
//! @brief Button demonstration: debounced press mirrors to LED + UART report
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
//!
|
||||
//! -----------------------------------------------------------------------------
|
||||
//!
|
||||
//! Demonstrates GPIO input using the button driver (button.rs).
|
||||
//! The onboard LED mirrors the button state and every edge transition is
|
||||
//! reported over UART.
|
||||
//!
|
||||
//! Wiring:
|
||||
//! GPIO15 -> One leg of push button
|
||||
//! GND -> Other leg of push button
|
||||
//! GPIO25 -> Onboard LED (no external wiring needed)
|
||||
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
#[allow(dead_code)]
|
||||
mod button;
|
||||
|
||||
use defmt_rtt as _;
|
||||
#[cfg(target_arch = "riscv32")]
|
||||
use panic_halt as _;
|
||||
#[cfg(target_arch = "arm")]
|
||||
use panic_probe as _;
|
||||
|
||||
use core::cell::RefCell;
|
||||
use fugit::RateExtU32;
|
||||
use hal::entry;
|
||||
use hal::Clock;
|
||||
use hal::gpio::{FunctionNull, FunctionUart, Pin, PullDown, PullNone};
|
||||
use hal::uart::{DataBits, Enabled, StopBits, UartConfig, UartPeripheral};
|
||||
|
||||
#[cfg(rp2350)]
|
||||
use rp235x_hal as hal;
|
||||
|
||||
#[cfg(rp2040)]
|
||||
use rp2040_hal as hal;
|
||||
|
||||
#[unsafe(link_section = ".boot2")]
|
||||
#[used]
|
||||
#[cfg(rp2040)]
|
||||
pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
|
||||
|
||||
#[unsafe(link_section = ".start_block")]
|
||||
#[used]
|
||||
#[cfg(rp2350)]
|
||||
pub static IMAGE_DEF: hal::block::ImageDef = hal::block::ImageDef::secure_exe();
|
||||
|
||||
const XTAL_FREQ_HZ: u32 = 12_000_000u32;
|
||||
|
||||
const UART_BAUD: u32 = 115_200;
|
||||
|
||||
const DEBOUNCE_MS: u32 = 20;
|
||||
const POLL_MS: u32 = 10;
|
||||
|
||||
type TxPin = Pin<hal::gpio::bank0::Gpio0, FunctionUart, PullNone>;
|
||||
type RxPin = Pin<hal::gpio::bank0::Gpio1, FunctionUart, PullNone>;
|
||||
type TxPinDefault = Pin<hal::gpio::bank0::Gpio0, FunctionNull, PullDown>;
|
||||
type RxPinDefault = Pin<hal::gpio::bank0::Gpio1, FunctionNull, PullDown>;
|
||||
type EnabledUart = UartPeripheral<Enabled, hal::pac::UART0, (TxPin, RxPin)>;
|
||||
|
||||
/// Initialise system clocks and PLLs from the external 12 MHz crystal.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `xosc` - XOSC peripheral singleton.
|
||||
/// * `clocks` - CLOCKS peripheral singleton.
|
||||
/// * `pll_sys` - PLL_SYS peripheral singleton.
|
||||
/// * `pll_usb` - PLL_USB peripheral singleton.
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
/// * `watchdog` - Mutable reference to the watchdog timer.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Configured clocks manager.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if clock initialisation fails.
|
||||
fn init_clocks(
|
||||
xosc: hal::pac::XOSC,
|
||||
clocks: hal::pac::CLOCKS,
|
||||
pll_sys: hal::pac::PLL_SYS,
|
||||
pll_usb: hal::pac::PLL_USB,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
watchdog: &mut hal::Watchdog,
|
||||
) -> hal::clocks::ClocksManager {
|
||||
hal::clocks::init_clocks_and_plls(
|
||||
XTAL_FREQ_HZ, xosc, clocks, pll_sys, pll_usb, resets, watchdog,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Unlock the GPIO bank and return the pin set.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `io_bank0` - IO_BANK0 peripheral singleton.
|
||||
/// * `pads_bank0` - PADS_BANK0 peripheral singleton.
|
||||
/// * `sio` - SIO peripheral singleton.
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// GPIO pin set for the entire bank.
|
||||
fn init_pins(
|
||||
io_bank0: hal::pac::IO_BANK0,
|
||||
pads_bank0: hal::pac::PADS_BANK0,
|
||||
sio: hal::pac::SIO,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
) -> hal::gpio::Pins {
|
||||
let sio = hal::Sio::new(sio);
|
||||
hal::gpio::Pins::new(io_bank0, pads_bank0, sio.gpio_bank0, resets)
|
||||
}
|
||||
|
||||
/// Initialise UART0 for serial output (stdio equivalent).
|
||||
///
|
||||
/// Configures UART0 at the requested baud rate with 8N1 framing on
|
||||
/// GPIO 0 (TX) and GPIO 1 (RX).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uart0` - PAC UART0 peripheral singleton.
|
||||
/// * `tx_pin` - GPIO pin to use as UART0 TX (GPIO 0).
|
||||
/// * `rx_pin` - GPIO pin to use as UART0 RX (GPIO 1).
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
/// * `clocks` - Reference to the initialised clock configuration.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Enabled UART0 peripheral ready for blocking writes.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the HAL cannot achieve the requested baud rate.
|
||||
fn init_uart(
|
||||
uart0: hal::pac::UART0,
|
||||
tx_pin: TxPinDefault,
|
||||
rx_pin: RxPinDefault,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
clocks: &hal::clocks::ClocksManager,
|
||||
) -> EnabledUart {
|
||||
let pins = (
|
||||
tx_pin.reconfigure::<FunctionUart, PullNone>(),
|
||||
rx_pin.reconfigure::<FunctionUart, PullNone>(),
|
||||
);
|
||||
let cfg = UartConfig::new(UART_BAUD.Hz(), DataBits::Eight, None, StopBits::One);
|
||||
UartPeripheral::new(uart0, pins, resets)
|
||||
.enable(cfg, clocks.peripheral_clock.freq())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Create a blocking delay timer from the ARM SysTick peripheral.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `clocks` - Reference to the initialised clock configuration.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Blocking delay provider.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the cortex-m core peripherals have already been taken.
|
||||
fn init_delay(clocks: &hal::clocks::ClocksManager) -> cortex_m::delay::Delay {
|
||||
let core = cortex_m::Peripherals::take().unwrap();
|
||||
cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz())
|
||||
}
|
||||
|
||||
/// Application entry point for the button debounce demo.
|
||||
///
|
||||
/// Initializes button and LED, then continuously polls button state
|
||||
/// and mirrors it to the LED with UART reporting on edge transitions.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Does not return.
|
||||
#[entry]
|
||||
fn main() -> ! {
|
||||
let mut pac = hal::pac::Peripherals::take().unwrap();
|
||||
let clocks = init_clocks(
|
||||
pac.XOSC, pac.CLOCKS, pac.PLL_SYS, pac.PLL_USB, &mut pac.RESETS,
|
||||
&mut hal::Watchdog::new(pac.WATCHDOG),
|
||||
);
|
||||
let pins = init_pins(pac.IO_BANK0, pac.PADS_BANK0, pac.SIO, &mut pac.RESETS);
|
||||
let uart = init_uart(pac.UART0, pins.gpio0, pins.gpio1, &mut pac.RESETS, &clocks);
|
||||
let delay = RefCell::new(init_delay(&clocks));
|
||||
let btn_pin = pins.gpio15.into_pull_up_input();
|
||||
let led_pin = pins.gpio25.into_push_pull_output();
|
||||
let mut btn = button::ButtonDriver::init(btn_pin, DEBOUNCE_MS, |ms| {
|
||||
delay.borrow_mut().delay_ms(ms);
|
||||
});
|
||||
let mut led = button::ButtonLed::init(led_pin);
|
||||
uart.write_full_blocking(b"Button driver initialized: button=GPIO15 led=GPIO25\r\n");
|
||||
let mut last_state = false;
|
||||
loop {
|
||||
let pressed = btn.is_pressed();
|
||||
led.set(pressed);
|
||||
if pressed != last_state {
|
||||
if pressed {
|
||||
uart.write_full_blocking(b"Button: PRESSED\r\n");
|
||||
} else {
|
||||
uart.write_full_blocking(b"Button: RELEASED\r\n");
|
||||
}
|
||||
last_state = pressed;
|
||||
}
|
||||
delay.borrow_mut().delay_ms(POLL_MS);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(link_section = ".bi_entries")]
|
||||
#[used]
|
||||
pub static PICOTOOL_ENTRIES: [hal::binary_info::EntryAddr; 5] = [
|
||||
hal::binary_info::rp_cargo_bin_name!(),
|
||||
hal::binary_info::rp_cargo_version!(),
|
||||
hal::binary_info::rp_program_description!(c"Button Debounce Demo"),
|
||||
hal::binary_info::rp_cargo_homepage_url!(),
|
||||
hal::binary_info::rp_program_build_attribute!(),
|
||||
];
|
||||
|
||||
// End of file
|
||||
Reference in New Issue
Block a user