5.4.2 Project 1.2 Breathing LED

1. Description

A“breathing LED”is a phenomenon where an LED’s brightness smoothly changes from dark to bright and back to dark, continuing to do so and giving the illusion of an LED“breathing. However, how to control LED’s brightness?

It makes sense to take advantage of PWM. Output the number of high level and low level in unit time, the more time the high level occupies, the larger the PWM value, the brighter the LED.

image36

We provide the PWM output library file < analogwrite.h > for ESP32, therefore solely a simple statement analogWrite(); can control the PWM output.

2. Test Code

#include <Arduino.h>
#define led_y 12    // Define LED pin

void setup()
{
  pinMode(led_y, OUTPUT);  // Set pin as output mode
}

void loop()
{
  for(int i = 0; i < 255; i++)  // For loop: increment variable i until it reaches 255
  {
    analogWrite(led_y, i);  // PWM output to control LED brightness
    delay(3);
  }

  for(int i = 255; i > 0; i--)  // For loop: decrement variable i until it reaches 0
  {
    analogWrite(led_y, i);
    delay(3);
  }
}

3. Test Result

The LED gradually gets dimmer then brighter, cyclically, like human breathe.