Python error in If-Then statement
I am writing a program in python that works like this:
- Enter an input string through the serial port when hit enter (carriage return)
- Mark
$
the first character of the input line, then continue if present - Delete all unnecessary characters and alphabets except
numerics
and,
, then print it.
Problem
The program gets stuck if a character is $
missing from the input line because next time if it receives an input line with $
it doesn't print the values
kindly review my codes below and tell me how to resolve it?
CODE
import serial,re
x = [0,0,0]
ser = serial.Serial('/dev/ttyAMA0', 9600)
buffer = ''
while True:
buffer += ser.read(ser.inWaiting())
if '\n' in buffer:
if buffer[0] == '$':
x= re.sub("[^0-9\,]","", buffer)
x1 = x.rstrip()
x2= x1.split(",")
print((x2[0]),(x2[1]),(x2[2]))
buffer = ""
source to share
While it's not entirely obvious what the purpose of your code is, you can just remove the last line to clear the buffer every time, otherwise you keep adding to it and if it doesn't start with $
, it never will.
while True:
buffer += ser.read(ser.inWaiting())
if '\n' in buffer:
if buffer[0] == '$':
x= re.sub("[^0-9\,]","", buffer)
x1 = x.rstrip()
x2= x1.split(",")
print((x2[0]),(x2[1]),(x2[2]))
buffer = ""
source to share
The problem is that you keep adding new lines to the end of the buffer, freeing it only if you have a command. So, once you get a line that is not a command, your buffer will never be started with the command.
I think the riddle question is what you asked for.
But it still won't work correctly if you can get two lines (or worse, part of one line and part of the next) in the same buffer. So, you really want something more:
while True:
buffer += ser.read(ser.inWaiting())
lines = buffer.split('\n')
for line in lines[:-1]:
if line[0] == '$':
x= re.sub("[^0-9\,]","", line)
x1 = x.rstrip()
x2= x1.split(",")
print((x2[0]),(x2[1]),(x2[2]))
buffer = lines[-1]
split
splits the buffer into all full lines plus an empty line or the remaining partial line. So, you process full lines and insert the remaining blank line or partial line into a buffer that will be appended to the next read.
source to share