badyjoke[m]: > <@badyjoke:matrix.org> Hi ! I'm having a weird issue with SPI. For context I use a ATSAM3X8 (Arduino Due) and I wrote my own HAL only for SPI. I'm reading data from a gyroscope but every byte I read is in double. I already played with baudrate/clock but it didn't change the behaviour. I also inspected with a probe and I have the expected result from the gyroscope and not any duplicated data. This is the implementation I have for send and receive data : > > ```rust > /// Sends a single byte over the SPI bus. > /// > /// # Arguments > /// > /// * `word` - The byte to send. > /// > /// # Returns > /// > /// * `Ok(())` if the byte was successfully sent. > /// * `Err(ErrorKind::Overrun)` if an overrun error occurred. > /// * `Err(ErrorKind::ModeFault)` if a mode fault error occurred. > pub fn send(&self, word: u8) -> Result<(), ErrorKind> { > if self.spi.sr().read().ovres().bit_is_set() { > return Err(ErrorKind::Overrun); > } else if self.spi.sr().read().modf().bit_is_set() { > return Err(ErrorKind::ModeFault); > } else { > // For simplicity reasons we write only blocking version > while !self.is_tdr_empty() {} > unsafe { > self.spi > .tdr() > .write_with_zero(|w| w.td().variant(word.into())) > } > } > Ok(()) > } > > /// Receives a single byte from the SPI bus. > /// > /// # Returns > /// > /// * `Ok(byte)` if a byte was successfully received. > /// * `Err(ErrorKind::Overrun)` if an overrun error occurred. > /// * `Err(ErrorKind::ModeFault)` if a mode fault error occurred > pub fn receive(&self) -> Result { > self.send(DUMMY_WRITE)?; > if self.spi.sr().read().ovres().bit_is_set() { > return Err(ErrorKind::Overrun); > } else if self.spi.sr().read().modf().bit_is_set() { > return Err(ErrorKind::ModeFault); > } else { > while !self.is_tx_empty() && self.is_rdr_full() {} > let rd = self.spi.rdr().read().rd().bits(); > Ok(rd as u8) > } > } > > ``` > > When reading the gyroscope ID and the gyroscope data and printing with defmt I get this : > > ```console > Device: a9 - x a98c y 8cfd z fd07 > └─ spi::__cortex_m_rt_main @ src\bin\spi.rs:117 > Device: 07 - x f0f0 y ebeb z 0606 > └─ spi::__cortex_m_rt_main @ src\bin\spi.rs:117 > Device: a9 - x a91d y 1def z ef68 > └─ spi::__cortex_m_rt_main @ src\bin\spi.rs:117 > Device: 68 - x e4e4 y c2c2 z 1a1a > └─ spi::__cortex_m_rt_main @ src\bin\spi.rs:117 > Device: a9 - x a958 y 5870 z 7064 > └─ spi::__cortex_m_rt_main @ src\bin\spi.rs:117 > ``` > > The expected device ID is A9. I'm still a beginner in embbeded and can't figure out this issue. > Thank in advance ! Often with SPI, you're going to be transceiving data, so there's a latency of 1 byte after sending a command before the data comes in. What this means is that usually during the first byte transfer, the peripheral is also sending some data to you (it is usually either a DONT-CARE or a status byte). The actual response to i.e. a register read is usually sent in the second byte. In your driver, are you taking this into account?