-1

In my program, I have 10 push buttons

In a certain function of my program, I need to check if a particular push button is pressed. If it is pressed, function A should be called, while if any other button is pressed, function B should be called.

Is there any way to do it WITHOUT writing 10 if statements? I know which button triggers function A, say it is on pin 18. So I have the code to check for that pin:

if GPIO.input(btn1): #btn1 is defined as 18 with all GPIO setup functions called
    A()

The other condition to be checked is if any of the other buttons are pressed. The usual way would be the similar if condition as in the above code snippet and trigger B(). But is there a more efficient way to do this?

3

2 Answers 2

0

A solution could be to set up the same callback for each pin of interest:

for channel in channels_of_interest:
    # add rising edge detection on a channel
    GPIO.add_event_detect(channel, GPIO.RISING, callback=cb) 

The callback, which I denoted cb, has a single argument that represents the channel being triggered:

def cb(channel):
    if channel == 18:
       A()
    else:
       B()

See more here

-1

According to https://gist.github.com/aitzol/1b1642712146adf5bcd8 we can use this simple code:

#!/usr/bin/env python
 
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
while True:
    data = input("Insert GPIO BCN number to check status (blank to quit): ")
    if (data == ''):
        break
    try:
        number = int(data)
    except:
        continue
    GPIO.setup(number, GPIO.IN) 
    st = GPIO.input(number)
    print(st)
2
  • 1
    Python 2 has been sunset and so should not be suggested as a solution. The above also doesn't really answer the question as it polls the GPIO pin but to act on the value you would need an if statement with the OP is looking to avoid. A better way to go would be to use RPi.GPIO interrupts
    – ukBaz
    Sep 28, 2021 at 6:42
  • @ukBaz Yeah your right. edited.
    – Pouya
    Sep 28, 2021 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.