Skip to content

Instantly share code, notes, and snippets.

@liborw
Created November 23, 2015 22:25
Show Gist options
  • Select an option

  • Save liborw/eda94bdb7d31b9863702 to your computer and use it in GitHub Desktop.

Select an option

Save liborw/eda94bdb7d31b9863702 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""Simple arduino scope visualization
Usage:
scope.py [options]
scope.py [options] channels <ch>...
scope.py --help
Options:
-h, --help
-r, --roll
-p PORT, --port PORT [default: /dev/tty.usbmodemFA131]
-b BUF, --buffer BUF [default: 1000]
"""
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
import serial
import threading
import logging
from docopt import docopt
import sys
class SerialScope(object):
def __init__(self, port, baud, buff=1000, channels=range(0,3), roll=False):
self.data = np.zeros((len(channels), buff))
self.buff = buff
self.i = 0
self.running = True
self.channels = channels
self.roll = roll
try:
self.ser = serial.Serial(port, baud)
except serial.SerialException as e:
logging.fatal(str(e))
sys.exit(1)
self.win = pg.GraphicsWindow(title="Basic plotting examples")
self.p = self.win.addPlot(title="Multiple curves")
self.curves = []
for i in self.channels:
self.curves.append(self.p.plot(pen=pg.intColor(i)))
self.lock = threading.Lock()
self.t = threading.Thread(target=self.read)
self.t.start()
def read(self):
while self.running:
try:
line = self.ser.readline()
vals = np.array([int(v) for v in line.split(',')])
self.store(vals)
except ValueError as e:
logging.warning(str(e))
except IndexError as e:
print vals
print self.channels
except serial.SerialException as e:
logging.fatal(str(e))
self.running = False
sys.exit(1)
def store(self, values):
self.lock.acquire()
try:
if self.roll:
self.data = np.roll(self.data, -1, 1)
self.data[0:len(self.channels), -1] = values[self.channels]
else:
self.data[0:len(self.channels), self.i] = values[self.channels]
finally:
self.lock.release()
self.i += 1
if self.i >= self.buff:
self.i = 0
def update(self):
self.lock.acquire()
try:
for i, data in enumerate(self.data):
self.curves[i].setData(data)
finally:
self.lock.release()
if __name__ == '__main__':
opt = docopt(__doc__)
opt_channels = opt['channels']
opt_chs = opt['<ch>']
opt_port = opt['--port']
opt_buffer = int(opt['--buffer'])
opt_roll = opt['--roll']
if opt_channels:
channels = [int(i) for i in opt_chs]
else:
channels = range(0,6)
app = QtGui.QApplication([])
scope = SerialScope(opt_port, 9600, buff=opt_buffer, channels=channels, roll=opt_roll)
timer = QtCore.QTimer()
timer.timeout.connect(scope.update)
timer.start(1)
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
scope.running = False
scope.t.join()
scope.ser.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment