python实时绘制串口数据有着巨大的滞后性

2024-05-28 23:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从串行端口读取数据,并使用matplot绘制图形中的数据。 以下是我的代码: 我看到由于plot,有一个巨大的滞后(队列中的数据增加到10000字节),所以我看不到实时绘图。如果我做错了什么事,你能帮帮我吗。在

<

import serial # import Serial Library
   import numpy  # Import numpy
   import matplotlib.pyplot as plt 

   Accelerometer= []
   COM_read = serial.Serial('COM5', 9600, timeout=None,parity='N',stopbits=1,rtscts=0) #Creating our serial object name
plt.ion() #Tell matplotlib you want interactive mode to plot live data
cnt=0
COM_read.flushInput()
COM_read.flushOutput()
def makeFig(): #Create a function that makes our desired plot

    plt.title('My Live Streaming Sensor Data')      #Plot the title
    plt.grid(True)                                  #Turn the grid on
    plt.ylabel('Acc in g')                          #Set ylabels
    plt.plot(Accelerometer, 'ro-', label='Accelerometer g') #plot the temperature
    plt.legend(loc='upper left')                    #plot the legend
    plt.ylim(15000,30000)                           #Set limits of second y axis- adjust to readings you are getting


print "came through"
while True: # While loop that loops forever
    print COM_read.inWaiting()
    while (COM_read.inWaiting()==0): #Wait here until there is data
            pass #do nothing
    s  = COM_read.readline() #read the line of text from the serial port
    decx = int(s[0:4],16)
    decy = int(s[5:9],16)
    decz = int(s[10:14],16)
    if decx > 32768:
          decx = decx - 65536;
    if decy > 32768:
         decy = decy - 65536;
    if decz > 32768:
         decz = decz - 65536;
    #print decx,decy,decz
    res = ((decx*decx) + (decy*decy) + (decz*decz))**(1.0/2.0)




    Accelerometer.append(res)                     #Build our Accelerometer array by appending temp readings

    drawnow(makeFig)                       #Call drawnow to update our live graph
    plt.pause(.000001)                     #Pause Briefly. Important to keep drawnow from crashing

    cnt=cnt+1
    if(cnt>50):                            #If you have 50 or more points, delete the first one from the array
        Accelerometer.pop(0)               #This allows us to just see the last 50 data points

>; ----------------基于约翰博士根据建议,代码编写如下---

^{pr2}$

Tags: thetoimportcomreadifplotserial
1条回答
网友
1楼 · 发布于 2024-05-28 23:20:12

在大多数情况下,while-true循环不是一个好主意。在

在大多数情况下,非OO编程是个坏主意。在

在大多数情况下,将绘图数据附加到列表是一个坏主意(laggy)。在

在定义的时间使用

import threading, time
threading.Timer(2, acquire_data).start() #starts function acquire_data every 2 sec and resets self.res with 0.5Hz

然后,为了您自己的利益,请定义基于类的函数,而不是while循环:

^{pr2}$

和阴谋

fig, ax = plt.subplots()
ax.plot(time.time(), self.res, 'o-')

向眼镜蛇医生问好

相关问题 更多 >

    热门问题