pyserial 无法将字符串转换为 float ''

问题描述 投票:0回答:1

这是我正在编写的一些代码。这个想法是使用远程串行终端向其发送舵机角度,并让它定期报告舵机的当前位置。

#!/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:
        if len(sio.readline()) > 0:
                go_to = float(sio.readline())
                tservo.angle = go_to
        angle_string = str(tservo.angle)+'\n'
        tuned_to = (angle_string.encode())
        sport.write(tuned_to)
        time.sleep(5)

它可以工作,但当我尝试发送号码时,我收到这些错误消息:

Sep  5 12:16:28 magloop1 rfcomm[2354]:     go_to = float(sio.readline())
Sep  5 12:16:28 magloop1 rfcomm[2354]: ValueError: could not convert string to float: ''

我尝试使用 TextIOWrapper 但没有什么不同

python python-3.x io pyserial
1个回答
0
投票

您收到的错误消息表明有人尝试将空字符串 (

''
) 转换为浮点数,这会导致
ValueError

问题的出现是因为

sio.readline()
被快速连续调用两次。第一次是检查返回字符串的长度是否大于零,第二次是当您尝试将其转换为浮点数时。如果第一个调用读取包含数据的行,则紧随其后的第二个调用将读取下一行,该行可能还没有数据,从而导致空字符串。

解决方案如下:

  1. 读取该行一次并将其存储在变量中。
  2. 检查存储值的长度是否大于零。
  3. 如果是,则尝试转换。

这是您更正后的循环:

while True:
    line = sio.readline().strip()  # strip to remove any leading/trailing whitespace
    if len(line) > 0:
        try:
            go_to = float(line)
            tservo.angle = go_to
        except ValueError:
            # Handle the invalid float value gracefully
            print(f"Received invalid value: {line}")
    angle_string = str(tservo.angle) + '\n'
    tuned_to = angle_string.encode()
    sport.write(tuned_to)
    time.sleep(5)
© www.soinside.com 2019 - 2024. All rights reserved.