Explanation on how SPI SLAVE (Arduino) sends data back to SPI MASTER (Arduino)

Hi,
Basically I have been reading and following this post on Nick Gammon's website : Gammon Forum : Electronics : Microprocessors : SPI - Serial Peripheral Interface - for Arduino and it is really useful so far. However I am not sure how on the SLAVE side, the data is being sent back to the MASTER when there's no actual explicit line that says spi.transfer... rather a few case/switch statements are there that specifies what SPDR's value should be. My question is how does setting the SPDR value on the SLAVE side sending some values back on the SPI MASTER side without using the spi.transfer command? Can someone please explain it to me? I am still trying to look at the equivalent of wire.send or wire.read of I2C on SPI. I know that on SPI data is being sent and received per transmission but im not sure where it is specified how data is sent from either side but the spi.transfer from the master side.
Thanks and Regards to everyone

When the SPI transfer starts the slave has to do two things:

  • Find what the master sent (read SPDR)
  • Set up a response for the next transfer (write to SPDR)

From the page you mentioned:

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;
 
  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;
    
  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;
    
  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

The interrupt routine reads SPDR (this is what was sent) and then writes to SPDR, which will be picked up by the master on the next SPI.transfer() on the master end.

First of all thanks for the prompt reply. The method where SPDR is read and then overwritten only works if you send one byte right? How is it possible to send from the MASTER side the string "Hello" and when the SLAVE received it, it will load the text "Hello" to its own char array and then send "Received" back to the MASTER? Would I need to create a for loop or something similar to send each character in the string? Also is spi.transfer() only stated in the MASTER because it is the only one that can initiate data transmission and the SLAVE have to yield to it and is it possible for the slave to request to send to the master?
thanks again

To handle more than one byte you need a state machine. My example even had that for doing what it did. The "state machine" remembers what it did last.

Yes, the master has to initiate transmission, that more-or-less is why it is called the master.

Think of your web browser. A page appears when you request it. Pages don't just get sent to you for no reason. In this situation your web browser is the master (it starts the transmission) and the web server is the slave (it responds).