Authorized Online Retailers:

AMAZON
AMAZON
amzuk

Introduction
The last two lessons have introduced how to program Raspberry Pi to output signal and  turn on LED. In this lesson, we will show you how to get input signal from Button switch and trigger output to turn on LED via program.

Hardware Preparation
1 * Raspberry Pi
1 * Breadboard
1 * LED
1 * Button
1 * Resistor (200Ω)
1 * Resistor (10KΩ)
Jumper wires
1 * T-Extension Board with 40-Pin Cable(Optional)

Software Preparation
Note: In this lesson, we remotely control raspberry pi via PuTTy on PC. To learn how to config raspberry pi, please visit lesson 1: getting started with raspberry pi.

Experimental Principle

The button is a common component, and works as a switch to turn on or off circuit. The button in our kit has 4 pins, as photo shows:


Pin 1 and Pin 2 are conductive, and Pin 3 and Pin 4 are conductive. After pressing button, Pin 1 and Pin 3 become conductive and Pin 2 and Pin 4 become conductive. As photo shows:

Not Press the button

Pressed the button

For this project, connect the button to B17, and the LED to B18 as the following circuit graph:

B17 for the button in above graph means BCM GPIO#17 or Physical pin#11 or wiringPi#0(zero). B18 for the LED in above graph means BCM GPIO#18 or Physical pin#12 or wiringPi#1.
Note: B means BCM(Broadcom pin number). If you don’t know what is BCM pin#, Physical pin#, wiringPi#, please review our lesson 2: Introduction Of Raspberry Pi GPIO

If the button is not pressed , B17(wiringPi#0(zero)) input voltage is pulled up to 3.3V through  10K resistor . Once our sample code reads high voltage from B17, it will output high level to B18(wiringPi#1) which will turn off LED.
If  the button is pressed , the B17(wiringPi#0(zero)) input is set to zero(connect to GND) , sample code will output  zero voltage to B18(wiringPi#1) which turns the LED on.

Hardware Setup
Assembling the Circuit as followed Connection Graph

Software
We’ll provide two kinds of codes for C language users and Python language users.

For C Language users,please follow the next steps:


Prerequisite:
If you don’t have libgpiod library installed in your Raspberry Pi 5, please install it by following commands:

sudo apt update
sudo apt install libgpiod-dev

Aftter installing libgpiod library, please
Step 1) Download sample code testgpio.c  from osoyoo.com by typing following commands in terminal:
wget http://osoyoo.com/driver/pi/testgpio.c

Step 2) Compile code by running following command
  gcc -o testgpio testgpio.c -lgpiod

Note: gcc: is GNU Compiler Collection. If you want to write your own C code and compile to run it, you need to master gcc. for more information about gcc, please visit here
-o: to name the compiled file. You can name the file as your like. here we name as button_led
testgpio.c: means the original file which is compiled
-lgpiod: is to load the library lgpiod library (l is short for library)

Step 3) Run the program
pi@raspberry:~ $ ./testgpio

Step 4) Program result
Once program starts running, the terminal will show print message as code firstly, and then show LED off. When pressing the button, the LED will turn on and the terminal shows LED On. when releasing the button, the LED will turn off and the terminal shows LED Off.  If you wan’t to stop the program, please go to terminal and type command: Ctrl + C.

C languange sample code and Explanation comments

#include "gpiod.h"
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"

#define GPIO_CHIP "/dev/gpiochip4"  // Adjust based on your Pi 5 configuration
#define BUTTON_GPIO 17              // BCM pin 17
#define LED_GPIO 18                 // BCM pin 18

int main() {
    struct gpiod_chip *chip;
    struct gpiod_line *button_line, *led_line;
    int button_val;

    // Open the GPIO chip
    chip = gpiod_chip_open(GPIO_CHIP);
    if (!chip) {
        perror("Open chip failed");
        return 1;
    }

    // Get lines
    button_line = gpiod_chip_get_line(chip, BUTTON_GPIO);
    led_line = gpiod_chip_get_line(chip, LED_GPIO);
    if (!button_line || !led_line) {
        perror("Get line failed");
        gpiod_chip_close(chip);
        return 1;
    }

    // Request lines
    if (gpiod_line_request_input(button_line, "button") < 0) {
        perror("Request button input failed");
        gpiod_chip_close(chip);
        return 1;
    }

    if (gpiod_line_request_output(led_line, "led", 1) < 0) {  // Initial HIGH = LED off
        perror("Request LED output failed");
        gpiod_chip_close(chip);
        return 1;
    }

    printf("Monitoring button on GPIO 17...\n");

    // Main loop
    while (1) {
        button_val = gpiod_line_get_value(button_line);
        if (button_val < 0) {
            perror("Read button failed");
            break;
        }

        if (button_val == 0) {  // Button pressed (LOW)
            gpiod_line_set_value(led_line, 0);  // LED ON (LOW)
        } else {  // Button released (HIGH)
            gpiod_line_set_value(led_line, 1);  // LED OFF (HIGH)
        }

        usleep(10000);  // Sleep 10ms to reduce CPU usage
    }

    gpiod_line_release(button_line);
    gpiod_line_release(led_line);
    gpiod_chip_close(chip);
    return 0;
}

For Python Language users, please follow the below step:


Step 1)  Download sample python code to /home/pi by following terminal command:
wget http://osoyoo.com/driver/pi/testgpio.py

Step 2) Run program
python testgpio.py

Step 3) Program result
Once program starts running, the terminal will show print message as code firstly. When pressing the button, the LED will turn on and the terminal shows LED On. when pressing the button again, the LED will turn off and the terminal shows LED Off.  If you wan’t to stop the program, please go to terminal and type command: Ctrl + C.

Python Code :


from gpiozero import OutputDevice,InputDevice

LED = OutputDevice(18)  #LED pin connects to GPIO18
BUTTON = InputDevice(17) # BUTTON connects to GPIO17

print('start testing, press Ctrl-C to quit...')
try:
    while True :
        if  BUTTON.is_active : LED.off()
        else : LED.on()
except KeyboardInterrupt:
    LED.close()
    BUTTON.close()