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.
Components Needed
- Arduino (e.g., Uno, Nano)
- LED
- 220-ohm resistor
- Jumper wires
Circuit Setup
- Connect the long leg (anode) of the LED to pin 9 on the Arduino.
- Connect the short leg (cathode) of the LED to one end of the 220-ohm resistor.
- Connect the other end of the resistor to GND on the Arduino.
Ensure the LED is correctly wired before uploading the code.
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:
analogWrite()
: Used to write a PWM value (0-255) to the LED, controlling its brightness.- The
for
loop increases the brightness from 0 to 255, then decreases it back to 0, creating a fade effect. delay(10)
: Adds a small delay between steps to control the fade speed.
Troubleshooting
- If the LED is not lighting up, check the wiring and ensure that the correct PWM pin (9) is used.
- If the LED is not dimming, verify that the LED is connected to a PWM-capable pin (pins 3, 5, 6, 9, 10, 11 on the Arduino Uno).