Skip to content

Pulsing an LED with ESPHome

Last updated on August 31, 2024

I might be dating myself, but I loved the way old Mac’s in my high school’s computer lab would pulse the LED when the unit was in standby mode. While I love how easy ESPHome makes it possible to make a wild variety of custom applications, smoothly pulsing an LED isn’t one of them.

I did some searching and found a good write up by SparkFun that walked you through a way of achieving it. Basically, you can leverage the sin function’s smooth output and appropriately scale/offset that output to drive your LED output.

Making it happen

The code below is running on my dining room switch as a lighting effect on a single pixel of WS2812. I’ve included some comments to help understand some of the pieces and how you can tailor it for your application.

light:
- platform: fastled_clockless
  chipset: WS2812B
  pin: GPIO2
  num_leds: 1
  rgb_order: GRB
  name: "${friendly_name} LED"
  id: status_led
  effects:
    - lambda:
        name: Pulse RED
        // SPEED
        update_interval: .05s
        lambda: |-
          static float in = 0;
          static float out = 0;
          
          // Scale sin output from -1/1 to 0/1
          out = sin(in) * 0.5 + 0.5;  

          auto call = id(status_led).turn_on();
          call.set_transition_length(100);
          // COLOR + BRIGHTNESS
          call.set_rgb(1.0, 0.0, 0.0);
          call.set_brightness(out);
          // Do not publish state to eliminate flooding of logs
          call.set_publish(false);
          call.set_save(false);
          call.perform();
          
          // RESOLUTION
          in += 0.314;
          if (in > 6.283)
            in = 0;
  • Speed
    • Change the update_interval to .15s to slow down the pulsing loop
  • Color & Brightness
    • Change the 1.0, 0.0, 0.0 to R, G, B color values (0-1.0) to set color and brightness
  • Resolution
    • Change the step size of the pulse loop

The pulsing glory

Here’s what it looks like in action:

Published inESPHome

Be First to Comment

Leave a Reply

Discover more from D Khaz

Subscribe now to keep reading and get access to the full archive.

Continue reading