友情提示:380元/半年,儿童学编程,就上码丁实验室。
本文涉及到双向列表的知识,请参考下文:
Python 生成器函数与 Deque(双向列表) 模块
我们要做什么
本文介绍的例子,是使用Arduino读取电位计的数值,然后用Python将电位计的值实时显示在图表上(类似于虚拟仪表盘)。
代码如下:
from matplotlib import pyplot
import pyfirmata
from collections import deque
from time import sleep
port =’COM3′
board = pyfirmata.Arduino(port)
it = pyfirmata.util.Iterator(board)
it.start()
sleep(1)
pot = board.get_pin(‘a:0:i’)
pyplot.ion()#启动实时
pData = deque(maxlen=30)
for i in range(30):
pData.append(0)
fig = pyplot.figure()
pyplot.title(‘Real-time Potentiometer reading’)
(l1,)= pyplot.plot(pData)
pyplot.ylim([0, 1])
while True:
try:
pyplot.pause(0.1)#暂停的时间
pData.append(float(pot.read()))
pyplot.ylim([0, 1])
l1.set_xdata([i for i in range(30)])
l1.set_ydata(pData) # 更新数据
pyplot.draw() # 更新绘制
except KeyboardInterrupt:
board.exit()
break
几点解释:
pyplot.pause(0.1)#暂停的时间
这行代码不能使用sleep函数进行替换,使用sleep函数的话将会出现未响应现象。
-
set_xdata
(x)¶ -
Set the data np.array for x
ACCEPTS: 1D array
详细信息见官网:
http://matplotlib.org/
几张截图:
请点击此处输入图片描述
请点击此处输入图片描述
喜欢文章,欢迎大家转发!!!