bitbang_hal/
serial.rs

1//! Serial communication (USART)
2//!
3//! This implementation consumes the following hardware resources:
4//! - Periodic timer to mark clock cycles
5//! - Output GPIO pin for transmission (TX)
6//! - Input GPIO pin for reception (RX)
7//!
8//! The timer must be configured to twice the desired communication frequency.
9//!
10
11use embedded_hal::digital::v2::{InputPin, OutputPin};
12use embedded_hal::serial;
13use embedded_hal::timer::{CountDown, Periodic};
14use nb::block;
15
16/// Serial communication error type
17#[derive(Debug)]
18pub enum Error<E> {
19    /// Bus error
20    Bus(E),
21}
22
23/// Bit banging serial communication (USART) device
24pub struct Serial<TX, RX, Timer>
25where
26    TX: OutputPin,
27    RX: InputPin,
28    Timer: CountDown + Periodic,
29{
30    tx: TX,
31    rx: RX,
32    timer: Timer,
33}
34
35impl<TX, RX, Timer, E> Serial<TX, RX, Timer>
36where
37    TX: OutputPin<Error = E>,
38    RX: InputPin<Error = E>,
39    Timer: CountDown + Periodic,
40{
41    /// Create instance
42    pub fn new(tx: TX, rx: RX, timer: Timer) -> Self {
43        Serial { tx, rx, timer }
44    }
45
46    #[inline]
47    fn wait_for_timer(&mut self) {
48        block!(self.timer.wait()).ok();
49    }
50}
51
52impl<TX, RX, Timer, E> serial::Write<u8> for Serial<TX, RX, Timer>
53where
54    TX: OutputPin<Error = E>,
55    RX: InputPin<Error = E>,
56    Timer: CountDown + Periodic,
57{
58    type Error = crate::serial::Error<E>;
59
60    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
61        let mut data_out = byte;
62        self.tx.set_low().map_err(Error::Bus)?; // start bit
63        self.wait_for_timer();
64        for _bit in 0..8 {
65            if data_out & 1 == 1 {
66                self.tx.set_high().map_err(Error::Bus)?;
67            } else {
68                self.tx.set_low().map_err(Error::Bus)?;
69            }
70            data_out >>= 1;
71            self.wait_for_timer();
72        }
73        self.tx.set_high().map_err(Error::Bus)?; // stop bit
74        self.wait_for_timer();
75        Ok(())
76    }
77
78    fn flush(&mut self) -> nb::Result<(), Self::Error> {
79        Ok(())
80    }
81}
82
83impl<TX, RX, Timer, E> serial::Read<u8> for Serial<TX, RX, Timer>
84where
85    TX: OutputPin<Error = E>,
86    RX: InputPin<Error = E>,
87    Timer: CountDown + Periodic,
88{
89    type Error = crate::serial::Error<E>;
90
91    fn read(&mut self) -> nb::Result<u8, Self::Error> {
92        let mut data_in = 0;
93        // wait for start bit
94        while self.rx.is_high().map_err(Error::Bus)? {}
95        self.wait_for_timer();
96        for _bit in 0..8 {
97            data_in <<= 1;
98            if self.rx.is_high().map_err(Error::Bus)? {
99                data_in |= 1
100            }
101            self.wait_for_timer();
102        }
103        // wait for stop bit
104        self.wait_for_timer();
105        Ok(data_in)
106    }
107}