3
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ You might want to add details on what you're connecting to, for most devices you probably need to send a command followed by a dummy send to clock back the results from the device. \$\endgroup\$ – PeterJ Aug 2 '13 at 9:50
5
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Simply see an SPI device as an intelligent shift register. Shift in your data, then add some clock cycles to allow the data to be shifted out. The data you send in the second phase is usually irrelevant (just send 0xff which seems to be the inofficial default unless noted otherwise).

Also take care of your SPI Mode (CPOL, CPHA; Modes 1-4).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.