Close

Reading serial data with Python

A project log for Load Frame Update

Add digital output to a mechanical testing load frame using arduino.

mark-bradshawMark Bradshaw 11/03/2016 at 14:580 Comments

At this point in the project I've given some brief descriptions of how the Arduino is reading the digital signals from the quadrature encoder that measures position and the analog output of the load cell. These data are then written to the serial port as the string "POSITION LOAD\n"

where POSITION and LOAD are integers with the current values. So at this point I need to receive the serial data on the computer that is going to display and store the data for me and this is where things get a little hack-ish.I found some helpful information on how to read serial data in Python from the project "Arduino Monitor" by Greg Pinero [1]. The approach is to have the serial-data-reading-class spawn a worker thread that is continuously reading the serial port and storing the data to a variable. The value in this variable is always the most up to date data received. The class will then return that value whenever polled by the main program. Sounds good so far.

I ran into a few problems, first is I am reading two channels of data, this is relatively simple to fix. First the string is broken up into two string variables for position and load using the string.split() command. Then those strings are returned as a tuple of integers by the command return (int(x), int(y) ).

More problematic for me has been that the worker thread does not always want to die. This has been mostly handled by adding a flag to the worker thread's loop:

while keep_going:
    read serial data and store it to variable
Then setting keep_going to False makes the thread die, great. But if there is an exception somewhere else in the program and it crashes then the thread stays... alive... forever... until I kill the process.


1. https://github.com/gregpinero/ArduinoPlot

Discussions