Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

šŸ‘‰ Ready to explore and create with us? Click [here] and join today!

Lesson 01: Button Module

In this lesson, you will learn the basics of using a button with Raspberry Pi. We will show you how to connect a button to GPIO pin 17 and write a simple Python script to monitor its state. You’ll learn how to program the Raspberry Pi to detect when the button is pressed and released, and respond with appropriate messages. This introductory project is an excellent way to get familiar with GPIO interaction and basic Python scripting, making it well-suited for beginners starting their journey in Raspberry Pi and hardware programming.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Universal Maker Sensor Kit

94

Universal Maker Sensor Kit

You can also buy them separately from the links below.

Component Introduction

Purchase Link

Raspberry Pi 5

BUY

Button Module

-

Breadboard

BUY

Wiring

../_images/Lesson_01_Button_Module_Pi_bb.png

Code

from gpiozero import Button

# Initialize button connected to GPIO pin 17
button = Button(17)

# Continuously check the button state
while True:
   if button.is_pressed:
      print("Button is pressed")  # Print when button is pressed
   else:
      print("Button is not pressed")  # Print when button is not pressed

Code Analysis

  1. Import Library

    Import the Button class from the gpiozero library for button control.

    from gpiozero import Button
    
  2. Initialize the Button

    Create a Button object connected to GPIO pin 17.

    button = Button(17)
    
  3. Monitor Button State Continuously

    Use a while True loop to continuously check the state of the button. If the button is pressed (button.is_pressed), it prints ā€œButton is pressedā€. Otherwise, it prints ā€œButton is not pressedā€.

    while True:
        if button.is_pressed:
            print("Button is pressed")
        else:
            print("Button is not pressed")