【发布时间】:2011-03-31 20:23:04
【问题描述】:
我正在用 Python 编写代码以通过串行端口与超声波测距仪通信,以执行以下操作:
-每隔0.1秒,向传感器发送命令进行距离测量,并记录传感器的响应
- 显示过去 5 秒内所有距离测量的图
这是我的代码:
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.'
现在,我的代码可以获取最近 50 个测量值的数组,但我不知道如何同时在图表中显示这些(我通常使用 Matplotlib 绘制图表)。我应该使用线程吗?或者使用 pyGTK 或 pyQt4 使用动画图?我也在考虑使用pygame?我的计时机制也不是很理想,但我认为它非常准确。
【问题讨论】:
标签: python multithreading matplotlib ipython