使用串口通过 USB 发送和接收数据

问题描述 投票:0回答:1

我正在尝试定期将数据从我的 PC 发送到 Raspberry Pi Pico。

PC 正在运行此代码:

import serial
import time

# Define the serial port and baud rate (adjust as needed)
serial_port = 'COM12'  # Replace 'X' with the actual COM port number
baud_rate = 9600

try:
    # Open the serial port
    ser = serial.Serial(serial_port, baud_rate, timeout=1)
    print(f"Connected to {serial_port} at {baud_rate} baud")

    while True:
        # Data to send to the Raspberry Pi Pico
        data_to_send = "Hello, Raspberry Pi Pico!\n"
        
        # Send the data
        ser.write(data_to_send.encode())
        
        # Wait for a while before sending again (adjust as needed)
        time.sleep(2)

except serial.SerialException as e:
    print(f"Error: {e}")
finally:
    ser.close()

当我运行上面的代码时,它在控制台中显示“以 9600 波特率连接到 COM12”。所以我希望它能正常运行。

Pico 正在运行此代码:

import machine
from machine import Pin
import time
import sys


led = Pin(25, Pin.OUT)
# Create a UART object on UART0 (default Pico UART)
uart = machine.UART(0, baudrate=9600)

while True:
    try:
        data = uart.readline()
        if data:
            print(data.decode('utf-8'), end='')  # Print received data
            led.toggle()
    except KeyboardInterrupt:
        sys.exit()
    except Exception as e:
        print(f"Error: {e}")
    
    time.sleep(0.1)  # Adjust the sleep time as needed

为了简单调试,我在 Pico 代码中添加了 LED 开关,以了解何时收到数据,但 LED 在代码运行时保持亮起状态,并永远保持这种状态。我期望看到的是每 2 秒打开和关闭一次。

Pico 代码被命名为 main.py,以使代码在 pico 通电时自动运行。

python serial-port pyserial micropython raspberry-pi-pico
1个回答
0
投票

这是与 通过 Raspberry Pi Pico USB 电缆读取/写入数据

相同/相似的问题

通过使用

machine.UART
,您可以利用原始 UART 连接,而不是 USB 端口。如果您确实想使用 UART,则必须连接 UART-USB 转换器,例如 CP2102 或类似于 Pico 上的相应引脚,请参阅 RP2 MicroPython 文档

© www.soinside.com 2019 - 2024. All rights reserved.