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
use embedded_hal::digital::{OutputPin, InputPin};
use embedded_hal::timer::{CountDown, Periodic};
use embedded_hal::serial;
use nb::block;
pub struct Serial<TX, RX, Timer>
where
TX: OutputPin,
RX: InputPin,
Timer: CountDown + Periodic,
{
tx: TX,
rx: RX,
timer: Timer,
}
impl <TX, RX, Timer> Serial <TX, RX, Timer>
where
TX: OutputPin,
RX: InputPin,
Timer: CountDown + Periodic
{
pub fn new(
tx: TX,
rx: RX,
timer: Timer
) -> Self {
Serial {
tx: tx,
rx: rx,
timer: timer
}
}
}
impl <TX, RX, Timer> serial::Write<u8> for Serial <TX, RX, Timer>
where
TX: OutputPin,
RX: InputPin,
Timer: CountDown + Periodic
{
type Error = ();
fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
let mut data_out = byte;
self.tx.set_low();
block!(self.timer.wait()).ok();
for _bit in 0..8 {
if data_out & 1 == 1 {
self.tx.set_high();
} else {
self.tx.set_low();
}
data_out >>= 1;
block!(self.timer.wait()).ok();
}
self.tx.set_high();
block!(self.timer.wait()).ok();
Ok(())
}
fn flush(&mut self) -> nb::Result<(), Self::Error> {
Ok(())
}
}
impl <TX, RX, Timer> serial::Read<u8> for Serial <TX, RX, Timer>
where
TX: OutputPin,
RX: InputPin,
Timer: CountDown + Periodic
{
type Error = ();
fn read(&mut self) -> nb::Result<u8, Self::Error> {
let mut data_in = 0;
while self.rx.is_high() {}
block!(self.timer.wait()).ok();
for _bit in 0..8 {
data_in <<= 1;
if self.rx.is_high() {
data_in |= 1
}
block!(self.timer.wait()).ok();
}
block!(self.timer.wait()).ok();
Ok(data_in)
}
}