本站改版新增arduino频道
Micropython ESP32 C3连接独立按键

from machine import Pin,I2C,PWM
import time
#合宙ESP32c3开发板
# 定义上、下、左、右、中、SET、RST七个按键
UP = Pin(10,Pin.IN,Pin.PULL_UP)
DWN = Pin(6,Pin.IN,Pin.PULL_UP)
LFT = Pin(7,Pin.IN,Pin.PULL_UP)
RHT = Pin(9,Pin.IN,Pin.PULL_UP)
MID = Pin(2,Pin.IN,Pin.PULL_UP)
SET = Pin(3,Pin.IN,Pin.PULL_UP)
RST = Pin(8,Pin.IN,Pin.PULL_UP)
# 定义led灯对象
led = Pin(13,Pin.OUT)
def Key():
# "up","down","left ","right","middle","set","rst"
key = 1
if (key == 1 and (UP.value() == 0 or DWN.value() == 0 or LFT.value() == 0 or RHT.value() == 0) or MID.value() == 0 or SET.value() == 0 or RST.value() == 0):
time.sleep(0.020)
key = 0
if UP.value() == 0:
return "upper"
elif DWN.value() == 0:
return "down "
elif LFT.value() == 0:
return "Left "
elif RHT.value() == 0:
return "right"
elif MID.value() == 0:
return "middle"
elif SET.value() == 0:
return "set "
elif RST.value() == 0:
return "rst "
if(not(key == 0 and (UP.value() == 0 or DWN.value() == 0 or LFT.value() == 0 or RHT.value() == 0) or MID.value() == 0 or SET.value() == 0 or RST.value() == 0)):
key = 1
return -1
def dispaly():
#code = ["upper","down","Left ","right","middle","set","rst"]
#code = ("upper","down","Left ","right","middle","set","rst")
code = {
0:"upper",
1:"down ",
2:"Left ",
3:"right",
4:"middle",
5:"set ",
6:"rst ",
}
if Key() == code[0]:
print("%s"%(code[0]))
elif Key() == code[1]:
print("%s"%(code[1]))
elif Key() == code[2]:
print("%s"%(code[2]))
elif Key() == code[3]:
print("%s"%(code[3]))
elif Key() == code[4]:
print("%s"%(code[4]))
elif Key() == code[5]:
print("%s"%(code[5]))
elif Key() == code[6]:
print("%s"%(code[6]))
# 创建LED函数
def LED():
if Key() == "middle": # 当按下mid键时,反转LED状态
led.value(not led.value())
# while not MID.value():
# pass
def main():
font.text(oled,str("独立按键"),32,24,color=1,font_size=16,reverse=False,clear=False,show=True,half_char=True, auto_wrap=True)
while True:
dispaly()
LED()
if __name__ == "__main__":
main()
Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号
执行时间: 0.0094048976898193 seconds