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
//! # Debouncr
//!
//! A simple and efficient `no_std` input debouncer that uses integer bit
//! shifting to debounce inputs. The 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.
//!
//! 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 logical-high 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.
//!
//! ```rust
//! use debouncr::{Debouncer, debounce_4};
//! let mut debouncer = debounce_4(); // Type: Debouncer<u8, Repeat4>
//! ```
//! 
//! ### Update
//!
//! In regular intervals, call the `update(pressed)` function to update the
//! internal state.
//!
//! ```rust
//! # use debouncr::{Debouncer, debounce_3, Edge};
//! let mut debouncer = debounce_3();
//! # 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::{Debouncer, debounce_3};
//! let mut debouncer = debounce_3();
//!
//! // 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());
//! ```
//!
//! ## Example: RTFM
//!
//! If you want to debounce a pin in an [RTFM](https://rtfm.rs/) project,
//! register a resource and a timer.
//!
//! ```ignore
//! use debouncr::{Debouncer, debounce_12, Edge, Repeat12};
//!
//! #[app(..., monotonic = rtfm::cyccnt::CYCCNT)]
//! const APP: () = {
//!     struct Resources {
//!         button: gpioa::PA11<Input<PullUp>>,
//!         button_state: Debounce<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(),
//!         }
//!     }
//!
//!     /// 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
//!     }
//!
//! };
//! ```
#![cfg_attr(not(test), no_std)]
#![deny(unsafe_code, missing_docs)]

use doc_comment::doc_comment;

/// The main debouncer instance.
///
/// 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>,
}

/// Rising or falling edge.
#[derive(Debug, PartialEq, Eq)]
pub enum Edge {
    /// A rising edge
    Rising,
    /// A falling edge
    Falling,
}

macro_rules! impl_logic {
    ($T:ty, $count:expr, $M:ident, $name: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 edge of ",
                $count,
                " consecutive logical-high states.",
            ),
            pub fn $name() -> Debouncer<$T, $M> {
                Debouncer {
                    state: 0,
                    mask: core::marker::PhantomData,
                }
            }
        }

        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_logic!( u8,  2,  Repeat2,  debounce_2,           0b0000_0011);
impl_logic!( u8,  3,  Repeat3,  debounce_3,           0b0000_0111);
impl_logic!( u8,  4,  Repeat4,  debounce_4,           0b0000_1111);
impl_logic!( u8,  5,  Repeat5,  debounce_5,           0b0001_1111);
impl_logic!( u8,  6,  Repeat6,  debounce_6,           0b0011_1111);
impl_logic!( u8,  7,  Repeat7,  debounce_7,           0b0111_1111);
impl_logic!( u8,  8,  Repeat8,  debounce_8,           0b1111_1111);
impl_logic!(u16,  9,  Repeat9,  debounce_9, 0b0000_0001_1111_1111);
impl_logic!(u16, 10, Repeat10, debounce_10, 0b0000_0011_1111_1111);
impl_logic!(u16, 11, Repeat11, debounce_11, 0b0000_0111_1111_1111);
impl_logic!(u16, 12, Repeat12, debounce_12, 0b0000_1111_1111_1111);
impl_logic!(u16, 13, Repeat13, debounce_13, 0b0001_1111_1111_1111);
impl_logic!(u16, 14, Repeat14, debounce_14, 0b0011_1111_1111_1111);
impl_logic!(u16, 15, Repeat15, debounce_15, 0b0111_1111_1111_1111);
impl_logic!(u16, 16, Repeat16, debounce_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();
        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();
        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();
        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();
        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() {
        assert_eq!(std::mem::size_of_val(&debounce_2()), 1);
        assert_eq!(std::mem::size_of_val(&debounce_8()), 1);
        assert_eq!(std::mem::size_of_val(&debounce_9()), 2);
        assert_eq!(std::mem::size_of_val(&debounce_16()), 2);
    }
}