在社区的帮助下,我能够为 matplotlib 安装新的后端,并从 Arduino 串行运行代码到 python 窗口的输出。
然后我能够制作一个漂亮的图表并显示出来,但当我收到以下错误时崩溃:
属性错误:“str”对象没有属性“inWaiting”
在 @elethan 的帮助下解决了这个问题
但是,我现在遇到错误:
pulse = float(dataArray[0])
ValueError: could not convert string to float:
此错误并非每次都会发生
好像这还不够,绘制的图表上的输出显示大部分绘图的值为 10,这不是 Arduino 串行输出的值。
我不确定为什么: 1)错误是间歇性的(可能是它抓取了一个“,”而不是一个值) 2) 为什么当图表绘制时我得到的稳定值是 10
代码如下:
import time
import serial
import matplotlib.pyplot as plt
import numpy
from drawnow import *
import os,sys
pulseArray = []
plt.ion()
clippingCounter = 0
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=115200,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
input=1
def plotPulseData():
plt.ylim(0,120)
plt.title('Plots from data of the Pulse Sensor')
plt.grid(True)
plt.ylabel('Pulse')
#plt.subplot(2, 2, 1)
plt.plot(pulseArray, 'ro-', label='BPM', linewidth=2)
plt.legend(loc='upper left')
while True:
#First things first, lets wait for data prior to reading
time.sleep(1)
if (ser.inWaiting()>4):
s = ser.read(4)
#print ser
dataArray = s.split(',')
pulse = float(dataArray[0])
pulseArray.append(pulse)
plt.figure(1)
drawnow(plotPulseData)
plt.pause(.000001)
clippingCounter = clippingCounter + 1
if(clippingCounter>50):
pulseArray.pop(0)
非常感谢您的帮助,提前谢谢您。
最佳答案
第一次通过 while 循环将 ser
从 Serial
对象重新分配给字符串:
ser = ser.read(4)
下次在循环中调用该对象的 inWaiting()
方法时,您会收到错误,因为您是在字符串上调用它,而不是原始的 Serial
对象:
ser.inWaiting() > 4
将 ser.read(4)
输出的变量名称更改为尚未使用的名称,此错误应该会消失:
s = ser.read(4)
...
dataArray = s.split(',')
关于python - 属性错误: 'str' object has no attribute 'inWaiting' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40663797/