Looking at the ARM STM32 code I'm trying to port I see the following:
/*
Description:- The spiRdWr function writes the data passed as the argument
and returns the data pushed out form the slave device
*/
UINT8 spiRdWr(UINT8 byte)
{
UINT8 readByte;
while((SPI1->SR & SPI_SR_BSY));
while(!(SPI1->SR & SPI_SR_TXE));
SPI1->DR = byte;
while(!(SPI1->SR & SPI_SR_RXNE));
readByte = (UINT8)SPI1->DR;
return readByte;
}
Based on how I'm reading this, both do the same -- send the byte and returns the read byte.
Yep sounds right. Microcontrollers with built-in SPI driver hardware employ a memory-addressable Shift Register where the I/O takes place, called "SPDR" in the AVR.
Writing to SPDR internally triggers activation of the SPI clock generator, which clocks out the bits in SPDR one at a time while shifting in the input bits from the MISO pin at the other end of the shift register, so that once the SPI clock has completed its 8 pulses the contents of SPDR are equal to the inputted byte from the slave.
There's usually a status register you can poll to check when the SPI clock is done. Both the AVR and ARM examples show this.
So I have made some progress with SPI. Which leaves me with the following question.
The Arduino Mega 1280 is SPI Master @ 5.0V
The device is SPI Slave @ 3.3V with 5V tolerant pins.
Most of the time I can send a request and it arrives at the other end just fine, everything in sync -- 0x01, 0x00, 0x00, 0x00.
Sometimes, it arrives at the other side as 0x00, 0x01, 0x00, 0x00 and so on -- like it's cycling a bit over.
Then on the MISO same thing happens -- first 5 "polls" are perfect, then it seems to get out of sync.
How do you troubleshoot something like this? I have a logic analyzer now.
Hook up the analyzer to the 4 pins (MISO/MOSI/SS/SCK) and take a snapshot. Maybe you are in the wrong SPI mode. Maybe SS goes low too soon/late or something.