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

使用PySerial接收串口角度控制舵机时遇字符串转浮点数错误求助

问题解决:串口舵机指令解析报错ValueError: could not convert string to float: ''

问题根源

你代码里的核心错误是连续两次调用sio.readline():第一次if len(sio.readline()) > 0已经读取了一行有效数据,第二次go_to = float(sio.readline())会尝试读取下一行数据(此时串口缓冲区可能为空),导致转换空字符串失败。

修复方案

  1. 只调用一次readline(),将读取结果存入变量后再做判断和处理
  2. 清理读取字符串中的空白字符(换行、空格等),避免无效转换
  3. 增加异常捕获,防止非法输入直接终止程序
  4. 可选:增加角度范围校验,避免超出舵机硬件限制的指令损坏设备

修复后完整代码

#!/usr/bin/python3
import time
import serial
import io
from gpiozero.pins.pigpio import PiGPIOFactory
from gpiozero import Device, AngularServo

sport = serial.Serial('/dev/rfcomm0', timeout=6)
sio = io.TextIOWrapper(io.BufferedRWPair(sport, sport))
Device.pin_factory = PiGPIOFactory()

tservo = AngularServo(17,
                     min_angle= -90,
                     max_angle= 90,
                     min_pulse_width= 1/1000,
                     max_pulse_width= 2/1000)
while True:
    # 仅读取一次串口数据,存入变量复用
    line = sio.readline()
    if line:
        # 去除字符串首尾的换行、空格等空白字符
        cleaned_line = line.strip()
        if cleaned_line:
            try:
                go_to = float(cleaned_line)
                # 校验角度是否在舵机支持范围内
                if -90 <= go_to <= 90:
                    tservo.angle = go_to
                else:
                    print("错误:角度超出-90~90范围")
            except ValueError:
                print(f"错误:无法将'{cleaned_line}'转换为数字")
    # 上报当前舵机角度
    angle_string = str(tservo.angle) + '\n'
    sport.write(angle_string.encode())
    time.sleep(5)

关键修改说明

  • 合并两次readline()调用,避免数据丢失或读取空内容
  • 使用strip()处理输入字符串,过滤掉无关的空白字符
  • 用try-except捕获ValueError,保证程序在收到非法输入时不会崩溃
  • 增加角度范围校验,保护舵机硬件不受非法指令损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:42:14