0
votes


Can you please tell me what's the best way to catch a low state (or falling-edge more precisely) of GPIO in an endless script?
To be clear I will run this script at boot (in the bg) and everytime when a user will push a button (connected to this GPIO) this will put this pin at LOW state. I want to detect each one of them and perform actions at every push.
I already have this code but it will consume to much CPU I think... I need sth like an interrupt in my mind :

import RPi.GPIO as GPIO

#Set GPIO numbering scheme to pinnumber
GPIO.setmode(GPIO.BCM)
#setup pin 4 as an input
GPIO.setup(4,GPIO.IN)

# To read the state
While true:
   state = GPIO.input(4)
   if state:
      print('on')
   else:
      print('off')

EDIT

Here the pinout by BCM or BOARD, I will work with BCM

As you can the the pin number is 4 because my push button is on GPIO4. Still get off all the time with your code or constant detection of edge event with the code of @jp-jee

EDIT

#!/usr/bin/env python3
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.IN)

def Callback(channel):
      print('pushed')

GPIO.add_event_detect(4, GPIO.FALLING, callback = Callback, bouncetime = 300)

while(True):
   time.sleep(1)

Now my code print always pushed when the button is released and print nothing when I push it...

2

2 Answers

0
votes

Have you tried to use interrupts?

import time
import RPi.GPIO as GPIO

GPIO.setup(4, GPIO.IN)

def Callback(channel):
   state = GPIO.input(channel)
   if state:
      print('on')
   else:
      print('off')

GPIO.add_event_detect(4, GPIO.FALLING, callback = Callback, bouncetime = 300)  

while(True):
   time.sleep(1)
0
votes

Take a look at the documentation of raspberry-gpio-python.

What you want is GPIO.add_event_detect(channel, GPIO.RISING) in combination with a callback function. Since you're using a button, you also need to consider bouncing.

In the end, you will end up with something like this (taken from the linked website):

def my_callback(channel):
    print('This is a edge event callback function!')

GPIO.add_event_detect(channel, GPIO.FALLING, callback=my_callback, bouncetime=200)