Arduino没有读取适当数量的字节

时间:2015-03-07 22:07:01

标签: c++ serial-port arduino usb raspberry-pi

我有一个Raspberry Pi连接到带有USB的Arduino Mega并试图从RPI向Arduino发送一个8字节的包。我正在使用WiringPi串行库来实现这一目标。 RPI部分扫描串行缓冲区以获取可用数据。如果没有,它会将数据写入串行。

for(;;) {
    if (int i = serialDataAvail(f_)) {
       printf("RPI received %d bytes\n", i);
       uint8_t buf[i];
       read(f_, buf, i);
       printf("%s",buf);
    }
    ..some code filling variable widthsChar with data...
    write(f_, widthsChar, sizeof(widthsChar));
    printf("amount sent: %d \n", sizeof(widthsChar));
    usleep(3000000); //3 sec;
}

这里有一个Arduino部分,它等待RPI数据到达并以收到的字节响应。

while(Serial.available() == 0);
String bytesNum = String(Serial.available());
String newString = "Arduino received " + bytesNum + " bytes\n";
Serial.print(newString);
delay(10000);

我猜,输出应该是这样的:

amount sent: 8
//waits for 3 sec
RPI received 25 bytes
Arduino received 8 bytes
amount sent: 8
//and so far

我实际上得到的并不是我可以解释并要求某人帮助理解它的东西。 在这里:

amount sent: 8
//nothings happens for 3 sec
amount sent: 8
RPI received 25 bytes
Arduino received 1 bytes
W??1??0mount sent: 8
// I tried to interpret random chars it displays that way
//and so far

1 个答案:

答案 0 :(得分:1)

您遇到的问题在于事件的实际时间表。

当RPi将数据发送到Arduino时,请记住它是串行发送,即一次发送一个字符。

一旦数据的第一个字节到达Arduino,Serial.available()将返回1,表示第一个字节已到达!然后你的代码开始工作只处理第一个字节(Arduino比串行通信快得多)。

一个简单的解决方案是使用Serial.readBytes(),它将继续读取字节,直到RPi停止发送,并为您缓冲它们。它将继续读取字节,直到达到串行超时(默认值:1秒),或者直到填充缓冲区为止。

while(Serial.available() == 0)
    ; // Waiting for data

char buffer[80];
int bytesRead = Serial.readBytes(buffer, 80);

String msg = "Arduino received ";
msg += bytesRead;
msg += " bytes";
Serial.println(msg);
delay(10000);

RPi在最后一行打印垃圾字符的问题可能是一个不同的单独问题。