/
realtime.py
78 lines (58 loc) · 1.93 KB
/
realtime.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import sys
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from pyfirmata2 import Arduino
PORT = Arduino.AUTODETECT
# create a global QT application object
app = QtGui.QApplication(sys.argv)
# signals to all threads in endless loops that we'd like to run these
running = True
class QtPanningPlot:
def __init__(self,title):
self.win = pg.GraphicsLayoutWidget()
self.win.setWindowTitle(title)
self.plt = self.win.addPlot()
self.plt.setYRange(-1,1)
self.plt.setXRange(0,500)
self.curve = self.plt.plot()
self.data = []
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(100)
self.layout = QtGui.QGridLayout()
self.win.setLayout(self.layout)
self.win.show()
def update(self):
self.data=self.data[-500:]
if self.data:
self.curve.setData(np.hstack(self.data))
def addData(self,d):
self.data.append(d)
# Let's create two instances of plot windows
qtPanningPlot1 = QtPanningPlot("Arduino 1st channel")
qtPanningPlot2 = QtPanningPlot("Arduino 2nd channel")
# sampling rate: 100Hz
samplingRate = 100
# called for every new sample which has arrived from the Arduino
def callBack(data):
# send the sample to the plotwindow
qtPanningPlot1.addData(data)
ch1 = board.analog[1].read()
# 1st sample of 2nd channel might arrive later so need to check
if ch1:
qtPanningPlot2.addData(ch1)
# Get the Ardunio board.
board = Arduino(PORT)
# Set the sampling rate in the Arduino
board.samplingOn(1000 / samplingRate)
# Register the callback which adds the data to the animated plot
board.analog[0].register_callback(callBack)
# Enable the callback
board.analog[0].enable_reporting()
board.analog[1].enable_reporting()
# showing all the windows
app.exec_()
# needs to be called to close the serial port
board.exit()
print("Finished")