This example illustrates how to use analog output to fade an LED.
This example shows how to use the "analogWrite()" function to fade an LED on and off using pulse width modulation (PWM), which rapidly switches a digital pin between on and off states to create a fading effect.
Arduino board
LED
220 ohm resistor
hook-up wires
breadboard
Connect the +ve of your LED to digital output pin 9 on your board through a 220 ohm resistor. Connect the -ve directly to ground.
Code:
In the main loop of your code, the "analogWrite()" function requires two arguments: the pin number to write to and the PWM value to be written.
To fade the LED on and off, the (PWM) value is gradually increased from 0 (completely off) to 255 (fully on), and then decreased back to 0 to complete the cycle. In the sketch, this is achieved by adjusting a variable called "brightness" within the loop, where it increments by the value of "fadeAmount" with each iteration.
When the "brightness" variable reaches either extreme (0 or 255), the "fadeAmount" variable changes its sign. For example, if "fadeAmount" is 5, it becomes -5, and vice versa. This change in "fadeAmount" reverses the direction of the "brightness" change in the next iteration of the loop.
The speed of the fading effect can be adjusted by modifying the delay value at the end of the sketch after using the "analogWrite()" function to change the PWM value rapidly. Experiment with different delay settings to observe variations in the fading effect.
// the setup function runs once when you press reset or power the board
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop()
{
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(10); // wait for a second
}
If you have completed this successfully, move on to the next step.