简体   繁体   English

pySerial程序无法正确读取串行

[英]pySerial program doesn't read serial correctly

I have a problem using pySerial, and I don´t know from where to start looking for. 我使用pySerial有问题,我不知道从哪里开始寻找。 I have a 64 bits Windows Seven OS, with Python 2.7.5 (32 bits), and pySerial and Arduino (Arduino working correctly) already installed. 我有一个64位Windows 7操作系统,Python 2.7.5(32位),pySerial和Arduino(Arduino正常工作)已经安装。

My Arduino code is the following: 我的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");
}

(Arduino conected in COM8, when using Serial Monitor I can see it saluting) (Arduino在COM8中连接,使用串行监视器时我可以看到它敬礼)

And my PySerial code looks like this: 我的PySerial代码如下所示:

import serial
import time

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

while True:
    print arduino.readline()

When I start this script, the program runs, but I can´t see the serial output (I think the configuration in the Python script is OK because if something - eg the port - is wrong, it crashes). 当我启动这个脚本时,程序运行,但我看不到串行输出(我认为Python脚本中的配置是正常的,因为如果有什么东西 - 例如端口 - 是错误的,它会崩溃)。

I don´t know what to do to find a solution. 我不知道如何找到解决方案。 Can you help me? 你能帮助我吗?

You might try using println instead of print on the Arduino/C side, and/or set a timeout for the serial read on the Python side. 您可以尝试在Arduino / C端使用println而不是print ,和/或为Python端的串行读取设置超时。

Since serial.readline() waits for a \\n , and you never send one using print, the serial read will just wait for a timeout. 由于serial.readline()等待\\n ,并且您从不使用print发送,因此串行读取将等待超时。 (But it's a bit more complicated than this, and it's worth reading the docs on readline and EOL.) (但它比这更复杂,值得阅读readline和EOL上的文档 。)

If this doesn't work, at least switch readline to just read and print out each character you may (or may not) be reading, but don't make it more complicated by waiting for the \\n that readline requires. 如果这不起作用,至少将readline切换为只read并打印出您可能(或可能不)读取的每个字符,但不要因为等待readline所需的\\n而使其变得更复杂。

From the demo docs : 从演示文档
Be carefully when using readline(). 使用readline()时要小心。 Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. 在打开串口时指定超时,否则如果没有收到换行符,它可能永远阻塞。 Also note that readlines() only works with a timeout. 另请注意,readlines()仅适用于超时。 readlines() depends on having a timeout and interprets that as EOF (end of file). readlines()取决于具有超时并将其解释为EOF(文件结束)。 It raises an exception if the port is not opened correctly. 如果端口未正确打开,则会引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM