树莓派设置关机重启键
#!/usr/bin/env python3
# coding=utf-8
import RPi.GPIO as GPIO
import time
import os,sys
import signal
GPIO.setmode(GPIO..BOARD)
# 定义引脚7为关机重启键
pin_btn=7
GPIO.setup(pin_btn, GPIO.IN, pull_up_down=GPIO.PUD_UP)#默认下降沿触发
press_time=0
count_down=10
def cleanup():
#释放资源,不然下次运行是可能会收到警告
GPIO.cleanup()
def handleSIGTERM(signum, frame):
sys.exit()#raise an exception of type SystemExit
def onPress(channel):
global press_time,count_down
press_time+=1
if press_time >3:
press_time=1
elif press_time==3:
count_down=10
#开始执行主函数,增加事件关联
#当引脚处于下降沿时,调用onPress函数,bouncetime用于消抖
GPIO.add_event_detect(pin_btn, GPIO.FALLING, callback= onPress,bouncetime=500)#默认下降沿触发
try:
while True:
if press_time==1:
if count_down==0:
print "start restart"
os.system("shutdown -r -t 5 now")
sys.exit()
led_on=not led_on
GPIO.output(pin_led, led_on)# blink led
if press_time==2 and count_down==0:
print "start shutdown"
os.system("shutdown -t 5 now")
sys.exit()
if press_time==1 or press_time==2:
count_down-=1
print "%s second"%(count_down)
time.sleep(1)
except KeyboardInterrupt:
print('User press Ctrl+c ,exit;')
finally:
cleanup()
参考文献:
1.给树莓派添加重启关机按钮