简体   繁体   English

在Pi上进行Python串行读取

[英]Python Serial Read on Pi

I am attempting to read serial data with my Pi from an Arduino Mega. 我试图用我的Pi从Arduino Mega读取串行数据。 Most of the time I get the correct read, but occasionally I do not read the correct number of bytes. 大多数情况下,我会读取正确的内容,但有时我不会读取正确的字节数。 My serial monitor from the Arduino shows the correct data being sent. 我的Arduino串行监视器显示了正确发送的数据。

Arduino Code Arduino代码

String reading = String(analogRead(0));
String out1 = reading + "\n";
Serial.print(out1);

Pi Python Code Pi Python代码

ser = serial.Serial('/dev/ttyACM0', 9600 , timeout = 1)
ser.open()
  num = ser.readline()
  print num
ser.close()

The value of num ranges from 60 to 200. num的取值范围是60〜200。

Here is an example of the output from seven consecutive executions (bold is bad read): 这是七个连续执行的输出示例(粗体字表示错误):

74 74

74 74

734 734

73 73

734 734

74 74

3 3

I have scoured the forums and cannot find anyone who has asked a question to address my issue. 我已经在论坛上进行了搜索,但是找不到有人提出问题来解决我的问题。 Everything I read says this should be a piece of cake, but I am still having issues. 我读到的所有内容都说这应该是小菜一碟,但我仍然遇到问题。

It's probably a timing issue. 这可能是时间问题。 The Arduino code presumably runs in a loop, correct? Arduino代码大概是循环运行的,对吗? It's just bashing out characters at some rate. 它只是在以某种速度扑灭角色。 It looks like the Python program has no loop, or if there is one, you're continually opening and closing the serial port. 看起来Python程序没有循环,或者如果有一个循环,您将不断打开和关闭串行端口。 The Arduino might be transmitting when the Pi isn't listening. 当Pi不监听时,Arduino可能正在传输。

Try this: 尝试这个:

ser = serial.Serial()  # whatever you need as arguments
ser.open()
while True:
    num = ser.readline()
    print(num)

You will have to break out of this with Control-C or something, but at least you can see if it works. 您将不得不使用Control-C或其他工具突破这一点,但是至少您可以看到它是否有效。

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

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