简体   繁体   中英

Parsing serial data in python

I'm new to this site and python. I've been working on a project that needs to extract variables from incoming serial data and eventually display it. I'm currently working on parsing the data and I'm having a bit of trouble. The serial data looks like this for example:

a3b5f45c9g8a4c10f64;
f4h87d34k9h4j3d3;
h6f54a12a13a14a15b12b13;

There's multiple variables denoted by the letter before the value and they arrive in no particular order. About once a second the line breaks with a semi-colon. The same variable can appear multiple times or not at all per line. The closest I've gotten is using regex to find the value between the identifying letter and the next non-number, if that makes sense. The problem I'm having is that it only returns the first match and then stops. I need the variable to be constantly updated. I've been scratching my head for the past few days, any guidance is greatly appreciated.

import serial
import re

ser = serial.Serial('COM6', 9600, timeout=2)

while True:
  data_raw = ser.readline()
  print(data_raw)

  apples = re.search('a(.+?)\D', data_raw)
  if apples:
    applesvar = apples.group(1)
    print applesvar

  cherries = re.search('c(.+?)\D', data_raw)
  if cherries:
    cherriesvar = cherries.group(1)
    print cherriesvar


ser.close

You are almost there. By using the first line of your example

line = 'a3b5f45c9g8a4c10f64'

re.findall('a(.+?)\D', line)
['3', '4']

re.findall('c(.+?)\D', line)
['9', '10']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM