spark_ser7seg/
i2c.rs

1use crate::{Error, SevenSegInterface};
2use embedded_hal::blocking::i2c::Write;
3
4#[non_exhaustive]
5#[derive(Debug, Eq, PartialEq)]
6pub enum I2cError<I2C> {
7    I2c(I2C),
8}
9
10pub struct SevSegI2c<I2C> {
11    i2c: I2C,
12    addr: u8,
13}
14
15impl<I2C> SevSegI2c<I2C>
16where
17    I2C: Write,
18{
19    /// Create a new SparkFun Serial Seven Segment display using an I2C
20    /// port. The I2C port supports 100kHz and 400kHz modes.
21    ///
22    /// If no address is supplied, the default 7-bit address of `0x71`
23    /// will be used.
24    pub fn new(i2c: I2C, addr: Option<u8>) -> Self {
25        Self {
26            i2c,
27            addr: addr.unwrap_or(0x71),
28        }
29    }
30
31    /// Update the address of the display used by the library.
32    ///
33    /// This does NOT reconfigure the display to use this new address.
34    ///
35    /// For now, this is probably not useful until we implement the
36    /// "change address" command in the main interface.
37    pub fn set_address(&mut self, addr: u8) {
38        self.addr = addr;
39    }
40
41    /// Release the components
42    pub fn release(self) -> I2C {
43        self.i2c
44    }
45}
46
47impl<I2C> SevenSegInterface for SevSegI2c<I2C>
48where
49    I2C: Write,
50{
51    type InterfaceError = I2cError<I2C::Error>;
52
53    fn send(&mut self, data: &[u8]) -> Result<(), Error<Self::InterfaceError>> {
54        self.i2c
55            .write(self.addr, &data)
56            .map_err(|e| Error::Interface(I2cError::I2c(e)))
57            .map(drop)
58    }
59}