Python 2.7串口RS232数据读取(2字节)

时间:2017-03-09 12:33:40

标签: python serial-port

我有这段代码。

import time
import serial

# configure the serial connections
ser = serial.Serial(
    port='/dev/ttyS0',
    baudrate=2400,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.EIGHTBITS
)

ser.open()
ser.isOpen()
print ser.portstr

x=ser.read(1)
print type(x)

while True:

        print x

        time.sleep(1)

当我运行这段代码时,我得到了矩形字符。(我不知道如何描述它 - 可能是某种类型的块元素???)。

所以我知道我收到的数据包括:

bit  0  1  2  3  4   5   6    7
LSB  D0 D1 D2 D3 D4  D5  par "0"
MSB  D6 D7 D8 D9 D10 D11 par "1"

整个数据均为2字节。第一个字节是8位(D0-D5是数据,奇偶校验后跟随字,停止位2)。

我的问题是如何接收读取此类数据以及如何将其转换为十进制数据...

谢谢

1 个答案:

答案 0 :(得分:0)

尝试:

binaryReceived = ser.read(2)
if len(binaryReceived)>=2:
    decimalReceived = (binaryReceived[0]&0x1f) | (binaryReceived[1]&0x1f)<<5
    print decimalReceived
else:
    print "two bytes not received"