spark_ser7seg/
spi.rs

1use crate::{Error, SevenSegInterface};
2use embedded_hal::{blocking::spi::Write, digital::v2::OutputPin};
3
4#[non_exhaustive]
5pub enum SpimError<SPIM, GPIO> {
6    Spim(SPIM),
7    Gpio(GPIO),
8}
9
10pub struct SevSegSpim<SPIM, CS> {
11    spim: SPIM,
12    csn: CS,
13}
14
15impl<SPIM, CS> SevSegSpim<SPIM, CS>
16where
17    SPIM: Write<u8>,
18    CS: OutputPin,
19{
20    /// Create a new SparkFun Serial Seven Segment display using a SPI (Master)
21    /// port. The SPI port has a maximum frequency of 250kHz, and must be in Mode 0.
22    pub fn new(spim: SPIM, csn: CS) -> Self {
23        Self { spim, csn }
24    }
25
26    /// Release the components
27    pub fn release(self) -> (SPIM, CS) {
28        (self.spim, self.csn)
29    }
30}
31
32impl<SPIM, CS> SevenSegInterface for SevSegSpim<SPIM, CS>
33where
34    SPIM: Write<u8>,
35    CS: OutputPin,
36{
37    type InterfaceError = SpimError<SPIM::Error, CS::Error>;
38
39    fn send(&mut self, data: &[u8]) -> Result<(), Error<Self::InterfaceError>> {
40        self.csn
41            .set_low()
42            .map_err(|e| Error::Interface(SpimError::Gpio(e)))?;
43
44        let ret = self
45            .spim
46            .write(&data)
47            .map_err(|e| Error::Interface(SpimError::Spim(e)))
48            .map(drop);
49
50        self.csn
51            .set_high()
52            .map_err(|e| Error::Interface(SpimError::Gpio(e)))?;
53
54        ret
55    }
56}