0
0
Raspberry Piprogramming~30 mins

LED toggle with button in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
LED toggle with button
📖 Scenario: You have a Raspberry Pi connected to an LED and a button. You want to control the LED so that each time you press the button, the LED turns on if it was off, and turns off if it was on.
🎯 Goal: Build a Python program that reads the button press and toggles the LED state accordingly.
📋 What You'll Learn
Use the gpiozero library to control the LED and button.
Create an LED object connected to GPIO pin 17.
Create a Button object connected to GPIO pin 2.
Toggle the LED state each time the button is pressed.
Print LED is ON or LED is OFF after each toggle.
💡 Why This Matters
🌍 Real World
This project shows how to control physical devices like LEDs using buttons, which is common in home automation and interactive electronics.
💼 Career
Understanding GPIO control and event-driven programming is useful for embedded systems, IoT development, and hardware prototyping jobs.
Progress0 / 4 steps
1
Set up LED and Button objects
Import LED and Button from gpiozero. Create an LED object called led connected to GPIO pin 17. Create a Button object called button connected to GPIO pin 2.
Raspberry Pi
Need a hint?

Use from gpiozero import LED, Button to import. Then create led = LED(17) and button = Button(2).

2
Create a function to toggle the LED
Define a function called toggle_led that toggles the led state. Inside the function, use led.toggle() to change the LED state. Then use an if statement to print LED is ON if led.is_lit is True, otherwise print LED is OFF.
Raspberry Pi
Need a hint?

Define toggle_led() that calls led.toggle(). Use if led.is_lit: to check LED state and print the correct message.

3
Connect the button press to toggle the LED
Use button.when_pressed = toggle_led to call the toggle_led function each time the button is pressed.
Raspberry Pi
Need a hint?

Assign toggle_led to button.when_pressed to run the function on button press.

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

Use from signal import pause and call pause() to keep the program running.