【问题标题】:Error handling when reading from a serial port从串口读取时的错误处理
【发布时间】:2015-08-17 18:11:09
【问题描述】:

我正在使用 Arduino 并制作一个小型 GUI 以在处理上与它进行通信。我只是将浮点值打印到串行端口上并使用处理将其读回。在大多数情况下,一切都很顺利,我能够读取这些值。但是,有时串行读取会吐出相当随意的值,我不知道为什么。例如,

我的 Arduino 代码:

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  for (int i =1;i<5;i++)
{  Serial.println(float(i)+2.0);
delay(1);
  // put your main code here, to run repeatedly:
}
}

串行监视器的输出如预期的那样是 3.0,4.0,5.0,6.0。

这是我用来读取数据的处理代码(Python模式)

def connect2Arduino(): 
    global arduinoPort
    arduinoPort= Serial(this, 'COM32',9600)

def setup():
   background(0)
   connect2Arduino()

def draw():
   global arduinoPort
   if arduinoPort.available()>0:
       dataIn = arduinoPort.readStringUntil(int(10))
       if (dataIn != None or int(dataIn) != 13):
           print dataIn  

处理的输出如下所示

4.00

5.00

6.00

3.00

4.00

5.‚j

6.°3.00

4.00

5.00

6.00

当我尝试更改 dataIn 的类型时,当输出为 5.,j 时会弹出错误,这与预期的一样。

首先,我不知道为什么会出现这些错误。我想知道为什么它首先出现。其次,什么是修复?我可以在我的 arduino 代码上打印而不是 println,也许可以修复它,但我正在寻找更好的东西。

谢谢

【问题讨论】:

    标签: java python serialization arduino processing


    【解决方案1】:

    您可能正在填充串行缓冲区。尝试检查 println 返回的值并验证是否已处理正确的字节数。您也可以尝试在每次打印后添加 Serial.flush() 调用,以确保数据已发送出去。

    【讨论】:

    • 这听起来像是一个非常愚蠢的问题。但是默认情况下串行缓冲区有多大?串行监视器看起来不错
    • 我相信它是 64 字节。当您说“串行监视器”时,您的意思是您在 Arduino 和 PC 之间连接了一个串行监视器吗?我刚刚意识到,考虑到您在错误之前没有发送 64 个字节,这可能不太可能是缓冲区问题。
    • 我的意思是 arduino UI 上的串行监视器。按 ctrl+shift+m​​ 时得到的那个。 64 字节似乎很多。我确定我只使用了 4 个字节
    猜你喜欢
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多