最近一段时间开始捣鼓树莓派了,弄的都是试验性质的。经常会出现些问题导致连不上树莓派可能是卡死或者断网什么的,有没有显示器也不知道到底是什么情况。 没办法只有拔掉电源重启了。
后来想想长期这样弄也不是办法SD卡禁不起折腾啊,于是就想办法给它添加了个“关机和重启按钮”。
这里实现上用了GPIO接口,通过读取一个接口的高低状态然后调用重启以及关机命令。
我的pi是B版v1。GPIO接口和v2稍微不一样。具体看下图把代码的接口定义替换成对应的就行了
另外使用pin的编号有两种方式
- Board Pin 这种是自然排序的,重p1到p26
- BCM GPIO Broadcom的编号方法 (上图中的绿色方块部分GPIO*)
我在代码中使用的是 *BCM *。
这里用到了两个GPIO接口,7和17 你也可以自己修改下。 一个用来接收按键信号,另外一个驱动led显示状态
led有三个状态 长亮:正在重启,闪动:正在关机,不亮:等待状态。
面包板连接
若你有杜邦线的话也可以不通过面包板连接,按钮那个GND的线也不是必须的,用手直接触摸 GPIO7 也能起到把这个电压拉低的效果
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | #!/usr/bin/env python # coding=utf-8 # author:ksc import RPi.GPIO as GPIO import time import os,sys import signal GPIO.setmode(GPIO.BCM) #define GPIO pin pin_btn = 7 pin_led = 17 GPIO.setup(pin_btn, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(pin_led, GPIO.OUT, initial = GPIO.LOW) press_time = 0 count_down = 10 led_on = 1 def cleanup(): '''释放资源,不然下次运行是可能会收到警告 ''' print ( 'clean up' ) GPIO.cleanup() def handleSIGTERM(signum, frame): #cleanup() sys.exit() #raise an exception of type SystemExit def onPress(channel): global press_time,count_down print ( 'pressed' ) press_time + = 1 if press_time > 3 : press_time = 1 if press_time = = 1 : GPIO.output(pin_led, 1 ) print ( 'system will restart in %s' % (count_down)) elif press_time = = 2 : print ( 'system will halt in %s' % (count_down)) elif press_time = = 3 : GPIO.output(pin_led, 0 ) print 'cancel ' count_down = 10 GPIO.add_event_detect(pin_btn, GPIO.FALLING, callback = onPress,bouncetime = 500 ) #signal.signal(signal.SIGTERM, handleSIGTERM) 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 2 3 4 5 6 | #创建程序,把代码粘贴进去保存 root@mypi:~ # vi reboot.py #修改可执行 root@mypi:~ # chomod 775 reboot.py #测试下 root@mypi:~ # ./reboot.py |
按一下按钮系统进入重启状态倒计时10秒,在这段时间内你可以接着按一下切换到关机状态。按第三下取消关机进入等待状态。这三种状态可通过按按钮不断切换。
1 2 3 4 5 | #若没问题就可以让它后台运行了, root@mypi:~ # nohup ./reboot.py & #想结束后台运行? ps auxf #查找PID kill PID |
没有指明具体方法