Open 4.5Temperature and humidity detection.py and click .
'''
* Filename : Temperature and humidity detection
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin
import time
import dht
#Connect XHT11 to pin (2)
XHT = dht.DHT11(Pin(2))
red = Pin(13, Pin.OUT)
yellow = Pin(14, Pin.OUT)
green = Pin(15, Pin.OUT)
# attain temperature and humidity value per second and print them
while True:
XHT.measure() # enable XHT11 sensor to measure the values once
# call dht built-in function to attain tempreature value, and print it on Shell
print('temperature:',XHT.temperature())
time.sleep(0.1)
if XHT.temperature() > 35:
red.on()
yellow.off()
green.off()
elif XHT.temperature() > 29:
yellow.on()
red.off()
green.off()
elif XHT.temperature() > 24:
green.on()
red.off()
yellow.off()
Conceive:
Set three thresholds to separate the temperature range: 24, 29, 35, which are adjustable according to needs.
preference temperature: 24°C ~ 29°C
warning temperature: 29°C ~ 35°C
high temperature: over 35°C
Corresponding LED will light up when the ambient temperature is within the related ranges.
Within preference temperature range: the green LED lights up
Within warning temperature range: the yellow LED lights up.
Within high temperature range: the red LED lights up.
Code structure:
Initialization. set the pins of XHT11 temperature and humidity sensor and the traffic light module.
Loop.
XHT11 sensor reads and outputs the temperature values.
Determine which section the temperature value is in, so then light up corresponding LED.
24°C ≤ temperature < 29°C: the green LED lights up and other LEDs are off.
29°C ≤ temperature < 35°C: the yellow LED lights up and other LEDs are off.
temperature > 35°C: the red LED lights up and other LEDs are off.