Arduino PWM LED Brightness Control

Difficulty Level: Beginner

In this experiment, you’ll learn how to control the brightness of an LED using Pulse Width Modulation (PWM) on an Arduino. PWM allows you to simulate an analog output using digital pins by varying the duty cycle of the signal.

Needed Components with eBay Links

Wiring the LED

To control the LED brightness, connect the components as follows:

Understanding PWM and Code

PWM is used to create a pseudo-analog signal by switching the digital pin on and off rapidly. The proportion of "on time" to "off time" determines the brightness of the LED. In Arduino, we use the analogWrite() function to control PWM-enabled pins (pins 3, 5, 6, 9, 10, and 11 on most Arduino boards).

Main Functions

Arduino Code

Here’s the code to control the LED brightness:


// PWM LED Brightness Control Experiment

int ledPin = 9;  // Pin connected to the LED
int brightness = 0;  // Initial brightness level
int fadeAmount = 5;  // Amount to increase/decrease brightness

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

void loop() {
  // Set the brightness of the LED
  analogWrite(ledPin, brightness);

  // Change brightness level
  brightness = brightness + fadeAmount;

  // Reverse the direction if we reach the ends (0 or 255)
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }

  // Pause briefly between changes
  delay(30);
}
                

Upload & Test

  1. Connect your Arduino to your computer using a USB cable.
  2. Open the Arduino IDE and copy the code above into the editor.
  3. In the IDE, select your board and the correct port.
  4. Upload the code by clicking the upload button.
  5. Observe how the LED gradually fades in and out, simulating smooth brightness control.

Code Breakdown

In the setup() function, the LED pin is set as an output using pinMode(ledPin, OUTPUT). In the loop() function, the brightness is adjusted using the analogWrite() function, which outputs a PWM signal to the LED. The brightness increases or decreases by the value of fadeAmount in each iteration, and when it reaches 0 or 255, the direction of the change is reversed.

Conclusion

This experiment demonstrates how to control the brightness of an LED using PWM and the analogWrite() function on an Arduino. By understanding PWM, you can control the speed of motors, adjust the intensity of lights, and more in your projects.