Search code examples
python-3.xautomationarduino

Reading serial data from arduino: Code works..on re run it errors


import serial 
from vpython import * 

arduinoSerialData = serial.Serial('com8', 9600)
measuringRod = cylinder( radius= .5, length=6, color=color.yellow, pos=vector(-3,0,0))
lengthLabel = label(pos=vector(0,1,0), text='Target Distance is: ', box=False, height=30)
while True:  
rate(20)
if (arduinoSerialData.inWaiting()>0): 
    Data = arduinoSerialData.readline().strip().decode("ascii") 
    print(Data) 
    distance = float(Data) 
    measuringRod.length=distance 
    myLabel= 'Target Distance is: ' + Data 
    lengthLabel.text = myLabel

The error on re running the program tells

11.85
11.53
13.07
13.43
11.66
16.53

Traceback (most recent call last): File "c:\Users\golut\OneDrive\Documents\Arduino\count\tempCodeRunnerFile.py", line 12, in
distance = float(Data) ValueError: could not convert string to float: ''

On disconnecting and reconnecting the arduino it works perfectly but then as I stop the program and re run it, it stops running


Solution

  • The numbers were being read individually, so splitting is not required, what I tried doing was, I included an if statement after printing "Data" and checked whether the data passed is null or not, if it wasn't, I converted the data into float. This way it works fine. The problem I was facing was the arduino on closing the program and restarting sent null values sometimes, don't know why, so the error kept occuring as there was nothing to be converted into float