button_driver/
config.rs

1use core::time::Duration;
2
3/// Default debounce time for a button.
4pub const DEFAULT_DEBOUNCE: Duration = Duration::from_micros(900);
5/// Default release time for a button.
6pub const DEFAULT_RELEASE: Duration = Duration::from_millis(150);
7/// Default hold time for a button.
8pub const DEFAULT_HOLD: Duration = Duration::from_millis(500);
9
10/// Various [Button](crate::Button) parameters.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ButtonConfig<D = Duration> {
13    /// How much time the button should be pressed to in order to count it as a press.
14    pub debounce: D,
15    /// How much time the button should not be held to be released.
16    pub release: D,
17    /// How much time the button should be pressed to be held.
18    pub hold: D,
19    /// Button direction.
20    pub mode: Mode,
21}
22
23impl<D> ButtonConfig<D> {
24    /// Returns new [ButtonConfig].
25    ///
26    /// As a general rule, `debounce` time is less then `release` time and `hold` time is larger them both.
27    pub fn new(debounce: D, release: D, hold: D, mode: Mode) -> Self {
28        Self {
29            debounce,
30            release,
31            hold,
32            mode,
33        }
34    }
35}
36
37impl Default for ButtonConfig<Duration> {
38    fn default() -> Self {
39        Self {
40            debounce: DEFAULT_DEBOUNCE,
41            release: DEFAULT_RELEASE,
42            hold: DEFAULT_HOLD,
43            mode: Mode::default(),
44        }
45    }
46}
47
48#[cfg(feature = "embassy")]
49impl Default for ButtonConfig<embassy_time::Duration> {
50    fn default() -> Self {
51        use embassy_time::Duration;
52        // `as` is safe here because these contacts won't exceed `u64` limit
53        Self {
54            debounce: Duration::from_micros(DEFAULT_DEBOUNCE.as_micros() as u64),
55            release: Duration::from_millis(DEFAULT_RELEASE.as_millis() as u64),
56            hold: Duration::from_millis(DEFAULT_HOLD.as_millis() as u64),
57            mode: Mode::default(),
58        }
59    }
60}
61
62/// Button direction.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum Mode {
65    /// Active 0.
66    #[default]
67    PullUp,
68    /// Active 1.
69    PullDown,
70}
71
72impl Mode {
73    /// Is button activated by logic zero?
74    pub const fn is_pullup(&self) -> bool {
75        matches!(self, Mode::PullUp)
76    }
77
78    /// Is button activated by logic one?
79    pub const fn is_pulldown(&self) -> bool {
80        !self.is_pullup()
81    }
82}