【问题标题】:Simultaneously acquire data and update graph using python and matplotlib使用python和matplotlib同时获取数据和更新图形
【发布时间】: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


    【解决方案1】:

    matplotlib 具有动画绘图,允许在显示绘图时更新数据:take a look at this page

    您的代码可能如下所示:

    import serial
    import numpy as np
    import time
    from matplotlib import pyplot as plt
    
    plt.ion() # set plot to animated
    
    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()  
    
    # make plot
    line, = plt.plot(gdists)
    
    !#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
    
            line.set_ydata(gdists)  # update the data
            plt.draw() # update the plot
    
            nsr=nsr+samplingRate  
            while time.time()<nsr:  
                pass  
    
    finally:  
        ser.close()#Close serial port  
        print 'Serial port closed.'  
    

    只是一些建议(可能不好):我个人会使用time.sleep 以释放一些处理器而不会失去准确性。我还会在您的 try/except 块上添加一些错误类型。而且我认为np.rollconcatenate 更好/更快。

    【讨论】:

    • 感谢您的评论,但我仍然无法更新剧情。与此同时,我在link 找到了一个完整的 python 代码来记录和显示来自 Eli Bendersky 的串行数据,这几乎完全符合我的要求。
    猜你喜欢
    • 1970-01-01
    • 2011-07-06
    • 2019-01-01
    • 2012-07-30
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 2015-10-12
    • 2019-09-27
    相关资源
    最近更新 更多