Parsing data from pyserial, an (inefficient) solution

Giovanni Bajo noway at ask.me
Mon Dec 4 03:19:24 EST 2006


Dennis Lee Bieber wrote:
> 
>> The really sad thing is that I get a perfectly constructed
>> packet from the reading variable, and that gets butchered when I
>> try to slice it up to pick out individual elements. Since
>> pyserial doesn’t do anything to rearrange the data, then the
>> CMUcam must do the heavy lifting of extracting a perfect packet
>> from the data stream. It’s a real shame I couldn’t use it
> 
> 	More likely it is running fast enough to keep up with the serial
> port, and synchronizes on the "\rM". Your code seems to be reading in
> bursts and somehow losing parts during your processing (which is
> strange, I'd have expected pyserial to buffer some data between reads).
> 
> 	Lacking that, I'd probably end up creating a thread to handle the
> serial port reading, which basically looks like:
> 
> while ser.read(1) != "\r": pass #synchronize
> while not Done:
> 	bfr = []
> 	while True:
> 		c = ser.read(1)
> 		bfr.append(c)
> 		if c == "\r": break
> 	queue.put("".join(bfr))
> 
> This should result in complete packets (from the "M" to a "\r") 

Oh well. readline(eol="\r") will do that much better.

while 1:
     data = ser.readline(eol="\r")
     args = data.split()
     if args[0] == "M":
        # command M; do something with args[1:]
     elif args[0] == "KK":
        # command KK; do something with args[1:]
     [.. process other commands ..]
     else:
        # Invalid command: might be an incomplete
        # packet. Just ignore it.
        pass



More information about the Python-list mailing list