import time
from machine import UART
from machine import FPIOA
import os
# 初始化退出点检测
os.exitpoint(os.EXITPOINT_ENABLE)
# 配置引脚
fpioa = FPIOA()
fpioa.set_function(11, FPIOA.UART2_TXD)
fpioa.set_function(12, FPIOA.UART2_RXD)
try:
# 初始化UART2,波特率115200,8位数据位,无校验,1位停止位
uart = UART(UART.UART2, baudrate=115200, bits=UART.EIGHTBITS,
parity=UART.PARITY_NONE, stop=UART.STOPBITS_ONE)
print("UART2 初始化完成,等待数据...")
print("发送任何数据到UART2,将会回显相同内容")
while True:
os.exitpoint() # 检查退出信号
# 检查是否有可用数据
if uart.any():
# 读取所有可用数据
data = uart.read()
if data:
# 打印接收到的原始数据
print("接收原始数据:", data)
try:
# 尝试将数据解码为UTF-8字符串
decoded_data = data.decode('utf-8').strip()
print("解码数据:", decoded_data)
# 准备回显消息
response = f"UART2 已接收: {decoded_data} (长度: {len(data)} 字节)\n"
except UnicodeDecodeError:
# 如果解码失败,以十六进制格式显示
hex_data = ''.join(f'{b:02X} ' for b in data)
print("十六进制数据:", hex_data)
response = f"UART2 已接收二进制数据: {hex_data} (长度: {len(data)} 字节)\n"
# 发送回响应
uart.write(response.encode('utf-8'))
print("已发送回显")
# 短延时减少CPU占用
time.sleep_ms(10)
except KeyboardInterrupt:
print("程序被用户中断")
except Exception as e:
print(f"发生错误: {e}")
finally:
# 释放UART资源
if 'uart' in locals():
uart.deinit()
print("UART资源已释放")
os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
time.sleep_ms(100)
print("程序结束")
998




被折叠的 条评论
为什么被折叠?



