Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared variable with GPIO callback function with Raspberry

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.

like image 874
NiBE Avatar asked Apr 23 '15 13:04

NiBE


2 Answers

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
like image 170
NiBE Avatar answered Sep 23 '22 06:09

NiBE


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.

like image 43
gth3q Avatar answered Sep 23 '22 06:09

gth3q