简体   繁体   中英

Python Serial Read on Pi

I am attempting to read serial data with my Pi from an 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 Code

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

Pi Python Code

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.

Here is an example of the output from seven consecutive executions (bold is bad read):

74

74

734

73

734

74

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? 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. The Arduino might be transmitting when the Pi isn't listening.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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