Know what temp/hum to complain about – a DHT22 sensor on a NodeMCU v3 with very simple MicroPython code

My first NodeMCU v3 board. Connected a DHT22 (includes PCB with breakout board) to 3V, ground and data pin to D1 (which is Pin 5). Kept Python code for measuring loop as simple as possible. You will find a fitting pinout at RandomNerdTutorials.

This code measures the temperature and humidity every 30 seconds and prints it on the console.

from machine import Pin
from dht import DHT22
from time import sleep

sensor = DHT22(Pin(5))
while True:
    try:
        sensor.measure()
        print(f'temp = {sensor.temperature()} | hum = {sensor.humidity()}')
        sleep(30)
    except OSError as e:
        print('Failed to read sensor.')

I used Thonny to write the Python code. No need for an additional tool in this case. Save the code to the device and start it. Below you see the console output of the measured values.

A more advanced version publishing the values to a server will be published soon as soon as I find the time to do it and am content with the code quality and the packages used.
I will extend this code for IoT sensors through the house which communicate with a local mosquitto server and generate a website with the current values / graphs in multiple rooms.

Until then – have fun!

All links are not affiliated. Just where I bought it myself.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.