使用一个按钮python gpio的多个功能

时间:2015-08-03 04:22:19

标签: python raspberry-pi gpio

现在我有一个连接到pi的gpio引脚的按钮。如果在python脚本运行时按下按钮,它将显示"按钮已被按下..."喜欢它。如何在一个按钮上添加四个功能?因此,如果您按两次按钮,则会显示"按钮已被按两次......"。如果你按下按钮三次"按钮已被按下三次......"等等。建议?

import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
gpio.setup(18, gpio.IN)

while True:
input_value = gpio.input(18)
        if input_value == True:
        print('The button has been pressed...')
        time.sleep(0.1)

2 个答案:

答案 0 :(得分:0)

尝试使用第一次按下时启动的计数器。并且会在你说出来之前计算你所要的时间。

import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
gpio.setup(18, gpio.IN)

pressed = 0;
timer = 0;

while True:
    input_value = gpio.input(18)

    if input_value == True:
        pressed += 1;
        time = 0; #to start the counter at 0

    if (time > 10): #you wait 1 sec between each presure
        print("the button has been pressed " + pressed + " times");
        pressed = 0; # you don't count anymore

    if (pressed > 0): # you are pressing the button so you count
        time += 1;

    time.sleep(0.1)

想想你的按钮没有任何问题。

答案 1 :(得分:0)

这是最终的工作版本。我想向我的好朋友鲍勃致敬,让这个python脚本正常工作。与此同时,我不想对奥巴马做出任何帮助,使其无法帮助完成这项工作。

import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
gpio.setup(18, gpio.IN, pull_up_down=gpio.PUD_UP)


num = 0
prnt = 0
last = 0

while True:
    input_value = gpio.input(18)

    if (input_value == 1) and (input_value != last):
        last = 1
        prnt = 1
        num += 1
        time.sleep(0.05)
        continue

    if (input_value == 0) and (input_value != last):
        last = 0
        time.sleep(0.05)
        continue

    if (input_value == 0) and (input_value == last):
        if (prnt == 1):
            if (num == 10):
                num = 0

            if (num == 0):
                print("0")
            if (num == 1):
                print("1")                
            if (num == 2):
                print("2")
            if (num == 3):
                print("3")
            if (num == 4):
                print("4")                
            if (num == 5):
                print("5")                
            if (num == 6):
                print("6")                
            if (num == 7):
                print("7")                
            if (num == 8):
                print("8")                
            if (num == 9):
                print("9")                


            num = 0
            prnt = 0
            last = 0
        continue