ValueError:无法将字符串转换为float:使用matplotlib,arduino和pyqt5

问题描述

使用arduino代码时(还将arduino uno中的引脚13连接到A0)以更改值

int PinOutput = 13;
int PinInput = A0;
int inph;
int inpl;

void setup() {
  // put your setup code here,to run once:
Serial.begin(9600);
pinMode(PinInput,INPUT);
pinMode(PinOutput,OUTPUT);

}

void loop() {
  // put your main code here,to run repeatedly:
inpl = analogRead(PinInput)/4;
Serial.println(inpl);
analogWrite(PinOutput,255);
delay(1000);
inph = analogRead(PinInput)/4;
Serial.println(inph);
analogWrite(PinOutput,0);
delay(1000);
}

然后尝试使用python读取代码,

from PyQt5 import QtCore,QtGui,QtWidgets
import serial
import time
import sys 
import random 
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
import matplotlib
matplotlib.use('Qt5Agg')

ser = serial.Serial('COM3',baudrate = 9600,timeout = 1)
time.sleep(3)
class Ui_MainWindow(object):
    def setupUi(self,MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(325,237)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(110,20,61,16))
        self.label.setObjectName("label")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(90,60,104,71))
        self.textEdit.setObjectName("textEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(100,150,75,23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0,325,21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)


    def retranslateUi(self,MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow","test window"))
        self.label.setText(_translate("MainWindow","pyqt5 tests"))
        self.pushButton.setText(_translate("MainWindow","test button"))
        self.pushButton.clicked.connect(self.label_change)  
        self.thread_start = MyThread()
        self.thread_start.ard_signal.connect(self.label.setText)        
        self.thread_start.start()
    
    def label_change(self):
        self.pushButton.setText('Button Clicked!')
        self.textEdit.setText('taco')

class MainWindowm(QtWidgets.QMainWindow):

    def __init__(self,*args,**kwargs):
        super(MainWindowm,self).__init__(*args,**kwargs)

        self.canvas = MplCanvas(self,width=5,height=4,dpi=100)
        self.setCentralWidget(self.canvas)

        n_data = 50
        self.xdata = list(range(n_data))
        self.ydata = [random.randint(0,10) for i in range(n_data)]

        self._plot_ref = None
        self.update_plot()

        self.show()

        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.update_plot)
        self.timer.start()

    def update_plot(self):

        time.sleep(1)
        self.ydata = self.ydata[1:] +  [float(ser.readline().decode().split('\r\n')[0].strip())]
        self.canvas.axes.cla()  
        self.canvas.axes.plot(self.xdata,self.ydata,'r')

        self.canvas.draw()

class MyThread(QtCore.QThread):
    ard_signal = QtCore.pyqtSignal(str)

    
    def __init__(self):
        QtCore.QThread.__init__(self)
        
    def run(self):
        counter = 0
        while 1:
            time.sleep(1)
            self.ard_signal.emit(str(ser.readline().decode().split('\r\n')[0]))
            counter += 1
        sys.exit()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    w = MainWindowm()

    sys.exit(app.exec_())

如果我将arduino代码中的延迟设置为delay(1),那么我看不到任何错误(至少,直到我尝试等待的时间,大约20分钟),并且显示的值在图和窗口中的值为0或255。但是在1000的延迟下,我得到了类似的错误,


Traceback (most recent call last):

  File "C:\Documents\ardmatlibpyqt5.py",line 141,in update_plot
    self.ydata = self.ydata[1:] +  [float(ser.readline().decode().split('\r\n')[0].strip())]

ValueError: could not convert string to float: '25\r0'

或以

结尾

ValueError: could not convert string to float: '255\r0'

,窗口中显示的值是可能是255或0或什么都不是的数字,或者是部分数字(使用的数字,而不是中间的数字)。因此,当arduino运行速度快时,没有错误,但是当它运行缓慢时,就有错误。我正在尝试一次运行多个东西,使用arduino和matplotlib的pyqt5。我已经将所有这些都单独运行(例如pyqt5和arduino,matplotlib和arduino,arduino和pyqt5),如果我只用arduino运行pyqt5并输出值,就没有错误。谢谢。关于可能导致该错误的原因的任何想法都将有所帮助。

解决方法

请勿使用pyserial,而应使用QSerialPort,因为它具有通过信号通知是否有数据的优势,因此您将避免使用计时器或time.sleep()。

var decoded

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...