1

I have this following chunk of code. fanSensor() is automatically run, but if I call fanOn(),fanOverride sets itself back to 0. Can someone help me figureout what I'm doing wrong?

..On a side note, will sleeping the while loop thread save on processing power?..

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 Answers1

1

Assuming the algorithm is correct, you need to declare fanOverride as global if you need the two functions to share its state (i.e. act on the same variable)

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

Have a look at this SO Q&A for further info on global

Community
  • 1
  • 1
Pynchia
  • 10,996
  • 5
  • 34
  • 43