electronut Programming & Embedded Systems - by Mahesh Venkitachalam

A Simple Python to Arduino Alert Scheme

My friend asked me the following yesterday:

"Is it possible to make the build script at my company flash some lights when it fails?"

I gave her some suggestions which involved the usual suspects - Python and Arduino. Now it's all up to you, I said. But soon, I started fidgeting, and I can't help it. I need to try this myself. ;-)

This is what I came up with:

  1. Run a Python program that communicates with an Arduino via serial port.
  2. Arduino is connected to some lights. (LEDs, for proof of concept.)
  3. When build script fails, it communicates with the Python program, and it sends some data via
    serial port, which the Arduino reads, and flashes some lights.

The only challenge here is the mechanism for a script on the build machine to communicate with our Python program. I am sure there are many sophisticated ways of doing this, but being a simpleton, I chose a very simple way - use a status file.

The build script writes 'OK' or 'BAD' (or whatever) to a file called status.txt, and the python code checks this file and sends some data to Arduino, which takes appropriate action.

The Python code sits in a loop, and every 2 seconds, reads the status file. If it reads 'OK', it sends a '1' via serial port. If it reads anything else, it sends a '0'. When it quits, it sends a '2', and this is used by the Arduino to cleanup.

Here is the Python code:

At the Arduno end, it turns a Green LED on if it reads a '1' via serial, and a Red LED when it reads a '0'. If it reads anything else, it turns both LEDs off. (This is important for cleanup - when the python script exits, we turn the LEDs off.)

Here is the code at the Arduino end:

Here is how I run it:

$ python ardu_alert.py --port /dev/tty.usbmodem411

To change the status I do:

$echo OK > status.txt $echo BAD > status.txt

It works quite well, as you can see below.

Instead of LEDs, you can hook up anything at the other end, provided you do some extra work. For example, use a MOSFET/transistor and a Relay to control lights, or maybe even hack a toy to do something silly.

That was fun. :D

If you liked this article, please consider supporting my efforts by purchasing my book.

Python Playground, published by No Starch Press, USA, is a collection of imaginative programming projects that will inspire you to use Python to make art and music, build simulations of real-world phenomena, and interact with hardware like the Arduino and Raspberry Pi. Do check it out!