Demo of Arduino control with a Python GUI program

In the updated versions of the Arduino and Python programs attached to this Post the Arduino sends a number (roughly the number of half-seconds since RESET) to the PC every 3.5 seconds and the Python program checks for and displays any new data every 2 seconds.

Broadly speaking there are two ways for the Python program to behave. It can check for data after specific events (for example everytime it sends something). Or it can check continuously at suitable intervals.

For this demo I have chosen the latter option as it illustrates the use of a separate Thread (running in parallel with the main code) to check for new data. When it finds new data it places it in a variable that is accessed by the main program and displayed at the bottom of the window. It would be a simple matter to do something else with the data - for example to save it to a database.

The code for the separate Thread is in the file arduinoCheckForData.py.

If the Python program only needed to check for incoming data when (for example) a button is pressed there would be no need for the separate Thread.

The display of the incoming data is, perhaps, a little bit too basic but I have left it like that as it illustrates the interaction of the different cycles of the Arduino (sends every 3.5 secs) and Python (checks every 2 secs). You can change either of these to see what happens. Obviously Python needs to check at least as often as the Arduino sends.

The Arduino program includes a function replyToPC() which is commented out in loop(). If you enable that function call in place of sendToPc() it will immediately send back the data it has just received. This works fine with a button press. But movements of the slider produce dozens of transmissions and equal numbers of replies which make the function rather impractical.

Finally, the code in arduinoCommsB.py has been updated slightly from arduinoComms.py in the first Post because I had not realized that the Python Serial.read() blocks until a character is received. This did not matter when Python was not checking for new data. The new version can be substituted for the version in the first Post if you wish.

Enjoy ...

...R

ArduinoGUI2Code.ino (3.33 KB)

arduinoGUI2.py (3.25 KB)

arduinoCommsB.py (2.94 KB)

arduinoCheckForData.py (1.08 KB)