Hello,
I see some potential problems with your slave code. You are clearing the SPI receive flag within the ISR, but are then reading and writing to SPDR within main and other functions. To maintain synchronism, I would suggest that the reading and writing also needs to be done within the ISR, with possibly the following sequence -
- Clear SPRF flag (read SPSCR)
- Read SPDR, test for command value, and place in global variable, if required.
- Test for data value to be returned (possibly by means of a global flag)
- If so, write return value to SPDR, else write "no data" value to SPDR
The data value will be returned when the master initiates the next transfer. All other processing should be done from outside the ISR, using the global variables to communicate with the ISR.
I presume that you have the SS pin tied permanently low at the slave. This could be problematic with the presence of any spurious clock pulses (perhaps caused by noise). IMHO it is better to frame the sequence by the master returning SS high after each transfer. With CPHA = 1, this could be done after the transfer of a number of bytes. However, with CPHA = 0, it must be done after the transfer of every byte.
I notice that you have set the master for the slowest SPI clock rate. Usual practice is to use the fastest clock rate available, that is compatible with the slave device. However, I also notice that you are sending a continuous data stream from the master, by virtue of the while loop. A better arrangement would be to pace the sending of data for a rate comparable with the slave command processing time, perhaps using the TIM module within the master. For the present code, the pacing is determined by the slow SPI clock rate.
Primarily within your code for the master, you have a separate line that reads SPSCR. This line is unnecessary since it alway occurs after the SPRF flag (within the same register) has been tested. When I use the SPI module, I would usually test for the SPTEF flag being set before writing to the SPDR register. While not always necessary, particularly for the HC908 SPI, it can avoid potential problems when using other 9S08 devices.
A final observation is your widespread use of 16-bit variables. With an 8-bit MCU, more efficient code will result if you declare 8-bit variables, preferably unsigned, unless it is absolutely necessary to use larger ones. Since 8-bit values are always used for peripherals such as the SPI and SCI, it makes no sense to use 16-bit values in these instances.
Regards,
Mac