Generic variable with raspberry GPIO callback function

I wrote this simple python test program to check if something happened 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 read only 0 values, and when I press the button, I see "Pressed!" but the variable has not changed. From what I understand, the reason lies in the fact that the callback function starts as a new thread, and, of course, the variable cannot be set correctly. Is there any way to send a generic var to a callback function?

Thanks so much for any helpful tips.

+4
source share
1 answer

, , , , . , .

, :

def my_callback(channel):
    global testVar
    print "Pressed!"
    testVar= 32
+3

Source: https://habr.com/ru/post/1584280/


All Articles