0
0
Raspberry Piprogramming~30 mins

Button press detection in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
Button press detection
📖 Scenario: You have a Raspberry Pi connected to a physical button. When you press the button, the Raspberry Pi should detect the press and respond.
🎯 Goal: Build a simple program that detects when the button is pressed and prints a message.
📋 What You'll Learn
Use the gpiozero library to interact with the button.
Create a Button object connected to GPIO pin 2.
Detect when the button is pressed.
Print a message when the button is pressed.
💡 Why This Matters
🌍 Real World
Detecting button presses is common in physical computing projects like home automation, games, or interactive devices.
💼 Career
Understanding hardware input handling is useful for roles in embedded systems, IoT development, and robotics.
Progress0 / 4 steps
1
Set up the button
Import the Button class from the gpiozero library and create a button object connected to GPIO pin 2.
Raspberry Pi
Need a hint?

Use from gpiozero import Button and then button = Button(2).

2
Create a press handler
Define a function called on_press that prints "Button was pressed!" when called.
Raspberry Pi
Need a hint?

Define a function named on_press that prints the message.

3
Connect the handler to the button press
Assign the on_press function to the when_pressed property of the button object.
Raspberry Pi
Need a hint?

Use button.when_pressed = on_press to connect the function.

4
Keep the program running
Import pause from signal and call pause() to keep the program running and listening for button presses.
Raspberry Pi
Need a hint?

Use from signal import pause and then call pause() at the end.