UART
Send and receive serial data over UART. This example uses a loopback wiring (TX connected to RX) to verify that data written on one pin is read back on the other. See the uart API reference for the full type surface.
Hardware
- Any ESP32 board with two available GPIO pins
- One jumper wire connecting TX to RX
- USB cable
Code
import {sleep} from 'mikro/sleep'
import {Uart} from 'mikro/uart'
// UART loopback: connect TX (GPIO 16) to RX (GPIO 17) with a jumper wire
const TX_PIN = 16
const RX_PIN = 17
await sleep(2000)
const uart = Uart(1, {tx: TX_PIN, rx: RX_PIN, baudRate: 115200}).orPanic('Failed to start UART')
const message = new TextEncoder().encode('Hello from UART!\n')
uart.write(message).orPanic('Failed to write')
const reader = uart.read()
if (!reader.ok) {
console.error('Failed to start reading:', reader.error)
} else {
// Give data a moment to loop back
await sleep(1000)
for await (const chunk of reader.value) {
if (!chunk.ok) {
console.error('UART read error:', chunk.error)
break
}
console.log('Received: %s', new TextDecoder().decode(chunk.value))
}
}
uart.end()
console.log('Done!')Walkthrough
UART instance.
Uart(port, options)claims the pins, installs the driver and returns aResultwith the handle. Port1is used here (port0is typically reserved for the USB console). ThebaudRatemust match between sender and receiver.Lifecycle.
.orPanic()on the factory's Result gives a clear crash message if the port cannot start.uart.end()releases the port.Writing.
uart.write()sends aUint8Array. UseTextEncoderto convert strings to bytes.Reading.
uart.read()returns an async iterator that yieldsResult<Uint8Array, UartError>items. Check.okbefore reading.value; a non-ok chunk reports a read failure. The iterator completes whenuart.end()is called. UseTextDecoderto convert bytes back to strings.Loopback test. With TX wired to RX, the message you send is immediately received. This is a simple way to verify UART works before connecting to an actual peripheral.
Create project
pnpm create mikro --template uartnpm create mikro -- --template uartyarn create mikro --template uartbun create mikro --template uartRun it
pnpm install
pnpm mikro flash # only needed once per board
pnpm mikro devnpm install
npx mikro flash # only needed once per board
npx mikro devyarn install
yarn mikro flash # only needed once per board
yarn mikro devbun install
bunx mikro flash # only needed once per board
bunx mikro devThe console output shows "Hello from UART!" echoed back.