Tuesday 3 May 2016

Arduino Tutorial # 7 - Push Button - Fading a LED (PWM)




Introduction



This tutorial is related to earlier lesson. We will use the same push button setup to Fade a LED by using Pulse Width Modulation (PWM
). On Tutorial # 3 we discussed about PWM and we fade a LED using PWM. This time we will use a digital input to control the fading of a LED.

Parts you will need



1X Breadboard
1X LED
1X 1K Resister
1X 330Ω Resister
1X Push button
Jumper wires

Connections


  • Connect the led positive to 330Ω resister and other side of the resistor to Arduino pin 11. LED negative should connect to ground.
  • Connect one pin of the pushbutton to VCC (5v) and other to ground though 1K resister.
  • Connect Arduino pin 8 to the same pin of the pushbutton that we connect 1K resister.



Pull-down resister



When the pushbutton is not activated it's value is pull down to ground.This is because the input is "floating", that means when it is not connected to either VCC (5V) or to ground (0V) it will more or less randomly return either HIGH or LOW. That's why you need a pull-down resistor in the circuit.


Sketch


We are defining 5 variables. more details of the about variables please check my earlier tutorials.  

int ledPin = 11; // choose the pin for the LED
int inPin = 8;   // choose the input pin (for a pushbutton)
boolean lastButton = LOW; //tracking previous button
boolean currentButton =LOW; // track current button value

int ledLevel= 0; //to set the brightness 

The setup and debounce function as same as previous tutorial.

void setup() {
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}


boolean debounce(boolean last)
{
boolean current = digitalRead(inPin);
if (last != current)
{
delay(5);
current = digitalRead(inPin);
}
return current;
}


In loop()


We have to change few lines and the rest will remain the same as  Push Button Sketch 3. Please check Tutorial #6



void loop()
{
currentButton = debounce(lastButton);

if (lastButton == LOW && currentButton == HIGH)

{
// to increment the brightness value by 51 levels (you can choose any number)
ledLevel = ledLevel + 51;

}
lastButton = currentButton;

if (ledLevel > 255) ledLevel = 0;
// Check the ledLevel stay within 0-255 (tutorial #3)

analogWrite(ledPin, ledLevel);
}
Now if you can upload sketch to arduino. And you can see when pressing the button the LED brightness level is increasing.

You can download sketch from here - Download 

No comments:

Post a Comment