Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 3847

Beginners • Re: Button to shutdown raspberry pi 4 (python), right track?

$
0
0
Yes, you can use "dtoverlay=gpio-shutdown,gpio_pin=27" but I wanted something with a little more feedback for someone other than me that was directed to shutdown my weather station. I took the same approach as the OP.
This works fine in terminal, but I understand that it cannot simply be a cronjob as it requires root privilege for the OS functions.
I use subprocess but if you add sudo then it should work. Here's snippet of the code I use

Code:

from gpiozero import LED, Buttonfrom subprocess import callfrom time import sleep    ...led = LED(19) # GPIO 19led.blink() # Indicates running and waiting for button pushbutton = Button(6) # GPIO6     ...if button.is_pressed:    print("Button pressed")    led.on() # Led user know the button pressed detected    sleep(5) # User has to hold the button down    if button.is_pressed:        led.off() # Let user know reboot/shutdown in progress        sleep(1)        if shutdown:            print("Shutting down")            call(["sudo","shutdown","-h","now"])        else:            print("Rebooting")            call(["sudo","reboot"])        return __failure__ # Should never get here    else:        led.blink() # Let user know reboot/shutdown was not initiated
From my understanding, this would be best handled by systemd. Does this sound like the correct direction to go in? Nothing is "easy" so I'm trying to avoid wasting time on the wrong things.
While systemd can be a strange beast, it does work well. Here is the service definition for the above program.

Code:

[Unit]Description=Reboot Button ServiceAfter=systemd-time-wait-sync.serviceWants=systemd-time-wait-sync.service[Service]Type=idleUser=piExecStart=/usr/bin/python3 -u /media/work/bin/button_action.pyc --shutdownWorkingDirectory=/media/workStandardOutput=append:/media/work/log/srv_reboot_button.logStandardError=append:/media/work/log/srv_reboot_button.logRestart=no[Install]WantedBy=multi-user.target

Statistics: Posted by DS256 — Mon Aug 05, 2024 6:49 pm



Viewing all articles
Browse latest Browse all 3847

Trending Articles