2

我在 Arduino 库中有这样的函数定义:

bool RHReliableDatagram::sendtoWait(uint8_t * buf, uint8_t len, uint8_t address)

当我使用:

uint8_t timePacket[] = "time\n";
sendtoWait(timePacket, sizeof(timePacket), SERVER_ADDRESS)

我在 pyserial 的 readline() 函数的另一端(SERVER_ADDRESS)得到了一个非常精细的字符串,该字符串使用 utf-8 编码完美解码。

现在我需要使用相同的sendtoWait()函数发送一些字节。我首先定义了一个 60 字节的 char 数组

char packetBuff[60] = "";

然后我得到每个字节并将其转换为字符

char value = (char)flash.readByte(dumpCounter++);

然后将每个值放入 char 数组中,如下所示:

packetBuff[charNo] = value;

找到一个新行字符后,我尝试使用以下sendtoWait()函数再次发送 char 数组:

if (value == '\n') {
    Serial.println(packetBuff);
    uint8_t buff[charNo];
    for (int i = 0; i < charNo; i++) {
        buff[i] = packetBuff[i];
    }
    sendtoWait(buff, charNo, SERVER_ADDRESS))
charNo++;

但是,尽管Serial.println(packetBuff)显示了正确的字符,例如“1559105487\n”(unix 时间戳),但buff数组无法正常工作,并显示随机字符,如分号、随机单个数字等。

如何正确转换 char 数组并使用发送sendtoWait()“time\n”之类的函数正确发送它?

编辑: 完整代码:

  int charNo = 0;
  char packetBuff[60] = "";
  if (dumpCounter != 0) {
    dumpCounter--;
  }
  while(dumpCounter < currentFlashLoc) {
    char value = (char)flash.readByte(dumpCounter++);
    packetBuff[charNo] = value;
    if (value == '\n') {
      Serial.println(packetBuff);
      uint8_t buff[charNo];
      for (int i = 0; i < charNo; i++) {
        buff[i] = packetBuff[i];
      }
      if (manager.sendtoWait(buff, charNo, SERVER_ADDRESS)) {
        // packet sent successfully
      }
      charNo = -1;
    }
    charNo++;
  }
4

1 回答 1

2

像这样转换 char 数组:

sendtoWait((uint8_t*)packetBuff, sizeof(packetBuff), SERVER_ADDRESS)

工作正常。buff不需要。

于 2019-05-29T05:45:18.917 回答