UART — pymcu.hal.uart#
from pymcu.hal.uart import UART
Serial communication over USART0. UART is an @inline class — it compiles to USART register
writes with zero SRAM allocation.
class UART#
UART(baud=9600)#
Initializes the hardware UART peripheral. On AVR, configures USART0.
Baud rate |
UBRR0 (16 MHz) |
|---|---|
9600 |
103 |
19200 |
51 |
38400 |
25 |
57600 |
16 |
115200 |
8 |
Methods#
Method |
Description |
|---|---|
|
Send a single byte (blocks until UDRE0 is set) |
|
Receive a byte (blocks until RXC0 is set) |
|
Non-blocking read; returns byte if available, else 0 |
|
Poll RXC until byte arrives and return it |
|
Direct UDR0 read for use inside |
|
Returns 1 if a byte is waiting in the receive buffer |
|
Send a flash string via LPM loop |
|
|
|
Print |
|
Read until |
|
Enable RXC interrupt (RXCIE0 in UCSR0B) |
|
ISR body: reads UDR0 into ring buffer |
Examples#
Hello, world#
from pymcu.hal.uart import UART
uart = UART(9600)
uart.println("hello")
Send and receive bytes#
from pymcu.hal.uart import UART
from pymcu.types import uint8
uart = UART(9600)
uart.write(65) # sends 'A'
b: uint8 = uart.read() # blocking receive
uart.write(b) # echo back
Echo loop#
from pymcu.hal.uart import UART
from pymcu.types import uint8
def main():
uart = UART(9600)
while True:
b: uint8 = uart.read()
uart.write(b)
Non-blocking receive with walrus#
from pymcu.hal.uart import UART
from pymcu.types import uint8
def main():
uart = UART(9600)
while True:
if c := uart.read_nb(): # walrus: assign and test in one
uart.write(c)
Interrupt-driven ring buffer#
from pymcu.hal.uart import UART
from pymcu.types import uint8
uart = UART(9600)
@interrupt(0x0018) # USART0 RX Complete (ATmega328P)
def on_rx():
uart.rx_isr() # stores byte in ring buffer
def main():
uart.enable_rx_interrupt()
while True:
if uart.available():
b: uint8 = uart.read_nb()
uart.write(b)
Read a line of text#
from pymcu.hal.uart import UART
from pymcu.types import uint8
uart = UART(9600)
buf: uint8[64] = [0] * 64
def main():
uart.println("send a line:")
while True:
n: uint8 = uart.read_line(buf, 64) # blocks until '\n' or 64 bytes
for i in range(n):
uart.write(buf[i]) # echo line back
read_line reads bytes until a \n (0x0A) is received or max_len bytes have been
stored — whichever comes first. The newline is not stored in the buffer. Returns the
number of bytes written.