Raspberry Pi GPIO tutorial How to control a button



In this tutorial we'll learn how to control a button using the GPIO and Python

Materiales:

- Raspberry Pi with Raspbian or similar

- Button

- 1K resistor

- 2 wires male/female

- Breadboard

The code to manage the button is:

import RPi.GPIO as GPIO


def button_pressed(data):
    data['remaining_clicks'] -= 1
    print("Remaining Clicks: {}".format(data['remaining_clicks']))


BUTTON_PIN = 12  # Set the button pin number into a variable

GPIO.setmode(GPIO.BOARD)  # Set GPIO mode to BOARD to use pin numbers
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Prepare button pin

data = {'remaining_clicks': 5}  # Create a dict because it's mutable

GPIO.add_event_detect(  # Detect button event on rising edge
    BUTTON_PIN, GPIO.RISING,
    callback=lambda x: button_pressed(data),  # Use lambda to pass parameters
    bouncetime=250  # Use bouncetime to avoid extra clicks
)

print("Exit script by pressing the button 5 times.")

while data['remaining_clicks'] > 0:
    pass

GPIO.cleanup()  # Clear GPIO

Here we can see the circuit between the rPi and the button:

circuit_button.png

Here you can see a video about how to assemble the circuit and run the code:

 

Leave a comment

You have to wait to comment again. Wait Time: