Keys are the simplest and most common input device. As shown from the diagram below, KEY1 is connected to Raspberry Pi pin 12 and KEY2 is connected to Raspberry Pi pin 13. The other end of the key is connected to the ground. So when the key is not pressed, a high level (1) is entered and when it is pressed, a low level (0) is entered.

The common command for Buttons
Button.is_pressed #To determine whether a button is pressed, if the return value is [True] or [1] means it is pressed, if it is [False] or [0] it is not pressed.
Lighting LED using Button
Aim: The LED red light is lit when the key is detected to be pressed, and the LED red light is turned off when the key is released
Steps:
- Import the Button and the LED module
- Initialize key 1 and red LED
- Detect whether key 1 is pressed
- If key 1 is pressed, turn on the red LED, or else turn off the red LED
- Repeat steps 3 & 4

Code:
from gpiozero import LED
from gpiozero import Button
#import related modules
key1 = Button(12)
LED_R = LED(4)
while True:
if key1.is_pressed: #check whether key1 is pressed
LED_R.on()
print("KEY1 is pressed")
else:
LED_R.off()
print("KEY1 is not pressed")
Final Result:
Now I will run the code, when KEY1 is pressed, the red light of LED_R is lit, and when it is released, it is extinguished, and the shell dialogue box has a printing prompt of the current state.
However, this is not good enough. Previously, when I used the Button, even though I could achieve the input and output functions in the IO port, but the code is continuously detecting the change of the IO input port, and it is not very efficient. So, it will waste a lot of time for real-time detection of buttons.
To solve this problem, I will need to use and concept called “External interrupt”, which means that when the key is pressed (resulting in an interrupt), then it will perform the relevant functions.
How to apply the concept? I need to use:
Button.when_pressed #it means that something would be done when the key is pressed.
Full code implementing this concept:
from gpiozero import LED
from gpiozero import Button
key = Button(12)
LED = LED(4)
def fun():
LED.toggle() #flip the status of the red LED, turn on if it is off, turn off if it is on.
key.when_pressed = fun #set the key interrupt
while True: #keep the program executing
pass
Unlike the previous code, where I had to constantly check if the button was pressed, the new code here does whatever needs to be done and only comes to handle the key whenever it is pressed causing an interrupt. It’s much more efficient than before.