I'm writing a code in Python to communicate to an ultrasonic distance meter over the serial port, to do the following:
-Every 0.1 seconds, send a command to the sensor to make a distance measurement, and register the response of the sensor
-Display a plot of all the distance measurements from the last 5 seconds
Here's my code:
import serial
import numpy as np
import time
from matplotlib import pyplot as plt
tagnr=2#Tag number of the sensor that we're pinging
samplingRate=.1#Sampling Rate in seconds
graphbuf=50.#Buffer length in samples of logger graph
!#Initialize logger graph
gdists=np.zeros(graphbuf)
ax1=plt.axes()
!#Main loop
nsr=time.time()#Next sample request
try:
while True:
statreq(tagnr)#Send status request to sensor over serial port
temp,dist=statread(tagnr)#Read reply from sensor over serial port
gdists=np.concatenate((gdists[1:],np.array([dist])))
print gdists
nsr=nsr+samplingRate
while time.time()<nsr:
pass
finally:
ser.close()#Close serial port
print 'Serial port closed.'
Right now, my code can acquire an array of the last 50 measurements, but I don't know how to display these in a graph at the same time (I usually plot my graphs using Matplotlib). Should I use threading? Or use an animated graph using pyGTK or pyQt4? I was also thinking of using pygame? My timing mechanism is not very optimal either but I'm thinking it's pretty accurate.