From 101ab3f8fb746be69229b7fefc10ab085cf26d22 Mon Sep 17 00:00:00 2001 From: Paul Sajna Date: Mon, 18 Feb 2019 02:40:06 -0800 Subject: [PATCH] uart rx --- src/serial.rs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/serial.rs b/src/serial.rs index d1de010..ce287a6 100644 --- a/src/serial.rs +++ b/src/serial.rs @@ -1,7 +1,6 @@ use embedded_hal::digital::{OutputPin, InputPin}; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::serial; -use embedded_hal::serial::{Write, Read}; use crate::time::Hertz; pub struct Serial @@ -48,16 +47,16 @@ where type Error = (); fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> { - let mut out_byte = byte; + let mut data_out = byte; self.tx.set_low(); // start bit self.delay.delay_us(self.delay_time); for _bit in 0..8 { - if out_byte & 1 == 1 { + if data_out & 1 == 1 { self.tx.set_high(); } else { self.tx.set_low(); } - out_byte >>= 1; + data_out >>= 1; self.delay.delay_us(self.delay_time); } self.tx.set_high(); // stop bit @@ -69,3 +68,31 @@ where Ok(()) } } + +impl serial::Read for Serial +where + TX: OutputPin, + RX: InputPin, + Delay: DelayUs +{ + + type Error = (); + + fn read(&mut self) -> nb::Result { + let mut data_in = 0; + // wait for start bit + while self.rx.is_high() {} + // catch the middle of the first bit + self.delay.delay_us((self.delay_time as f32 * 1.5) as u32); + for _bit in 0..8 { + data_in <<= 1; + if self.rx.is_high() { + data_in |= 1 + } + self.delay.delay_us(self.delay_time); + } + // wait for stop bit + self.delay.delay_us(self.delay_time); + Ok(data_in) + } +}