Needed Components with eBay Links
Wiring the LED
To control the LED brightness, connect the components as follows:
- Connect the positive (long leg) of the LED to digital pin 9 through a 220Ω resistor.
- Connect the negative (short leg) of the LED to GND on the Arduino.
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
analogWrite(pin, value)
: Writes a PWM signal to a pin. The value can range from 0 (off) to 255 (fully on).delay(ms)
: Adds a delay to allow time between brightness changes.
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
- Connect your Arduino to your computer using a USB cable.
- Open the Arduino IDE and copy the code above into the editor.
- In the IDE, select your board and the correct port.
- Upload the code by clicking the upload button.
- 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.