【问题标题】:converting the serial read(ASCII) to floating number将串行读取(ASCII)转换为浮点数
【发布时间】:2016-10-09 07:48:25
【问题描述】:

我正在通过我的 Raspberry Pi(python) 从 Arduino 检索串行输出。

使用的代码:

import serial
ser=serial.Serial('/dev/ttyACM0',115200)
while True:
    value = float(ser.readline().strip())
    print '{0:0.2f}'.format(value)

问题:我能够打印串行输出,去除一些读数中不需要的字符,之后它会给出错误“valueError:could not convert string to float:”

【问题讨论】:

  • 浮点字符串,十六进制,字节,哪个是传入的?都有不同的提取方法。如果 float 是 hex 样式(32,64,128,256 位),您需要检查 byte size'{0:0.2f}'.format(float(value))

标签: python


【解决方案1】:

当我试图以太快的速度读取数据时,我遇到了同样的错误。通过打印 ASCII 数据(在转换为浮点数之前)发现了这一点。有时它打印为空行。我只是放慢了循环速度:

while True:
   # readline, etc
   time.sleep(1)

首先我有:

time.sleep(.5)

Arduino 也每 0.5 秒发送一次数据,所以有时还没有数据。

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 2023-03-13
    • 2014-09-25
    • 1970-01-01
    • 2019-10-19
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多