Arduino与Python串口通信获取浮点值绘图异常问题求助
解决方案
核心故障原因
- Arduino侧单次仅读取1字节串口数据,无法完整接收Python发送的浮点数字符串,转换浮点值直接出错
- 两侧收发数据未添加明确的结束分隔符,导致Arduino无法判断单条数据结束位置、Python的readline接口无法拆分返回的单条数值,最终所有返回值拼接成一整段字符串
- Python侧初始化串口后延时调用错误,将
time.sleep(1)写成了time.sleep = 1,未等待Arduino串口初始化完成就开始发数据 - Arduino返回数据未加换行符,
Serial.print只会输出纯数值内容,多条返回会直接拼接
修改后的Arduino代码
String IncomingByte; //Serial Data float x[] = {0,0,0}; float y[] = {0,0,0}; float valor = 0.0; void setup() { Serial.begin(9600); } void loop() { if (Serial.available() > 0) { // 读取直到换行符的完整字符串 IncomingByte = Serial.readStringUntil('\n'); valor = IncomingByte.toFloat(); x[0] = valor; y[0] = 1.91122623*y[1] + -0.91500257*y[2] + 0.00094408*x[0] + 0.00188817*x[1] + 0.00094408*x[2]; delay(10); //10ms for(int i = 1; i >= 0; i--){ x[i+1] = x[i]; y[i+1] = y[i]; } // 输出带换行符,方便Python按行读取 Serial.println(y[0]); } }
修改后的Python代码
#Librerias import serial import time import matplotlib.pyplot as plt import numpy as np #Comunicación Serial arduino = serial.Serial('COM3',9600,timeout = 2) # 修正延时调用,等待Arduino重启完成 time.sleep(1) t = 0 #Noisy Signal d_señal = [] #For plots d_filtro = [] while (t <= 1): señal = np.sin(2*np.pi*5*t) + 0.5*np.sin(2*np.pi*50*t) t=t+0.3 d_señal.append(señal) for i in d_señal: # 发送数据添加换行符作为分隔 arduino.write((str(i) + '\n').encode('utf-8')) salida = arduino.readline().decode('utf-8').strip() # 过滤空值后转浮点 if salida: d_filtro.append(float(salida)) print(d_filtro) arduino.close() # 直接用拿到的浮点列表绘图即可 plt.plot(d_señal, label='原始信号') plt.plot(d_filtro, label='滤波后信号') plt.legend() plt.show()
内容的提问来源于stack exchange,提问作者Carlos Garcia Pintos
相关产品推荐
相关产品推荐

