我目前正在开发一个连接树莓派的键盘。按下每个按钮时,都需要将一个字符串附加到列表中一次,然后重新启动循环,以便放置下一个输入。代码如下:
message = [] #final list will be stored here
loop = 0 #determines the position of each number inputted
while True:
if (GPIO.input(12) == GPIO.HIGH) and (GPIO.input(19) == GPIO.HIGH): #the character pad works in an array, when 2 "buttons" are pressed, they correspond do a location on the pad
message.insert(loop, "1") #inserts the number into the list
loop = loop + 1
if (GPIO.input(12) == GPIO.HIGH) and (GPIO.input(15) == GPIO.HIGH):
messege.insert(loop, "4")
loop = loop + 1
#this repeats for the other 14 buttons however the code is the same
如果用于";1〃;被按压;4〃;按下时,该代码的输出应该如下所示:
['1' '4']
然而,输出看起来是这样的:
['1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1' '1...]
有没有办法让每个按钮每次按下都激活一次?
此代码中的按钮都是在pud_down 中设置的
这里有一个面向对象的方法。您可以创建一个Button
类。每个按钮可以处于pressed
或released
状态。每当最初按下按钮时,它都会向类变量Button.messages
附加一条消息。同一个按钮在释放之前不会附加另一条消息。在主轮询循环中,我们对所有按钮进行迭代,然后按下或释放它们,具体取决于哪些引脚处于高位:
class Button:
messages = []
def __init__(self, value):
self.value = value
self.is_pressed = False
def hold(self):
if not self.is_pressed:
Button.messages.append(value)
self.is_pressed = True
def release(self):
self.is_pressed = False
buttons = {
(12, 19): Button("1"),
(12, 15): Button("4"),
# ...
}
row_pins = (12, 13, 14) # You'll have to change these. I don't know what these values should be
col_pins = (19, 15, 10) # You'll have to change these. I don't know what these values should be
while True:
for row in row_pins:
for col in col_pins:
button = buttons[(row, col)]
(button.release, button.hold)[all((GPIO.input(pin) for pin in (row, col)))]()
考虑这样的事情。关键是不要评估状态,除非你知道有什么变化:
message = [] #final list will be stored here
loop = 0
states = {
12: GPIO.LOW,
15: GPIO.LOW,
19: GPIO.LOW
}
while True:
change = False
for line in (12,15,19):
if GPIO.input(line) != states[line]:
states[line] = GPIO.input(line)
change = True
if change:
change = False
if states[12]==GPIO.HIGH and states[19]==GPIO.HIGH:
message.insert(loop, "1") #inserts the number into the list
loop = loop + 1
if states[12]==GPIO.HIGH and states[15]==GPIO.HIGH:
messege.insert(loop, "4")
loop = loop + 1
试试这个
message = [] #final list will be stored here
loop = 0 #determines the position of each number inputted
val i = 0
val k = 0
bool canPressAgain =true
while True:
if (GPIO.input(i) == GPIO.LOW) and (GPIO.input(k) == GPIO.LOW):
canPressAgain=true;
if (GPIO.input(12) == GPIO.HIGH) and (GPIO.input(19) == GPIO.HIGH):
#the character pad works in an array, when 2 "buttons" are pressed, they correspond do a location on the pad
i = 12
k = 19
message.insert(loop, "1") #inserts the number into the list
loop = loop + 1
if (GPIO.input(12) == GPIO.HIGH) and (GPIO.input(15) == GPIO.HIGH):
i = 12
k = 15
messege.insert(loop, "4")
loop = loop + 1
canPressAgain = false; #Put this at the end of all 'if' statements
#this repeats for the other 14 buttons however the code is the same