PWM with LEDs

Pulse Width Modulation (PWM) with LEDs Experiment

Introduction

In this experiment, we will use Pulse Width Modulation (PWM) to control the brightness of an LED. PWM allows you to adjust the brightness by varying the duty cycle of the signal sent to the LED.

LED with PWM Control

Components Needed

Circuit Setup

  1. Connect the long leg (anode) of the LED to pin 9 on the Arduino.
  2. Connect the short leg (cathode) of the LED to one end of the 220-ohm resistor.
  3. Connect the other end of the resistor to GND on the Arduino.

Ensure the LED is correctly wired before uploading the code.

LED PWM Circuit Setup

Code for PWM with LEDs

Upload the following code to your Arduino to control the LED brightness with PWM:


int ledPin = 9;  // Pin connected to the LED

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

void loop() {
  // Fade the LED in and out
  for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(ledPin, brightness);  // Set LED brightness
    delay(10);  // Wait for 10 milliseconds
  }
  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(ledPin, brightness);  // Set LED brightness
    delay(10);  // Wait for 10 milliseconds
  }
}
            

Explanation

This code uses PWM to gradually increase and decrease the brightness of the LED. Here's how the code works:

Troubleshooting