expression
Debounce an input with consecutive stable samples
Mechanical contacts can bounce, producing multiple transitions for one action. This fixed-rate sample model accepts a change after three consecutive samples differ from the current stable state. The sample interval and threshold must be selected for the actual switch and responsiveness requirements. No timing is measured. Expected host stdout (not executed): 0 0 0 0 1 done Common mistake: Counting nonconsecutive noisy samples or claiming a sample threshold defines a time without a known sampling interval.
Formal Syntax & Structure
rust syntaxrust
stable_samples >= thresholdWorking Example
Example Snippetrust
#![no_std]pub struct Debounce { stable: bool, count: u8 }impl Debounce { pub const fn new(initial: bool) -> Self { Self { stable: initial, count: 0 } } pub fn sample(&mut self, value: bool) -> bool { if value == self.stable { self.count = 0; } else { self.count += 1; if self.count == 3 { self.stable = value; self.count = 0; } } self.stable }}