DHT22 Temperature and Humidity Sensor- Raspberry Pi4

Shalav Kakati
5 min readFeb 12, 2021

DHT22 sensor( white ) on breadboard, attached to Pi 4 by ribbon cables ( left side ).

This is my third project on the Raspberry Pi 4, my second which I do not document here was to only bring up the DHT22 sensor to see if it worked. Now wanted to try something a little more realistic. The project that I made was a DHT22 sensor attached to a breadboard along with 2 lights, one red one green, to indicate if the temperature and the humidity were in the safe range. The user python program could setup a range for temp and humidity and outside of these the red led should blink, and within it the green. The Pi being a full computer with ethernet/wifi/sound, a real product may trigger all forms of alerts from such a “weather station/industrial safety monitor” including logging to a remote server, email, sound etc.

The cheaper DHT11 sensor has a narrower temp range (only +ve 0–50C) than DHT22 (-40 to +125C) which is also very cheap, so I selected this one. Purchased much of the kit from an excellent store https://sumeetinstruments.com/ in kolkata and through amazon india.

The items required:

A breadboard

Jumper wires for connection ( the black, red, yellow wires)

2 Lights( one red and one green for temperature and humidity safe range indication )

I used the flat ribbon cable and educational marked red plate identifying all the 40 gpio pins connected from Pi to the breadboard for convenience and to keep the wires short.

The code:

On the python shell itself, we need to write certain code(which I took some help of my dad since I’m still a bit raw in python), The basic idea is python has libraries for controlling any sensor and also to control the gpio pins as input or output. we import the libraries and look around for example code to adapt to our own needs, blending multiple pieces to get the functionality we want,

The following code was what I used for scanning the temperature and showing the user whether it was in the safe range by programming the lights to indicate as such.


import Adafruit_DHT #library to read the dht22
import time
import RPi.GPIO as GPIO #library to manage the gpio pins
from datetime import datetime
GPIO.setmode(GPIO.BCM) #there are two modes bcm and board
GPIO.setwarnings(False) #clear any stale state
GPIO.setup(4, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 27

humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
GPIO.output(4, False)
GPIO.output(4, False)
print(“testing read of sensor once”)
if humidity is not None and temperature is not None:
print(“Temp={}C Humidity={}”.format(temperature, humidity))
else:
print(“Sensor failure. Check wiring.”)
exit()
time.sleep(1)print(“will build base value by taking average of next 5 reads”)avgtemp = avghum = 0.0for i in range(1,6):
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
print(“Baseline loop %d temp %3.3f humidity %3.3f” % (i, temperature, humidity))
else:
print(“Sensor failure. Check wiring.”)
exit()
avgtemp += temperature
avghum += humidity
time.sleep(1)
#create the baseline avg values from the previous readings
avghum /= 5.0
avgtemp /= 5.0

print(“baseline values temperate=%3.3f humidity=%3.3f”%(avgtemp,avghum))
#initially we set the range violation flags to false
temp_violate = False
hum_violate = False
#variables to control the LED state and make the right LED blink
greenstate = True
redstate = False
ttoggler = htoggler = False
print(“starting monitoring phase”)while True:
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
now = datetime.now()
current_time = now.strftime(“%d:%m:%y %H:%M:%S”)
print(“%s temp %3.3f humidity %3.3f” % (current_time,temperature, humidity))
else:
print(“Sensor failure. Check wiring.”)
exit()
time.sleep(1)
#logic is if temp deviates -2C or +2C from the initial baseline,
#shut the green led and blink the red led
#logic for humidity is -4% or +4% for the red led
#if temp, humidity are within these bounds, green led will keep
#blinking
if (temperature < avgtemp-2) or (temperature > avgtemp+2):
print(“WARNING temperature has violated safety bound”)
ttoggler = True
temp_violate = True
else:
temp_violate = False
if ttoggler:
ttoggler = False
print(“WARNING CLEAR temperature has returned within safety bounds”)
if (humidity < avghum-4) or (humidity > avghum+4):
print(“WARNING humidity has violated safety bound”)
htoggler = True
hum_violate = True
else:
hum_violate = False
if htoggler:
htoggler = False
print(“WARNING CLEAR humidity has returned to within safety bounds”)
if not temp_violate and not hum_violate:
if greenstate:
GPIO.output(13, True)
else:
GPIO.output(13, False)
greenstate = not greenstate
else:
GPIO.output(13, False)
if redstate:
GPIO.output(4, True)
else:
GPIO.output(4, False)
redstate = not redstate

For reference I used these videos to get an idea “how to use a DHT sensor with Pi” and “How to setup a LED on Pi”

If the temperature and humidity were in the safe bounds, the green light would start blinking on the board, and if they were out of safe bounds, the green light would stop blinking and the red would start to blink.

Blinking red light on the breadboard

The blinking red light indicates that the temperature and humidity were out of safe bounds.

Code segment from executing the python program:

“08:02:21 09:14:46 temp 24.100 humidity 49.200
08:02:21 09:14:48 temp 24.100 humidity 49.200
08:02:21 09:14:49 temp 24.100 humidity 49.000
08:02:21 09:14:51 temp 24.100 humidity 48.700
08:02:21 09:14:52 temp 24.100 humidity 48.500
08:02:21 09:14:54 temp 24.100 humidity 48.400
08:02:21 09:14:55 temp 24.100 humidity 48.400
08:02:21 09:14:59 temp 24.000 humidity 48.300
08:02:21 09:15:01 temp 24.000 humidity 48.100
08:02:21 09:15:10 temp 24.000 humidity 47.500
08:02:21 09:15:11 temp 23.900 humidity 47.400”

This segment of code shows the output of the python program I had used for testing the temperature and humidity. It displays the time along with the temperature reading (in Celsius) and the percentage of humidity in the air during that exact time.

To try a change of temperature I used a lit match to change it for a few seconds and left it overnight in a room with windows open, the temp had dropped below the avg-4 range by early morning so red was blinking. For the humidity I blew moist air from mouth onto the sensor which sharply spiked the value up, and then it came down again. There seems to be a dampening feature in the sensor to avoid spiky readings, so readings head where we expect but with a lag of a couple secounds (plus we have a 1 sec delay in each loop as that is the recommended delay for continuously reading the DHT22)

The following video demonstrates the usage of the temperature and humidity sensor in concert with the code on the shell.

Accident — I had another sensor to measure humidity BMP180, was playing around with it and by mistake connected it onto the ground and power rails on edge of the board inside of the middle and shorted the rails…”a kind of burning smell came and the Pi4 froze and rebooted” , I was scared it would never return but it came back fine (in meantime realized my error and pulled it out). Not sure if the sensor was dead on arrival or this “incident” made it go bad but was never able to make it work. If anyone wants to try it, youtube has easy to follow guides. for me the i2c read never worked unlike what is seen here.

--

--

Shalav Kakati

Grade 11 IBDP student, interested in the intersections of mechanical, electrical and biomedical engineering.