0

I am trying to read lightware rangefinder SF11 through serial but using Raspberry, and I am not familiar with Python, but I tried this:

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

When I run the code it's turn this:

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
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 1
    Is this Python 2 or Python 3 code? Don't just tag with both. Also, provide the complete traceback and any input fed to the code, we need a [MCVE], not just a code dump with a snippet of an error message. If the problem occurs on the line `distanceCM = float(distanceStr) * 100`, consider printing `distanceStr` (or better, `repr(distanceStr)` before using it, so you can see what it's trying to parse. – ShadowRanger Oct 24 '19 at 02:00
  • 3
    Clearly `1.72 m 0.086 V` cannot be converted to floating – eyllanesc Oct 24 '19 at 02:06
  • Could you tell us the output of `str(distanceStr)` and `type(distanceStr)`? – MAO3J1m0Op Oct 24 '19 at 02:07
  • @MAO3J1m0Op and eyllanesc i want to measure distance in cm – user7366508 Oct 24 '19 at 02:11
  • 1
    Possible duplicate of [python ValueError: invalid literal for float()](https://stackoverflow.com/questions/21943877/python-valueerror-invalid-literal-for-float) – xiutiqianshi Oct 24 '19 at 02:15
  • @eyllanesc when i tried ```distanceCM= float(distanceStr.split()[0]) * 100``` it returning ```ValueError: could not convert string to float:``` – user7366508 Oct 24 '19 at 02:22

0 Answers0