We're trying to use SPI to communicate with another IC using an atmel atmega328 MCU. The target IC takes a command (the header in the code) and then feeds us back the information stored in the requested register (or writes to it if the command is a write). However, we're having two problems here:
Nothing comes out of the SPI, the only change is on the CS line (which we control). No SPI clock, no data on the data lines.
The first iteration of the for loop when writing the header the program does not enter the while loop (The LED on port 6 won't turn on).
Any help with this would be much appreciated, code provided down below.
#define DDR_SPI DDRB
#define DD_MISO DDB4
#define DD_MOSI DDB3
#define DD_SCK DDB5
#define DD_SS DDB6
void SPI_MasterInit(void)
{
/* Set MOSI, SCK and CS output, all others input */
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK)|(1<<DD_SS);
/* Enable SPI, Master, set clock rate = System clock / 16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
int readfromspilow(uint16 headerLength, const uint8 *headerBuffer, uint32 readLength, uint8 *readBuffer)
{
PORTB &= ~(1 << PORTB6); // Set CS low
for(int i=0; i<headerLength; i++)
{
SPDR = headerBuffer[i]; //Send entry i of the header to the spi register
sleep_us(5); // Give the flag time to reset, might be unnecessary
PORTD |= (1 << PORTD5); //LED for diagnostics
while(!(SPSR & (1<<SPIF))){ //Wait for SPIFinished flag
PORTD |= (1 << PORTD6); //LED for diagnostics
}
PORTD &= ~(1 << PORTD3); //LED for diagnostics
//readBuffer[0] = SPDR; // Dummy read as we write the header
}
for(int i=0; i<readLength; i++)
{
SPDR = 0xFF; // Dummy write as we read the message body
sleep_us(5); // Give the flag time to reset, might be unnecessary
while(!(SPSR & (1<<SPIF))); //Wait for SPIFinished flag
readBuffer[i] = SPDR ; //Store the value in the buffer
}
PORTB |= (1 << PORTB6); // Set CS high
return;
}
Edit: Added the defines for the initialization