Hello,
I suspect there might be a slight misunderstanding in the way that the SPI operates.
Whenever the master sends a byte to the slave, the slave will simultaneously return a byte to the master, and the byte value will be whatever was in the slave data register just prior to the transaction commencing. If you need to obtain a return byte from the slave in response to the byte it has just received (as I suspect you do), you will need to commence a second transaction from the master in order to get the response, and this should be delayed by a sufficient amount for the slave to process the received byte, and to load a new value to its data register.
For the master I would generally prefer to emphasize that SPI is a two-way "transaction", so would combine the send and receive processes, for each byte, within a single function. This might avoid some of the confusion.
byte SPItrans( byte value )
{
// while ( !SPIS_SPTEF ); // Probably unnecessary for modified code
SPID = value;
while ( !SPIS_SPRF );
return SPID;
}
This function will return the immediate value from the slave, not the response to the byte sent. The function would be used in the following manner -
SPItrans( command1 ); // Ignore garbage return
// Wait for slave to process command
resp1 = SPItrans( command2 ); // Receive response to first command
// Wait for slave to process command
resp2 = SPItrans( command3 ); // Receive response to second command
// Wait for slave to process command
resp3 = SPItrans( 0 ); // Send dummy byte if no further data
For the slave end, receive and send should remain as individual functions.
Regards,
Mac