Search code examples
pythonraspberry-piserial-communication

Raspberry Pi is stuck when no char is received on the serial port


I am using an XBee module connected to my RPI, serial communication is established between both, the problem is my code gets stuck if there is no data present by the XBee, is there a away to solve this, I tried timeout but wasn't successful.

code:

ser = serial.Serial (
port = "/dev/ttyAMAO",
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial,STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 0
)

ser = serial.Serial("/dev/ttyAMAO")

for c in ser.read():
l.append(c)

Solution

  • ser.read()
    

    is a blocking call it is probably better to check if there is anything there to read first

    if ser.inWaiting(): #only true if there is data waiting to be read
       for c in ser.read():
              ....
    

    or if you want your serial thread to run in parallel to your main program (ie. dont block user interface ever at all..) you should maybe look into something like twisted or asyncio

    although typically with serial you are working with some device that wants 2-way communication, usually initiated with a query to the serial device, and you do want to actually block until you get a response. I will usually make a class to handle this for me

    class MySerial:
        def __init__(self,port,baudrate):
           self.ser = serial.Serial(port,baudrate)
        def query(cmd,terminal_char="\r"):
           self.ser.write(cmd)
           return ''.join(iter(ser.read,terminal_char))
    
    s = MySerial("COM9",11200)
    result = s.query("get -temp\r")
    print result
    

    this will accumulate an entire response until the specified terminal character is recieved