Monday, 22 September 2014

Reading a Push-Button with Arduino Uno

                   This example will explain you how to interface a Push Button(Push to ON switch) with Arduino UNO. The Push Button is connected to the Pin No.7 of Arduino and a LED is connected to the Pin No.13 of Arduino as shown in the Schematic below. A 1K ohm resistor is being used along with Push Button for connecting it to Pin no.7, this is to normally pull down the Pin No.7 to ground when the pin is not read otherwise the pin will foat sometimes and lead to wrong reading by Arduino.

                     Another 220 ohm resistor is also being used with LED, this is to limit the current to the LED approximately to 23mA (5V/220 ohm = 23 mA). After wiring the complete schematic, write the code shown below into the Arduino IDE and build it. Now, if you press the Push Button, immediately the LED becomes ON, if you leave the Push Button, immediately the LED becomes OFF.

Code 1:

// Reading a Push Button through Arduino UNO.
int ledPin = 13;                        // Pin for the LED
int inputPin = 7;                       // Pin for Push Button
int val = 0;                               // variable for reading the pin status

void setup()
{
pinMode(ledPin, OUTPUT); // configure ledPin as output
pinMode(inputPin, INPUT);  // configure inputPin as input
}

void loop()
{
val = digitalRead(inputPin);       // read input value
if (val == HIGH) // check if the input is HIGH (button released)
{
digitalWrite(ledPin, HIGH);       // turn LED ON
}
else
{
digitalWrite(ledPin, LOW);       // turn LED OFF
}
}

Same above code can be simply modified as for blinking of LED when the Push Butt
on is pressed totally OFF the LED when the Push Button is released from pressing.

Code 2:

// Reading a Push Button through Arduino UNO.
int ledPin = 13;                        // Pin for the LED
int inputPin = 7;                       // Pin for Push Button
int val = 0;                                // variable for reading the pin status

void setup()
{
pinMode(ledPin, OUTPUT);   // configure ledPin as output
pinMode(inputPin, INPUT);   // configure inputPin as input
}

void loop()
{
val = digitalRead(inputPin);   // read input value
if (val == HIGH) // check if the input is HIGH (button released)
{
digitalWrite(ledPin, HIGH);   // Blinking of LED starts here
delay(100);                              // set the delay of 100 milli Seconds for blinking
digitalWrite(ledPin, LOW);
delay(100);
}
else
{
digitalWrite(ledPin, LOW);  // turn LED OFF
}
}

No comments:

Post a Comment