1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
#![doc = include_str!("../README.md")]
#![cfg_attr(not(any(test, feature = "std")), no_std)]
#![warn(missing_docs)]
pub use config::{ButtonConfig, Mode};
mod config;
#[cfg(test)]
mod tests;
cfg_if::cfg_if! {
if #[cfg(any(test, feature = "std"))] {
use std::time::Duration;
use tokio::time::timeout as with_timeout;
} else {
use embassy_time::{with_timeout, Duration, Timer};
}
}
/// A generic button that asynchronously detects [`ButtonEvent`]s.
#[derive(Debug, Clone, Copy)]
pub struct Button<P> {
pin: P,
state: State,
count: usize,
config: ButtonConfig,
}
#[derive(Debug, Clone, Copy)]
enum State {
/// Initial state.
Unknown,
/// Debounced press.
Pressed,
/// The button was just released, waiting for more presses in the same sequence, or for the
/// sequence to end.
Released,
/// Fully released state, idle.
Idle,
/// Waiting for the button to be released.
PendingRelease,
}
/// Detected button events
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ButtonEvent {
/// A sequence of 1 or more short presses.
ShortPress {
/// The number of short presses in the sequence.
count: usize,
},
/// A long press. This event is returned directly when the button is held for more than
/// [`ButtonConfig::long_press`].
LongPress,
}
impl<P> Button<P>
where
P: embedded_hal_async::digital::Wait + embedded_hal::digital::InputPin,
{
/// Creates a new button with the provided config.
pub const fn new(pin: P, config: ButtonConfig) -> Self {
Self {
pin,
state: State::Unknown,
count: 0,
config,
}
}
/// Updates the button and returns the detected event.
///
/// Awaiting this blocks execution of the task until a [`ButtonEvent`] is detected so it should
/// **not** be called from tasks where blocking for long periods of time is not desireable.
pub async fn update(&mut self) -> ButtonEvent {
loop {
if let Some(event) = self.update_step().await {
return event;
}
}
}
async fn update_step(&mut self) -> Option<ButtonEvent> {
match self.state {
State::Unknown => {
if self.is_pin_pressed() {
self.state = State::Pressed;
} else {
self.state = State::Idle;
}
None
}
State::Pressed => {
match with_timeout(self.config.long_press, self.wait_for_release()).await {
Ok(_) => {
// Short press
self.debounce_delay().await;
if self.is_pin_released() {
self.state = State::Released;
}
None
}
Err(_) => {
// Long press detected
self.count = 0;
self.state = State::PendingRelease;
Some(ButtonEvent::LongPress)
}
}
}
State::Released => {
match with_timeout(self.config.double_click, self.wait_for_press()).await {
Ok(_) => {
// Continue sequence
self.debounce_delay().await;
if self.is_pin_pressed() {
self.count += 1;
self.state = State::Pressed;
}
None
}
Err(_) => {
// Sequence ended
let count = self.count;
self.count = 0;
self.state = State::Idle;
Some(ButtonEvent::ShortPress { count })
}
}
}
State::Idle => {
self.wait_for_press().await;
self.debounce_delay().await;
if self.is_pin_pressed() {
self.count = 1;
self.state = State::Pressed;
}
None
}
State::PendingRelease => {
self.wait_for_release().await;
self.debounce_delay().await;
if self.is_pin_released() {
self.state = State::Idle;
}
None
}
}
}
fn is_pin_pressed(&self) -> bool {
self.pin.is_low().unwrap_or(self.config.mode.is_pulldown()) == self.config.mode.is_pullup()
}
fn is_pin_released(&self) -> bool {
!self.is_pin_pressed()
}
async fn wait_for_release(&mut self) {
match self.config.mode {
Mode::PullUp => self.pin.wait_for_high().await.unwrap_or_default(),
Mode::PullDown => self.pin.wait_for_low().await.unwrap_or_default(),
}
}
async fn wait_for_press(&mut self) {
match self.config.mode {
Mode::PullUp => self.pin.wait_for_low().await.unwrap_or_default(),
Mode::PullDown => self.pin.wait_for_high().await.unwrap_or_default(),
}
}
async fn debounce_delay(&self) {
delay(self.config.debounce).await;
}
}
async fn delay(duration: Duration) {
cfg_if::cfg_if! {
if #[cfg(any(test, feature = "std"))] {
tokio::time::sleep(duration).await;
} else {
Timer::after(duration).await;
}
}
}