Detecting a button press through GPIO using Raspberry pi

If you want to build electronic devices, at some point you’re going to need to read data through GPIO. In this exercise, we’re going to read the value of a push button on a breadboard.

Detecting a button press through GPIO

Set up the circuit as shown in the pictures on the right. Note that one end of the 4.7kOhm resistor connected to pin 23 is connected to the positive supply rail. The red jum[er cable links the positive rail on the breadboard to the 3.3V pin on the GPIO header. The green jumper wire connected to one of the pins on the button is connected to the negative rail on the breadboard, and there’s another jumper cable linking that negative supply rail to a GND pin on the GPIO header.

The resistor is used to pull up the voltage on pin 23 to logic 1. Without it, pin 23 would have an indeterminate value. When the button is pressed, pin 23 is connected directly to ground, so it switches to logic 0.

Save the following code in a file called

#!/usr/bin/env python

import time
import RPi.GPIO as GPIO

def main():

    # tell the GPIO module that we want to use the 
    # chip's pin numbering scheme

    # setup pin 25 as an output
Detecting a button press through GPIO
    while True:
        if GPIO.input(23):
             # the button is being pressed, so turn on the green LED
             # and turn off the red LED
             print "button true"
             # the button isn't being pressed, so turn off the green LED
             # and turn on the red LED

For more detail: Detecting a button press through GPIO

About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top