Parsing data from pyserial

Grant Edwards grante at visi.com
Sun Dec 3 09:30:57 EST 2006


On 2006-12-03, Lone Wolf <lone_wolf at ureach.com> wrote:

> import serial
>
> ser=serial.Serial('com1',baudrate=115200, bytesize=8,
> parity='N', stopbits=1,xonxoff=0, timeout=1)
>
> ser.write("PM 1") #This sets the CMUcam to poll mode
>
> for i in range(0,100,1):
> 	ser.write("TC 016 240 100 240 016 240\r\n")
> 	reading = ser.read(40)
> 	print reading
> 	components = reading.split()
> 	print components
> ser.close
>
> Here is an example output: 
>
> M 37 79 3 4 59 124 86 25
> ['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59',
> '124', '86', '25', 'M
> ']
> M 38 77 3 2 59 124 86 25
> ['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124', '86',
> '25', 'M', '38'
> , '7']
>
> My problem is that I am trying to get each data point of the
> packet into a separate variable. Ordinarily, this would be
> easy, as I would just parse the packet, read the array and
> assign each element to a variable eg. mx = components[1].
> However, that doesn't work here because the original packet
> and the array that I got from using the split() method are
> different.

I doubt it.  Try printing `reading` instead of reading.  I
suspect that the string you're getting from ser.read() has a
carraige-return in it that you aren't seeing when you do print
reading.

> If I were to try read the array created in the first example
> output, mx would be 123 instead of 37 like it is in the
> packet. In the second example, the array is 85 while the
> packet is 38.
>
> As near as I can figure out, pyserial is reading a stream of
> data and helpfully rearranging it so that it fits the original
> packet format M xxx xxx xxx xxx xxx xxx xxx xxx.

No, it isn't.  I wrote the Posix low-level code that's in
pyserial.  I've used pyserial extensively on both Windows and
Linux.  It doesn't rearrange anything.

> I would have thought the split() method that I used on
> original packet (ie the "reading" variable) would have just
> returned an array with nine elements like the packet has. This
> is not the case, and I am at a loss about how to fix this.  

When something odd seems to be happening with strings, always
print `whatever` rather than whatever

> I've searched the archive here and elsewhere with no luck. Any
> help REALLY appreciated!


-- 
Grant Edwards                   grante             Yow!  There's a SALE on
                                  at               STRETCH SOCKS down at the
                               visi.com            "7-11"!!



More information about the Python-list mailing list