Arduino Experiment: PWM to Control LED Brightness

Difficulty Level: Beginner

In this tutorial, you'll learn how to control the brightness of an LED using PWM (Pulse Width Modulation) on an Arduino. PWM allows you to adjust the power supplied to the LED, which in turn adjusts its brightness.

Required Components

Wiring Instructions

Code Explanation

This code uses PWM to fade the LED brightness. The LED is connected to pin 9 (a PWM pin), and the brightness is adjusted by varying the duty cycle of the PWM signal. The brightness increases and decreases repeatedly, creating a fade effect.

Key Functions

Arduino Code

The following code adjusts the brightness of an LED connected to pin 9 using PWM:


// PWM control of LED brightness
int ledPin = 9;  // Pin connected to the LED
int brightness = 0;  // Initial brightness
int fadeAmount = 5;  // Amount to increase/decrease brightness by

void setup() {
  // Set pin 9 as output
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // Set the brightness of pin 9 (PWM pin)
  analogWrite(ledPin, brightness);

  // Change the brightness
  brightness += fadeAmount;

  // Reverse fade direction at limits
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;  // Reverse the direction
  }

  // Delay for smooth fading
  delay(30);
}
            

Upload and Test

  1. Connect your Arduino to your computer using the USB cable.
  2. Open the Arduino IDE and copy the code above into the editor.
  3. Select the correct board and port in the IDE.
  4. Click the upload button to send the code to the Arduino.
  5. Observe the LED fade in and out smoothly as the brightness is controlled via PWM.

Optional: Potentiometer for Manual Control

If you want to manually control the brightness using a potentiometer, modify the code as shown below:


int potPin = A0;  // Potentiometer connected to analog pin A0
int ledPin = 9;

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

void loop() {
  int potValue = analogRead(potPin);  // Read the potentiometer value (0-1023)
  int brightness = map(potValue, 0, 1023, 0, 255);  // Map to PWM range (0-255)
  analogWrite(ledPin, brightness);  // Set LED brightness
}
            

Conclusion

In this experiment, you learned how to control the brightness of an LED using PWM on an Arduino. PWM is a versatile technique for controlling the speed of motors, brightness of LEDs, and more. By changing the duty cycle of the PWM signal, you can control how much power is delivered to the component.