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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
//! # Debouncr //! //! A simple and efficient `no_std` input debouncer that uses integer bit //! shifting to debounce inputs. The basic algorithm can detect rising and //! falling edges and only requires 1 byte of RAM for detecting up to //! 8 consecutive high/low states or 2 bytes of RAM for detecting up to //! 16 consecutive high/low states. //! //! While the regular algorithm will detect any change from "bouncing" //! to "stable high/low" as an edge, there is also a variant that will //! only detect changes from "stable high" to "stable low" and //! vice versa as an edge (see section "Stateful Debouncing"). //! //! The algorithm is based on the [Ganssle Guide to //! Debouncing](http://www.ganssle.com/debouncing-pt2.htm) (section "An //! Alternative"). //! //! ## API //! //! ### Instantiate //! //! First, decide how many consecutive states you want to detect. For example, //! if you poll the input pin every 5 ms and require 4 consecutive logical-high //! states to trigger a debounced press event, that event will happen after 20 ms. //! //! On initialization, you also need to specify the initial state: `true` for //! logical-high, `false` for logical-low. //! //! ```rust //! use debouncr::debounce_4; //! //! let mut debouncer = debounce_4(false); // Type: Debouncer<u8, Repeat4> //! ``` //! //! ### Update //! //! In regular intervals, call the `update(pressed)` function to update the //! internal state. //! //! ```rust //! use debouncr::{debounce_3, Edge}; //! //! let mut debouncer = debounce_3(false); //! # fn poll_button() -> bool { true }; //! assert_eq!(debouncer.update(poll_button()), None); //! assert_eq!(debouncer.update(poll_button()), None); //! assert_eq!(debouncer.update(poll_button()), Some(Edge::Rising)); //! ```` //! //! The `update` function will return a rising/falling edge, or `None` if the //! input is still bouncing. //! //! ### Query Debounced State //! //! You can also query the current debounced state. If none of the `n` recent //! updates were pressed, then the debounced state will be low. If all `n` //! recent updates were pressed, then the debounced state will be high. //! //! ```rust //! use debouncr::debounce_3; //! //! let mut debouncer = debounce_3(false); //! //! // Initially low //! assert!(debouncer.is_low()); //! assert!(!debouncer.is_high()); //! //! // Update, now it's neither high nor low //! debouncer.update(true); //! assert!(!debouncer.is_low()); //! assert!(!debouncer.is_high()); //! //! // After two more updates, it's high //! debouncer.update(true); //! debouncer.update(true); //! assert!(debouncer.is_high()); //! ``` //! //! ### Stateful Debouncing //! //! By default, the debouncer will report any change from "bouncing" to //! "stable high/low" as an edge. If instead you want to detect only //! changes from a stable state to the opposite stable state, use the //! stateful debouncer instead. It has slightly higher (but still tiny) memory //! overhead than the regular debouncer, because it also stores the previous //! state in addition to the debouncing updates. //! //! ```rust //! use debouncr::{debounce_stateful_3, Edge}; //! //! let mut debouncer = debounce_stateful_3(false); //! //! // Ensure initial low state //! assert!(debouncer.is_low()); //! //! // Temporary bouncing states will not trigger an edge //! assert_eq!(debouncer.update(true), None); //! assert_eq!(debouncer.update(false), None); //! assert_eq!(debouncer.update(false), None); //! assert_eq!(debouncer.update(false), None); //! //! // However, stable opposite states will trigger an edge //! assert_eq!(debouncer.update(true), None); //! assert_eq!(debouncer.update(true), None); //! assert_eq!(debouncer.update(true), Some(Edge::Rising)); //! ``` //! //! ## Example: RTIC //! //! If you want to debounce a pin in an [RTIC](https://rtic.rs/) project, //! register a resource and a timer. //! //! ```ignore //! use debouncr::{Debouncer, debounce_12, Edge, Repeat12}; //! //! #[app(..., monotonic = rtic::cyccnt::CYCCNT)] //! const APP: () = { //! struct Resources { //! button: gpioa::PA11<Input<PullUp>>, //! button_state: Debouncer<u16, Repeat12>, //! } //! //! #[init(spawn = [poll_button])] //! fn init(ctx: init::Context) -> init::LateResources { //! // ... //! ctx.spawn.poll_button().unwrap(); //! init::LateResources { //! button, //! button_state: debounce_12(false), //! } //! } //! //! /// Regularly called task that polls the buttons and debounces them. //! #[task( //! resources = [button, button_state], //! spawn = [button_pressed, button_released], //! schedule = [poll_button], //! )] //! fn poll_button(ctx: poll_button::Context) { //! // Poll button //! let pressed: bool = ctx.resources.button.is_low().unwrap(); //! //! // Update state //! let edge = ctx.resources.button_state.update(pressed); //! //! // Dispatch event //! if edge == Some(Edge::Rising) { //! ctx.spawn.button_pressed().unwrap(); //! } else if edge == Some(Edge::Falling) { //! ctx.spawn.button_released().unwrap(); //! } //! //! // Re-schedule the timer interrupt //! ctx.schedule //! .poll_button(ctx.scheduled + POLL_PERIOD.cycles()) //! .unwrap(); //! } //! //! /// The button was pressed. //! #[task] //! fn button_pressed(ctx: button_pressed::Context) { //! // Button was pressed, handle event somehow //! } //! //! /// The button was released. //! #[task] //! fn button_released(ctx: button_pressed::Context) { //! // Button was released, handle event somehow //! } //! //! }; //! ``` //! //! ## Memory Consumption //! //! Memory size of a debouncer instance: //! //! |Debouncer|Repetitions|Bytes| //! |--|--|--| //! |[`Debouncer`]|2..8|1| //! |[`DebouncerStateful`]|2..8|2| //! |[`Debouncer`]|9..16|2| //! |[`DebouncerStateful`]|9..16|4| //! //! [`Debouncer`]: struct.Debouncer.html //! [`DebouncerStateful`]: struct.DebouncerStateful.html #![cfg_attr(not(test), no_std)] #![deny(unsafe_code, missing_docs)] use doc_comment::doc_comment; /// A debouncer. /// /// It wraps a `u8` or `u16`, depending on the number of required consecutive /// logical-high states. /// /// To create an instance, use the appropriate `debounce_X` function (where `X` /// is the number of required consecutive logical-high states). #[repr(transparent)] pub struct Debouncer<S, M> { state: S, mask: core::marker::PhantomData<M>, } /// A stateful debouncer. /// /// The regular [`Debouncer`](struct.Debouncer.html) will report any change /// from "bouncing" to "stable high/low" as an edge. That means that if a /// button is not pressed, bounces twice and then goes back to unpressed, it /// will report a falling edge even though there was no rising edge. /// /// This `DebouncerStateful` on the other hand stores the previous stable state /// and will only report a falling edge if there was previously a rising edge /// (and vice versa). /// /// The memory cost for this is storing an extra enum value per debouncer. pub struct DebouncerStateful<S, M> { debouncer: Debouncer<S, M>, last_edge: Edge, } /// Rising or falling edge. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Edge { /// A rising edge Rising, /// A falling edge Falling, } macro_rules! impl_logic { ($T:ty, $count:expr, $M:ident, $name:ident, $name_stateful:ident, $mask:expr) => { doc_comment! { concat!( "Detect ", $count, " consecutive logical-high states.\n\n", "This type should not be used directly. ", "Instead, construct a [`Debouncer`](struct.Debouncer.html) through [`debounce_", $count, "()`](fn.debounce_", $count, ".html).", ), pub struct $M; } doc_comment! { concat!( "Create a new debouncer that can detect a rising or falling edge of ", $count, " consecutive logical states.", ), pub fn $name(initial_state_pressed: bool) -> Debouncer<$T, $M> { Debouncer { state: if initial_state_pressed { $mask } else { 0 }, mask: core::marker::PhantomData, } } } doc_comment! { concat!( "Create a new stateful debouncer that can detect stable state changes after ", $count, " consecutive logical states.", ), pub fn $name_stateful(initial_state_pressed: bool) -> DebouncerStateful<$T, $M> { DebouncerStateful { debouncer: $name(initial_state_pressed), last_edge: if initial_state_pressed {Edge::Rising} else {Edge::Falling}, } } } impl Debouncer<$T, $M> { /// Update the state. pub fn update(&mut self, pressed: bool) -> Option<Edge> { // If all bits are already 1 or 0 and there was no change, // we can immediately return. if self.state == $mask && pressed { return None; } if self.state == 0 && !pressed { return None; } // Update state by shifting in the press state & masking self.state = ((self.state << 1) | (pressed as $T)) & $mask; // Query updated value if self.state == $mask { Some(Edge::Rising) } else if self.state == 0 { Some(Edge::Falling) } else { None } } /// Return `true` if the debounced state is logical high. pub fn is_high(&self) -> bool { self.state == $mask } /// Return `true` if the debounced state is logical low. pub fn is_low(&self) -> bool { self.state == 0 } } impl DebouncerStateful<$T, $M> { /// Update the state. pub fn update(&mut self, pressed: bool) -> Option<Edge> { self.debouncer.update(pressed).and_then(|edge| { if edge != self.last_edge { self.last_edge = edge; Some(edge) } else { None } }) } /// Return `true` if the debounced state is logical high. pub fn is_high(&self) -> bool { self.debouncer.is_high() } /// Return `true` if the debounced state is logical low. pub fn is_low(&self) -> bool { self.debouncer.is_low() } } }; } impl_logic!(u8, 2, Repeat2, debounce_2, debounce_stateful_2, 0b0000_0011); impl_logic!(u8, 3, Repeat3, debounce_3, debounce_stateful_3, 0b0000_0111); impl_logic!(u8, 4, Repeat4, debounce_4, debounce_stateful_4, 0b0000_1111); impl_logic!(u8, 5, Repeat5, debounce_5, debounce_stateful_5, 0b0001_1111); impl_logic!(u8, 6, Repeat6, debounce_6, debounce_stateful_6, 0b0011_1111); impl_logic!(u8, 7, Repeat7, debounce_7, debounce_stateful_7, 0b0111_1111); impl_logic!(u8, 8, Repeat8, debounce_8, debounce_stateful_8, 0b1111_1111); impl_logic!(u16, 9, Repeat9, debounce_9, debounce_stateful_9, 0b0000_0001_1111_1111); impl_logic!(u16, 10, Repeat10, debounce_10, debounce_stateful_10, 0b0000_0011_1111_1111); impl_logic!(u16, 11, Repeat11, debounce_11, debounce_stateful_11, 0b0000_0111_1111_1111); impl_logic!(u16, 12, Repeat12, debounce_12, debounce_stateful_12, 0b0000_1111_1111_1111); impl_logic!(u16, 13, Repeat13, debounce_13, debounce_stateful_13, 0b0001_1111_1111_1111); impl_logic!(u16, 14, Repeat14, debounce_14, debounce_stateful_14, 0b0011_1111_1111_1111); impl_logic!(u16, 15, Repeat15, debounce_15, debounce_stateful_15, 0b0111_1111_1111_1111); impl_logic!(u16, 16, Repeat16, debounce_16, debounce_stateful_16, 0b1111_1111_1111_1111); #[cfg(test)] mod tests { use super::*; #[test] fn test_rising_edge() { // Initially not pressed let mut debouncer: Debouncer<u8, Repeat3> = debounce_3(false); assert!(debouncer.is_low()); // Three pressed updates required assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); // Further presses do not indicate a rising edge anymore assert_eq!(debouncer.update(true), None); // A depressed state resets counting assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); } #[test] fn test_falling_edge() { // Initially not pressed let mut debouncer: Debouncer<u8, Repeat3> = debounce_3(false); assert!(debouncer.is_low()); // A single non-pressed update does not trigger assert_eq!(debouncer.update(false), None); assert!(debouncer.is_low()); // Trigger a falling edge assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); assert_eq!(debouncer.update(false), None); assert!(debouncer.is_low()); } #[test] fn test_debounce_16() { // Sixteen pressed updates required let mut debouncer: Debouncer<u16, Repeat16> = debounce_16(false); assert!(debouncer.is_low()); for _ in 0..15 { assert_eq!(debouncer.update(true), None); assert!(!debouncer.is_high()); } assert_eq!(debouncer.update(true), Some(Edge::Rising)); assert!(debouncer.is_high()); assert_eq!(debouncer.update(true), None); assert!(debouncer.is_high()); } #[test] fn test_is_low_high() { // Initially low let mut debouncer: Debouncer<u8, Repeat8> = debounce_8(false); assert!(debouncer.is_low()); assert!(!debouncer.is_high()); // Depressed updates don't change the situation debouncer.update(false); assert!(debouncer.is_low()); assert!(!debouncer.is_high()); // A pressed update causes neither low nor high state for _ in 0..7 { assert!(debouncer.update(true).is_none()); assert!(!debouncer.is_low()); assert!(!debouncer.is_high()); } // Once complete, the state is high assert_eq!(debouncer.update(true), Some(Edge::Rising)); assert!(!debouncer.is_low()); assert!(debouncer.is_high()); // Consecutive pressed updates don't trigger an edge but are still high assert!(debouncer.update(true).is_none()); assert!(!debouncer.is_low()); assert!(debouncer.is_high()); } /// Ensure the promised low RAM consumption. #[test] fn test_ram_consumption() { // Regular debouncers assert_eq!(std::mem::size_of_val(&debounce_2(false)), 1); assert_eq!(std::mem::size_of_val(&debounce_8(false)), 1); assert_eq!(std::mem::size_of_val(&debounce_9(false)), 2); assert_eq!(std::mem::size_of_val(&debounce_16(false)), 2); // Stateful debouncers assert_eq!(std::mem::size_of_val(&debounce_stateful_8(false)), 2); assert_eq!(std::mem::size_of_val(&debounce_stateful_9(false)), 4); } /// Ensure that the initial state can be specified. #[test] fn test_initial_state() { let mut debouncer = debounce_2(false); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); let mut debouncer = debounce_2(false); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); let mut debouncer = debounce_2(true); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); let mut debouncer = debounce_2(true); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); // Stateful debouncers let mut debouncer = debounce_stateful_2(false); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); let mut debouncer = debounce_stateful_2(false); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); let mut debouncer = debounce_stateful_2(true); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), Some(Edge::Rising)); let mut debouncer = debounce_stateful_2(true); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(true), None); assert_eq!(debouncer.update(false), None); assert_eq!(debouncer.update(false), Some(Edge::Falling)); } }