ValueError:float()的文本无效

2024-06-28 20:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过串口阅读lightware rangefinder SF11,但使用的是Raspberry,我不熟悉Python,但我尝试了以下方法:

import time
import serial

print('Code is Running.')

# Make a connection to the com port.
serialPortName = '/dev/ttyUSB0'
serialPortBaudRate = 115200
port = serial.Serial(serialPortName, serialPortBaudRate, timeout=0.1)


port.write('www\r\n')
port.readline()     # Read and ignore any unintended responses


port.write('?\r\n')     # Get the product information
productInfo = port.readline()

print('Product information: ' + productInfo)

while True: 

    port.write('LD\r\n')     # reading distance  (First return, default filtering)
    distanceStr = port.readline()
    distanceCM = float(distanceStr) * 100   # Convert the distance string into a number
    print(distanceCM)
    time.sleep(0.05)     # Wait for 50ms before the next reading

当我运行代码时,它是这样的:

Traceback (most recent call last):
  File "range.py", line 25, in <module>
    distanceCM = float(distanceStr) * 100   # Convert the distance string into a number
ValueError: invalid literal for float(): 1.72 m  0.086 V

Tags: theimportreadlineinformationtimeportserialfloat