python - 如何从一个类中显示连续计算的函数值?
问题描述
一旦在引脚上检测到信号梯度,我希望程序连续运行并输出方法 (func1 - func4) 的值。
这只是一个测试代码,用于了解我如何访问这些值,因为我编写了一个“程序”,其表面显示来自我仅使用全局变量的机器的不间断值,我不想在这里发布它,因为这很尴尬......我想摆脱所有的全局变量
树莓派连接到我通过gpio截获4个信号的机器。
cavity = 2
count = 0
scrap = 0
uptime = datetime.timedelta(0)
downtime = datetime.timedelta(0)
def func1(channel):
if GPIO.input(7) == 0:
while True:
uptime = uptime + datetime.timedelta(0,1)
time.sleep(1)
if GPIO.input(7) == 1 or GPIO.input(37) == 0:
break
def func2(channel):
scrap = scrap + cavity
def func3(channel):
count = count + cavity
def func4(channel):
if GPIO.input(37) == 0:
while True:
downtime = downtime + datetime.timedelta(0,1)
if GPIO.inpu(37) == 1:
break
GPIO.add_event_detect(7, GPIO.RISING, callback = func1, bouncetime = 100) #Run
GPIO.add_event_detect(29, GPIO.RISING, callback = func2, bouncetime = 100) #Scrap
GPIO.add_event_detect(13, GPIO.RISING, callback = func3, bouncetime = 100) #Count
GPIO.add_event_detect(37, GPIO.RISING, callback = func4, bouncetime = 100) #Alarm
class Output(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.show()
def show(self):
print('ich werde aufgerufen')
while True:
print(uptime)
print(scrap)
print(count)
print(downtime)
print('############################')
time.sleep(5)
thread2 = Output()
thread2.start()
只输出零这是意料之中的,但我如何访问变量,以便在信号检测时值增加
解决方案
您的函数只是创建自己的局部变量,因此全局变量不会改变。
试试这个:
def func1(channel):
global uptime
if GPIO.input(7) == 0:
while True:
uptime = uptime + datetime.timedelta(0,1)
time.sleep(1)
if GPIO.input(7) == 1 or GPIO.input(37) == 0:
break
def func2(channel):
global scrap
scrap = scrap + cavity
def func3(channel):
global count
count = count + cavity
def func4(channel):
global downtime
if GPIO.input(37) == 0:
while True:
downtime = downtime + datetime.timedelta(0,1)
if GPIO.inpu(37) == 1:
break
推荐阅读
- javascript - 带按钮的多个复选框
- sql - CASE WHEN 错误 - 根据另一列的条件为列设置值
- android - 我安装了最新版本的 Android Studio。我在同步 gradle 时遇到错误
- python - 代码只给我发一篇文章,而不是我所有的抓取数据
- flutter - 如何在飞镖中更改 SizedBox 的颜色
- docker - 我对 jenkins docker 集成有疑问
- excel - 在某些值之间运行 IF 函数时,VBA 类型不匹配/运行时错误“13” - 为什么会发生这种情况?试图隐藏空行
- python - 如何在 Python Flask 中实现事件处理
- typescript - 我无法在 TypeScript 中指定准确的导出值
- php - 为什么我收到字段类型的枚举值对于此搜索消息无效?