Blinky
The classic first program: blink an LED on and off.
Hardware
- Any ESP32 board with a built-in LED, or an external LED connected to a GPIO pin
- USB-C cable
Wiring an external LED
Connect the LED's longer leg (anode) to GPIO 20 through a 220-ohm resistor. Connect the shorter leg (cathode) to GND. If your board has a built-in LED, check the board documentation for its pin number.
Code
import {digitalWrite, pinMode} from 'mikrojs/pin'
import {sleep} from 'mikrojs/sleep'
import {memoryUsage} from 'mikrojs/sys'
const mem = memoryUsage()
console.log('free heap:', (mem.heapTotal - mem.heapUsed) / 1000 + 'KB')
let value: 0 | 1 = 0
const PIN = 20
pinMode(PIN, 'OUTPUT').orPanic('Failed to configure LED pin')
while (true) {
value = value === 0 ? 1 : 0
console.log(value ? 'ON' : 'OFF')
const mem = memoryUsage()
console.log('free memory', (mem.heapTotal - mem.heapUsed) / 1000 + 'KB')
const writeResult = digitalWrite(PIN, value)
if (!writeResult.ok) {
console.error('Write failed:', writeResult.error.name)
}
await sleep(1000)
}Walkthrough
Memory check.
memoryUsage()reports heap usage at startup. Useful for spotting leaks over time.Pin setup.
pinMode(PIN, 'OUTPUT')configures GPIO 20 for output..orPanic()crashes with a clear message if this fails (e.g., invalid pin number).Main loop. Toggles the pin between HIGH and LOW every second.
digitalWritereturns aResult, so the code checks.okand logs the error variant name if it fails.Async delay.
await sleep(1000)pauses for 1 second.
Run it
npx mikro dev
You should see the LED blinking and memory usage printed to the console every second.