Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Display analog data from Arduino using Python (matplotlib animation)
"""
ldr.py
Display analog data from Arduino using Python (matplotlib)
Author: Mahesh Venkitachalam
Website: electronut.in
"""
import sys, serial, argparse
import numpy as np
from time import sleep
from collections import deque
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# plot class
class AnalogPlot:
# constr
def __init__(self, strPort, maxLen):
# open serial port
self.ser = serial.Serial(strPort, 9600)
self.ax = deque([0.0]*maxLen)
self.ay = deque([0.0]*maxLen)
self.maxLen = maxLen
# add to buffer
def addToBuf(self, buf, val):
if len(buf) < self.maxLen:
buf.append(val)
else:
buf.pop()
buf.appendleft(val)
# add data
def add(self, data):
assert(len(data) == 2)
self.addToBuf(self.ax, data[0])
self.addToBuf(self.ay, data[1])
# update plot
def update(self, frameNum, a0, a1):
try:
line = self.ser.readline()
data = [float(val) for val in line.split()]
# print data
if(len(data) == 2):
self.add(data)
a0.set_data(range(self.maxLen), self.ax)
a1.set_data(range(self.maxLen), self.ay)
except KeyboardInterrupt:
print('exiting')
return a0,
# clean up
def close(self):
# close serial
self.ser.flush()
self.ser.close()
# main() function
def main():
# create parser
parser = argparse.ArgumentParser(description="LDR serial")
# add expected arguments
parser.add_argument('--port', dest='port', required=True)
# parse args
args = parser.parse_args()
#strPort = '/dev/tty.usbserial-A7006Yqh'
strPort = args.port
print('reading from serial port %s...' % strPort)
# plot parameters
analogPlot = AnalogPlot(strPort, 100)
print('plotting data...')
# set up animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 100), ylim=(0, 1023))
a0, = ax.plot([], [])
a1, = ax.plot([], [])
anim = animation.FuncAnimation(fig, analogPlot.update,
fargs=(a0, a1),
interval=50)
# show plot
plt.show()
# clean up
analogPlot.close()
print('exiting.')
# call main
if __name__ == '__main__':
main()
@mattvenn

This comment has been minimized.

Copy link

commented Oct 5, 2014

nice python

@cefn

This comment has been minimized.

Copy link

commented Feb 6, 2015

Really nice approach. Might try to use this in a ShrimpKey lesson plan, thanks.

@linuscl

This comment has been minimized.

Copy link

commented May 7, 2015

Unfornately it is very slow. When the sensor data changes, I'll wait 10 seconds. Then it changes.

@mebjas

This comment has been minimized.

Copy link

commented Aug 10, 2015

yeah its really slow :(

@ThePiGuy

This comment has been minimized.

Copy link

commented Jan 23, 2016

That is really awesome. Is there a way to add labels on the right side of the Y-Axis (for example, for plotting both altitude and pressure, each with different units)? I'm still learning about these tools and am curious if there's a quick solution for this. How about adding a little text box right on the graph? Thanks!

@exclaimedpower

This comment has been minimized.

Copy link

commented Aug 1, 2016

Where in the code do you input the Port your running your Arduino on. I don't know where to insert my 'COM4' port location?????

@GabrielMachine

This comment has been minimized.

Copy link

commented Jul 19, 2017

I tried to run your code to my arduino test, but it seems that not worked. It is simply don't plotting anything. thanks for the help

@nidhipillai

This comment has been minimized.

Copy link

commented Feb 1, 2018

@exclaimedpower while running your script you can use --port flag in linux
eg your command will be
python ldr.py --port COM4

@fmendes75

This comment has been minimized.

Copy link

commented May 3, 2018

I'm having this problem.

$ python3 ldr.py --port /dev/tty.usbmodem411
Traceback (most recent call last):
File "ldr.py", line 10, in
import sys, serial, argparse
ImportError: No module named 'serial'

I've installed $python install serial

@ruimartinsptl

This comment has been minimized.

Copy link

commented May 6, 2018

@fmendes75 I think that I installed 'pyserial' with pip install pyserial (or pip3 install pyserial). Try, I guess that this solve your problem

@mamamiya77

This comment has been minimized.

Copy link

commented Oct 25, 2018

Nice. Thanks for sharing !

@ta18

This comment has been minimized.

Copy link

commented Nov 7, 2018

Very helpfull but I have this error when I run my code usage: ldr.py [-h] --port PORT ldr.py: error: the following arguments are required: --port
can you help me ?

@carloszoom3000

This comment has been minimized.

Copy link

commented Apr 4, 2019

I'm having the following error:
usage: ldr.py [-h] --port PORT
ldr.py: error: the following arguments are required: --port
An exception has occurred, use %tb to see the full traceback.

@JuanDanielSoto

This comment has been minimized.

Copy link

commented Apr 21, 2019

Hi, i really like your job. Can you tell me how could i change de direction of the grafic?, for this code run to turn left, i want to right

@CaptainFatty

This comment has been minimized.

Copy link

commented Aug 1, 2019

JuanDanielSoto,

Change addToBuffer to:

add to buffer

def addToBuf(self, buf, val):
if len(buf) < self.maxLen:
buf.append(val)
#buf.extendleft(val)
else:
#buf.pop()
#buf.appendleft(val)
buf.popleft()
buf.append(val)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.