Search code examples
c++spimbed

Why spi.recieve() function always return zero in SPI of mbed?


I want to set up a SPI connection between two mbed boards and I found that the spi.recieve() function which is used to detect the data transmission from the master always return zero and the connection can't be established.

I try to remove 'if' in my code, and it works, but I still don't understand why the function returns zero.

here is some code:

while (1)
  {
    transmit_value = 100 * voltage;
    spislave.reply(transmit_value);
    if (spislave.receive())
    {
      receive_value = spislave.read();
    }

here is my completed code:

#include <mbed.h>
Serial pc(USBTX, USBRX);
SPISlave spislave(p5, p6, p7, p8);
AnalogIn voltage(p20);
PwmOut led(p21);
BusOut display(p9, p10, p11, p12, p13, p14, p15, p16);
DigitalOut GroundLeft(p27);
DigitalOut GroundRight(p28);
int main()
{
  char transmit_value = 50;
  char receive_value = 60;
  spislave.format(8,0);
  spislave.frequency(1000000);
  while (1)
  {
    transmit_value = 100 * voltage;
    spislave.reply(transmit_value);
    if (!spislave.receive())
    {
      receive_value = spislave.read();
    }
    led.write(receive_value / 100.0);
    int leftnum = receive_value / 10;
    int rightnum = receive_value % 10;
    pc.printf("%d\n", receive_value);
    GroundLeft = 0;
    GroundRight = 1;
    switch (leftnum)
    {
    case 0:
      display = 0x3F;
      break;
    case 1:
      display = 0x06;
      break;
    case 2:
      display = 0x5B;
      break;
    case 3:
      display = 0x4F;
      break;
    case 4:
      display = 0x66;
      break;
    case 5:
      display = 0x6D;
      break;
    case 6:
      display = 0x7D;
      break;
    case 7:
      display = 0x07;
      break;
    case 8:
      display = 0x7F;
      break;
    case 9:
      display = 0x6F;
      break;
    }
    wait(0.01);
    GroundLeft = 1;
    GroundRight = 0;
    switch (rightnum)
    {
    case 0:
      display = 0x3F;
      break;
    case 1:
      display = 0x06;
      break;
    case 2:
      display = 0x5B;
      break;
    case 3:
      display = 0x4F;
      break;
    case 4:
      display = 0x66;
      break;
    case 5:
      display = 0x6D;
      break;
    case 6:
      display = 0x7D;
      break;
    case 7:
      display = 0x07;
      break;
    case 8:
      display = 0x7F;
      break;
    case 9:
      display = 0x6F;
      break;
    }
    wait(0.01);
  }
}

Solution

  • Why are you not following the reference code? https://os.mbed.com/docs/mbed-os/v5.9/reference/spislave.html

    With SPI you have to understand that RX and TX happen at the same time and that the operation will take some amount of time.

    .reply() sets up what to send, .receive() checks if something has been received (which probably won't be immediately), and .read() gets data from SPI controller.