I am trying to get a script to work where a button is monitored and if operated once then turn on something. Then if operated again turn it off. Like a toggle button. I have it working with the following code however this is not good as it always waits for the button edge to trigger. So any other code in the while loop will not be carried out. How can I check in the function if a button has been operated and if not then carry on with the rest of the code.
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # using broadcomm pin numbers
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
prevWater = 0
def buttonControl ():
global prevWater
# take a reading
GPIO.wait_for_edge(21, GPIO.FALLING)
prevWater = not prevWater
return prevWater
while 1:
waterButton = buttonControl ()
if (waterButton == True):
print ("Turn water on")
if (waterButton == False):
print ("Turn water off")
# check what is returned from function
print (waterButton)
# need to do other stuff here
GPIO.cleanup()
Any help will be much appreciated
I have tried callback as shown below
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # using broadcomm pin numbers
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
prevWater = 0
def my_callback(channel):
global prevWater
print("button pressed")
prevWater = not prevWater
return prevWater
while 1:
GPIO.add_event_detect(21, GPIO.RISING, callback=my_callback)
waterButton = prevWater
if (waterButton == True):
print ("Turn water on")
if (waterButton == False):
print ("Turn water off")
# check what is returned from function
print (waterButton)
# need to do other stuff here
GPIO.cleanup()
but I am getting an error as shown below
File "test.py", line 19, in GPIO.add_event_detect(21, GPIO.RISING, callback=my_callback) RuntimeError: Conflicting edge detection already enabled for this GPIO channel