-3

I'm having a lot of trouble with something that should be simple but I just can't get it working.

I have the following function that loops forever on it's own thread. There's some variables inside the function I need to edit from another function.

This is always checking DS18B20 temp sensors and records a min/max temp. These are some of the variables I need to access and reset from another function.

def getTemp():
while True:
    try:
        i = 0
        # count how many ds18b20s are found
        for sensor in W1ThermSensor.get_available_sensors():
            i = i + 1

        global temperatures
        # setup arrays
        IDs = [0]*i  
        temps = [0]*i
        minTemp = [0]*i
        maxTemp = [0]*i
        i = 0  # reset counter

        for sensor in W1ThermSensor.get_available_sensors():
            prevTemps[i] = temps[i]
            IDs[i] = sensor.id  # get IDs
            temps[i] = (sensor.get_temperature(W1ThermSensor.DEGREES_F))  # get temps
            temps[i] = (round(temps[i], 2))  # round
            if temps[i] > maxTemp[i]:
                maxTemp[i] = temps[i]
                saveDs18b20Max(maxTemp[i],IDs[i])
            if temps[i] < minTemp[i]:
                minTemp[i] = temps[i]
                saveDs18b20Min(minTemp[i],IDs[i])

            i = i + 1  # count

        temperatures = temps[:]
    
    except:
        print('error')

The above works good but I can't access any variables. I added a global temperatures variable and later I copy the contents of temps list to it but when I call it from another function I get the following error.

NameError: name 'temperatures' is not defined

This is the function I call trying to print temperatures.

def resetMin(addr):
     print("resetMin")
     print(addr)
     print(temperatures)

I use Visual Studio Code and as far as it's concerned temperatures is global as it doesn't show an error when I call it.

Thanks

2 Answers2

0

first of all you should try declare temperatures outside of the method and then declare global cause global only tells you that you're not creating a local method variable but that it's using a global variable. Make temperatures outside of the method.

So edit the last method to this.

def resetMin(addr):
   global temperatures
   print("resetMin")
   print(addr)
   print(temperatures)
Redfer
  • 162
  • 11
0

Suggest to raise a class C which contains the data you want to operate in the loop and access in another method.

class C:
    def __init__(self):
        self.temperatures=0

def getTemp(c):
while True:
    try:
        #...
        # hanlde c.temperatures
    except:
    sleep(0.1)
def resetMin(addr, c):
    # hanlde c.temperatures
c=C()
# thread.start_new_thread(getTemp,(c,))
# thread.start_new_thread(resetMin,('addr1',c,))
Yang Liu
  • 346
  • 1
  • 6