Categories

VMAC PiHat v2 Reset Button

WIKI:

The VMAC PiHat board has a PCB mounted button which is connected to GPIO 4 and can be used for any required purpose.

As the GPIO pin that the button is connected is held high, through a pull up resistor. pressing the button will take the GPIO pin low.

A typical use of this button could be to add a GPIO controlled shutdown, hard or soft reboot of the Raspberry Pi and that is what this article will demonstrate in the below examples.

The below Python example will loop and check for a button press. Once the button is pressed, a message will appear on the screen.

# Setup Button and when button is pressed, a message will appear on the screen.
# Dave Williams, G8PUO, January 2018

import RPi.GPIO as GPIO

#====== GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#Define GPIO Inputs
Button = 4

#Setup Input with pull-ups enabled
GPIO.setup(Button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#Loop
while True:
    #Loop and check for button Press
    if GPIO.input(Button) == False:
        print ("Button Pressed!")

 

Now we add some extra code to reset the Pi when the button is pressed.  This will force a restart of the Raspberry Pi with the ‘sudo reboot’ command.

All we need to do is add these two lines into our button code:

import os
os.system("sudo reboot")

Note: Be aware that your Raspberry will reboot with this example but if you run the code in Thonny, then it will automatically save first.

# Setup Button and when button is pressed, the Raspberry Pi will reboot.
# Dave Williams, G8PUO, January 2018

import RPi.GPIO as GPIO
import os

#====== GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#Define GPIO Inputs
Button = 4

#Setup Input with pull-ups enabled
GPIO.setup(Button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#Loop
while True:
    #Loop and check for button Press
    if GPIO.input(Button) == False:
        print ("Button Pressed!")
        os.system("sudo reboot")

 

Alternative code to shutdown the Raspberry Pi when the button is pressed, using the ‘sudo poweroff’ command.

# Setup Button and when button is pressed, the Raspberry Pi will shut down.
# Dave Williams, G8PUO, January 2018

import RPi.GPIO as GPIO
import os

#====== GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#Define GPIO Inputs
Button = 4

#Setup Input with pull-ups enabled
GPIO.setup(Button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

#Loop
while True:
    #Loop and check for button Press
    if GPIO.input(Button) == False:
        print ("Button Pressed!")
        os.system("sudo poweroff")

Leave a Reply

This site uses User Verification plugin to reduce spam. See how your comment data is processed.