我正在研究一个气象站(raspberry pi),我正在使用python。我开发了一个正在工作的程序,但现在我决定更新我的代码并构建所有的东西(生成类等等)。但是现在我遇到了来自gpiozero的Button的两个问题。
首先,当我试图在一个函数或类Button.when_pressed 中分配一个函数时,当按钮被按下时,这个函数就不会被调用。
下面的代码只是尽量少使用代码的一个示例:
from gpiozero import Button
import time
number = 0
def function_that_gets_called():
global number
number += 1
def main():
wind_sensor = Button(6)
wind_sensor.when_pressed = function_that_gets_called
main()
while True:
# Sleep, so the program doesn't exit immediately
time.sleep(60)
# Do some other stuff with number为什么在按下按钮时不调用function_that_gets_called。类似地,当我试图在类中分配when_pressed时,两者都不能工作。
第二,为什么我必须使用global number?否则,数字变量不会被更改,但是是否有另一种解决方案可以更好地实现呢?
非常感谢你!
编辑:编辑time.sleep(60)。我特别指出,我的意思是不起作用。这是我在这里关于堆叠溢出的第一个问题,所以请原谅,如果还不够精确,很高兴告诉我如何改进我的问题。
发布于 2021-02-16 00:44:09
当调用wind_sensor后主函数退出时,我不知道main()会发生什么。我猜它会被摧毁。无论如何,如果您移除主命令和对它的调用,您的代码就会正常工作。尝试在增量后添加一个print(number),这样当您按下按钮时就可以看到一些东西。
关于这个的课程..。
我还在一个类中与这个when_pressed做斗争。但我已经让它在我的案子里发挥作用了。我的应用程序可以有一个可变数目的按钮,它们都是用代码开头实例化的对象来管理的。应用程序不会退出,因为它有一个带有ws.runForever()的底层websocket客户端。在您的情况下,您可以使用像while 1: pass这样的循环,它将使用大约12%到15%的CPU或pause()来保持代码的运行,而不需要使用处理器(与ctrl+c一起退出)。
现在,我使用dict来处理位于我的类中的按钮变量N以及我的处理程序。像这样的东西可以使用类,继续运行,并且您可以展开代码以拥有一个动态的按钮数。
from gpiozero import Button
import json
class myController()
theButtons={}
yourNumber=0
def __init__(self):
self.yourNumber=0 #here is the right place to initialize the variables!
def handler(self,Button): # here the first parameter is the class itself and then the button that generated the interrupt --> this works like that, but could not confirm that self needs to exist before the mandatory arg "Button" because it is inside the class, or by other reason. Can somebody confirm? not clear in documentation.
print("Pressed button in pin: ",str(Button.pin.number))
self.yourNumber +=1
def addButton(msg): # Example json: '[{"id":"button1","pin":2},{"id":"button2","pin":4}]' the msg is the message that is received via websocket with the configuration of buttons. you can make it at you own needs. id and pin are string that I choose for machines dialog
btns=json.loads(msg)
for b in btns:
theButtons[b.get('id')]=Button(b.get('pin'))
theButtons[b.get('id')].when_pressed=self.handler
#and that's it for the class no let's instantiate and make the code persist running
if __name__ == "__main__": # this is executed only if you call this file. if you use it as import it will not run. it's a best practice, should you need to import the class in other file and don't want the code to execute.
btnController=myController()
pause()类在这个usecase上有点过分,但是我相信它解决了您的问题而不使用全局变量。
https://stackoverflow.com/questions/65612021
复制相似问题