Fading and Blinking are two basic examples in Arduino. Fading uses analogWrite() function to fade the LED, ON and OFF. Whereas Blink uses the digitalWrite() function to turn the LED ON and OFF. You can view the desired outputs in the video at the end of the post or here
Fading a LED using Arduino
analogWrite() uses pulse width modulation (PWM), turning a digital pin on and off very quickly with different ratios between on and off, to create a fading effect.
Components Required
You will need the following components :
- 1 × Breadboard
- 1 × Arduino Uno R3
- 1 × LED
- 1 × 330Ω Resistor
- 2 × Jumper
Circuit Diagram
After you finish connecting the circuit. You can upload the code:
/*
Fade
This example shows how to fade an LED on pin 9 using the analogWrite() function.
The analogWrite() function uses PWM, so if you want to change the pin you're using, be
sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with
a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
*/
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(300);
}
For Code Explanation watch the video at the end of the post or Fading Code Explanation.
Blinking a LED using Arduino
Blinking a LED is the Hello World of Physical Computing.
Using same circuit diagram above you can now blink your LED by just uploading a new code to your Arduino.
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/
// the setup function runs once when you press reset or power the board
void setup() { // initialize digital pin 13 as an output.
pinMode(9, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(9, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
pinMode(9, OUTPUT) − Before you can use one of Arduino’s pins, you need to tell Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode() to do this.
digitalWrite(9, HIGH) − When you are using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts), or LOW (output 0 volts).
One Reply on “Easy way to Fade and Blink using Arduino – Simplified”