ESP8266/ESP32-based mini IoT system with network diagram, code, and cloud integrations
Imagine a small connected device that measures temperature and humidity, sends data to a local MQTT broker or the cloud, and can be controlled remotely. With ESP8266 or ESP32 you can build all this in a few dozen lines of firmware, while maintaining scalability, security, and integration with dashboards and automations.
Objectives and use cases
The goal is to build a simple, low-cost, and reliable IoT node capable of:
- Sensing environmental parameters (e.g., temperature/humidity via DHT22).
- Publishing telemetry via MQTT on the LAN or to a cloud service.
- Receiving commands (e.g., turning an LED or a relay on/off).
- Making integration easy with platforms such as Mosquitto, Node-RED, Home Assistant, or AWS IoT Core.
Required hardware and software
- ESP8266 (NodeMCU / Wemos D1 mini) or ESP32 (DevKitC or compatible).
- DHT22 sensor (optional) and a 10kΩ resistor between VCC and DATA.
- 5V/USB power supply, jumper wires.
- Arduino IDE with ESP8266 or ESP32 cores installed.
- Libraries: PubSubClient, DHT sensor library, ArduinoJson (optional), ArduinoOTA (optional).
Network diagram
The following diagram shows the basic topology for the local network and cloud integrations:
[DHT22 Sensor] --GPIO--> [ESP8266/ESP32] --WiFi--> [Router]
| |
| +--> [Local MQTT broker (Mosquitto)]
| |
| +--> [Node-RED / Home Assistant / InfluxDB/Grafana]
|
+-----------------------> [Cloud MQTT/IoT (AWS IoT Core)]
Data flow and architectural choices
The node connects to the Wi-Fi network, registers with an MQTT broker, and periodically publishes a JSON telemetry payload. At the same time it listens to a command topic to perform actions. For the cloud, use MQTT over TLS with certificates; on a LAN you can simplify by using Mosquitto without TLS (only on trusted networks), or enable authentication and encryption.
Firmware for ESP8266/ESP32 (local MQTT, no TLS)
The following firmware works on both ESP8266 and ESP32 by switching the Wi-Fi libraries automatically. It publishes DHT22 readings and receives commands for the built-in LED. Adjust the SSID/password, broker address, and sensor pin for your board.
// WiFi selection based on platform
#ifdef ARDUINO_ARCH_ESP8266
#include
#else
#include
#endif
#include
#include
// Wi-Fi config
const char* WIFI_SSID = "SSID";
const char* WIFI_PASS = "PASSWORD";
// MQTT config (local broker, e.g., Mosquitto)
const char* MQTT_HOST = "192.168.1.50";
const uint16_t MQTT_PORT = 1883;
const char* MQTT_CLIENT_ID = "esp-mini-001";
const char* MQTT_USER = ""; // optional
const char* MQTT_PASS = ""; // optional
// Topics
const char* TOPIC_TELEMETRY = "lab/sensor/mini001";
const char* TOPIC_COMMAND = "lab/cmd/mini001";
// DHT22 sensor
#define DHTPIN 5 // GPIO5 (D1 on NodeMCU)
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// LED / relay (LED_BUILTIN is inverted on many boards)
const int LED_PIN = LED_BUILTIN;
bool ledInverted =
#ifdef ARDUINO_ARCH_ESP8266
true;
#else
true;
#endif
WiFiClient net;
PubSubClient mqtt(net);
unsigned long lastPublish = 0;
const unsigned long PUB_INTERVAL = 10000; // ms
void setLed(bool on) {
if (ledInverted) {
digitalWrite(LED_PIN, on ? LOW : HIGH);
} else {
digitalWrite(LED_PIN, on ? HIGH : LOW);
}
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String cmd;
for (unsigned int i = 0; i 20000) break;
}
}
void connectMQTT() {
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(mqttCallback);
while (!mqtt.connected()) {
if (mqtt.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS)) {
mqtt.subscribe(TOPIC_COMMAND);
} else {
delay(2000);
}
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
setLed(false);
Serial.begin(115200);
delay(50);
dht.begin();
connectWiFi();
connectMQTT();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) connectWiFi();
if (!mqtt.connected()) connectMQTT();
mqtt.loop();
unsigned long now = millis();
if (now - lastPublish > PUB_INTERVAL) {
lastPublish = now;
float h = dht.readHumidity();
float t = dht.readTemperature(); // °C
if (isnan(h) || isnan(t)) {
Serial.println("DHT not available");
return;
}
// Build a lightweight JSON
String payload = "{";
payload += ""device":"mini001",";
payload += ""ts":" + String((unsigned long)(millis()/1000)) + ",";
payload += ""temp":" + String(t, 1) + ",";
payload += ""hum":" + String(h, 1) + ",";
payload += ""rssi":" + String(WiFi.RSSI()) + ",";
payload += ""ip":"" + WiFi.localIP().toString() + """;
payload += "}";
mqtt.publish(TOPIC_TELEMETRY, payload.c_str(), true);
Serial.println(payload);
}
}
Build notes
In the Arduino IDE, install the “ESP8266” or “ESP32” cores from the Board Manager. Add the PubSubClient and DHT libraries. If you use an ESP8266 with an inverted LED, the code already handles the logic; for a relay on a dedicated pin, replace LED_PIN with the correct GPIO and set ledInverted to false if needed.
Local MQTT integration with Mosquitto and Node-RED
To get started quickly on a LAN:
- Install Mosquitto on a server or NAS and enable listening on port 1883.
- Install Node-RED and add an mqtt in node listening on lab/sensor/mini001.
- Add a function node for validation/parsing and a dashboard chart or gauge node to display temperature/humidity.
- To send commands, use an mqtt out node on lab/cmd/mini001 with an on/off payload.
For LAN security, enable username/password authentication on Mosquitto and consider TLS with a self-signed certificate or Let’s Encrypt.
Cloud integration: AWS IoT Core (MQTT over TLS)
To go beyond the local network with secure, managed channels, AWS IoT Core is a solid choice. Main steps:
- Create a “Thing” in AWS IoT, generate a certificate and private key, and also download the Root CA.
- Attach a policy allowing connect/publish/subscribe to the desired topics.
- Get your account’s ATS endpoint (e.g., a1b2c3d4e5-ats.iot.eu-west-1.amazonaws.com).
- Embed the certificates in the firmware and use WiFiClientSecure on port 8883.
Example (excerpt) for TLS: replace the endpoint and paste your PEMs between triple quotes.
#include
#include
const char* AWS_ENDPOINT = "xxxxxx-ats.iot.eu-west-1.amazonaws.com";
const int AWS_PORT = 8883;
const char AWS_ROOT_CA[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
)EOF";
const char DEVICE_CERT[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
)EOF";
const char DEVICE_KEY[] PROGMEM = R"EOF(
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
)EOF";
WiFiClientSecure secureNet;
PubSubClient mqtt(secureNet);
void connectMQTTAws() {
secureNet.setCACert(AWS_ROOT_CA);
secureNet.setCertificate(DEVICE_CERT);
secureNet.setPrivateKey(DEVICE_KEY);
mqtt.setServer(AWS_ENDPOINT, AWS_PORT);
while (!mqtt.connected()) {
if (mqtt.connect(MQTT_CLIENT_ID)) {
mqtt.subscribe(TOPIC_COMMAND);
} else {
delay(3000);
}
}
}
The rest of the loop stays the same: publish the JSON payload to the desired topics (e.g., iot/mini001/telemetry) and subscribe for commands. In production, add exponential backoff, QoS 1, and use retained messages only where it makes sense.
Scalability, security, and reliability
- Unique identities: separate clientId and topics for each device.
- Security: use TLS for the cloud, strong credentials for the local broker, and segment the IoT network.
- Reliability: automatic reconnection, watchdog, timestamped publishing, minimal buffering in RAM.
- Maintenance: enable OTA for remote updates; stream logs over Serial or to a diagnostic topic.
- Power: for battery-powered nodes enable deep sleep and longer publish intervals.
Extensions and integrations
In addition to Mosquitto and AWS IoT, you can integrate with:
- Home Assistant via MQTT Discovery to have sensor and switch entities automatically.
- InfluxDB + Grafana for historical storage and advanced charts.
- Webhook/HTTP to your own servers using ESP32 HTTPClient as an alternative channel.
Debug and troubleshooting
- If the Wi-Fi connection is unstable, check for busy channels and signal quality (RSSI in the logs).
- If MQTT doesn’t connect, confirm IP/port and policy (for AWS), as well as correct date/time for TLS.
- If the DHT22 returns NaN, check power, pull-up resistor, and data pin wiring.
Conclusion
With a few components and lean firmware, you can build a complete IoT node ready for local dashboards or secure cloud integrations. Starting from the project described here, you can expand the number of sensors, add actuators, and orchestrate complex automations with open-source tools or managed services.
Take action
Download the libraries, copy the firmware, connect the DHT22, and power up your first node. Set up a local MQTT broker or try the AWS IoT Core integration right away: in a few minutes you’ll have real-time telemetry and remote control. Need a personalized guide or a ready-made template for your device fleet? Contact me to get a complete kit optimized for your application.

Comments