Skip to content

Instantly share code, notes, and snippets.

@jg3
Created March 29, 2022 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jg3/57d0af75996ed4696aa91a6aa8d083af to your computer and use it in GitHub Desktop.
Save jg3/57d0af75996ed4696aa91a6aa8d083af to your computer and use it in GitHub Desktop.
Raspberry Pi buttons
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BCM) # Use Broadcom GPIO numbers
# not BOARD for pin numbers
# This example is based on using the buttons in this hardware:
# https://learn.adafruit.com/adafruit-2-2-pitft-hat-320-240-primary-display-for-raspberry-pi/
Button1 = 17 # Board pin 11
Button2 = 22 # Board pin 15
Button3 = 23 # Board pin 23
Button4 = 27 # Board pin 25
GPIO.setup(Button1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(Button2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(Button3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(Button4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True: # Run forever
if GPIO.input(Button1) == GPIO.LOW:
print("Button1 was pushed!")
if GPIO.input(Button2) == GPIO.LOW:
print("Button2 was pushed!")
if GPIO.input(Button3) == GPIO.LOW:
print("Button3 was pushed!")
if GPIO.input(Button4) == GPIO.LOW:
print("Button4 was pushed!")
@jg3
Copy link
Author

jg3 commented Apr 15, 2022

Note -- while this works, you should use gpiozero instead of RPi.GPIO as is done in this gist.
https://gpiozero.readthedocs.io/en/stable/api_input.html#button

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment