Raspberry Pi - Button - LED
This tutorial instructs you how to use the Raspberry Pi and button to control the LED. We will learn two different applications:
Application 1 - The LED state is synchronized with the button state. In detail:
- Raspberry Pi turns on the LED when the button is being pressed.
- Raspberry Pi turns off the LED when the button is NOT being pressed.
Application 2 - The LED state is toggled each time the button is pressed. More specifically:
- If Raspberry Pi detects that the button has been pressed (changing from a HIGH state to a LOW state), it will turn ON the LED if it's currently OFF, or turn OFF the LED if it's currently ON.
- Releasing the button does not affect to the LED state.
In the Application 2, We need to debounce the button to make sure it works properly. We'll figure out why it's important by comparing how the LED behaves when we use the Raspberry Pi code with and without debouncing the button.
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.
Additionally, some of these links are for products from our own brand, DIYables.
Wiring Diagram
This image is created using Fritzing. Click to enlarge image