I wrote this simple test program in python to check if something happen when I press a button in my Raspberry Pi:
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
testVar=0
def my_callback(channel):
print "Pressed!"
testVar= 32
GPIO.add_event_detect(24, GPIO.FALLING, callback=my_callback, bouncetime=200)
while True:
print str(testVar)
sleep(0.5)
I'm reading only 0 values and when I pressed the button I see "Pressed!" but the variable did not change. From what I understand the reason is because the the callback function is lunched as new Thread and of course the variable cannot be setted correctly. Is there a way to send a shared var to the callback function in some way?
thanks a lot for any good advice.
Hi just find the solution, I'm posting it maybe it can be useful. using the word global make it works.
So the call back function becomes:
def my_callback(channel):
global testVar
print "Pressed!"
testVar= 32
I had the same issue driving me crazy... set the variable to global
was the solution. The explanation is according to this tutorial on global variables that the variable remains in scope local to the function as long as it is not marked as global. Making the variable global inside the function has two consequences:
a) If a global variable x don't exists: global x = 0
creates a new global variable x
and sets its value to 0
b) If a global variable x already exists: global x = 0
changes the existing global variable's value to 0 (in opposition to x = 0
without the global keyword which would assign the value 0 to a local-scoped variable).
So b was the solution to alter the global var's value inside the callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With