use embedded_hal::blocking::spi; use embedded_hal::spi::{Mode, Phase, Polarity}; use embedded_hal::digital::v2::OutputPin; use crate::{Interface, Error}; /// SPI mode pub const MODE: Mode = Mode { polarity: Polarity::IdleLow, phase: Phase::CaptureOnFirstTransition, }; /// `Interface` implementation for SPI interfaces pub struct SpiInterface { spi: SPI, cs: CS, dc: DC, } impl SpiInterface where SPI: spi::Transfer + spi::Write, CS: OutputPin, DC: OutputPin, { pub fn new(spi: SPI, cs: CS, dc: DC) -> Self { Self { spi, cs, dc, } } } impl Interface for SpiInterface where SPI: spi::Transfer + spi::Write, CS: OutputPin, DC: OutputPin, { type Error = Error; fn write(&mut self, command: u8, data: &[u8]) -> Result<(), Self::Error> { self.cs.set_low().map_err(Error::OutputPin)?; self.dc.set_low().map_err(Error::OutputPin)?; self.spi.write(&[command]).map_err(Error::Interface)?; self.dc.set_high().map_err(Error::OutputPin)?; self.spi.write(data).map_err(Error::Interface)?; self.cs.set_high().map_err(Error::OutputPin)?; Ok(()) } fn write_iter(&mut self, command: u8, data: impl IntoIterator) -> Result<(), Self::Error> { self.cs.set_low().map_err(Error::OutputPin)?; self.dc.set_low().map_err(Error::OutputPin)?; self.spi.write(&[command]).map_err(Error::Interface)?; self.dc.set_high().map_err(Error::OutputPin)?; for w in data.into_iter() { self.spi.write(&w.to_be_bytes()).map_err(Error::Interface)?; } self.cs.set_high().map_err(Error::OutputPin)?; Ok(()) } }