代码之家  ›  专栏  ›  技术社区  ›  ThatsRightJack

Python从RS232串行端口编码/解码数据

  •  0
  • ThatsRightJack  · 技术社区  · 6 年前

    这是我第一次不得不通过RS232串行连接到一个设备来读/写数据,我被编码/解码程序困住了。

    pyserial

    import serial
    
    ser = serial.Serial()
    ser.port = '/dev/ttyUSB0'
    ser.baudrate = 115200
    ser.bytesize = serial.EIGHTBITS
    ser.parity = serial.PARITY_NONE
    ser.stopbits = serial.STOPBITS_ONE
    ser.timeout = 3
    
    ser.open()
    
    device_write = ser.write(bytearray.fromhex('AA 55 00 00 07 00 12 19 00'))
    
    device_read = ser.read_until()
    

    连接/通信似乎按预期工作。的输出 device_read 是

    b'M1830130A2IMU v3.2.9.1 26.04.19\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x0527641\x00\x00\x00IMHF R.1.0.0 10.28.2018 td:  6.500ms\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00'
    

    这就是我被困的地方。我不知道怎么解释。附件是数据表中的一个图像,它解释了输出应该表示什么。

    enter image description here

    ser.read_until()

    1 回复  |  直到 6 年前
        1
  •  2
  •   Ozan Bellik    6 年前

    ser.write(bytes([0x12])) ,相当于 ser.write(bytes([18]))

    看起来你的输出是154字节而不是98字节,而且大部分是非人类可读的。 但如果你有图中描述的数据,你可以这样分解它:

    ID_sn = device_read[0:8].decode('ascii')
    ID_fw = device_read[8:48].decode('ascii')
    Press_Sens = device_read[48]
    

        2
  •  1
  •   ThatsRightJack    6 年前

    这不是一个答案,只是@ozangds的想法得到了充实(可能会帮你节省一些打字时间):

    def decode_bytes(data, start, stop):
        return data[start:stop+1].decode('ascii').rstrip('\x00')
    
    
    device_read = b'M1830130A2IMU v3.2.9.1 26.04.19\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x0527641\x00\x00\x00IMHF R.1.0.0 10.28.2018 td:  6.500ms\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00'
    
    ID_sn = decode_bytes(device_read, 0, 7)
    ID_fw = decode_bytes(device_read, 8, 47)
    Press_sens = device_read[48]
    IMU_type = device_read[49]
    IMU_sn = decode_bytes(device_read, 50, 57)
    IMU_fw = decode_bytes(device_read, 58, 97)
    
    label_fmt = '{:>10}: {!r}'
    print(label_fmt.format('ID_sn', ID_sn))
    print(label_fmt.format('ID_fw', ID_fw))
    print(label_fmt.format('Press_sens', Press_sens))
    print(label_fmt.format('IMU_type', IMU_type))
    print(label_fmt.format('IMU_sn', IMU_sn))
    print(label_fmt.format('IMU_fw', IMU_fw))
    

    输出:

         ID_sn: 'M1830130'
         ID_fw: 'A2IMU v3.2.9.1 26.04.19'
    Press_sens: 2
      IMU_type: 5
        IMU_sn: '27641'
        IMU_fw: 'IMHF R.1.0.0 10.28.2018 td:  6.500ms'