Free tech learning for everyone, from basics to pro

IoT ProjectsIoT SecurityBeginner

Project: a Wi-Fi temperature and humidity monitor

In short: In this project you wire a temperature and humidity sensor to an ESP32 board, write a short MicroPython program and publish readings every minute to an MQTT broker over TLS. It is a perfect first IoT build and teaches the security basics every device needs.

What you will build and what you need

You will build a small sensor node for a server cupboard, greenhouse or bedroom. It measures temperature and relative humidity and sends a JSON message to an MQTT broker once a minute. A dashboard or alert rule can then warn you when a comms room gets too hot.

PartNotes
ESP32 development boardAny board with USB and Wi-Fi; flash the current MicroPython firmware
DHT22 (AM2302) sensorCheap and simple; for better accuracy use an SHT31 or SHT4x on I2C
10 kilohm resistorPull-up for the DHT22 data line (many breakout boards include it)
Breadboard and jumper wiresFor the prototype
USB power supply and cableA good-quality 5 V supply avoids random resets
An MQTT brokerMosquitto on a Raspberry Pi or server in your lab

Design

Temperature monitor designDHT22 / SHT31reads airESP32MicroPythonWi-FiIoT VLANMQTT brokerTLS, port 8883Dashboardgraphs, alerts
Figure 1. The sensor node reads the room and publishes JSON over TLS to a broker that feeds a dashboard.

Wire the DHT22 pin 1 to 3.3 V, pin 2 (data) to GPIO 4 with the pull-up to 3.3 V, and pin 4 to ground. Mount the sensor away from the ESP32 itself, because the board's own heat will raise the reading by a degree or more. Readings go to the topic home/<room>/<device-id>/env, which keeps permissions simple: each device can publish only under its own ID.

Build steps

  1. Flash MicroPython to the ESP32 with esptool and connect with a tool such as Thonny or mpremote.
  2. Install the MQTT client library on the board: mpremote mip install umqtt.simple.
  3. Create the broker user for this device and copy the broker's CA certificate (in DER format) to the board as ca.der.
  4. Create secrets.py on the board with the Wi-Fi and MQTT credentials. Never commit it to Git.
  5. Upload main.py below, reset the board and watch the topic with mosquitto_sub.
  6. Check the readings against a trusted thermometer and note any offset.
import time, json, ssl, network, machine, dht
from umqtt.simple import MQTTClient
import secrets   # SSID, WIFI_PASS, MQTT_HOST, MQTT_USER, MQTT_PASS, DEVICE_ID

sensor = dht.DHT22(machine.Pin(4))
TOPIC = "home/lab/" + secrets.DEVICE_ID + "/env"

def wifi_up():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect(secrets.SSID, secrets.WIFI_PASS)
        for _ in range(20):
            if wlan.isconnected():
                break
            time.sleep(1)
    return wlan.isconnected()

def mqtt_client():
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.verify_mode = ssl.CERT_REQUIRED
    ctx.load_verify_locations(cafile="ca.der")
    c = MQTTClient(secrets.DEVICE_ID, secrets.MQTT_HOST, port=8883,
                   user=secrets.MQTT_USER, password=secrets.MQTT_PASS,
                   keepalive=120, ssl=ctx)
    c.connect()
    return c

while True:
    try:
        if wifi_up():
            sensor.measure()
            msg = {"t": sensor.temperature(), "h": sensor.humidity()}
            c = mqtt_client()
            c.publish(TOPIC, json.dumps(msg), qos=1)
            c.disconnect()
    except Exception as e:
        print("error:", e)
    time.sleep(60)

The program reconnects each cycle, which is simple and robust. For battery power, replace time.sleep with machine.deepsleep(60000) so the board sleeps between readings.

Security checklist and next steps

  • Unique credentials per device, stored in secrets.py, not in the main code or in Git.
  • TLS with certificate verification to the broker; no plain port 1883 outside the lab.
  • Broker ACL allowing this device to publish only to its own topic.
  • Separate network: put sensors on an IoT VLAN or SSID that cannot reach your laptops.
  • Disable unused services: if you enabled WebREPL during development, turn it off.
  • Plan updates: keep a note of the firmware version and update MicroPython periodically.

Common mistakes are reading the DHT22 more often than every two seconds, which returns errors, and placing the sensor in direct sunlight. Next, feed the data into the MQTT dashboard project and add an alert when the temperature passes a limit you choose.

Practice

Why should the sensor be placed away from the ESP32 board?
The board's processor and Wi-Fi radio generate heat, which would make the temperature reading higher than the real room temperature.
Why does each device publish only under its own device ID topic?
It allows a simple broker ACL so a device can write only to its own topic. A compromised device then cannot fake readings for other devices or send commands.
What change would make the node suitable for battery power?
Use deep sleep between readings (machine.deepsleep) instead of time.sleep, and keep Wi-Fi on only while sending.

Key takeaways

  • An ESP32, a DHT22 or SHT31 and MicroPython make a complete sensor node.
  • Publish small JSON messages to a per-device MQTT topic.
  • Keep secrets in a separate file and out of version control.
  • Use TLS with certificate checking and broker ACLs, even at home.
  • Calibrate against a trusted thermometer and keep the sensor away from heat.
Tracks your learning on this device only. See your progress on the learning paths.

About the author

Mohamed Fayas

Founder of FM TecHub. CCNA certified, with a BTEC HND in Network Engineering, and BEng (Hons) in Computer Networking and Cloud Security. He writes practical, plain-English guides on networking, security and cloud.

More about the author

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Stay up to date by email

New notes, tools and security news from FM TecHub, explained simply. Free.

We only use your email to send these updates. See our privacy policy.