按键脚本 python-树莓派按键关机PYTHON脚本

#!/usr/bin/env python

# coding=utf-8

import RPi.GPIO as GPIO

import time

import os,sys

import signal

#定义关机键和关机状态指示灯的GPIO引脚

GPIO.setmode(GPIO.BCM)

pin_btn = 23

pin_led_reboot = 7

pin_led_halt = 8

#初始化SAKS上相应按键和LED的状态,按键内部上拉、LED不亮

GPIO.setup(pin_btn, GPIO.IN, pull_up_down = GPIO.PUD_UP)

GPIO.setup(pin_led_reboot, GPIO.OUT, initial = GPIO.HIGH)

GPIO.setup(pin_led_halt, GPIO.OUT, initial = GPIO.HIGH)

#初始化按下关机键的次数

press_times = 0

#按下关机键后等待并倒数10次

count_down = 10

led_on_reboot = 0

led_on_halt = 0

def onPress(channel):

global press_times, count_down

print("pressed")

press_times += 1

if press_times > 3:

press_times = 1

#重启模式

if press_times == 1:

GPIO.output(pin_led_reboot, 0)

GPIO.output(pin_led_halt, 1)

print("system will restart in %s" % (count_down))

#关机模式

elif press_times == 2:

GPIO.output(pin_led_reboot, 1)

GPIO.output(pin_led_halt, 0)

print("system will halt in %s" % (count_down))

#模式取消

elif press_times == 3:

GPIO.output(pin_led_reboot, 1)

GPIO.output(pin_led_halt, 1)

print "cancel"

count_down = 10

#设置按键检测,检测到按下时调用 onPress 函数

GPIO.add_event_detect(pin_btn, GPIO.FALLING, callback = onPress, bouncetime = 500)

try:

while True:

#重启模式

if press_times == 1:

if count_down == 0:

print "start restart"

os.system("shutdown -r -t 5 now")

sys.exit()

led_on_reboot = not led_on_reboot

#黄色 LED 闪烁

GPIO.output(pin_led_reboot, led_on_reboot)

#关机模式

if press_times == 2:

if count_down == 0:

print "start shutdown"

os.system("shutdown -t 5 now")

sys.exit()

led_on_halt = not led_on_halt

#红色 LED 闪烁

GPIO.output(pin_led_halt, led_on_halt)

if press_times == 1 or press_times == 2:

count_down -= 1

print "%s second" % (count_down)

time.sleep(1)

except KeyboardInterrupt:

print("User press Ctrl+c, exit;")

finally:

GPIO.cleanup()

开机自动运行脚本 :

vim/etc/rc.local

python /home/pi/powerbutton.py &

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值