Required Components
- 1 x Arduino (e.g., Uno)
- 1 x LED
- 1 x Resistor (220Ω)
- Potentiometer (optional, to manually control brightness)
- Breadboard and jumper wires
Wiring Instructions
- Connect the long leg (anode) of the LED to pin 9 of the Arduino (PWM pin).
- Connect the short leg (cathode) of the LED to one end of a 220Ω resistor.
- Connect the other end of the resistor to GND.
- If using a potentiometer, connect it to analog pin A0, VCC, and GND (optional).
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
analogWrite()
: Writes a PWM signal to a pin, with values from 0 to 255 representing the duty cycle (0 is fully off, 255 is fully on).pinMode()
: Sets a pin as an output or input. In this case, pin 9 is set as an output for the LED.delay()
: Pauses the program for a specified number of milliseconds. Here it controls the speed of the fade effect.
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
- Connect your Arduino to your computer using the USB cable.
- Open the Arduino IDE and copy the code above into the editor.
- Select the correct board and port in the IDE.
- Click the upload button to send the code to the Arduino.
- 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.