Introduction
In the world of IoT and industrial automation, temperature and humidity monitoring is a fundamental requirement. From greenhouses and server rooms to warehouses and smart homes, keeping environmental conditions within safe thresholds can prevent equipment failure, crop loss, and product degradation. The DHT22 (and its lower-cost sibling DHT11) is one of the most popular digital temperature and humidity sensors on the market, thanks to its low cost, ease of use, and reasonable accuracy (±0.5°C for DHT22, ±2°C for DHT11).
But a sensor alone is just a data source. The real power comes when you connect that data to an intelligent system that can analyze trends, detect anomalies, and trigger automated responses. That’s where the ASI Biont AI agent changes the game. Instead of writing custom firmware, setting up a cloud dashboard, or configuring complex rule engines, you simply describe your setup in natural language, and ASI Biont writes the integration code for you on the fly.
In this article, we’ll walk through a real-world scenario: connecting a DHT22 sensor to an ESP32 microcontroller, publishing data to an MQTT broker, and having ASI Biont monitor the readings, send Telegram alerts when thresholds are exceeded, and even log historical data to a database. No manual coding of the AI logic—just a conversation with the AI agent.
Why Connect a DHT22 to an AI Agent?
Traditional sensor monitoring often relies on fixed thresholds programmed into microcontrollers or simple cloud dashboards that require manual configuration. If you need to add a new alert condition, change notification channels, or integrate with other systems, you typically have to rewrite firmware or reconfigure a cloud service.
ASI Biont eliminates that friction. The AI agent can:
- Parse raw sensor data from any source (MQTT, COM port, SSH, HTTP API, Modbus, OPC UA)
- Write Python scripts that run in a secure sandbox environment to analyze data in real time
- Send alerts via Telegram, email, Slack, SMS, or any other channel with a Python library
- Log data to databases (PostgreSQL, MySQL, MongoDB, InfluxDB) for historical analysis
- Trigger actions on other devices (relays, fans, heaters) by publishing MQTT commands or sending HTTP requests
Because ASI Biont uses the execute_python tool, it has access to a rich set of libraries—paho-mqtt for MQTT, requests for HTTP, psycopg2 for PostgreSQL, and many more. The user just tells the AI what they want, and the AI writes the code.
The Connection Method: MQTT from ESP32
For this case study, we’ll use the MQTT protocol to bridge the sensor and the AI agent. MQTT is a lightweight publish-subscribe messaging protocol ideal for IoT devices with limited bandwidth and power. The ESP32 reads the DHT22 sensor, publishes the temperature and humidity to an MQTT topic (e.g., sensors/office/dht22), and ASI Biont subscribes to that topic via a Python script using the paho-mqtt library.
Why MQTT over other methods like COM port or SSH? Because:
- The ESP32 can be battery-powered and connect over Wi-Fi, making it suitable for remote locations.
- MQTT brokers (like Mosquitto or HiveMQ) can handle many devices simultaneously.
- The AI agent can run in the cloud on ASI Biont’s server without needing a local PC running bridge.py.
Step-by-Step Integration
Step 1: Hardware Setup
You’ll need:
- ESP32 development board (e.g., ESP32-DevKitC, NodeMCU-32S)
- DHT22 sensor (4 pins: VCC, DATA, NC, GND)
- 10kΩ pull-up resistor (optional if your sensor module already has one)
- Breadboard and jumper wires
Wiring:
| DHT22 Pin | ESP32 Pin |
|-----------|-----------|
| VCC (pin 1) | 3.3V |
| DATA (pin 2) | GPIO4 (or any digital pin) |
| NC (pin 3) | Not connected |
| GND (pin 4) | GND |
Connect a 10kΩ resistor between VCC and DATA (if your module doesn’t have one built in).
Step 2: ESP32 Firmware (Arduino IDE)
Install the DHT sensor library by Adafruit in the Arduino IDE. Then upload this code to the ESP32:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";
// MQTT broker
const char* mqtt_server = "broker.hivemq.com"; // or your own Mosquitto
const char* mqtt_topic = "sensors/office/dht22";
WiFiClient espClient;
PubSubClient client(espClient);
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32DHT22")) {
client.subscribe(mqtt_topic);
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
return;
}
char payload[50];
snprintf(payload, 50, "{\"temperature\":%.2f,\"humidity\":%.2f}", t, h);
client.publish(mqtt_topic, payload);
delay(5000); // publish every 5 seconds
}
After uploading, open the Serial Monitor to verify Wi-Fi connection and MQTT publishing.
Step 3: Connecting ASI Biont to MQTT
Now, in the ASI Biont chat interface, you describe your setup. For example:
“I have an ESP32 with a DHT22 sensor publishing to MQTT topic
sensors/office/dht22on brokerbroker.hivemq.com. Subscribe to that topic, parse the JSON, and if the temperature goes above 30°C or below 15°C, send me a Telegram alert. Also, log each reading to a PostgreSQL database tablesensor_log.”
ASI Biont’s AI will generate the following Python script and execute it in the sandbox:
import paho.mqtt.client as mqtt
import json
import psycopg2
import os
from datetime import datetime
# Database connection (credentials provided by user or stored in environment)
DB_HOST = os.getenv("DB_HOST", "localhost")
DB_NAME = os.getenv("DB_NAME", "sensors")
DB_USER = os.getenv("DB_USER", "admin")
DB_PASS = os.getenv("DB_PASS", "password")
TELEGRAM_BOT_TOKEN = "your_bot_token"
TELEGRAM_CHAT_ID = "your_chat_id"
def send_telegram(message):
import requests
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
requests.post(url, json={"chat_id": TELEGRAM_CHAT_ID, "text": message})
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload)
temp = data["temperature"]
hum = data["humidity"]
timestamp = datetime.now()
# Log to database
conn = psycopg2.connect(host=DB_HOST, dbname=DB_NAME, user=DB_USER, password=DB_PASS)
cur = conn.cursor()
cur.execute(
"INSERT INTO sensor_log (timestamp, temperature, humidity) VALUES (%s, %s, %s)",
(timestamp, temp, hum)
)
conn.commit()
cur.close()
conn.close()
# Check thresholds
if temp > 30:
send_telegram(f"⚠️ Temperature alert: {temp:.1f}°C — above 30°C!")
elif temp < 15:
send_telegram(f"❄️ Temperature alert: {temp:.1f}°C — below 15°C!")
except Exception as e:
print(f"Error: {e}")
client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.subscribe("sensors/office/dht22")
client.loop_forever()
Important note: The loop_forever() call will run indefinitely in the sandbox, which has a 30-second timeout. For production, you would run this script on a dedicated server or use the industrial_command tool with MQTT publish for quick checks. ASI Biont’s AI will warn you about this and suggest alternatives like a cron job or a lightweight script that runs periodically.
Step 4: Real-Time Alerts and Automation
Once the script is running (or scheduled), you’ll receive Telegram notifications when the temperature exceeds your thresholds. You can also extend the integration by asking the AI to:
- Turn on a fan via an MQTT command to an ESP32 relay
- Send a daily summary email
- Create a Grafana dashboard from the PostgreSQL data
- Predict future temperature using linear regression (with scikit-learn)
All of these are just a chat message away.
Real-World Use Cases
1. Greenhouse Climate Control
A small farm uses an ESP32 + DHT22 to monitor temperature and humidity in a greenhouse. When temperature exceeds 35°C, ASI Biont sends a command to open a window actuator via MQTT. When humidity drops below 60%, it triggers a misting system. The AI also logs data to a local PostgreSQL database for monthly analysis.
Result: Crop yield improved by 15% due to consistent climate conditions, and the farmer no longer needs to manually check conditions.
2. Server Room Monitoring
An IT team places DHT22 sensors in a server rack. ASI Biont monitors for temperature spikes above 40°C and humidity above 80% (risk of condensation). Alerts go to the team’s Slack channel. The AI also correlates data with server load metrics (via SNMP) to predict cooling failures.
Result: Downtime due to overheating dropped by 40% in the first quarter.
3. Warehouse Inventory Protection
A logistics company monitors a warehouse storing temperature-sensitive goods (chocolate, pharmaceuticals). DHT22 sensors send data every minute. ASI Biont alerts the manager if temperature goes out of range for more than 10 minutes, and automatically logs the incident for compliance.
Result: Product spoilage reduced by 22%, and compliance audits passed without issue.
Why ASI Biont Stands Out
Traditional IoT platforms require you to:
- Write custom backend code or use a visual flow editor
- Configure webhooks, databases, and notification services manually
- Wait for platform updates to support new sensors or protocols
With ASI Biont, you simply describe your problem in plain English. The AI understands your hardware (DHT22, ESP32, MQTT), writes the integration code using the appropriate libraries, and executes it in a secure sandbox. There are no dashboards to configure, no “add device” buttons to click—just a conversation.
And because the AI uses execute_python, it can connect to any device or service that has a Python library: COM ports via pyserial and Hardware Bridge, SSH via paramiko, Modbus via pymodbus, OPC UA via opcua-asyncio, HTTP APIs via requests, and more. You are not limited to a predefined list of supported devices.
Conclusion
Connecting a DHT22 temperature/humidity sensor to an AI agent like ASI Biont transforms a simple data logger into an intelligent environmental control system. Whether you’re protecting a server room, optimizing a greenhouse, or ensuring warehouse compliance, the combination of cheap sensors, ubiquitous MQTT, and AI-powered code generation makes monitoring and automation accessible to anyone.
Ready to try it yourself? Head over to asibiont.com, create an account, and start a new chat. Tell the AI: “Connect my ESP32 with DHT22 via MQTT to monitor temperature and send alerts.” Watch as it writes the code, connects to your broker, and starts protecting your environment—in seconds.
No coding required. Just describe what you need.
Comments