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:

Application 2 - The LED state is toggled each time the button is pressed. More specifically:

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

1×Raspberry Pi 4 Model B
1×Breadboard-mount Button with Cap
1×Breadboard-mount Button Kit
1×Panel-mount Push Button
1×LED
1×220 ohm resistor
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) USB-C Power Cable with On/Off Switch for Raspberry Pi 4B
1×(Optional) Plastic Case and Cooling Fan for Raspberry Pi 4B

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.

Overview of LED and Button

If you are unfamiliar with LED and button (including pinout, operation, and programming), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and Button LED

This image is created using Fritzing. Click to enlarge image

Application 1 - The LED state is in sync with the button state

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file button_led.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-button-led """ import RPi.GPIO as GPIO # Constants won't change. They're used here to set pin numbers: BUTTON_PIN = 16 # The number of the pushbutton pin LED_PIN = 18 # The number of the LED pin # Variables will change: button_state = 0 # Variable for reading the pushbutton status # Set up GPIO GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering GPIO.setup(LED_PIN, GPIO.OUT) # Initialize the LED pin as an output GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Initialize the pushbutton pin as a pull-up input try: while True: # Read the state of the pushbutton value: button_state = GPIO.input(BUTTON_PIN) # Control LED according to the state of the button if button_state == GPIO.LOW: # If the button is pressed GPIO.output(LED_PIN, GPIO.HIGH) # Turn on LED else: # Otherwise, the button is not pressed GPIO.output(LED_PIN, GPIO.LOW) # Turn off LED except KeyboardInterrupt: # Clean up GPIO on program exit GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 button_led.py
  • Press the button and hold it for a few seconds.
  • Check out the alteration in the LED's condition. You will see that the LED state is in sync with the button state.

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Application 2 - Button toggles LED

Detailed Instructions

  • Create a Python script file button_toggle_led.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-button-led """ import RPi.GPIO as GPIO import time # Constants won't change BUTTON_PIN = 16 # The number of the pushbutton pin LED_PIN = 18 # The number of the LED pin # Variables will change led_state = GPIO.LOW # The current state of the LED prev_button_state = GPIO.LOW # The previous state of the button button_state = GPIO.LOW # The current state of the button # Set up GPIO GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering GPIO.setup(LED_PIN, GPIO.OUT) # Initialize the LED pin as an output GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Initialize the pushbutton pin as a pull-up input try: while True: # Read the state of the pushbutton value prev_button_state = button_state # Save the last state button_state = GPIO.input(BUTTON_PIN) # Read new state if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: time.sleep(0.1) # 100 milliseconds debounce time print("The button is pressed") # Toggle the state of the LED if led_state == GPIO.LOW: led_state = GPIO.HIGH else: led_state = GPIO.LOW # Control LED according to the toggled state GPIO.output(LED_PIN, led_state) except KeyboardInterrupt: # Clean up GPIO on program exit GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 button_toggle_led.py
  • Press and release the button several times.
  • Check out the change in the LED's state. You will see that the LED's state is changed each time you press the button.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!