交互式打印后matplotlib没有响应

2024-09-30 20:39:16 发布

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

我用python和Arduino一起做一个项目,我用库(pyfirmata,matplot,draw now)绘制实时传感器数据,我得到了实时输出,但是在固定的迭代之后,图形没有响应。我附上下面的代码

import pyfirmata
import time
import matplotlib.pyplot as plt
from drawnow import *
import sys
board = pyfirmata.Arduino('COM8')
iter8 = pyfirmata.util.Iterator(board)
iter8.start()

LED = board.get_pin('d:13:o')
ldr=board.get_pin('a:0:o')
val=0
converted=1023
converted2=5.0/1023.0
s=[]
i=0

def makeFig():

    plt.figure(1)
    plt.ion()
    plt.plot(s)
    plt.title('My Live Streaming Sensor Data')  # Plot the title
    plt.grid(True)

while(i<=50):

    time.sleep(0.01)
    val=ldr.read()
    print(val * converted * converted2)
    s.append(val)
    i=i+1
    drawnow(makeFig)  # Call drawnow to update our live graph
    plt.pause(.000001)
plt.show()

我想在迭代之后保存传感器绘图,这是我的最终目标


Tags: importboardgettimepinpltval传感器
1条回答
网友
1楼 · 发布于 2024-09-30 20:39:16

您可能想在plt.show()之前调用plt.ioff()。在

一般来说,最好完全在事件循环内部工作,如下所示。在

import pyfirmata
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


board = pyfirmata.Arduino('COM8')
iter8 = pyfirmata.util.Iterator(board)
iter8.start()

LED = board.get_pin('d:13:o')
ldr=board.get_pin('a:0:o')
val=0
converted=1023
converted2=5.0/1023.0
s=[]
i=0

fig, ax = plt.subplots()
line,= ax.plot([],[])

def update(i):

    val=ldr.read()
    print(val * converted * converted2)
    s.append(val)
    line.set_data(range(len(s)), s)
    ax.autoscale()
    ax.relim()
    ax.autoscale_view()

FuncAnimation(fig, update, frames=50, repeat=False)

plt.show()

相关问题 更多 >