TakwayBoard/tools/orangepi_uart5.py

40 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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:
# 尝试读取一行数据
ori_data = ser.readline() # 读取一行原始数据
print(f"原始数据: {ori_data}")
data = ori_data.decode('utf-8').strip() # 读取一行并解码
print(f"解码后数据: {data}, 类型: {type(data)}")
if data: # 如果读取到数据
try:
num = int(data) # 尝试将读取的数据转换为整数
print(f"接收到的数字: {num}")
# print(f"接收到的字符串: {data}")
battery_level = num / 4096 * 4.8 /4.2 * 100 # 计算电池电量
print(f"电池电量: {battery_level}%")
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()