just do it

Python使用pyserial进行串口通信

安装pyserial

1
pip install pyserial

查看可用的端口

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
import serial.tools.list_ports
port_list = list(serial.tools.list_ports.comports())
if len(port_list) == 0:
   print('无可用串口')
else:
    for i in range(0,len(port_list)):
        print(port_list[i])

所发十六进制需转换为以下格式

1
2
# 所发十六进制字符串010591F50000F104
cmd = [0x01, 0x05, 0x91, 0xF5, 0x00, 0x00, 0xF1, 0x04]

串口通信
Windows下端口为COM*, Ubuntu下为/dev/ttyS0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# -*- coding: utf-8 -*
import serial
import time
# 打开串口
ser = serial.Serial("COM8", 9600)
def main():
    while True:
        # 获得接收缓冲区字符
        count = ser.inWaiting()
        if count != 0:
            # 读取内容并回显
            recv = ser.read(count)
            ser.write(recv)
        # 清空接收缓冲区
        ser.flushInput()
        # 必要的软件延时
        time.sleep(0.1)
 
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if ser != None:
            ser.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- coding: utf-8 -*
import serial
import time
# 打开串口
#ser = serial.Serial("/dev/ttyUSB0",9600)
# 创建serial实例
ser = serial.Serial()
ser.port = '/dev/ttyUSB0'
ser.baudrate = 9600
ser.parity = 'N'
ser.bytesize = 8
ser.stopbits = 1
ser.timeout = 0.2
def main():
    # 打开串口
    ser.open()
    # 发送
    code = '01 03 40 00 00 02 D1 CB'
    ser.write(bytes.fromhex(code))
    while True:
 
        # 获得接收缓冲区字符
        count = ser.inWaiting()
        if count != 0:
            # 读取内容并回显
            recv = ser.read(count)
            data= recv.hex()
            print(data);
#            ser.write(recv)
        # 清空接收缓冲区
        ser.flushInput()
        # 必要的软件延时
        time.sleep(0.1)
 
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if ser != None:
            ser.close()
点赞