Skip to content

Commit

Permalink
uart rx
Browse files Browse the repository at this point in the history
  • Loading branch information
sajattack committed Feb 18, 2019
1 parent 8df60a3 commit 101ab3f
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions src/serial.rs
Original file line number Diff line number Diff line change
@@ -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<TX, RX, Delay>
Expand Down Expand Up @@ -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
Expand All @@ -69,3 +68,31 @@ where
Ok(())
}
}

impl <TX, RX, Delay> serial::Read<u8> for Serial <TX, RX, Delay>
where
TX: OutputPin,
RX: InputPin,
Delay: DelayUs<u32>
{

type Error = ();

fn read(&mut self) -> nb::Result<u8, Self::Error> {
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)
}
}

0 comments on commit 101ab3f

Please sign in to comment.