树莓派实现按钮关机、重启、多功能等(按钮点击篇)

僤鯓⒐⒋嵵緔 提交于 2019-12-14 22:44:14

视频

代码解析,实物演示 [视频]

准备

  • 按钮
  • 面包板
  • 杜邦线

接线

在这里插入图片描述

代码(python3)

# -*- coding: utf-8 -*-
import time,os
import RPi.GPIO as GPIO
# 树莓派 关机/重启按钮(单击篇)
BUTTON=18

GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)

# 单击
def click():
	times=0 # 点击次数(当按下后,抬起算一次)
	click_status=1 # 记录上次循环点击状态,1:按下 0:断开(抬起)
	# 检测约0.8秒内按下按钮的次数
	for x in range(80):
		v=GPIO.input(BUTTON)
		# 按下
		if v==1 and click_status==0:
			click_status=1
			
		# 抬起,算按一次
		if v==0 and click_status==1:
			click_status=0
			times+=1

		time.sleep(0.01)
	return times

while True:
	if GPIO.input(BUTTON)==1:
		times=click()
		if times!=0:
			print('按下次数:',times)

		if times==2:
			print('关机键')
			os.system('sudo poweroff')

		if times==3:
			print('重启')
			os.system('sudo reboot')

	time.sleep(0.01)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!