Python Multiple Serial Ports Guide

In Python, you can use the third-party library pyserial to access multiple serial ports. Here is a simple example code:

import serial

# 设置串口参数
ser1 = serial.Serial('COM1', 9600)
ser2 = serial.Serial('COM2', 9600)

# 发送数据到串口1
ser1.write(b'Hello from COM1')

# 发送数据到串口2
ser2.write(b'Hello from COM2')

# 读取串口1的数据
data1 = ser1.read(10)
print(data1)

# 读取串口2的数据
data2 = ser2.read(10)
print(data2)

# 关闭串口
ser1.close()
ser2.close()

In the example above, we first import the serial library, then open two serial ports COM1 and COM2, send and receive data respectively, and finally close the two ports. You can pass in different serial port parameters, send different data, and read different data according to your needs.

bannerAds