[tool] uart

This commit is contained in:
IrvingGao 2024-06-26 12:20:40 +08:00
parent f4f45e1391
commit 6a4834a186
1 changed files with 32 additions and 0 deletions

32
tools/orangepi_uart5.py Normal file
View File

@ -0,0 +1,32 @@
import serial
import time
# UART配置
uart_port = '/dev/ttyS5' # UART端口路径
baud_rate = 115200 # 波特率
try:
# 初始化串口连接
ser = serial.Serial(uart_port, baud_rate, timeout=1)
print("UART初始化成功开始读取数据...")
while True:
# 尝试读取一行数据
data = ser.readline().decode('utf-8').strip() # 读取一行并解码
if data: # 如果读取到数据
try:
num = int(data) # 尝试将读取的数据转换为整数
print(f"接收到的数字: {num}")
except ValueError: # 如果转换失败,说明不是有效的数字
print("接收到的数据无法转换为数字")
time.sleep(1) # 每隔一秒检查一次新数据
except KeyboardInterrupt:
print("程序被中断正在关闭UART连接...")
ser.close()
print("UART连接已关闭。")
except Exception as e:
print(f"发生错误: {e}")
if 'ser' in locals():
ser.close()