Python serial data aquisition
mfuhr at fuhr.org
Sun Jan 9 18:03:15 EST 2005
fccoelho at gmail.com (Flavio codeco coelho) writes:
> my hardware represents analog voltages as 12bit numbers. So, according
> to the manufacturer, this number will be stored in two bytes like
> 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.
Is byte1 the high-order byte or the low-order byte? Is n1 the
high-order bit or the low-order bit? In my example below I'll
assume that byte1 and n1 are in the high-order positions.
> My problem is to how to recover my reading from these bytes, since
> pyserial gives me a character (string) from each byte...
You could convert the characters to their integer ASCII values with
ord() and perform bitwise operations on them. For example, suppose
you have the following characters:
byte1 = '\xd2' # 1101 0010
byte2 = '\xb5' # 1011 0101
If byte1 is the high-order byte and n1 is the high-order bit, then
you need to mask off the upper three bits of byte1 (giving 0001 0010)
and the upper bit of byte2 (giving 0011 0101), then shift byte1 left 7
positions (not 8) and OR it with byte2 (giving 1001 0011 0101).
value = ((ord(byte1) & 0x1f) << 7) | (ord(byte2) & 0x7f)
If the actual byte and/or bit order is different then you'll have
to modify the expression, but this should at least give you ideas.
More information about the Python-list