Skip to content

Blinky

The classic first program: blink an LED on and off.

APIs used: pin, sys

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

ts
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

  1. Memory check. memoryUsage() reports heap usage at startup. Useful for spotting leaks over time.

  2. Pin setup. pinMode(PIN, 'OUTPUT') configures GPIO 20 for output. .orPanic() crashes with a clear message if this fails (e.g., invalid pin number).

  3. Main loop. Toggles the pin between HIGH and LOW every second. digitalWrite returns a Result, so the code checks .ok and logs the error variant name if it fails.

  4. 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.

View source on GitHub