Raspberry Pi Getting Started Tutorial 1 - Using Raspberry Pi to Control an LED with an External Switch

Using Raspberry Pi 5 to Control an LED with an External Switch

Introduction

Raspberry Pi 5 is a powerful single-board computer that can interface with various electronic components. In this tutorial, we will learn how to control an LED using an external push button switch. When the switch is pressed, the LED will turn on; when released, the LED will turn off.

Materials Needed

  1. Raspberry Pi 5 (with Raspberry Pi OS installed)

  2. Breadboard

  3. LED (any color)

  4. 220Ω resistor

  5. Push button switch

  6. 10kΩ pull-down resistor

  7. Jumper wires

Wiring Diagram

  1. Connect the LED’s anode (longer leg) to GPIO 18 through a 220Ω resistor.

  2. Connect the LED’s cathode (shorter leg) to the ground (GND) on the Raspberry Pi.

  3. Connect one leg of the push button to 3.3V on the Raspberry Pi.

  4. Connect the other leg of the push button to GPIO 23.

  5. Add a 10kΩ pull-down resistor between GPIO 23 and GND to ensure a stable low signal when the button is not pressed.

Setting Up the Raspberry Pi

Ensure that the Raspberry Pi is powered on and has Python installed. We will use the RPi.GPIO library to control the GPIO pins.

Python Code to Control LED

import RPi.GPIO as GPIO
import time

# Define GPIO pins
LED_PIN = 18
BUTTON_PIN = 23

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

try:
    while True:
        if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
            GPIO.output(LED_PIN, GPIO.HIGH)
        else:
            GPIO.output(LED_PIN, GPIO.LOW)
        time.sleep(0.1)

except KeyboardInterrupt:
    GPIO.cleanup()

Explanation of Code

  1. The RPi.GPIO library is used to interface with the GPIO pins.

  2.The LED is set as an output, and the button is set as an input with a pull-down                   resistor.

  3. In the loop, the program continuously checks if the button is pressed.

  4. If the button is pressed, the LED turns on; otherwise, it remains off.

  5. The try-except block ensures that GPIO cleanup occurs when the program is                  terminated.

Running the Script

  1. Save the script as led_control.py.

  2. Open the terminal and run:

   python3 led_control.py

  3. Press the button to turn on the LED.

Conclusion

This project demonstrates how to use a Raspberry Pi 5 to control an LED with an external switch. By understanding this setup, you can expand it to control other devices like buzzers, relays, or motors. Rapid Up!

 

Back to blog