PWM LED
A "breathing" LED effect: smoothly fades an LED in and out using PWM. See the pwm API reference for the full type surface.
Hardware
- Any ESP32 board with a GPIO pin that supports PWM
- An LED connected through a 220-ohm resistor
- USB cable
Code
import {Pwm} from 'mikro/pwm'
// GPIO 15 is the built-in LED on XIAO ESP32C6. Replace with your board's LED pin.
const LED_PIN = 15
const led = Pwm(LED_PIN, {freq: 50, duty: 0}).orPanic('Failed to set up the LED')
// Breathe: smoothly fade in and out forever
while (true) {
const fadeIn = await led.fade(1.0, 1000)
if (!fadeIn.ok) {
console.error('Fade in failed:', fadeIn.error)
break
}
const fadeOut = await led.fade(0.0, 1000)
if (!fadeOut.ok) {
console.error('Fade out failed:', fadeOut.error)
break
}
}Walkthrough
PWM setup.
Pwm(gpio, {freq, duty})claims the GPIO pin, creates a PWM channel on it and returns aResultwith the handle.freqsets the PWM frequency in Hz;dutysets the initial duty cycle (0.0 to 1.0).Hardware fading.
led.fade(target, durationMs)smoothly transitions the duty cycle totargetoverdurationMsmilliseconds. This runs in hardware on the ESP32's LEDC peripheral, so it does not block the event loop.Error handling. Both
fade()calls return aPromise<Result>(see Result). If something goes wrong (for example an invalid pin), the loop breaks with a clear error message.
Create project
pnpm create mikro --template pwm-lednpm create mikro -- --template pwm-ledyarn create mikro --template pwm-ledbun create mikro --template pwm-ledRun 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 LED fades smoothly in and out in a continuous breathing pattern.