[英]Random character at the beginning of serial.readline() in python and arduino
当我执行serial.readline()时,我会得到随机字符,有时是其他麻烦,有时是整条消息。 输出应为“ 1,2”或“ 2,2”
这是serial.readline()输出的屏幕截图。 我试图在serial.readline()之前放置一个延迟,但是没有任何区别。 一开始通常会有一个奇怪的角色:
我还收到了奇怪的消息:
程序中稍后会出现一个问题,该问题会导致程序无法使用,因为有时我只是收到空白行。
有没有办法从串行获得一致的输出?
这是arduino代码:
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
Serial.println("1,2");
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
Serial.println("2,2");
}
}
这是python代码:
ser = serial.Serial('/dev/ttyUSB0', 9600)
line=ser.readline()
coord= line.strip()
print coord
编辑:我尝试将ser.flushInput()放在ser.open()之后,并且得到相同的输出。
您是否刷新了串行缓冲区
ser.flushInput()
在pyserial和Arduino之间进行接口时,我遇到了同样的问题。 这可能是一个过时的帖子,但是如果其他人遇到同样的麻烦,我可以通过插入以下内容来解决问题:
ser.flushInput()
...就在我的ser.readline()
调用之前。
这里没什么好看的。 我正在获取当前端口配置,将输入/输出速度设置为9600波特,将数据期望设置为每个字8位,没有奇偶校验位和停止位,设置规范模式,然后将这些更改提交回串行端口。
如果我没记错的话,通过串行端口连接时,您必须更改上述设置。
您没有提及它,但是我想您正在使用pySerial库。 无论您如何使用它,都可以通过正确的设置进行串行连接。 API的构造函数允许所有在下面说明的参数: Pyserial库
我没有测试过这种方法,因为我在C语言(而非Python)中遇到了类似的问题。
如果将其分解为更简单的东西会发生什么?
在Arduino上:
void setup()
{
Serial.begin(9600);
}
int i = 0;
void loop()
{
delay(1000);
Serial.print("Hello World ");
Serial.println(i);
i++;
}
在Python REPL中...
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while(1):
ser.readline()
您应该观察到的第一个行为是,当您启动串行连接时,Arduino将重新启动。 这需要几秒钟。
您应该观察到的第二个行为是(如果您在REPL中缓慢地键入它)在while(1)循环开始时,您将获得自启动串行连接以来累积的所有串行数据。 我花了几秒钟来输入所有内容,所以当我在ser.readline()之后按Enter时,我看到:
'Hello World 1\r\n'
'Hello World 2\r\n'
'Hello World 3\r\n'
我仅提及这一点是为了确保您熟悉上次我与Arduino进行串行通信时让我有点恼火的两件事:连接后需要时间重新启动,以及串行数据缓冲区。 readline()只会在缓冲区中给您一行,而不是缓冲区中的所有内容。
重新启动完成之前,您是否可能要尝试发送/接收数据? 按钮弹跳如何-十几个高/低状态检测会弄乱某些东西吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.