On 9 Jan 2005 14:13:28 -0800, [EMAIL PROTECTED] (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...
>
The others have shown how to recover a 12 bit positive value 0 through 4095,
but if the number is signed, and you want the signed value, you'll have to
find out how signed numbers are represented. An offset is common, in which
case you would subtract 2048 (2**11). If it's two's complement by some chance,
you'll want  (I think -- untested ;-) to do num -= 2*(num&2048) instead of 
always num -= 2048

If you need speed in converting large strings of byte pairs, you could
convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers)
and use the resulting 16-bit numbers as indices into another array of final 
values
prepared beforehand with redundant information that will accomplish the effect
of masking and shifting and adjusting sign.

If you need this speed, volunteers will magically appear. Maybe even if you 
don't ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to