前言
4X4矩阵键盘应用
代码
Python
代码如下):
#创建按键对象 列 行
#Key = KEY(C1,C2,C3,C4,R1,R2,R3,R4)
#接收按键值
#temp = Key.matrix()
from machine import Pin
import time
code = [
['1','2','3','a'],
['4','5','6','b'],
['7','8','9','c'],
['*','0','#','d'],
]
class KEY(object):
def __init__(self,C1,C2,C3,C4,R1,R2,R3,R4):
self.C1 = C1
self.C2 = C2
self.C3 = C3
self.C4 = C4
self.R1 = R1
self.R2 = R2
self.R3 = R3
self.R4 = R4
#按键扫描函数
def matrix(self):
#行
R1 = Pin(self.R1,Pin.OUT)
R2 = Pin(self.R2,Pin.OUT)
R3 = Pin(self.R3,Pin.OUT)
R4 = Pin(self.R4,Pin.OUT)
#列
C1 = Pin(self.C1,Pin.IN,Pin.PULL_UP)
C2 = Pin(self.C2,Pin.IN,Pin.PULL_UP)
C3 = Pin(self.C3,Pin.IN,Pin.PULL_UP)
C4 = Pin(self.C4,Pin.IN,Pin.PULL_UP)
key = 'None'
#设置第一行拉低
[R1.value(0),R2.value(1),R3.value(1),R4.value(1)]
#扫描每一列键值
if(C1.value() == 0 or C2.value() == 0 or C3.value() == 0 or C4.value() == 0):
time.sleep(0.020)
if C1.value() == 0:
key = code[0][0]
while not C1.value():
pass
elif C2.value() == 0:
key = code[0][1]
while not C2.value():
pass
elif C3.value() == 0:
key = code[0][2]
while not C3.value():
pass
elif C4.value() == 0:
key = code[0][3]
while not C4.value():
pass
else:
R1.value(1)
#设置第二行拉低
[R1.value(1),R2.value(0),R3.value(1),R4.value(1)]
#扫描每一列键值
if(C1.value() == 0 or C2.value() == 0 or C3.value() == 0 or C4.value() == 0):
time.sleep(0.020)
if C1.value() == 0:
key = code[1][0]
while not C1.value():
pass
elif C2.value() == 0:
key = code[1][1]
while not C2.value():
pass
elif C3.value() == 0:
key = code[1][2]
while not C3.value():
pass
elif C4.value() == 0:
key = code[1][3]
while not C4.value():
pass
else:
R2.value(1)
#设置第三行拉低
[R1.value(1),R2.value(1),R3.value(0),R4.value(1)]
#扫描每一列键值
if(C1.value() == 0 or C2.value() == 0 or C3.value() == 0 or C4.value() == 0):
time.sleep(0.020)
if C1.value() == 0:
key = code[2][0]
while not C1.value():
pass
elif C2.value() == 0:
key = code[2][1]
while not C2.value():
pass
elif C3.value() == 0:
key = code[2][2]
while not C3.value():
pass
elif C4.value() == 0:
key = code[2][3]
while not C4.value():
pass
else:
R3.value(1)
#设置第四行拉低
[R1.value(1),R2.value(1),R3.value(1),R4.value(0)]
#扫描每一列键值
if(C1.value() == 0 or C2.value() == 0 or C3.value() == 0 or C4.value() == 0):
time.sleep(0.020)
if C1.value() == 0:
key = code[3][0]
while not C1.value():
pass
elif C2.value() == 0:
key = code[3][1]
while not C2.value():
pass
elif C3.value() == 0:
key = code[3][2]
while not C3.value():
pass
elif C4.value() == 0:
key = code[3][3]
while not C4.value():
pass
else:
R4.value(1)
return key
#返回的的是字符串类型