为什么 spi.recieve() 函数在 mbed 的 SPI 中总是 return 零?

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

我想在两个 mbed 板之间建立一个 SPI 连接,我发现用于检测来自主机的数据传输的 spi.recieve() 函数总是 return 零和无法建立连接。

我尝试在我的代码中删除 'if',它起作用了,但我仍然不明白为什么函数 return 为零。

这是一些代码:

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

这是我完成的代码:

#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);
  }
}

你为什么不遵循参考代码? https://os.mbed.com/docs/mbed-os/v5.9/reference/spislave.html

对于 SPI,您必须了解 RX 和 TX 同时发生,并且该操作需要一些时间。

.reply() 设置要发送的内容,.receive() 检查是否已收到某些内容(可能不会立即收到),.read() 从 SPI 控制器获取数据。