Hardware button

Hardware buttons work by opening/closing a circuit. This circuit is connected to a digital pin on the Arduino which is thus able to read the status of the button.

 

buttonThe resistor makes sure that the current is compatible with the Arduino’s digital pins. The code is very simple, and only concerns doing a boolean test on the value read from the digital pin.

const int buttonPin = 2;     // the number of the pushbutton pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialise the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  if (buttonState == HIGH) {
    // DO SOMETHING when button is pressed
  } else {
    // DO SOMETHING ELSE when the button is released
  }
}