Adjust the brightness of an LED with an Arduino
Arduino Uno tutorials
🕑 This lesson will take about 10 minutes
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) pins to adjust the brightness of the LED. This works by the Arduino repeatedly switching 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 lesson, we will look at how to use PWM to adjust the brightness of an LED.
The Arduino provides PWM (Pulse Width Modulation) that 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 digital pins do not support PWM output.
To change the brightness of your LED, you will need to connect your LED to one of the six available PWM pins. You will also need to modify your code to use the analogWrite() function instead of the digitalWrite() function. The analogWrite() function accepts a value (between 0 and 255) that represents brightness, rather than values HIGH or LOW.
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, for example.
Required parts
Arduino Uno
1 x LED (any colour)
1 x resistor (can be any value between 100 Ohms and ~10K Ohms). We will use a 220 Ohm resistor in this example.
2 x male-to-male jumper wire
Wiring schematic
Connect the short pin of the LED to one of the GND (ground) slots on the Arduino via a breadboard.
Connect the long pin of the LED to one of the PWM pins (with ~ next to their number) on the Arduino via a resistor (any value between 200 and 10k Ohm eg. a 220 Ohm resistor) on the breadboard. In the example, we will connect the long pin of the LED to digital pin 5 on the Arduino.
The code
Example 1 - setting a specific brightness
In the example code below, we will just set the brightness of the LED to be a specific value (eg. 80). Remember, the brightness value must be between 0 and 255.
Example 2 - adjust brightness gradually using a loop
In the example below, we will use a loop to gradually increase the brightness of the led until it has reached maximum brightness, and then gradually decrease the brightness until it has reached minimum brightness (then repeat this process again). This will make the LED gradually fade off and on.