树莓派按键关机PYTHON脚本

本文介绍了一个基于Python的脚本,用于控制Raspberry Pi的关机和重启过程。通过使用GPIO接口,脚本能够监测关机按钮的按下次数,并根据不同的次数执行重启、关机或取消操作。同时,脚本还利用LED指示灯显示当前的操作模式。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

链接: http://www.tongxinmao.com/Article/Detail/id/266.

#!/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 &

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值