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.
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.
Readline In Python
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.
Code
Python 3 Serial Readline Example
Installing matplotlib and pyserial on Ubuntu 18 sudo apt-get install python3-matplotlib sudo apt-get install python3-serial Generating some fake serial data with an Arduino. To test my code, I used an Arduino to put some data on the serial port. In the example code below, the arduino simulates a coin toss using the function random. Python serial port access library. Contribute to pyserial/pyserial development by creating an account on GitHub. Python Serial.readline - 30 examples found. These are the top rated real world Python examples of serial.Serial.readline extracted from open source projects. You can rate examples to help us improve the quality of examples. Parameter details; port: Device name e.g. /dev/ttyUSB0 on GNU/Linux or COM3 on Windows. Baudrate: baudrate type: int default: 9600 standard values: 50, 75, 110, 134.