1

I wrote a small script to shutdown the pi once the button is pressed for 2 seconds. It should print a message and after one second shutdown the pi. I also have this script to run automatically on each boot (init.d). The problem is that the first time I run the script, when i press the button it works as it should. But after I turn on the pi again (and the script starts automatically on boot) the button is still turning off my pi but no message is printed.

here is my script:

#!/usr/bin/env python

import RPi.GPIO as GPIO
import time
import subprocess

def Shutdown():
    print("message")
    time.sleep(1)
    subprocess.call(['shutdown', '-h', 'now'], shell=False)

GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    GPIO.wait_for_edge(3, GPIO.FALLING)
    #sleep and check button state again (in case of accidental button press)
    time.sleep(2)
    if GPIO.input(3) == 0:
        break
Shutdown()

I tried it both on a pi zero and a 3b.

Do you have any idea why this would happen? Thnks for you time.

0
2

It is probably about the privileges. Shutdown needs sudo privilege. So you probably run the script as root thats why you are able to shutdown the pi with button. But when script is started at boot it dont have root privilege. Give your script sudo privilege with "sudo chmod 777" and add your script to crontab

7
  • Thnx for the answer Hakan. However my pi is shutting down after boot. Problem is the message is not printed. I’ll try, however, what you mentioned tomorrow and I’ll let you know. – qeiynn Aug 10 '20 at 15:23
  • oh I missunderstood the problem. Where do you want to see the printed message? on terminal? – Hakan Ulusoy Aug 10 '20 at 16:05
  • Forgot to write that. Yes on the terminal. I use raspios lite. – qeiynn Aug 10 '20 at 16:07
  • As I know, the scripts that started at boot dont print to terminal. If you run it over terminal manually you can see but when OS did it, you cant see it over terminal. You can check "/var/log/messages" to see output of the scripts that OS run. You can also write it to a log file with python file open and write. – Hakan Ulusoy Aug 10 '20 at 16:12
  • I didn’t know that. Thanks for the info! – qeiynn Aug 10 '20 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.