[PYTHON] Binary transmission / reception with Pyserial

Introduction

I will describe Binary transmission and reception using pyserial as a reminder.

How to send Binary with Pyserial

Reference: Binary data using pyserial (python serial port) Among them, the Serial.write () method of pyserial sends only the character string data. Is written.

You can send a Binary-converted version so that the output is something like "\ x00". ("\ X" means to interpret the following two characters as hexadecimal integer values.)

As a conversion example It describes how to use array – fixed data type sequence.

import serial
import array

#I want to send Binary Data
b = [0xc0, 0x04, 0x00]
print(b)
#It is converted to a decimal number and displayed.
# >>>[192, 4, 0]

#Method using conversion array to Python Binary
b_data=array.array('B', [0xc0, 0x04, 0x00]).tostring()
print(b_data)
# >>>b'\xc0\x04\x00'

#Method using conversion bytes for Python Binary
b2_data = bytes(b)
print(b2_data)
# >>>b'\xc0\x04\x00'

#Both are the same when compared.
print(b_data==b2_data)
# >>>True

It is easier to use bytes (), so use this. It can be used when exchanging in Binary mode of TWELITE mentioned in the previous article.

Send

#Send, for example
senddata=[0xA5,0x5A,0x80,0x07,0x00,0x00,0x00,0x64,0xFF,0xFF,0x02,0x67]

print(senddata)
#Print output will be in decimal notation
# [65, 90, 128, 7, 1, 0, 0, 100, 255, 255, 2, 103]

#Convert to Binary
send_binary =bytes(senddata) 
# bytearray()May be
# send_binary =bytearray(senddata) 

print(send_binary)
#Send data Binary
# b'\xa5Z\x80\x07\x01\x00\x00d\xff\xff\x02g'

#Send by pyserial
with serial.Serial('COM12', 115200) as ser:
    print('---')
    ser.write(send_binary)
    print('---')

Receive


with serial.Serial('COM12', 115200) as ser:
    #Specify the number of bytes to read in the read argument.
    b_reply = ser.read(23)
    #When reading all
    b_reply = ser.read_all()

    print(b_reply)
    # >>> b'\xa5Z\x80\x04\xdb\xa1\x98\x01\xe3\x04\xa5Z\x80\x07\x01\x04\x00\x013<")\x04'

    #It is necessary to specify how many bytes and what type to read using the struct module.
    #This time, 23 bytes are read in 1-byte increments.
    #23B is the same as having 23 Bs lined up. B is an unsigned char type in C language, and in Python it is an integer of 1 Byte.

    reply =struct.unpack('23B',b_reply)

    print(reply)
    # >>> 165, 90, 128, 4, 219, 161, 152, 1, 227, 4, 165, 90, 128, 7, 1, 4, 0, 1, 51, 60, 34, 41, 4
    #The last 4 is(EOT)End of transmission character (End)-of-Transmission character)
    #Analyze according to the specifications of what number of Byte has which information.

Recommended Posts

Binary transmission / reception with Pyserial
Binary search with python
Binary search with Python3
Serial communication with Raspberry Pi + PySerial