Skip to content

Instantly share code, notes, and snippets.

@MercuryRising
Created June 24, 2012 01:40
Show Gist options
  • Save MercuryRising/2980955 to your computer and use it in GitHub Desktop.
Save MercuryRising/2980955 to your computer and use it in GitHub Desktop.
Threaded Arduino Reader / Plotter / Writer
'''
I adapted the live plotting code from somewhere but I cannot remember where.
If you know where, I would be happy to add it to the comment here.
'''
'''
I adapted the live plotting code from somewhere but I cannot remember where.
If you know where, I would be happy to add it to the comment here.
'''
import threading
import time
import gobject
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
import serial
import Queue
import datetime
import random
class Arduino(threading.Thread):
def __init__(self, queue, timeout):
threading.Thread.__init__(self)
self.ser = serial.Serial("/dev/ttyUSB0", 115200)
self.queue = queue
self.writeData = True
self.timeout = timeout
self.timer = time.time()
print 'initiated arduino'
def run(self):
while True:
if time.time() - self.timer > self.timeout:
self.ser.write('t')
self.timer = time.time()
if self.ser.inWaiting() > 0:
reading = ''
while '\r\n' not in reading:
reading += self.ser.read()
#print 'Data from Arduino: ', reading
reading.split('\r\n')[0]
newData = int(reading)
newData = random.randint(0, 255)
self.queue.put(newData)
if self.writeData:
writeData(newData)
def update():
global q
if not q.empty():
newData = q.get()
data.pop(0)
data.append(newData)
f.clear()
f.suptitle("Temperature")
a = f.add_subplot(111)
x, = a.plot(range(winLength), data, 'b-')
a.grid(True)
plt.xlabel("Time")
plt.ylabel("Temperature")
minY = min(data)
maxY = max(data)
a.axis([0, winLength, minY-0.3, maxY+0.3])
f.canvas.draw_idle()
return True
def writeData(data):
fileName = str(datetime.date.today())+'.log'
with open(fileName, 'ab') as f:
f.write(str(data))
f.write('\n')
if __name__ == '__main__':
q = Queue.Queue()
timeout = 1 # second
print 'Starting Arduino'
ard = Arduino(q, timeout)
ard.start()
f = plt.figure()
winLength = 25
data = [0 for _ in range(winLength)]
gobject.timeout_add(timeout*1000, update)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment