Skip to content

Digital Inputs (Button Press)

Glenn Salaman edited this page Feb 25, 2021 · 2 revisions

One way to get user input is to connect a button to one of our digital ports. We configure that port to be "pulled up" (meaning that it's default state is "HIGH"), and then attach one end of the button to that port, and the other end to Ground. By doing this, when the button is pressed, that pin will read "LOW", and when it's not pressed, it will read "HIGH".

Let's see this in action! We'll use this button press to light an LED, and we'll count how many times the button is pressed.

We start by defining the two pins we're going to use for the button and LED:

#define BUTTON_PIN  3
#define LED_PIN     8

...and then, in setup, we need to tell the Uno to make that button pin "pulled up":

  pinMode(BUTTON_PIN, INPUT_PULLUP);

To read a pin, we use "digitalRead" like so:

  int button_state;
  
  button_state = digitalRead(BUTTON_PIN);

Arduino defines two constants for us: HIGH and LOW. The variable button_state will contain one of those constants, depending on whether the button is pushed or not.

Now, to light the LED, we'll do that read in our "loop" function, and use it's result to light the LED. Remember to put a resistor either before or after the LED going to ground...

  // We want our LED on when the button is pressed, and off when
  // it's not.  Since we've got a pull-up resistor, the line is LOW
  // when it's pressed and HIGH when it's not.
  digitalWrite(LED_PIN, !button_state);

Full sketch, with code to also count the number of presses is here.

A couple notes: Since we're only counting presses, we need to look for transitions on the button from "HIGH" (unpressed) to "LOW" (pressed).

We've got a 1 second delay each time through the loop...meaning that we'll only check the button once per second.