【问题标题】:Formatting string from serial device来自串行设备的格式化字符串
【发布时间】:2021-10-08 20:33:51
【问题描述】:

我知道我之前问过类似的问题 (Formatting a return value from a serial device),但这次我的问题有所不同。我正在从 Arduino 读取一个值,看起来像这样:

值 = b'446.45 mV\r\n'

我需要的只是 446.45。我下面的代码可以提取这个值,但每隔一段时间它就会决定不起作用。我多次调用此值,最多为 10,000 或更多。当我在数据收集的第 9000 次迭代中收到错误消息时,我感到很沮丧:“ValueError:无法将字符串转换为浮点数:''”。有谁知道我的问题可能是什么?

value = ser2.readline() # gives something like: b'446.45 mV\r\n'
val_str = str(value)
count = val_str.count('.') #count number of decimal points
if count != 1: #make sure there is only one decimal point
    val_str = val_str[:6] #keep two decimal points 
w = val_str.strip("b")
x = w.strip("mV\\r\\n")
y = float(x) # usually gives: 446.45

【问题讨论】:

  • 当您收到 ValueError 时,valueval_str 是什么?将您的代码包装在 try/except 中,以便您可以在出错时打印它。
  • 使用 try except 并打印有问题的值

标签: python arduino serial-port


【解决方案1】:

假设您将模拟数据从 Arduino 发送到 Python,我强烈建议您发送原始 10 位(或有时 12 位)整数。这将使转换更容易。

如果你让你的 Arduino 做这样的事情:

Serial.println(analogRead(some_port));

然后 Arduino 将以 ascii 字节发送 int 数据。

然后您可以通过在 python 中执行以下操作来获取它们:

value = ser2.readline()
int_value = str(int(value))

# Here you can then calculate voltages based on that

voltage = 5/1023 * int_value

【讨论】:

    【解决方案2】:

    我认为这是因为您的设备由于串行端口或电缆损坏而提供不同的输出,并且您的程序无法将其转换为浮点数。

    很遗憾,您没有提供所有数据,所以我无法测试解决方案,但这是我能想到的最好的解决方案。

    my_str = b'446.45 mV\r\n'
    def separate(value):
       value = value.decode("utf8") # decoding the value (it is better to use my_str.decode() instead of str(my_str))
       value = value.split('m')[0] # removing all the letter that go after m
       return float(value) # returning the separated value
    separate(my_str)
    

    【讨论】:

    • 谢谢。我想我可能找到了原因。 Arduino 每隔一段时间就会同时输出两个电压读数,看起来像这样:306.632293.96。通过在我的字符串中有两位小数,代码不知道如何转换为浮点数。所以我需要一个错误代码或解决方案。
    • 我已经编辑了我的代码以包含修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多