Python3.6读写串口操作

1.安装串口python库
# pip install pyserial

2.操作串口
<1>.方案一
#-*- coding:utf-8 -*-
import serial

ser = serial.Serial("COM4", 115200, timeout=0.5)
def str_2_hex(data):
    text = ""
    for i, data in enumerate(data.hex()):
        text += data
        if i % 2 != 0:
            text += " "
    return text 

def send(data):
    print("send ==== ", str_to_hex(data))
    ser.write(data)

def recv():
    recv = ser.read(100)
    text_str = str_to_hex(recv)
    print("recv === ",text_str)

if __name__=="__main__":
    data = b'\x12\x34\xff\xab\x56\xac'
    send(data)
    recv()

<2>.方案二
# emacs test.py

#-*- coding:utf-8 -*-
import serial

baudrate = 115200
#wsl
port = "/dev/ttyS4"
#windows
# port = "COM3"

ser = serial.Serial(port, baudrate, timeout=0.5)
def check_data(nums):
    checksum = 0
    for n in nums[2:]:
        checksum ^=  n
    print("checksum = ",hex(checksum))
    return (checksum)

def list_2_hex(s):
    return " ".join([hex(int(i)) f

你可能感兴趣的:(Python)