Skip to content
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Scripts used in our official [Raspberry Pi power button guide](https://howchoo.c
## Installation

1. [Connect to your Raspberry Pi via SSH](https://howchoo.com/g/mgi3mdnlnjq/how-to-log-in-to-a-raspberry-pi-via-ssh)
1. Clone this repo: `git clone https://github.com/Howchoo/pi-power-button.git`
1. Clone this repo: `git clone https://github.com/N6RDV/pi-power-button.git`
1. Optional: Edit line 9/10 in listen-for-shutdown.py to your preferred pin (Please see "Is it possible to use another pin other than Pin 5 (GPIO 3/SCL)?" below!)
1. Run the setup script: `./pi-power-button/script/install`

Expand Down
34 changes: 31 additions & 3 deletions listen-for-shutdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,38 @@

import RPi.GPIO as GPIO
import subprocess
import time
from time import sleep

button_gpio=3
light_gpio=27
fan_gpio=22

short_press=0.1
long_press=10

GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.wait_for_edge(3, GPIO.FALLING)
GPIO.setup(button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(light_gpio, GPIO.OUT)
GPIO.setup(fan_gpio, GPIO.OUT)

def main():
while True:
GPIO.wait_for_edge(button_gpio, GPIO.FALLING)
counter = 0
while GPIO.input(button_gpio) == 0 and counter < long_press:
time.sleep(0.1)
counter = round(counter + 0.1, 1)
print('Shutdown button is pressed ' + str(counter))
if counter >= long_press:
print('Shutting down')
subprocess.call(['shutdown', '-h', 'now'], shell=False)
elif counter >= short_press:
relay_state = not (GPIO.input(light_gpio) or GPIO.input(fan_gpio))
print('Changing relay state to: ' + str(relay_state))
GPIO.output(light_gpio, relay_state)
GPIO.output(fan_gpio, relay_state)
time.sleep(short_press)

subprocess.call(['shutdown', '-h', 'now'], shell=False)
if __name__ == '__main__':
main()