Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If else statement not behaving correctly

I am using a Raspberry Pi Pico-W with MicroPython to build a small temperature alarm.
I have tried to build in some hysteresis however the output is using the upper value not the lower one.

I.e. in the code below alarm 1 switches on at 31 but off again at 30.8

from machine import Pin, I2C
import utime as time
from dth import DHT11, InvalidChecksum, InvalidPulseCount
pin = Pin(16, Pin.OUT, Pin.PULL_DOWN)
sensor1 = DHT11(pin)

pwr = Pin(22,Pin.OUT, Pin.PULL_DOWN)
alarm1 = Pin(21,Pin.OUT, Pin.PULL_DOWN)
alarm2 = Pin(20,Pin.OUT, Pin.PULL_DOWN)

alarm1temp = 30
alarm1hum = 60

alarm2temp = 35
alarm2hum = 80

temphys = 1
humhys = 2

temp = 0
hum = 0
retrys = 5
pwr.on()
while True:
    time.sleep(2)
    retrycounter = 0
    while retrycounter <= retrys:
        try:
            new_temp = sensor1.temperature
            new_hum = sensor1.humidity
            temp = new_temp
            hum = new_hum
            break
        except:
            print("Error reading data. Try: "+str(retrycounter))
            time.sleep(1)
            if retrycounter > retrys-1:
                    temp = alarm2temp + 1
            retrycounter += 1
            
            
    print("Temperature: {}".format(temp))
    print("Humidity: {}".format(hum))
    
    if temp >= (alarm1temp+temphys) or hum >= (alarm1hum+humhys):
        alarm1.on()
        print("Alarm 1 On")
    elif temp < alarm1temp or hum < alarm1hum:
        alarm1.off()
        print("Alarm 1 Off")
        
    if temp >= (alarm2temp+temphys) or hum >= (alarm2hum+humhys):
        alarm2.on()
        print("Alarm 2 On")
    elif temp < alarm2temp or hum < alarm2hum:
        alarm2.off()
        print("Alarm 2 Off")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I assume that the humidity is below the alarm threshold, so this section will reset alarm1, as soon as the temperature drops below alarm1temp+temphys (and therefore the initial if is false)

elif temp < alarm1temp or hum < alarm1hum:
    alarm1.off()
    print("Alarm 1 Off")

Changing the or to and should fix it.

TL;DR: You need either thing to be true to set the alarm, but both to be false to clear it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading