Python Serial Timeout Example

Python Serial Timeout Example

Introduction

To use Python as a graphical interface for an Arduino powered robot, programmatically read the USB with the pySerial library. However, waiting for input from pySerial's Serial object is blocking, which means that it will prevent your GUI from being responsive. The process cannot update buttons or react to input because it is busy waiting for the serial to say something.

ExamplePython Serial Timeout Example

SerialTimeoutException: Write timeout I'm using PySerial (Current Version), and Python 2.7.5. I am also using PyGame (Version for Python 2.7.5), but it's not throwing the errors, PySerial is. Python function calls are expensive, so performance will be best if we can read more than one byte at a time. We want any data received returned in a timely fashion. A key parameter in the pyserial Serial class is the timeout parameter. This parameter is defined as: timeout=None, #set a timeout value, None for waiting forever.

The first key is to use the root.after(milliseconds) method to run a non-blocking version of read in the tkinter main loop. Keep in mind that when TkInter gets to the root.mainloop() method, it is running its own while loop. It needs the things in there to run every now and then in order to make the interface respond to interactions. If you are running your own infinite loop anywhere in the code, the GUI will freeze up. Alternatively, you could write your own infinite loop, and call root.update() yourself occasionally. Both methods achieve basically the same goal of updating the GUI.

Timeout

However, the real issue is making sure that reading from serial is non-blocking. Normally, the Serial.read() and Serial.readline() will hold up the whole program until it has enough information to give. For example, a Serial.readline() won't print anything until there is a whole line to return, which in some cases might be never! Even using the after() and update() methods will still not allow the UI to be updated in this case, since the function never ends. This problem can be avoided with the timeout=0 option when enitializing the Serial object, which will cause it to return nothing unless something is already waiting in the Serial object's buffer.

Python

Python Serial Time Out Example Sentences

Code

Comments are closed.