Skip to content

Commit

Permalink
add error for reading before sending, and insert bit reads at the cor…
Browse files Browse the repository at this point in the history
…rect locations
  • Loading branch information
sajattack committed May 14, 2019
1 parent e0c47d0 commit de66010
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions src/spi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use nb::block;

#[derive(Debug)]
pub enum Error {
Unimplemented,
NoData,
}

/// A Full-Duplex SPI implementation, takes 3 pins, and a timer running at 2x
Expand All @@ -22,7 +22,7 @@ where
mosi: Mosi,
sck: Sck,
timer: Timer,
read_val: u8,
read_val: Option<u8>,
}

impl <Miso, Mosi, Sck, Timer> SPI<Miso, Mosi, Sck, Timer>
Expand All @@ -45,7 +45,15 @@ where
mosi: mosi,
sck: sck,
timer: timer,
read_val: 0,
read_val: None,
}
}

fn read_bit(&mut self) {
if self.miso.is_high() {
self.read_val = Some((self.read_val.unwrap_or(0) << 1) | 1);
} else {
self.read_val = Some(self.read_val.unwrap_or(0) << 1);
}
}
}
Expand All @@ -60,7 +68,10 @@ where
type Error = Error;

fn read(&mut self) -> nb::Result<u8, Error> {
Ok(self.read_val)
match self.read_val {
Some(val) => Ok(val),
None => Err(nb::Error::Other(Error::NoData))
}
}

fn send(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
Expand All @@ -72,32 +83,31 @@ where
} else {
self.mosi.set_low();
}
if self.miso.is_high() {
self.read_val = (self.read_val << 1) | 1
} else {
self.read_val = self.read_val << 1
}
if self.mode.phase == CaptureOnFirstTransition {
if self.mode.polarity == IdleLow {
block!(self.timer.wait()).ok();
self.sck.set_high();
self.read_bit();
block!(self.timer.wait()).ok();
self.sck.set_low();
} else {
block!(self.timer.wait()).ok();
self.sck.set_low();
self.read_bit();
block!(self.timer.wait()).ok();
self.sck.set_high();
}
} else {
if self.mode.polarity == IdleLow {
self.sck.set_high();
block!(self.timer.wait()).ok();
self.read_bit();
self.sck.set_low();
block!(self.timer.wait()).ok();
} else {
self.sck.set_low();
block!(self.timer.wait()).ok();
self.read_bit();
self.sck.set_high();
block!(self.timer.wait()).ok();
}
Expand Down

0 comments on commit de66010

Please sign in to comment.