Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error in If-Then statement

I am writing a program in python, which works like this:

  1. Take input string through Serial port, when press enter (Carriage Return)
  2. Check $ sign on the first character of input string then continue if present
  3. Remove all the unwanted character and alphabetics except numerics and , and then print it.

Problem

Program stuck, if $ sign is not present in input string because next time if It get input string with $, it doesn't print the values

kindly review my codes below and guide me on how do I 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 = ""
like image 873
Irfan Ghaffar7 Avatar asked Mar 26 '26 21:03

Irfan Ghaffar7


2 Answers

Although it's not exactly obvious what the end intent of your code is, you might just need to unindent the last line to clear the buffer every time, otherwise you are constantly adding to it, and if it doesn't start with a $, 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 = ""
like image 69
enigma Avatar answered Mar 28 '26 11:03

enigma


The problem is that you keep adding the new lines onto the end of the buffer, only clearing it out if you happen to have a command. So, once you get a line that isn't a command, your buffer will never start with a command.

I think enigma's answer is what you were asking for.


But it's still not going to work right if you can ever get two lines (or, worse, part of one line and part of the next) in the same buffer. So, you really want something more like this:

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]

The split will break the buffer into all of the complete lines, plus either an empty string or a leftover partial line. So, you process the complete lines, and stick the leftover empty string or partial line into the buffer to be added to on the next read.

like image 45
abarnert Avatar answered Mar 28 '26 12:03

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!