Description#

Your Arduino comes with a variety of cool features and one of them is the ability to dim LEDs. This is a simple example of how you can use the analogWrite() function to dim an LED connected to one of the PWM pins on your Arduino.

What is PWM you may ask? PWM stands for Pulse Width Modulation. It is a technique used to generate analog-like signals using digital means. You can read more about PWM here. Your Arduino comes with a specific series of pins that support PWM. These pins are usually marked with a ~ (tilde) symbol. To find ones for your specific Arduino model, check the table here.

The code below will gradually increase the brightness of an LED from 0 to 255 and then decrease it back to 0 by looping through those values. The analogWrite() function is used to set the brightness of the LED. The delay() function is used to control the speed of the dimming effect.

Why is the range from 0 to 255? Because the analogWrite() function uses a range of 0 to 255 to control the brightness of the LED. 0 is off, and 255 is full brightness.

Code#

#define LED_PIN 11 // Be sure to use a PWM pin

void setup()
{
  pinMode(LED_PIN, OUTPUT);
}

void loop()
{
  for (int i = 0; i < 255; i++) {
    analogWrite(LED_PIN, i);
    delay(5);
  }
  for (int i = 255; i > 0; i--) {
    analogWrite(LED_PIN, i);
    delay(5);
  }
}