Python Forum
Problem with serial data. How do I ignor incorrect data?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with serial data. How do I ignor incorrect data?
#1
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:

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
Reply
#2
Okay here's what I've gotten to work thus far. I'd still like to know how I might ignore the "None" return and still get 5 full readings. Here's what I came up with :
from serial import Serial
import time

ser = Serial('/dev/ttyUSB0', 57600, 8, 'N', 1, timeout=3)

numPoints = 5
reading = [0] * numPoints
avgDistance = 0

def getValues():
    c = ser.read()
    print("c1:", c)         # used for debugging only
    if c != b'\x00':
        if c == b'R':
            c = ser.read(5).decode('ascii').rstrip('\r')
            print("c2:", c) # used for debugging only
            return int(c)
    else:
        print("Error")      # used for debugging only

while 1:
    for i in range(0, numPoints):
        data = getValues()
        if data is not None:
            reading[i] = data
            avgDistance += data
        else:
            numPoints = numPoints - 1   # reduce divisor by number of "None" returned
    avgDistance = avgDistance / numPoints
    
    print(reading)
    print("Average:", avgDistance)
    break
    
ser.close()
And here's some output:

>>> ================================ RESTART ================================
>>> 
c1: b'\x00'
Error
c1: b'\r'
c1: b'R'
c2: 0416
c1: b'R'
c2: 0416
c1: b'R'
c2: 0416
[0, 0, 416, 416, 416]
Average: 416.0
>>> ================================ RESTART ================================
>>> 
c1: b'\x00'
Error
c1: b'\r'
c1: b'R'
c2: 0416
c1: b'R'
c2: 0418
c1: b'R'
c2: 0417
[0, 0, 416, 418, 417]
Average: 417.0
>>> ================================ 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: 0416
[417, 417, 417, 417, 416]
Average: 416.8
>>> 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with to check an Input list data with a data read from an external source sacharyya 3 403 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  Take data from web page problem codeweak 5 905 Nov-01-2023, 12:29 AM
Last Post: codeweak
  pyserial/serial "has no attribute 'Serial' " gowb0w 9 3,903 Aug-24-2023, 07:56 AM
Last Post: gowb0w
  Code is returning the incorrect values. syntax error 007sonic 6 1,206 Jun-19-2023, 03:35 AM
Last Post: 007sonic
  Matplot / numpy noisy data problem the57chambers 1 693 Feb-09-2023, 03:27 AM
Last Post: deanhystad
  Write sql data or CSV Data into parquet file mg24 2 2,419 Sep-26-2022, 08:21 AM
Last Post: ibreeden
  Load multiple Jason data in one Data Frame vijays3 6 1,536 Aug-12-2022, 05:17 PM
Last Post: vijays3
  Django: Adding Row Data To Existing Model Instance Question/Problem. Steven_Pinkerton 1 1,244 Aug-09-2022, 10:46 AM
Last Post: Addweb
  Issue in changing data format (2 bytes) into a 16 bit data. GiggsB 11 2,655 Jul-25-2022, 03:19 PM
Last Post: deanhystad
  error 1102 (42000) incorrect database name 's' Anldra12 4 1,702 Jun-08-2022, 09:00 AM
Last Post: Anldra12

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020