Python变量覆盖自身

时间:2015-11-08 22:48:46

标签: python multithreading

我有以下代码块。 fanSensor()会自动运行,但如果我拨打fanOn()fanOverride会将自己设置为0.有人可以帮我弄清楚我做错了什么吗?

..旁边注意,是否会在while循环线程中保持处理能力?

import RPi.GPIO as GPIO
import os
import time
import _thread

fanOnTemp = 57
fanOffTemp = 54
fanPin = 40
currentTemp = 0.0
fanOverride = 0

GPIO.setmode(GPIO.BOARD) #Labels the pins by order on the board
GPIO.setup(fanPin, GPIO.OUT) #Allows control of fanPin

def getFanState():
    print(GPIO.input(fanPin)) #Prints the state of the fanPin

def fanOn():
    GPIO.output(fanPin, 1)  #Set fanPin on
    fanOverride = 1

def fanOff():
    GPIO.output(fanPin, 0) #Set fanPin off
    fanOverride = 0

def getTempF():
    print(Temp()*(9/5)+32)

def getTemp():
    print(Temp())

def Temp():
    seconds=10
    x=0
    for i in range(0,seconds):
        temp=((os.popen('vcgencmd measure_temp').readline()).replace("temp=","").replace("'C\n",""))
        x+=float(temp)
        time.sleep(1) #Sleep the thread for 1 second
    x=x/seconds #Calculate the average temperature
    return(x)

def fanSensor():
    while 1:
        time.sleep(5)
        currentTemp = float((os.popen('vcgencmd measure_temp').readline()).replace("temp=","").replace("'C\n",""))
        print ("Fan Temperature: %.2f" % currentTemp) #removes all but 2 decimal places
        print ("Fanoverride: "+str(fanOverride))
        if fanOverride == 0: #Check for fan override on
            if currentTemp > fanOnTemp:
                GPIO.output(fanPin, 1)
            elif currentTemp < fanOffTemp:
                GPIO.output(fanPin, 0)

_thread.start_new(fanSensor,())

1 个答案:

答案 0 :(得分:1)

假设算法正确,如果需要两个函数来共享其状态(即对同一个变量进行操作),则需要将null声明为全局

fanOverride

有关def fanOn(): global fanOverride GPIO.output(fanPin, 1) #Set fanPin on fanOverride = 1 def fanOff(): global fanOverride GPIO.output(fanPin, 0) #Set fanPin off fanOverride = 0

的更多信息,请查看this SO Q&A