I have to interface an Arduino Mega as a slave with a SPI master running at 1 MHz SCK
. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in acc
and return local data ret
, which is simply an integer to be incremented every transaction.
However, while the master data is stored in acc
(verified through serial output), the data returned to the master is not the value in ret
. Instead, the first response byte is correct (MSB of ret
) and the second response byte is just the first byte received by the Mega, which was the value already present in SPDR
.
How do I send the second byte of ret
as the second byte of the response? What am I doing wrong?
// SPI Slave
#include <SPI.h>
// return to master
volatile unsigned int ret;
// accept from master
volatile unsigned int acc;
// MSB/LSB indicator
volatile byte SB;
void setup(void)
{
ret = 0;
SB = 0;
pinMode(MISO, OUTPUT);
// turn on SPI in slave mode
SPCR |= _BV(SPE);
// turn on interrupts
SPCR |= _BV(SPIE);
// set CPOL, CPHA modes
// byte dataMode = 0;
// SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;
}
// SPI interrupt routine
ISR(SPI_STC_vect)
{
if(SB == 0) {
acc = SPDR << 8;
SPDR = ret;
ret++;
}
else {
acc += SPDR;
SPDR = ret >> 8;
}
SB = (SB + 1) & 0x01;
}
void loop(void)
{
// interrupt processing only
}
Edit Changed SCK
from 16 MHz to 1 MHz