簡體   English   中英

使用PyQtGraph和Pyserial及時繪圖

[英]Plotting in time using PyQtGraph and Pyserial

我正在嘗試使用pyqtgraph進行實時繪圖。 我正在使用Pyserial從和arduino讀取數據。 我在使用pyqtgraph之前嘗試了matplotlib庫,但它沒有給我我需要繪制的速度。 因此,搜索另一種繪制實時數據的方法,我遇到了PyQtgraph。 我閱讀了文檔和很多例子,我發現了這兩個例子:

用樣本間隔繪圖

使用pyqt4繪圖

兩者都是作為時間的函數繪制的,這是我需要做的。 我已修改它們中的每一個以使用Pyserial從Arduino獲取數據。 問題在於它仍然很慢。

這是我正在使用的代碼(來自第二個鏈接):

class TimeAxisItem(pg.AxisItem):
  def __init__(self, *args, **kwargs):
    super(TimeAxisItem, self).__init__(*args, **kwargs)

  def tickStrings(self, values, scale, spacing):
    return [QTime().addMSecs(value).toString('mm:ss') for value in values]

class MyApplication(QtGui.QApplication):
  def __init__(self, *args, **kwargs):
    super(MyApplication, self).__init__(*args, **kwargs)
    self.t = QTime()
    self.t.start()

    self.data = deque(maxlen=20)

    self.win = pg.GraphicsWindow(title="Basic plotting examples")
    self.win.resize(1000,600)

    self.plot = self.win.addPlot(title='Timed data', axisItems={'bottom':  TimeAxisItem(orientation='bottom')})
    self.curve = self.plot.plot()

    self.tmr = QTimer()
    self.tmr.timeout.connect(self.update)
    self.tmr.start(100)

    print "Opening port"
    self.raw=serial.Serial("com4",9600)
    print "Port is open"


  def update(self):
    line = self.raw.read()
    ardString = map(ord, line)
    for number in ardString:
        numb = float(number/77.57)
        print numb
        self.data.append({'x': self.t.elapsed(), 'y': numb})
        x = [item['x'] for item in self.data]
        y = [item['y'] for item in self.data]
        self.curve.setData(x=x, y=y)

def main():
  app = MyApplication(sys.argv)
  sys.exit(app.exec_())

if __name__ == '__main__':
  main()

我可以做些什么來隨着時間的推移更快地繪制?似乎我用這段代碼丟失了一些數據。

真的希望你能幫助我。

在您的更新功能中,嘗試呼叫

self.curve.clear()

在功能的最開始。

稍微讓我感到震驚的是這里發生的事情的時間,而不是pyqtgraph細節。 您的更新方法是按照QTimer對象以100ms的間隔輪詢串行端口,因此在9600波特率下,您的端口可以生成9600bps * .1sec = 960字節。 但是,沒有參數的serial.Serial.read()默認為size = 1: http ://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.read

因此,在您的更新調用中,您似乎每100毫秒只讀取1個字節:

line = self.raw.read()

所以我的猜測是你應該在讀取大小1024中放一些更合理的東西:

line = self.raw.read(1024)

在serial.Serial實例中指定超時:

self.raw=serial.Serial("com4",9600,timeout=0)

這樣,讀取不會阻塞,只返回緩沖區中可用的全部數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM