electronut Programming & Embedded Systems - by Mahesh Venkitachalam

Plotting real-time data from Arduino using Python

Arduino is fantastic as an intermediary between your computer and a raw electronic circuit. Using the serial interface, you can retrieve information from sensors attached to your Arduino. (You can also send information via the serial interface to actuate circuits and devices (LEDs, relays, servos, etc.) connected to your Arduino.) Once you have the data in your computer, you can do all sorts of things with it - analyze it, display it, or share it on the internet, for instance.

In this post, I will be reading and displaying analog data from a pair of LDRs connected to an Arduino. Here is the schematic:

Here is how you hook it up to the Arduino:

The Arduino sketch is very simple - it just reads the values from analog pins A0 and A1 (in the range [0, 1023]) and prints it to the serial port. Here is the code:

The serial port sends values in the format:

512 300
513 280
400 200

On the computer side, I need to read these values, and plot them as a function of time. I am using Python and the Matplotlib library for this. I wanted to display this as a scrolling graph that moves to the right as data keeps coming in. For that, I am using the Python deque class to keep and update a fixed number of data points for each time frame.

You can see the full implementation here:

UPDATE: I have upgraded the code below to use the matplotlib animation class. You can still get to the old code here.

And here is what the plot looks like. It scrolls to the right as data keeps coming in.

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!