Friday, February 16, 2018

Raspberry Pi - input system command with button

Input button to execute #linux system command on Raspberry Pi
with #python. In this case it's #poweroff or #reboot command to safely turn off or restart your #RPi in case you don't have display and have no time to #ssh. But you can use any system command you want.
Connecting:
Pin 1 (3.3v) > 1 kOhm resistor > Pin 11 (GPIO 17) > Button > Ground
Here is #code, name it as you want with ".py" extension (for example button.py) and later run it with #admin privileges ("sudo python button.py")

import RPi.GPIO as gpioimport os

#set up pin 17 as an input

gpio.setmode(gpio.BCM) 
gpio.setup(17, gpio.IN)

while True:  input_value = gpio.input(17) 
   if input_value == False: 
     os.system("sudo poweroof") #or "sudo reboot" 
  while input_value == False: 
   input_value = gpio.input(17) 
Support me on xw0rks.tk