Search code examples
pythonraspberry-pigpio

How can I assign multiple functions to a single botton on Raspberry?


I'm trying to assign multiple functions to one press button. If I press the button once, it will do one thing, if I press it twice it will do something else and so on. This is my program:

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

pressed = 0;
timer = 0;

while True:
    input_value = gpio.input(10)

    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;

    if (pressed == 1):
        print("t=1"); # do something
    if (pressed == 2):
        print("t=2"); # do something
    if (pressed == 3):
        print("t=3"); # do something
        
    time.sleep(0.1)

I get this error:

Traceback (most recent call last):
  File "/home/pi/Desktop/button.py", line 16, in <module>
    if (time > 10): #you wait 1 sec between each presure
TypeError: '>' not supported between instances of 'module' and 'int'

Anyone know how I can solve it?


Solution

  • The error is due to the use of time instead of timer.

    ...
    ...
    
        if input_value == True:
            pressed += 1;
            timer = 0; #to start the counter at 0
    
        if (timer > 10): #you wait 1 sec between each presure
            print("the button has been pressed " + pressed + " times");
            pressed = 0; # you don't count anymore
    ...