Search code examples
pythonbuttoninputraspberry-pigpio

GPIO.wait_for_edge triggering randomly


I've put together a raspberry pi to send a few requests at the press of a momentary switch. all works fine and as expected until i realized that turning on and off plugs nearby was also triggering the program to fire. I'm very new to python but learning as i go. here's the relevant parts of my code

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_UP)

try
  while True:
    print("waiting for input")
    GPIO.wait_for_edge(10, GPIO.FALLING)

       #do requests

except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

I've read somewhere that it could be the wires i'm using for the button that are acting as an antenna and producing the falling edge but not sure how to confirm this or fix it.

Also whether it would be worth putting in a time.sleep delay then rechecking to see if the edge is still true after a short delay?

With a button press it should be false after about half a second whereas with the random triggers potentially its true for longer? Not sure so just looking for some advice really!

Also may be worth pointing out that i'm using one of the first gen raspberry pis as not need for any heavy lifting!


Solution

  • Just in case anyone else stumbles across this, i ended up implementing a wait time of .3 seconds in my program after the button is pressed, then checking to see if it is still a falling edge (Low).

    If it is then continue with my desired code as it's a button press, if not then do nothing as its interference.

    Does mean i have to hold my momentary switch down for about a second to make sure it passes my check but no biggie!

    while True:
       print("waiting for input")
       GPIO.wait_for_edge(10, GPIO.FALLING)
       time.sleep(.3)
       if GPIO.input(10) == GPIO.LOW:
          #do the thing i want as it's a button press
       else:
          #do nothing as its interference