Tutorial 3- Button Input

In this tutorial, we will learn how to connect a button to the Raspberry Pi 5 and control use it to control an LED.

Introduction

Components Needed

ComponentQuantity
Raspberry Pi 51
Breadboard1
WiresSeveral
LED1
300 - 1K Ohm Resistor1
Components
Image credit: SunFounder

Fritzing Diagram

Connect the LCD to your Raspberry Pi as shown in the following diagram.

LED connected Raspberry Pi
Image credit: SunFounder

Code

from gpiozero import LED
from time import sleep

# Initialize an LED connected to GPIO pin 17 using the GPIO Zero library.
led = LED(17)


while True:
    # Turn on the LED and print a message to the console.
    led.on()
    print('LED ON')

    # Wait for 0.5 seconds with the LED on.
    sleep(0.5)

    # Turn off the LED and print a message to the console.
    led.off()
    print('LED OFF')

    # Wait for 0.5 seconds with the LED off.
    sleep(0.5)

Code Explanation

Importing Libraries

from gpiozero import LED
from time import sleep

from gpiozero import LED: This line imports the LED class from the gpiozero library, which is a simple and easy-to-use library to control GPIO devices on a Raspberry Pi. from time import sleep : This imports the sleep function from the time module, enabling us to pause the execution of the program for a specified amount of time.

Initializing the LED

led = LED(17)

led = LED(17): Here, an instance of the LED class is created and assigned to the variable led. This instance is connected to GPIO pin 17 on the Raspberry Pi. This means our program will control an LED connected to that specific pin.

Infinite Loop

while True:

while True: : This starts an infinite loop, allowing the code inside it to run repeatedly until the program is manually stopped (e.g., by pressing Ctrl+C).

Turning the LED On

led.on()
print('...LED ON')

led.on(): This method turns on the LED that is connected to GPIO pin 17. print(’…LED ON’) : This outputs the message “…LED ON” to the console, indicating that the LED has been turned on.

Delay After Turning On

sleep(0.5)

sleep(0.5): This pauses the execution of the program for 0.5 seconds while the LED remains on. It effectively keeps the LED illuminated for this duration.

Turning the LED Off

led.off()
print('LED OFF...')

led.off(): This method turns off the LED. print(‘LED OFF…’) : This outputs the message “LED OFF…” to the console, indicating that the LED has been turned off.

Delay After Turning Off

sleep(0.5)

sleep(0.5): Similar to the previous sleep(), this pauses the program for another 0.5 seconds while the LED remains off.

Summary

This code creates a simple blinking LED effect by turning the LED on for 0.5 seconds, turning it off for 0.5 seconds, and repeating this cycle indefinitely. The printed messages help in tracking the state of the LED in the console.

Feel free to ask if you need further clarification on any part!