Python if temperature is to high for X minutes then

Viewed 32

i'm busy building a python script which will monitor the temperature of an Sensor. What i want is that i've get an SMS if the temperature is to high or low for at least 5 minutes.

For this i've tried this:

#//Create a new empty array
tempArray = array('f', [])
    
#//If tempCelcius from sensor Fridge_sen is higher then 5°C for 5 Minutes send SMS
    if readTempLines(Fridge_sen)[0] > 28:
        time_start = time.time()
        while time.time() < t_end: #While time is less then t_end add tempCelcius from Fridge_sen to array every 10 seconds
            tempArray.append(readTempLines(Fridge_sen)[0])
            time.sleep(10)
            if readTempLines(Fridge_sen)[0] < 28:
                #//clear tempArray
                tempArray = array('f', [])
                break
        #//If tempArray is not empty send SMS with average tempCelcius from array
        if len(tempArray) > 25:
            time_end = time.time() 
            #//difference between time_start and time_end in minutes
            time_diff = (time_end - time_start) / 60
            timediff = time_diff.strftime('%M')
            print (timediff)
            sendSMS("Kühlschrank", readTempLines(Freezer_sen)[0], "hoch")
            print("Temperatur um " + time.strftime('%H:%M:%S') +" Fridge: " + str(sum(tempArray) / len(tempArray)) + " °C")
            #//clear tempArray
            tempArray = array('f', [])

To test if everything is working i've written this and it works:

#//If tempCelcius from sensor Fridge_sen is higher then 5°C send SMS
if readTempLines(Fridge_sen)[0] > 5:
    sendSMS("Kühlschrank", readTempLines(Fridge_sen)[0], "hoch")
    print("Temperatur um " + time.strftime('%H:%M:%S') +" Fridge: " + str(readTempLines(Fridge_sen)[0]) + " °C")

How can i build a loop which checks the temperature every 10 Seconds and only send me an alert if after 5 minutes the temperature of the 10 second check is still to high?

Any hints? Thank you!

Regards

Florian

1 Answers

you can do something like this.

counter = 0
reading_period_s = 10
max_time_high_s = 5 * 60   # 5 minutes to seconds

# max_time_high_s  // reading_period_s gives us the max val of the counter
max_counter = max_time_high_s // reading_period_s

while True:
    tooHigh = isTemperatureTooHigh()
    if tooHigh:
        counter +=1   # increase a counter every time temp is too high
    else:
        counter = 0   # if a reading shows no high temp reset the counteer

  
    if counter > max_counter :
        print(f"ERROR, temperatur has been too high for {max_time_high_s } seconds")
    time.sleep(reading_period_s)   # sleep 
Related