[ Raspberry Pi C ++ ] Push Buttons (Reading GPIO Input)

This post has been long overdue and will bring the GPIO tutorial to a close. We focus here on how to read input from external devices. This tutorial will keep things as basic as possible by using a simple push button.  

Previous Post: Our First LED

The push button used in this tutorial has four prongs/legs and looks as follows: 

Image of push Button
Example of a Push Button


Before we begin, there are two other components we require to complete our circuit… 1x 10kOhm resister and 1x 1kOhm resister 

The 1kOhm resister is simply used to dampen the voltage going from the 3.3V pin directly into the GPIO pin when the button is pressed.  

The 10kOhm resister plays a much more important role and is known as a “pull-down” resistor. It sits between an open (un-pressed) button and ground (GND). A pull-down resister is used to prevent erroneous reading from a GPIO pin on an open circuit. I would recommend to learn more about resistors.

A button in this un-pressed state (with a valid pull-down resister) will yield an input reading of 0 (LOW). 

Then when the button is pushed down, the voltage will flow from the 3.3V pin into the INPUT GPIO pin (whilst continuing through the 1kOhm resister) to give us a reading of 1 (HIGH).  

This is how your circuit should look: 

circuit diagram
Complete circuit diagram of push button with valid resistors


The code for this example is very simple (even more so than lighting up our first LED)

#include <stdio.h>
#include <wiringPi.h>

int main(int argc, char** argv)
    // Intialize the wiringPi Library

	const int INPUT_PIN = 12;
    // Read input on this pin
    pinMode(INPUT_PIN, INPUT);

        // As soon as we dedect an input, log and quit.
        if(digitalRead(INPUT_PIN) == HIGH)
			printf("Button is pressed!\n");	

    // Exit program
    return 0;
Reading GPIO Input with C++ and wiringPi

As always, see here on how to compile and run this code.

The code starts by flagging the pin to be used as an input. Later on we detect it’s reading via the digitalRead() function. This will return HIGH / LOW depending on the buttons pressed state.

The program will exit as soon as a HIGH input is received, shortly after printing that the button was pressed. The circuit between the GPIO pin and the 3.3V pin is compete when you press the button thus resulting in a HIGH read.

Earlier on in this post we talked about a pull-down resistor, and without it we may get erroneous reads through the GPIO pin.

I will leave this as a task to the reader, but I would suggest removing the pull-down resistor and tweaking the code to infinitely check the value of the input and see what happens.

Previous Post: Our First LED