我在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++;
}
答案 0 :(得分:2)
像这样铸造char数组:
sendtoWait((uint8_t*)packetBuff, sizeof(packetBuff), SERVER_ADDRESS)
正常工作。不需要buff
。