Python serial data aquisition

Steve Holden steve at
Sun Jan 9 23:19:31 CET 2005

Flavio codeco coelho wrote:

> Hi,
> I am using pyserial to acquire data from an A/D converter plugged to
> my serial port.
> my hardware represents analog voltages as 12bit numbers. So, according
> to the manufacturer, this number will be stored in two bytes like
> this;
>          |-------------bits(1-8)-----------|
> Byte1: x  x   x   n1 n2 n3   n4   n5
> Byte2: x  n6 n7 n8 n9 n10 n11 n12
> where x is some other information, and nx are the digits of my number.
> My problem is to how to recover my reading from these bytes, since
> pyserial gives me a character (string) from each byte... I dont know
> how to throw away the   unneeded bits and concatenate the remaining
> bits to form a number...
> Flávio Codeço Coelho

Try something like (here I'm assuming that n12 is the least-significant 
bit) (untested):

	((ord(byte1) & 31) << 7 ) + (ord(byte2) & 127)

This takes the rightmost five bits from the first byte's integer value, 
shifts them up seven bits, and then adds the rightmost seven bits of the 
second byte's integer value.

Steve Holden     
Python Web Programming
Holden Web LLC      +1 703 861 4237  +1 800 494 3119

More information about the Python-list mailing list