声明:本人不是技术男,只是兴趣爱好,不妥之处轻喷,谢谢。(_)**
一、添加一个按钮
如下图接线方式
rpi-pins-40-0.jpg
rpi-pins-40-0.jpg
代码如下:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
button = 4
#因为代码第二行设置了BCM所以GPIO口是BCM编号,所以是四号
GPIO.setup(button, GPIO.IN,pull_up_down=GPIO.PUD_UP)
while True:
if GPIO.input(button ) == 0:
print("press button")
time.sleep(.3)
二、长短按监测
我这里长短按监测采用的是通过监测GPIO口信号不为“0”时之前为0的次数来判断用户在按下按钮期间,共收到多少次为“0”信号
代码如下:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
button = 4
GPIO.setup(button, GPIO.IN,pull_up_down=GPIO.PUD_UP)
press_times=0
while True:
if GPIO.input(button) == 0:
press_times+=1
elif press_times>0:
if press_times<4:
#4为我自己设置的长短按钮分界线,大家可以根据自己的按按钮习惯通过代码自己设定
print("短按按钮")
else:
print("长按按钮")
press_times = 0
time.sleep(.1)