我正在开发基于arduino的小型嵌入式系统,它使用中断来计算事件。代码是这样的:
volatile float count= 0;
attachInterrupt(0, increaseCount, CHANGE);
void increaseCount(){
++count;
}
count 变量应该是易失性的,以便在中断中访问它。现在,我正在使用python在Raspberry pi上编写它。但是,python没有什么叫做易失性的。那么,有没有另一种技术可以在线程/事件期间增加变量。当事件发生并且变量增加时,Python 会给我这个错误。
File "MyApp.py", line 5, in my_callback
count += 1
UnboundedLocalError: local variable 'count' referenced before assignment
有什么帮助吗?
不,Python 中没有 volatile
这样的东西,这是一个太低级的概念。
您应该确保变量可以驻留在一些共享上下文(如对象实例),以便可以在两个上下文之间共享它。Python将完成剩下的工作。
class MyApp(object):
def __init__(self):
self._counter = 0
registerInterrupt(self.interruptHandler)
def interruptHandler(self):
self._counter += 1
def getCount(self):
return self._counter
这样的事情可能就足够了,当然,您必须填写详细信息并进行所需的调用以创建MyApp
实例,并确保有一个函数registerInterrupt()
可以执行所需的工作来设置实例的回调。
另外,请注意,counter
事件几乎不应该在 C 中float
,这是非常奇怪的设计。