Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用带有Raspberry的GPIO回调函数共享变量_Python_Raspberry Pi_Gpio_Raspberry Pi2 - Fatal编程技术网

Python 使用带有Raspberry的GPIO回调函数共享变量

Python 使用带有Raspberry的GPIO回调函数共享变量,python,raspberry-pi,gpio,raspberry-pi2,Python,Raspberry Pi,Gpio,Raspberry Pi2,我用python编写了这个简单的测试程序,以检查当我按下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 G

我用python编写了这个简单的测试程序,以检查当我按下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)
我只读取0个值,当我按下按钮时,我看到“按下!”,但变量没有改变。据我所知,原因是回调函数作为新线程使用,当然变量不能正确设置。有没有办法以某种方式向回调函数发送共享变量


非常感谢您的建议。

您好,请找到解决方案,我正在发布它,也许它会有用。 使用单词global让它起作用

因此,回调函数变为:

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

我也有同样的问题让我发疯。。。将变量设置为
global
是解决方案。解释是根据关于全局变量的教程,只要变量没有标记为全局变量,它就保持在函数的局部范围内。在函数中使变量成为全局变量有两个后果:

a) 如果全局变量x不存在:
global x=0
创建一个新的全局变量
x
,并将其值设置为0

b) 如果全局变量x已经存在:
global x=0
将现有全局变量的值更改为0(与不带global关键字的
x=0
相反,该关键字会将值0分配给局部范围的变量)


因此,b是在回调函数中更改全局var值的解决方案。

答案是正确的,但OP已经找到了此解决方案,请避免使用已在将来发布的解决方案添加答案。