0
0
Raspberry Piprogramming~30 mins

Button class with callbacks in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
Button class with callbacks
📖 Scenario: You are building a simple program to handle button presses on a Raspberry Pi. Buttons can do different things when pressed, so you want to create a Button class that can run a special function (called a callback) whenever the button is pressed.This is like having a doorbell that plays a different sound depending on who is at the door. The button press triggers the sound.
🎯 Goal: Create a Button class that stores a callback function. When the button is pressed, it should run the callback. You will then create a button instance, assign a callback, and simulate a button press to see the callback run.
📋 What You'll Learn
Create a Button class with an __init__ method that takes a callback parameter and stores it.
Add a press method to the Button class that calls the stored callback function.
Create a function called say_hello that prints 'Hello! Button pressed.'.
Create a Button instance called button with say_hello as the callback.
Call the press method on the button instance to run the callback.
Print the output of the callback when the button is pressed.
💡 Why This Matters
🌍 Real World
Buttons on Raspberry Pi or other devices often need to run specific code when pressed. Using callbacks lets you easily change what happens without rewriting the button code.
💼 Career
Understanding callbacks and event-driven programming is important for embedded systems, hardware interfacing, and GUI programming jobs.
Progress0 / 4 steps
1
Create the Button class with callback storage
Create a class called Button with an __init__ method that takes a parameter called callback and stores it in self.callback.
Raspberry Pi
Need a hint?

Remember, __init__ is the method that runs when you create a new object. Store the callback function in self.callback.

2
Add the press method to call the callback
Add a method called press to the Button class that calls the stored callback function using self.callback().
Raspberry Pi
Need a hint?

The press method should run the callback function stored in self.callback. Just call it like a normal function.

3
Create a callback function say_hello
Create a function called say_hello that prints 'Hello! Button pressed.' when called.
Raspberry Pi
Need a hint?

Define a simple function that prints the message exactly as shown.

4
Create Button instance and press it to run callback
Create a Button instance called button with say_hello as the callback. Then call button.press() to run the callback and print the message.
Raspberry Pi
Need a hint?

Create the button with say_hello as callback and call press() to see the message.