Arduino Buttons

1. Every GPIO-pin (when configured as an input line) can be optionally connected with an internal pull-up resistor (Fig-1). In that case, there is no need to use external pull-up or pull-down resistors.

sw1led1D
Figure-1:

2. The following sketch checks that Button is closed and then turns on Led3.

#define Button 12  //GPIO-12
#define Led3 4

void setup()
{
    Serial.begin(115200);
    pinMode(Button, INPUT_PULLUP);    //internal pull-up is connected
    pinMode(Led3, OUTPUT);
    digitalWrite(Led3, LOW);    //Led3 is OFF
}

void loop()
{
    if(digitalRead(Button) == LOW)  //when Button is closed, logic level at Dpin-12 is LOW
    {
          digitalWrite(Led3, HIGH);  //Led3 is ON
          while(1);    //wait for ever
    }
}

3. Button is a mechanical switch, and it makes hundreds of make-and-break events before settling at the final closed position. This behavior is known as bouncing. If you want to detect the final state of the Button once bouncing has disappered, you may apply software debouncing by including the Debounce.h Library in the sketch. Here is the sketch that detects the closed condition of the debounced Button.

#include<Debounce.h>
Debounce Button(12);       //Here, Button is an objcet attached with DPin-12
#define Led3 4

void setup()
{
    Serial.begin(115200);
    pinMode(12, INPUT_PULLUP);    //internal pull-up is connected
    pinMode(Led3, OUTPUT);
    digitalWrite(Led3, LOW);    //Led3 is OFF
}

void loop()
{
    if(!Button.read() == LOW)  //when Button is closed, logic level at Dpin-12 is LOW
    {
          digitalWrite(Led3, HIGH);  //Led3 is ON
          while(1);    //wait for ever
    }
}
1 Like