Electronic – How to wait for a response from an SPI slave with an ATmega16

avrspi

I'm trying to connect to a slave in SPI net, I need to send a command and receive a response. I've used the below code for connection:

  char SPI_sendchar(char chr) {
      char receivedchar = 0;
      SPDR = chr;
      while(!(SPSR & (1<<SPIF)));
      receivedchar = SPDR;
      return (receivedchar);
  }

But I always "receivedchar" variable equal to variable "chr", I'm try to use this code without any slave in net but the result is the same.

Best Answer

What PeterJ said in his comment is correct. For any device that works based on commands, you must send a command to it like you are, then send a "dummy command" or just a character of data, say 0xFF.

Here is what happens with most SPI communication: the master sends a command, after the command is sent, the slave reads it and prepares its response. Then the slave sends its response at the same time the master sends the next byte.

What this means for you is that you need to add a dummy command:

char SPI_sendchar(char chr) {
  char receivedchar = 0;
  SPDR = chr;
  while(!(SPSR & (1<<SPIF)));

  SPDR = 0xFF;
  while(!(SPSR & (1<<SPIF)));

  receivedchar = SPDR;
  return (receivedchar);
}

Hope this helps.