指间ESP触摸片与蜂鸣器操作
502748957@qq.com(讨论 | 贡献)2019年7月25日 (四) 06:50的版本
指间ESP按键操作
import machine, display
from machine import Pin, PWM
tc0 = machine.TouchPad(Pin(32))
tc1 = machine.TouchPad(Pin(33))
tc2 = machine.TouchPad(Pin(27))
tc3 = machine.TouchPad(Pin(14))
tc4 = machine.TouchPad(Pin(2))
bkcolor = 0x333333
music = PWM(Pin(4))
music.duty(0)
touchli = [False, False, False, False, False]
notes = [523, 587, 659, 698, 784, 880]
tft = display.TFT()
tft.init(tft.ST7789)
tft.clear()
tft.rect(0, 0, 240, 240, bkcolor, bkcolor)
def getTouch():
if tc0.read() < 100:
touchli[0] = True
else:
touchli[0] = False
if tc1.read() < 100:
touchli[1] = True
else:
touchli[1] = False
if tc2.read() < 100:
touchli[2] = True
else:
touchli[2] = False
touchli[2] = False
if tc3.read() < 100:
touchli[3] = True
else:
touchli[3] = False
if tc4.read() < 100:
touchli[4] = True
else:
touchli[4] = False
while True:
getTouch()
for i in range(5):
if touchli[i]:
tft.rect(10 + 45 * i, 190, 40, 25, bkcolor, 0x00F0F0)
music.duty(50)
music.freq(notes[i])
else:
tft.rect(10 + 45 * i, 190, 40, 25, bkcolor, 0xF0F000)
if (
(not touchli[0])
and (not touchli[1])
and (not touchli[2])
and (not touchli[3])
and (not touchli[4])
):
music.duty(0)
程序详解:import为引用所需文件,包括display(屏幕驱动),Pin(IO口驱动)、蜂鸣器PWM驱动 import machine, display
from machine import Pin, PWM
之后声明5个触摸按键 tc0 = machine.TouchPad(Pin(32))
tc1 = machine.TouchPad(Pin(33))
tc2 = machine.TouchPad(Pin(27))
tc3 = machine.TouchPad(Pin(14))
tc4 = machine.TouchPad(Pin(2))
初始化TFT并使用背景色"bkcolor"填充屏幕 bkcolor = 0x333333
tft = display.TFT()
tft.init(tft.ST7789)
tft.clear()
tft.rect(0, 0, 240, 240, bkcolor, bkcolor)
声明触摸状态数组与蜂鸣器音色数组 touchli = [False, False, False, False, False]
notes = [523, 587, 659, 698, 784, 880]
编写gettouch函数,按下为true,否则为false def getTouch():
if tc0.read() < 100:
touchli[0] = True
else:
touchli[0] = False
if tc1.read() < 100:
touchli[1] = True
else:
touchli[1] = False
if tc2.read() < 100:
touchli[2] = True
else:
touchli[2] = False
touchli[2] = False
if tc3.read() < 100:
touchli[3] = True
else:
touchli[3] = False
if tc4.read() < 100:
touchli[4] = True
else:
touchli[4] = False
主程序中扫描触摸片,按下则绘制黄色矩形,否则绘制青色矩形。music.duty(50)为占空比,music.freq(notes[i])为音高 while True:
getTouch()
for i in range(5):
if touchli[i]:
tft.rect(10 + 45 * i, 190, 40, 25, bkcolor, 0x00F0F0)
music.duty(50)
music.freq(notes[i])
else:
tft.rect(10 + 45 * i, 190, 40, 25, bkcolor, 0xF0F000)
if (
(not touchli[0])
and (not touchli[1])
and (not touchli[2])
and (not touchli[3])
and (not touchli[4])
):
music.duty(0)
|