If you have an unread byte, and the SPI master sends another one, then you get an "overrun condition". The second byte sent is lost.
You can check if this has happened by checking the OVR flag in the status register (SR) for the SPI peripheral you're interested in, using this function:
bool hasOverrunOccurred() {
return SPI1_BASE->SR & SPI_SR_OVR;
}
hasOverrunOccurred()
will return true
if you've missed a byte, and false
otherwise.
If that happens, you need to clear the OVR flag in the status register. If you don't, then you won't be able to detect later overruns anymore -- hasOverrunOccurred()
will just return true
forever.
You clear the OVR flag by reading the first unread byte, then reading the status register again. Here's some (untested) code that should do the trick:
// Read the unread byte
byte unread = spi.read();
// Read the status register
uint32 sr = SPI1_BASE->SR;