Binary data with pyserial(python serial port)

前端 未结 3 521
滥情空心
滥情空心 2021-02-04 04:43

serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any

3条回答
  •  无人及你
    2021-02-04 05:26

    I faced a similar (but arguably worse) issue, having to send control bits through a UART from a python script to test an embedded device. My data definition was "field1: 8 bits , field2: 3 bits, field3 7 bits", etc. It turns out you can build a robust and clean interface for this using the BitArray library. Here's a snippet (minus the serial set-up)

    from bitstring import BitArray
    
    cmdbuf = BitArray(length = 50)     # 50 byte BitArray
    cmdbuf.overwrite('0xAA', 0)       # Init the marker byte at the head
    

    Here's where it gets flexible. The command below replaces the 4 bits at bit position 23 with the 4 bits passed. Note that it took a binary bit value, given in string form. I can set/clear any bits at any location in the buffer this way, without having to worry about stepping on values in adjacent bytes or bits.

    cmdbuf.overwrite('0b0110', 23)
    
    # To send on the (previously opened) serial port 
    ser.write( cmdbuf )
    

提交回复
热议问题