In this write-up, we will explore the method to shut down the Raspberry Pi using the python code and some components of electronics.
Hardware assembling on breadboard
To shutdown the Raspberry Pi using a push-button, we need a push-button, male-female jumper wires, a Raspberry Pi 4, and a breadboard which is used for prototyping. We will first place a push-button, Raspberry Pi 4 on the breadboard:
Next step is to connect one terminal of the button with the GPIO 26 and the other terminal with the ground:
How to set up a button to control the power of the Raspberry Pi with a Python code
We can control the Raspberry Pi using the button with the help of the Python code. For this purpose, we will first create a Python file with the name “shutdown” having an extension of “py”:
Write the Python code which is mentioned below:
#import button library from the Pi GPIOZero library
# import time library
#imports OS library
shut_But = Button(26)
# declared GPIO 26 pin for input of button
# declared the infinite loop
#Check to see if button is pressed
# wait for the hold time
#check to see if button is pressed
os.system("shutdown now -h")
#shut down the Pi
# wait to loop again so we don’t use the processor too much.
Explanation of code: In the code, first we have imported three libraries that are used for the purposes described:
|gpiozero||The gpiozero library provides the functions which are used to manage the GPIO pins|
|time||The time library provides the functions used to produce the time delays and time-related functions|
|os||The OS library provides the functions which are used to manage the operating system|
Now to run the above code of the shutdown.py file, we will use the command:
When the push button is pressed from the hardware configuration and then released, the Raspberry Pi shutdowns but for this every time we have to run the shutdown Python code file.
Now, we will make some changes so that it will shut down by using the button directly without running the Python file. For this purpose, we will run the command:
And then add the following line before the “exit 0” (make sure to replace the path of the Python code file):
To save the changes, reboot the Raspberry Pi by using the reboot command:
When the system is rebooted, press the button for a while and the system will be shut down.
We can control the power supply of the Raspberry Pi by using a push-button and with the help of a Python script. This will make the system shut down safely like other computers. In this write-up, we have configured a circuit consisting of a Raspberry Pi 4 and a push-button and made it shut down using a Python script.