Python3 Two-Way Serial Communication: Reading In Data

久未见 提交于 2019-12-04 14:58:48

Apparently much more simpler version of the code solved the issue.

import serial
import time

ser = serial.Serial('/dev/ttyUSB0', 115200, timeout = 1) # ttyACM1 for Arduino board

readOut = 0   #chars waiting from laser range finder

print ("Starting up")
connected = False
commandToSend = 1 # get the distance in mm

while True:
    print ("Writing: ",  commandToSend)
    ser.write(str(commandToSend).encode())
    time.sleep(1)
    while True:
        try:
            print ("Attempt to Read")
            readOut = ser.readline().decode('ascii')
            time.sleep(1)
            print ("Reading: ", readOut) 
            break
        except:
            pass
    print ("Restart")
    ser.flush() #flush the buffer

Output, as desired:

Writing:  1
Attempt to Read
Reading: 20
Restart
Writing:  1
Attempt to Read
Reading:  22
Restart
Writing:  1
Attempt to Read
Reading:  24
Restart
Writing:  1
Attempt to Read
Reading:  22
Restart
Writing:  1
Attempt to Read
Reading:  26
Restart
Writing:  1
Attempt to Read
Reading:  35
Restart
Writing:  1
Attempt to Read
Reading:  36

It seems to me that your ser.timeout = None may be causing a problem here. The first cycle of your while loop seems to go through fine, but your program hangs when it tries ser.readline() for the second time.

There are a few ways to solve this. My preferred way would be to specify a non-None timeout, perhaps of one second. This would allow ser.readline() to return a value even when the device does not send an endline character.

Another way would be to change your ser.readline() to be something like ser.read(ser.in_waiting) or ser.read(ser.inWaiting()) in order to return all of the characters available in the buffer.

try this code

try:
  ser = serial.Serial("/dev/ttyS0", 9600) #for COM3
  ser_bytes = ser.readline()
  time.sleep(1)
  inp = ser_bytes.decode('utf-8')
  print (inp)
except:
  pass
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!