Creating a Fading Effect
We see how to use an analogwrite() function in order to implement a fading ON/OFF of an LED. The function incorporates PWM pulses across a pinout for accomplishing the suggested fading action over the connected LED.
Along with your Arduino, other materials such as a breadboard, an LED and a 220 ohm, 1/4 wat resistor would be required for the experiment.
The steps involved for the proposed LED ON/OFF fading with an Arduino are as follows:
1. Attach the longer terminal of the LED to the digital output pin#9 via the 220 ohm resistor in series, while the cathode or the shorter terminal of the LED with the ground directly or the negative supply rail
For initiating a fading ON/OFF effect on the connected LED, the PWM could be consistently varied from zero to maximum or to 255 and vice versa, completing the entire single cycle of operation.
The code below shows the PWM magnitude being determined through a variable named as brightness. Also the it increments by variable fadeAmount in the loop.