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")
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.