Adjusting the brightness of an LED

LEDs can be switched between HIGH (on) and LOW (off) states when they are connected to the Arduino’s digital pins. However, digital output can only be in either of two states (off or on / 0 or 1) which means that you cannot adjust the brightness of the LED using digital output.

However, you can use the Arduino’s PWM (Pulse Width Modulation) output to adjust the brightness of the LED which repeatedly switches between the HIGH and LOW states to gradually increase or decrease brightness. In other words, the LED brightness is adjusted by changing the duration of lighting. In this tutorial, we will look at how to use PWM to adjust the brightness of an LED.

The Arduino provides PWM (Pulse Width Modulation) which can output HIGH and LOW at different rates to adjust the LED brightness. However, only some pins on the Arduino provide PWM. These pins have a ~ symbol next to their number. The PWM pins are 3, 5, 6, 9, 10, and 11. The other pins do not support PWM output.

To change the brightness of your LED, you will need to connect your LED to one of the PWM pins. You will also need to modify your code to use the analogWrite() function instead of the digitalWrite() function.

The brightness can be set anywhere between the range of 0 to 255. 0 is LOW (no light), 255 is HIGH (full brightness), and 127 would be medium brightness.

Wiring schematic

Connect the long pin of the LED to one of the PWM pins (with ~ next to their number) on the Arduino. In the example, we will connect the long pin of the LED to pin 5. Then connect the short pin of the LED to GND (ground).

Screen Shot 2021-02-11 at 11.00.48 am

The code

In the example below, we will just specify the brightness for the LED.

int led_pin = 5;

int led_brightness = 80;

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

void loop(){
    analogWrite(led_pin, led_brightness);
}

In the example below, we will use a loop to gradually increase the brightness of the led by increasing the led_brightness variable.

int led_pin = 5;
int led_brightness = 0;

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

void loop(){
  // increase brightness value
  led_brightness = led_brightness + 1;

  // if maximum brightness reached, reset brightness to 0
  if(led_brightness > 255){
    led_brightness = 0;
  }

  // set the brightness of the led using the brtightness value
  analogWrite(led_pin, led_brightness);

  // set a delay before increasing brightness again
  delay(100);
}