Re: Question about communication between two mcu via spi
Posted: Mon Aug 11, 2025 11:20 am
This is caused by the synchronous transfer of data (as mentioned above)
So while the slave is receiving the first byte of data (10) the value set in the last transmission is being sent. So this will be the last byte from the the previous data block (here 128).
So the received data is always 'off by one'.
The simplest solution is to ignore the first byte of the reply and send an extra 'dummy' byte at the end of transmission.
For example
Data to send by slave = {1,2,3,4,5} (5 bytes expected)
Master sends {1,2,3,4,5,6} (6 bytes including an extra 'final' value)
Slave replies with {x,1,2,3,4,5} and the master 'ignores' x. (5 bytes received + 'x' on first byte received)
The alternative is to 'preload' the SPI send buffer with the first byte of the reply - though this might be unknown (whether a sensor reading or based on the data received from the master) - but you could possibly use the CS going low to 'wake' the slave and do the preload. Depending on application - the slave may sleep the MCU to save power until data is requested by master (CS - goes low - data send in response to master - master pulls CS high - slave sleeps)
Also in the slave interrupt:
Try:
SPI_SendChar(); (or SPI_Slave_Calc())
SPI_Slave::GetChar() // This receives AND sends a data byte (which is set by SendChar())
Martin
So while the slave is receiving the first byte of data (10) the value set in the last transmission is being sent. So this will be the last byte from the the previous data block (here 128).
So the received data is always 'off by one'.
The simplest solution is to ignore the first byte of the reply and send an extra 'dummy' byte at the end of transmission.
For example
Data to send by slave = {1,2,3,4,5} (5 bytes expected)
Master sends {1,2,3,4,5,6} (6 bytes including an extra 'final' value)
Slave replies with {x,1,2,3,4,5} and the master 'ignores' x. (5 bytes received + 'x' on first byte received)
The alternative is to 'preload' the SPI send buffer with the first byte of the reply - though this might be unknown (whether a sensor reading or based on the data received from the master) - but you could possibly use the CS going low to 'wake' the slave and do the preload. Depending on application - the slave may sleep the MCU to save power until data is requested by master (CS - goes low - data send in response to master - master pulls CS high - slave sleeps)
Also in the slave interrupt:
Try:
SPI_SendChar(); (or SPI_Slave_Calc())
SPI_Slave::GetChar() // This receives AND sends a data byte (which is set by SendChar())
Martin