pySerial程序无法正确读取串行

mek*_*oda 3 python windows serial-port arduino pyserial

我使用pySerial有问题,我不知道从哪里开始寻找.我有一个64位Windows 7操作系统,Python 2.7.5(32位),pySerial和Arduino(Arduino正常工作)已经安装.

我的Arduino代码如下:

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the serial in 19200 baud rate
  Serial.begin(19200);     
}

// the loop routine runs over and over again forever:
void loop() {
  delay(1000);               // wait for a second
  Serial.print("hello");
}
Run Code Online (Sandbox Code Playgroud)

(Arduino在COM8中连接,使用串行监视器时我可以看到它敬礼)

我的PySerial代码如下所示:

import serial
import time

arduino = serial.Serial("COM8", 19200)
time.sleep(2)  

while True:
    print arduino.readline()
Run Code Online (Sandbox Code Playgroud)

当我启动这个脚本时,程序运行,但我看不到串行输出(我认为Python脚本中的配置是正常的,因为如果有什么东西 - 例如端口 - 是错误的,它会崩溃).

我不知道如何找到解决方案.你能帮助我吗?

tom*_*m10 6

您可以尝试使用println而不是print在Arduino/C端,和/或为Python端的串行读取设置超时.

由于serial.readline()等待a \n,而你从不使用print发送,串行读取只会等待超时.(但它比这更复杂,值得阅读readline和EOL上的文档.)

如果这不起作用,至少切换readline到just read并打印出你可能(或可能不)正在阅读的每个字符,但不要因为等待\n那个readline需要而使它变得更复杂.

从演示文档:
使用readline()时要小心.在打开串口时指定超时,否则如果没有收到换行符,它可能永远阻塞.另请注意,readlines()仅适用于超时.readlines()取决于具有超时并将其解释为EOF(文件结束).如果端口未正确打开,则会引发异常.