You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32读取Flash浮点值:Python与Arduino串口输出不一致求助

ESP32串口输出float值Python读取乱码问题及解决办法

问题描述

从ESP32的Flash存储器中读取每行存储的float值,打算在Python中绘制这些值,但Python读取的结果与Arduino串口监视器显示的完全不同。尝试过在Arduino中直接打印float以及转为字符串,两种方式在Arduino串口监视器中均正常,但Python读取时出现乱码(如-0.50.000)。

相关代码

Arduino代码

while(file.available()){
    num = file.parseFloat();
    str = String(num, 3);
    Serial.println(str);
    //Serial.println(num);
}
Serial.println("\nDone");

Python代码

while(1):
    line = ser.readline()   # read a byte string
    if line:
        string = line.decode()  # convert the byte string to a unicode string
        
        if ("Done" in string):
            break

        #num = float(string) # convert the unicode string to a float
        
        print(string)
        #print(num)

解决办法

  • 确保串口参数完全匹配:Python初始化串口时,波特率、数据位、停止位、奇偶校验必须和Arduino的Serial.begin()一致。例如Arduino用Serial.begin(115200),Python对应代码:
    import serial
    ser = serial.Serial('COMx', 115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1)
    
  • 清空串口缓冲区:Python开始读取前,先清空残留数据:
    ser.flushInput()
    ser.flushOutput()
    
  • 清洗读取的字符串:对读取的内容做去空白处理,跳过空行:
    string = line.decode().strip()
    if not string:
        continue
    
  • 改用二进制传输(更可靠):避免字符串转换误差,直接传输float的二进制字节:
    Arduino端代码:
    while(file.available()){
        float num = file.parseFloat();
        Serial.write((byte*)&num, sizeof(num));
    }
    Serial.println("\nDone");
    
    Python端解析代码:
    import struct
    while True:
        data = ser.read(4)
        if len(data) == 4:
            num = struct.unpack('f', data)[0]
            print(num)
        if ser.in_waiting > 0:
            line = ser.readline().decode().strip()
            if line == "Done":
                break
    
  • 增加数据格式校验:Arduino输出固定格式的字符串,Python用正则验证后再转换:
    Arduino端:
    Serial.printf("%.3f\n", num);
    
    Python端:
    import re
    pattern = re.compile(r'^-?\d+\.\d{3}$')
    if pattern.match(string):
        num = float(string)
    else:
        print(f"无效数据: {string}")
    

内容的提问来源于stack exchange,提问作者Alexandru Manolache

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:01:20