• sales

    +86-0755-88291180

RPi Tutorial Series: External Button User Guide

Using a external button to do some control is so cool a thing but knowledge of event interruption is often required in such case. This section gives some examples under different libraries.

BCM2835

#include <bcm2835.h>
#include <stdio.h>

#define  KEY  20

int main(int argc, char **argv)
{
    if (!bcm2835_init())return 1;
    // Sets the pin as input.
    bcm2835_gpio_fsel(KEY, BCM2835_GPIO_FSEL_INPT);
    // Sets the Pull-up mode for the pin.
    bcm2835_gpio_set_pud(KEY, BCM2835_GPIO_PUD_UP);
    printf("Key Test Program!!!!\n");  
    while (1)
    {  
        // Reads the current level on the specified pin and returns either HIGH or LOW (0 or 1).
        if(bcm2835_gpio_lev(KEY) == 0)
        {  
            printf ("KEY PRESS\n") ;
            while(bcm2835_gpio_lev(KEY) == 0)
                bcm2835_delay(100);
        }  
        bcm2835_delay(100);
    }  
    bcm2835_close();
    return 0;
}

Save the file as "key.c" and then compile it. Run the program and give a low level to the pin, the terminal will prompt "KEY PRESS". Hit Ctrl + C to terminate the process.

gcc -Wall key.c -o key -lbcm2835
sudo ./key

WiringPi (Polling)

#include <stdio.h>
#include <wiringPi.h>
 
char KEY = 29;
 
int main()
{
    if (wiringPiSetup() < 0)return 1 ;
    // Sets the pin as input.
    pinMode(KEY,INPUT);
    // Sets the Pull-up mode for the pin.
    pullUpDnControl(KEY, PUD_UP);
    printf("Key Test Program!!!\n");
    while(1)
    {  
        if (digitalRead(KEY) == 0) 
        {  
            printf ("KEY PRESS\n") ;
            // Returns the value read at the given pin. It will be HIGH or LOW (0 or 1).
            while(digitalRead(KEY) == 0)
                delay(100);
        }  
        delay(100);
    }  
}

Save the file as "key.c" and then compile it. Run the program and give a low level to the pin, the terminal will prompt "KEY PRESS". Hit Ctrl + C to terminate the process.

gcc -Wall key.c -o key -wiringPi
sudo ./key

WiringPi (Interruption)

#include <stdio.h>
#include <wiringPi.h>
 
#define button 29

char flag = 0;
// The function will be called when the interrupt triggers.
void myInterrupt()
{
    flag ++;
}
 
int main()
{
    // This initialises the wiringPi system 
    // and assumes that the calling program is going to be using the wiringPi pin numbering scheme.
    if(wiringPiSetup() < 0)return 1;
    // This function registers a function to received interrupts on the specified pin.
    if(wiringPiISR(button, INT_EDGE_FALLING, &myInterrupt) < 0)
    {  
        printf("Unable to setup ISR \n");
    }  
    printf("Interrupt test program\n");
    while(1)
    {  
        if(flag)
        {  
            while(digitalRead(button) ==0);
            printf("button press\n");
            flag = 0;
        }  
    }  
}

Save the file as "Interrupt.c" and then compile and execute it. Hit Ctrl + C to terminate the process.

gcc -Wall Interrupt.c -o key -wiringPi
sudo ./Interrupt

Python (Polling)

#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import time

KEY = 26
# pin numbers are interpreted as BCM pin numbers.
GPIO.setmode(GPIO.BCM)
# Sets the pin as input and sets Pull-up mode for the pin.
GPIO.setup(KEY,GPIO.IN,GPIO.PUD_UP)
while True:
    time.sleep(0.05)
    # Returns the value read at the given pin. It will be HIGH or LOW (0 or 1).
    if GPIO.input(KEY) == 0:
        print("KEY PRESS")
        while GPIO.input(KEY) == 0:
            time.sleep(0.01)

Run the program and then give a low level to the pin, the terminal will prompt "KEY PRESS", Hit Ctrl + C to terminate the process.

sudo python key.py

Python (Interruption)

#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import time
 
KEY = 26
# The function will be called when the interrupt triggers.
def MyInterrupt(KEY):
    print("KEY PRESS")
# pin numbers are interpreted as BCM pin numbers.
GPIO.setmode(GPIO.BCM)
GPIO.setup(KEY, GPIO.IN, GPIO.PUD_UP)
# add falling edge detection on a channel (i.e. KEY)
# ignoring further edges for 200ms for switch bounce handling.
GPIO.add_event_detect(KEY, GPIO.FALLING, MyInterrupt, 200)
 
while True:
    time.sleep(1)
TAG: Raspberry Pi 5 Pure-Copper Active Cooler Lichee-Tang-Primer-20K-FPGA-Unboxing ESP32 C6 Development board 1.9 inch LCD display 1.9inch Screen 172×320 With SD slot RGB LED QMI8658 6-Axis-Sensor ST7789 CST816 Raspberry Pi Compute Module 5 CM5 Cortex A76 BCM2712 With/Without Wi-Fi RAM 2/4/8/16GB eMMC Lite/8/16/32/64GB NanoKVM-USB-Development Raspberry Pi UGV Rover ROS2 PT AI OpenCV Robot Car MediaPipe Multi Protection Raspberry Pi Game Jetson Nano Raspberry Pi Pico rp2040 Display image 1.3inch LCD ST7789 change bmp to hex Raspberry Pi Pico 2 RP2350 1.8 inch AMOLED Development Board Display 368×448 TouchScreen Programmable Watch QSPI NVIDIA Jetson 14 inch Dual LCD Computer PC Monitor Display Double Secondary Screen Type C Mini HDMI 1080P For Windows/MacOS Raspberry Pi DSI LCD Raspberry Pi 5 USB Audio Raspberry Pi 5 PCIe to SSD Raspberry Pi 5 Box Case Ki-A PCIe to RJ45 Gigabit Ethernet All Ports To Pi's USB Side Industrial UART To WiFi 1.47 inch LCD AXS5106L TouchScreen JD9853 Display 172x320 For Arduino/Raspberry Pi/Pico/ESP32 ESP32