import serial
import time
# 打开串口
ser = serial.Serial(
port='COM3', # 设置串口号,例如 'COM3' 或 '/dev/ttyUSB0'
baudrate=9600, # 波特率
parity=serial.PARITY_NONE, # 校验位
stopbits=serial.STOPBITS_ONE, # 停止位
bytesize=serial.EIGHTBITS, # 数据位
timeout=1 # 超时设置
)
if ser.is_open:
print("串口打开成功")
else:
print("串口打开失败")
try:
while True:
if ser.in_waiting > 0: # 检查串口缓冲区是否有数据
data = ser.readline() # 读取一行数据
print("收到的数据:", data.decode('utf-8')) # 解码并打印数据
time.sleep(0.1) # 短暂休眠,防止CPU占用过高
except KeyboardInterrupt:
print("程序终止")
finally:
ser.close() # 关闭串口
print("串口已关闭")
serial 和 time 模块。serial.Serial() 方法配置串口的端口号、波特率、校验位、停止位、数据位和超时设置。ser.readline() 方法从串口读取数据,并解码为字符串后打印出来。KeyboardInterrupt 异常,允许用户通过 Ctrl+C 终止程序。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站