首页 > 解决方案 > 如何从一个类中显示连续计算的函数值?

问题描述

一旦在引脚上检测到信号梯度,我希望程序连续运行并输出方法 (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()

只输出零这是意料之中的,但我如何访问变量,以便在信号检测时值增加

标签: pythonmultithreading

解决方案


您的函数只是创建自己的局部变量,因此全局变量不会改变。

试试这个:

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

推荐阅读