I'm reading data via USB serial @ 57600 baud. I'm trying to take 5 readings and then get the average. Occasionally I get an error and I don't know how to get around it.
Here's my code:
Edit: The print c1 and print c2 are for debugging.
I should have mentioned- the message it's receiving looks like this: Rxxxx\r
The message begins with "R", has 4 ascii digits (xxxx) then ends with a "\r" line return.
I tried using ser.readline() but I couldn't get it to work. Does it only respond to "\n"? Or "\r\n"?
Thanks
Here's my code:
from serial import Serial
ser = Serial('/dev/ttyUSB0', 57600, 8, 'N', 1, timeout=1)
numPoints = 5
reading = [0] * numPoints
avgDistance = 0
def getValues():
ser.flush()
c = ser.read()
print("c1:", c)
if c == b'R':
c = ser.read(5).decode('ascii').strip('\r')
print("c2:", c)
return int(c)
ser.flush()
while 1:
for i in range(0, numPoints):
data = getValues()
reading[i] = data
avgDistance += data
avgDistance = avgDistance / numPoints
print(reading)
print("Average:", avgDistance)
break
ser.close()And here's my output screen showing an error and a good read:Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
c1: b'\x00'
Traceback (most recent call last):
File "/home/pi/Documents/Python Projects/PySerialCode/Lesson1E.py", line 24, in <module>
avgDistance += data
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
>>> ================================ RESTART ================================
>>>
c1: b'R'
c2: 0417
c1: b'R'
c2: 0417
c1: b'R'
c2: 0417
c1: b'R'
c2: 0417
c1: b'R'
c2: 0417
[417, 417, 417, 417, 417]
Average: 417.0
>>>Any constructive help much appreciated. Thanks.Edit: The print c1 and print c2 are for debugging.
I should have mentioned- the message it's receiving looks like this: Rxxxx\r
The message begins with "R", has 4 ascii digits (xxxx) then ends with a "\r" line return.
I tried using ser.readline() but I couldn't get it to work. Does it only respond to "\n"? Or "\r\n"?
Thanks
