LEDs
Fading LED
This sketch demonstrates the basic implementation of how to set up and control a fading LED. This example requires a PWM-capable pin for brightness control.
The code
NOTE: Fading requires a PWM-capable pin. Create the LED with a maxBrightness parameter to enable PWM mode.
#include <CtrlLed.h>
// The pin of the board's built-in LED. Some boards (e.g. the ESP32 Dev Module)
// don't define LED_BUILTIN, so pin 2 is used there. Change it to match your wiring.
#ifdef LED_BUILTIN
const uint8_t LED_PIN = LED_BUILTIN;
#else
const uint8_t LED_PIN = 2;
#endif
// PWM mode example (PWM-capable pin with brightness control):
// This assumes you have connected your LED to a pin with PWM capabilities:
// The maximum brightness (second parameter) can be used to calibrate an LED,
// in case you are using multiple LEDs that have different maximum brightness.
CtrlLed led(LED_PIN, 50);
void setup()
{
// Turn on the LED and set the brightness to 0%.
led.turnOn();
led.setBrightness(0);
}
void loop() {
// Fade LED brightness from 0 to 100.
for (uint8_t brightness = 0; brightness < 100; brightness++) {
led.setBrightness(brightness);
delay(10); // Adjust the delay time to change the transition speed.
}
// Fade LED brightness from 100 to 0.
for (uint8_t brightness = 100; brightness > 0; brightness--) {
led.setBrightness(brightness);
delay(10); // Adjust the delay time to change the transition speed.
}
}