开发环境
MCU:双 Pico1(无wifi版),串口相连,需要共地 使用固件:自编译版本 开发环境:MacBook Pro Sonoma 14.5 开发工具:Thonny 4.1.6 开发语言:MicroPython 1.24.0
上位机
from machine import UART,Pin
# 初始化 UART
uart = UART(1, 9600, tx=Pin(4), rx=Pin(5))
def read_data():
buffer = b''
while True:
# 读取一行数据
line = uart.read(1) # 每次读取一个字节
if line:
print(line)
# 将读取到的字节添加到缓冲区
buffer += line
# 检查是否接收到标记符 '\n'
if line == b'\n':
# 去除标记符,并解码字节数据为字符串
data = buffer[:-1].decode('utf-8').strip()
print("Received data:", data)
# 清空缓冲区
buffer = b''
read_data()
下位机
from machine import UART, Pin
import time
# 初始化 UART
uart = UART(0, 9600) # 使用 gp0 (TX) 和 gp1 (RX)
def send_data():
while True:
# 模拟获取传感器数据
sensor_data = "Hello, UART!\n" # 示例数据
# 确保发送的数据是字节类型
uart.write(sensor_data.encode()) # 编码为字节
print(sensor_data.encode())
# 打印发送的数据(可选)
print("Sent data:", sensor_data)
time.sleep(2)
send_data()