4.ESP32-按键实验
"""
按键实验
2022.10.9
"""
from machine import Pin
import time
key1=Pin(4,Pin.IN,Pin.PULL_UP)#GPIO2,设置为输出模式,输入模式为Pin.IN,设置为上拉
key2=Pin(5,Pin.IN,Pin.PULL_UP)
led1=Pin(2,Pin.OUT)
led2=Pin(3,Pin.OUT)
KEY1_RPESS,KEY2_RPESS=1,2
key_en=1
def key_scan():
global key_en
if key_en==1 and (key1.value()==0 or key2.value()==0):
time.sleep_ms(10) #消抖
key=0
if key1.value()==0: #key1按下
return KEY1_RPESS
elif key2.value()==0: #key2按下
return KEY2_RPESS
elif key1.value()==1 and key2.value()==1:
key_en=1
return 0
if __name__=="__main__":
key=0
i_led1,i_led2=0,0#状态变量,
led1.value(i_led1)#熄灭
led1.value(i_led2)
while True:
key=key_scan()
if key==KEY1_RPESS:
i_led1=not i_led1
led1.value(i_led1)
elif key==KEY2_RPESS:
i_led2=not i_led2
led2.value(i_led2)