How do I use the Arduino Mega as a 16-bit SPI slave? 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 &lt;SPI.h&gt;

// 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 &amp; ~SPI_MODE_MASK) | dataMode;

}

// SPI interrupt routine
ISR(SPI_STC_vect)
{

  if(SB == 0) {
    acc = SPDR &lt;&lt; 8;
    SPDR = ret;
    ret++;
  }
  else {
    acc += SPDR;
    SPDR = ret &gt;&gt; 8;
  }
  SB = (SB + 1) &amp; 0x01;

}

void loop(void)
{
  // interrupt processing only
}


Edit Changed SCK from 16 MHz to 1 MHz
You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.


  In SPI Slave mode, the control logic will sample the incoming signal
  of the SCK pin. To ensure correct sampling of the clock signal, the
  minimum low and high periods should be: Low period: longer than 2 CPU
  clock cycles. High period: longer than 2 CPU clock cycles.


This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz). 

Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:


Time between slave mode chip select and clock must be stretched to compensate for the ISR latency. 
The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).


Cheers!