Home Tutorials Fade an LED
Tutorials

Fade an LED

Use the ESP32 PWM surface to fade an LED with a named, current-Frothy wrapper.


This tutorial is board-specific. It uses the ESP32 PWM bindings exposed by the ESP32 path, not the first LED/button tutorial path. If you are using a first board, treat this as an advanced ESP32 exercise.

PWM works by switching a pin quickly enough that your eye sees average brightness. Higher duty means more on-time and a brighter LED.

Open a PWM Handle

Open one PWM channel on the built-in LED pin at 1 kHz. pwm.open returns a handle you pass back into later calls:

led is pwm.open: $led_builtin, 1000

Set the duty with pwm.write. Duty is parts-per-ten-thousand of each cycle spent on: 0 is off, 5000 is half, 10000 is fully on:

pwm.write: led, 0
pwm.write: led, 2500
pwm.write: led, 5000

Fade In Software

Start with a simple upward fade:

to fade.up with handle, step, delay [
  here duty is 0;
  while duty <= 10000 [
    pwm.write: handle, duty;
    wait: delay;
    set duty to duty + step
  ]
]

Then the downward half:

to fade.down with handle, step, delay [
  here duty is 10000;
  while duty >= 0 [
    pwm.write: handle, duty;
    wait: delay;
    set duty to duty - step
  ]
]

Run both:

fade.up: led, 200, 8
fade.down: led, 200, 8

Breathe

Compose the two halves:

to breathe with handle, count [
  repeat count [
    fade.up: handle, 200, 6;
    wait: 120;
    fade.down: handle, 200, 6;
    wait: 240
  ]
]

Try it:

breathe: led, 5

When you are done, close the handle:

pwm.close: led