Search code examples
pythonsplittext-processingstrip

Data received through serial in Python


I have configured on Raspberry Pi UART and this is my serial reading / writing code:

ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1)
ser.open()
string = '#SET0\r\n'
print string
ser.write(string)
bytes2read = ser.inWaiting()
print bytes2read
if (ser.inWaiting()>0):
  incoming = ser.readline()
  print incoming
time.sleep(5)
bytes2read1= ser.inWaiting()
print bytes2read1
if (ser.inWaiting()>0):
  print "Data:"
  cont = ser.read(bytesaleer1)
print cont

cont has this format:

#D0:0:0:10
#D1:0:0:56
#D2:0:0:23
#D3:1:1:90
--------

My question is, How can I get and save the last 0 on that variable? I want to save in c0,c1,c2,c3 values obtained from cont; 10,56,23 and 90. Have tried with line.strip but with no good results.


Solution

  • If cont is a string containing all five lines of text, including the -------- separator line, I'd start by splitting it into lines:

    cont.splitlines()
        => [ '#D0:0:0:10',
             '#D1:0:0:56',
             '#D2:0:0:23',
             '#D3:1:1:90',
             '--------' ]
    

    Then you can loop over all the lines, and if the line includes a colon, pull off the last value and save it.

    vals = []
    for line in cont.splitlines():
        if ':' in line:
            v = int(line.split(':')[-1])
            vals.append(v)
    
    >>> vals
    [10, 56, 23, 90]