uart-commandes.py

Raspberry Pi Pico · File : uart-commandes.py · Language : Python · Use case : Servir des commandes sur un port UART (module série, GPS...)

A mini command server on UART0 (GP0/GP1): classic serial modules (GPS, cellular modem, another microcontroller) can toggle the LED, read the temperature or poll the board with simple text lines.

Hardware

A Raspberry Pi Pico (RP2040 dual Cortex-M0+ @ 133 MHz) with MicroPython installed, powered over USB. A 3.3 V serial module or a USB-serial cable to test (never exceed 3.3 V on RX/TX).

Wiring

TX (GP0) to module RX, RX (GP1) to module TX, common grounds. Power the module at 3.3 V or add a level shifter.

How it works

uart.any() reports received bytes without blocking; the buffer is split on lines. Each command returns one reply line, a format that is easy to extend.

Running it

Install MicroPython if needed (hold BOOTSEL, plug USB, drop the .uf2 file), then copy the script to the board drive or via Thonny. The script auto-starts when named main.py.

Variants

Raise the baud rate (921600) for data streams, or move to UART1 (GP4/GP5) to keep the MicroPython shell on USB.

uart-commandes.py

# Serveur de commandes sur UART0 (GP0 = TX, GP1 = RX) a 115200 bauds.
# Permet de dialoguer avec un module serie (GPS, modem, autre carte).
from machine import UART, Pin
import machine
import time

uart = UART(0, baudrate=115200, tx=Pin(0), rx=Pin(1))

led = Pin(25, Pin.OUT)
buffers = b""

print("UART0 pret : 'l' bascule, 't' temperature, 's' etat")

def temperature():
    adc = machine.ADC(4)
    v = adc.read_u16() * 3.3 / 65535.0
    return 27.0 - (v - 0.706) / 0.001721

while True:
    if uart.any():                       # octets disponibles ?
        buffers += uart.read(uart.any())
        while b"
" in buffers:          # decoupage en lignes
            ligne, buffers = buffers.split(b"
", 1)
            cmd = ligne.strip().decode("utf-8", "ignore").lower()
            if cmd == "l":
                led.value(not led.value())
                uart.write("LED=%d
" % led.value())
            elif cmd == "t":
                uart.write("T=%.1f
" % temperature())
            elif cmd == "s":
                uart.write("OK uptime=%d
" % (time.ticks_ms() // 1000))
    time.sleep_ms(10)

← Back to the board