树莓派 python 按键红绿交替闪烁测试
作者:互联网
树莓派 python 按键红绿交替闪烁测试代码注释
# 测试按键,结果红绿交替闪烁
import RPi.GPIO as GPIO
import time
BtnPin = 19
Gpin = 5 # 绿色接在管脚5
Rpin = 6 # 红色接在管脚6
def setup():
GPIO.setwarnings(False) #关闭警告
GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location按物理位置对GPIO编号
# 输出模式
GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output将绿色Led引脚模式设置为输出
GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output将红色Led引脚模式设置为输出
# 按键输入模式
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V)设置BtnPin的模式为输入,并向上拉至高电平(3.3V)
if __name__ == '__main__': # Program start from here
setup()
try:
while True:
# 检测按键为高电平
if GPIO.input(BtnPin) == True:
time.sleep(0.01)
if GPIO.input(BtnPin)==True:
GPIO.output(Rpin,1)
GPIO.output(Gpin,0)
elif GPIO.input(BtnPin) == False:
time.sleep(0.01)
if GPIO.input(BtnPin) == False:
# 按键按下交替闪烁
while GPIO.input(BtnPin) ==True:
pass
GPIO.output(Rpin,0)
GPIO.output(Gpin,1) #绿亮
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
GPIO.cleanup()
标签:树莓,output,python,setup,BtnPin,按键,input,GPIO,红绿 来源: https://blog.csdn.net/dujuancao11/article/details/113095922