virt_ic/chip/
inputs.rs

1use crate::{generate_chip, State};
2
3use super::{ChipBuilder, ChipRunner, ChipSet, Pin, PinType};
4
5/// # A simple button
6/// Transmit the IN signal in the OUT pin when he is down
7/// you'll need to use `press()` and `release()` to change its state
8///
9/// # Diagram
10/// ```
11///        --------
12///  IN  --|1    2|-- OUT
13///        --------
14/// ```
15#[derive(Debug, Clone, Default)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct Button {
18    down: bool,
19    i: Pin,
20    o: Pin,
21}
22
23impl Button {
24    pub const I: usize = 1;
25    pub const O: usize = 2;
26
27    pub fn press(&mut self) {
28        self.down = true;
29    }
30
31    pub fn release(&mut self) {
32        self.down = false;
33    }
34}
35
36generate_chip!(Button, i: Button::I, o: Button::O);
37
38impl ChipBuilder<ChipSet> for Button {
39    fn build() -> ChipSet {
40        ChipSet::Button(Button {
41            down: false,
42            i: Pin::from(PinType::Input),
43            o: Pin::from(PinType::Output),
44        })
45    }
46}
47
48impl ChipRunner for Button {
49    fn run(&mut self, _: std::time::Duration) {
50        if self.down {
51            self.o.state = self.i.state;
52        } else {
53            self.o.state = State::Undefined
54        }
55    }
56}