Digital Input 

In this lesson we will use Bush button to turn ON/Off LED.The circuit below, is working as following, the Arduino waits for a LOW signal on PIN 9, this PIN comes LOW when the Push Button is pressed, where it shorts the path between the GND line and PIN 9. when PIN 9 is LOW PIN 8 is set to HIGH, and the LED is ON now, on the next LOW signal the LED goes OFF, and that's why we need the OnFlag to tell us the LED status. 

  Arduino Uno R3Arduino Uno R3 Microcontroller

  16.00 JD                  Add to cart

  T1 (3mm) LEDT1 (3mm) Blue LED (select color)

  00.05 JD                  Add to cart

  170 Tie-points Breadboard

170 Tie-points Breadboard

   1.60 JD                   Add to cart

  Tactile Push Button

Tactile Button

   0.15 JD                   Add to cart


Circuit

Just note that the LED Anode is connected to the Resistor. note that the bush putton should be connected as shown is circuit.

Code

int led =8;      // LED is Connected to PIN 8
int button =9;   // Pushbutton PIN is 9
int  OnFlag=0;   // Flag we need to tell if the LED is ON or OFF
void setup()
{
pinMode(led,OUTPUT); pinMode(button,INPUT_PULLUP); // Setting the PINs direction, we need to set PIN9 as output and the other PIN as input
}
void loop()
{
if(digitalRead(button)==LOW && OnFlag=0) // if the button is pressed and the LED is OFF then
{
delay(250);                          // 250 ms delay for debounce
digitalWrite(led,HIGH);              // Then Turn ON LED(Anode PIN of LED is connected to GND
OnFlag=1;                           // Set the Flag to 1
}
if(digitalRead(button)==LOW && OnFlag==1) // Now if the button is Pressed and the LED is ON
{
 delay(250);                               // 250 ms delay for debounce
digitalWrite(led,LOW);                    // Then Turn OFF LED
OnFlag=0;                                 // Clear the Flag to 0 

}
}