Skip to content

Commit

Permalink
spi: enable both LSB first and MSB first transfers
Browse files Browse the repository at this point in the history
Enable both LSB first and MSB first transfers: add
function set_bit_order to select configuration.
By default MSB first configuration is used.

Signed-off-by: Sergey Matyukevich <geomatsi@gmail.com>
  • Loading branch information
geomatsi committed Jun 29, 2019
1 parent b81ca5e commit c88b122
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/spi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ pub enum Error {
NoData,
}

#[derive(Debug)]
pub enum BitOrder {
MSBFirst,
LSBFirst,
}

impl Default for BitOrder {
/// Default bit order: MSB first
fn default() -> Self {
BitOrder::MSBFirst
}
}

/// A Full-Duplex SPI implementation, takes 3 pins, and a timer running at 2x
/// the desired SPI frequency.
pub struct SPI<Miso, Mosi, Sck, Timer>
Expand All @@ -25,6 +38,7 @@ where
sck: Sck,
timer: Timer,
read_val: Option<u8>,
bit_order: BitOrder,
}

impl <Miso, Mosi, Sck, Timer> SPI<Miso, Mosi, Sck, Timer>
Expand All @@ -48,9 +62,14 @@ where
sck: sck,
timer: timer,
read_val: None,
bit_order: BitOrder::default(),
}
}

pub fn set_bit_order(&mut self, order: BitOrder) {
self.bit_order = order;
}

fn read_bit(&mut self) {
if self.miso.is_high() {
self.read_val = Some((self.read_val.unwrap_or(0) << 1) | 1);
Expand All @@ -77,14 +96,18 @@ where
}

fn send(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
let mut data_out = byte;
for _bit in 0..8 {
let out_bit = (data_out >> 7) & 1;
for bit in 0..8 {
let out_bit = match self.bit_order {
BitOrder::MSBFirst => (byte >> (7 - bit)) & 0b1,
BitOrder::LSBFirst => (byte >> bit) & 0b1,
};

if out_bit == 1 {
self.mosi.set_high();
} else {
self.mosi.set_low();
}

if self.mode.phase == CaptureOnFirstTransition {
if self.mode.polarity == IdleLow {
block!(self.timer.wait()).ok();
Expand Down Expand Up @@ -114,7 +137,6 @@ where
block!(self.timer.wait()).ok();
}
}
data_out <<= 1;
}
Ok(())
}
Expand Down

0 comments on commit c88b122

Please sign in to comment.