bme280_multibus/
spi1.rs

1/// BME280 bus.
2#[derive(Debug)]
3pub struct Bme280Bus<SPI> {
4    spi: SPI,
5}
6
7/// SPI mode for the BME280.
8///
9/// The BME280 also supports mode 3.
10pub const MODE: eh1::spi::Mode = eh1::spi::MODE_0;
11
12impl<SPI> Bme280Bus<SPI> {
13    /// Creates a new `Bme280Bus` from a SPI peripheral and a chip select
14    /// digital I/O pin.
15    ///
16    /// # Safety
17    ///
18    /// The chip select pin must be high before being passed to this function.
19    ///
20    /// # Example
21    ///
22    /// ```
23    /// # let spi = ehm::eh1::spi::Mock::new::<&[ehm::eh1::spi::Transaction<u8>; 0]>(&[]);
24    /// use bme280_multibus::spi1::Bme280Bus;
25    ///
26    /// let mut bme: Bme280Bus<_> = Bme280Bus::new(spi);
27    /// # bme.free().done();
28    /// # Ok::<(), ehm::eh1::MockError>(())
29    /// ```
30    #[inline]
31    #[allow(clippy::unnecessary_safety_doc)]
32    pub fn new(spi: SPI) -> Self {
33        Bme280Bus { spi }
34    }
35
36    /// Free the SPI bus and CS pin from the BME280.
37    ///
38    /// # Example
39    ///
40    /// ```
41    /// # let spi = ehm::eh1::spi::Mock::new::<&[ehm::eh1::spi::Transaction<u8>; 0]>(&[]);
42    /// use bme280_multibus::spi1::Bme280Bus;
43    ///
44    /// let mut bme: Bme280Bus<_> = Bme280Bus::new(spi);
45    /// let mut spi = bme.free();
46    /// # spi.done();
47    /// # Ok::<(), ehm::eh1::MockError>(())
48    /// ```
49    #[inline]
50    pub fn free(self) -> SPI {
51        self.spi
52    }
53}
54
55impl<SPI> crate::Bme280Bus for Bme280Bus<SPI>
56where
57    SPI: eh1::spi::SpiDevice,
58{
59    type Error = SPI::Error;
60
61    fn read_regs(&mut self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
62        let a = &[reg | (1 << 7)];
63        let mut ops = [
64            eh1::spi::Operation::Write(a),
65            eh1::spi::Operation::Read(buf),
66        ];
67        self.spi.transaction(&mut ops)
68    }
69
70    fn write_reg(&mut self, reg: u8, data: u8) -> Result<(), Self::Error> {
71        let buf = &[reg & !(1 << 7), data];
72        let mut ops = [eh1::spi::Operation::Write(buf)];
73        self.spi.transaction(&mut ops)
74    }
75}
76
77impl<SPI> crate::Bme280BusAsync for Bme280Bus<SPI>
78where
79    SPI: eha1::spi::SpiDevice,
80{
81    type Error = SPI::Error;
82
83    async fn read_regs(&mut self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
84        let a = &[reg | (1 << 7)];
85        let mut ops = [
86            eh1::spi::Operation::Write(a),
87            eh1::spi::Operation::Read(buf),
88        ];
89        self.spi.transaction(&mut ops).await
90    }
91
92    async fn write_reg(&mut self, reg: u8, data: u8) -> Result<(), Self::Error> {
93        let buf = &[reg & !(1 << 7), data];
94        let mut ops = [eh1::spi::Operation::Write(buf)];
95        self.spi.transaction(&mut ops).await
96    }
97}