How to automate sensor metrics collection with ESP32
Learn how to develop lightweight firmware on ESP32 to collect sensor metrics and integrate them via MQTT into residential and industrial monitoring systems.
Summary
- The ESP32 combines Wi-Fi, Bluetooth, and low power consumption in an affordable microcontroller for automation.
- The MQTT protocol acts as a lightweight mail carrier delivering data packets quickly across local or cloud networks.
- Native C++ programming in the Arduino IDE ensures complete control over memory and execution timing.
- Handling connection drops with automatic reconnection prevents the loss of critical industrial telemetry data.
- Isolating sensor reads from the main networking loop maintains operational hardware stability for months.
Why choose the ESP32 for lightweight telemetry projects?
Building residential or industrial monitoring networks requires reliable hardware, low power consumption, and stable connectivity. The ESP32 meets these demands perfectly by integrating dual-core processors, Wi-Fi, and Bluetooth radio into a tiny, low-cost chip. In practice, this means you can turn any analog or digital sensor for temperature, humidity, or electrical current into an intelligent device capable of talking directly to data servers. As how to dimension industrial switches for high-load networks shows, infrastructure stability starts at the edge, where the ESP32 acts by sending continuous metrics without overloading the local network.
The great advantage of developing your own firmware instead of using closed commercial solutions is freedom. You define exactly how often sensors are read, which data is discarded to save bandwidth, and how the microcontroller handles power or internet outages. For beginners, the initial challenge is understanding that microcontrollers do not run heavy operating systems like Linux; they execute a single program in an infinite loop, requiring extreme code efficiency to prevent unwanted freezes after days of continuous operation.
Preparing the environment to program the microcontroller
Before writing any telemetry code, we need to set up the development environment. The most accessible method to program the ESP32 is using the Arduino IDE with the support core for the chip installed in the preferences. In practice, this installs the hardware libraries that translate simple commands into complex instructions for the processor's internal registers, allowing easy control of input and output pins.
To ensure predictable code execution, file organization and proper library inclusion make all the difference. We need libraries to manage Wi-Fi connectivity and to handle the MQTT protocol, which is the industry standard for sending lightweight messages in Internet of Things systems. MQTT communication works based on topics and messages, where the ESP32 acts as a publisher sending raw readings to a central intermediary known as a broker.
Developing the data reading and transmission firmware
The core of our project lies in concise code that reads sensor pins and packages this information into JSON or plain text format for fast transmission. The example below demonstrates the basic C++ structure to connect the ESP32 to the wireless network and publish temperature metrics collected from a sensor connected to an analog pin:
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "YourWiFiNetwork";
const char* password = "YourPassword";
const char* mqtt_server = "192.168.1.100";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
while (!client.connected()) {
client.connect("ESP32Client");
delay(5000);
}
}
client.loop();
float sensorValue = analogRead(34) * (3.3 / 4095.0);
char msg[50];
sprintf(msg, "{\"--temp--\": %.2f}", sensorValue);
client.publish("home/room/temperature", msg);
delay(10000);
}In the code above, the setup function initializes the serial port and triggers the connection to the Wi-Fi router, while the main loop continuously checks if the MQTT connection remains active. If the broker crashes or the network signal fluctuates, the automatic reconnection routine prevents the device from going silent forever, ensuring the operational resilience required in both homes and manufacturing plants.
Integrating telemetry with monitoring platforms
With data flowing via MQTT, the next step is storing and displaying it in a visual, useful way. Tools like Home Assistant for home environments or Node-RED connected to Grafana for the industrial sector allow transforming cold numbers into trend charts and automated alerts. In practice, you subscribe to the topic published by the ESP32 and configure visual triggers to notify when a temperature exceeds safety limits.
Just as we discussed when exploring how to test systems in production with chaos engineering, anticipating network failure scenarios in sensor arrays avoids unpleasant surprises during critical moments. If the monitoring server becomes unreachable for maintenance, the ESP32 firmware must be robust enough not to hang waiting for a response that will never arrive, discarding old packets or temporarily storing them in flash memory if space permits.
Final considerations on reliability and remote maintenance
Automating metric collection with an ESP32 turns home projects into highly efficient, low-cost telemetry solutions. The secret to long-term success lies in firmware simplicity and rigorous implementation of network error handling routines. By keeping clean code and energy consumption under control, your hardware will run for months or years without physical intervention, providing the vital data needed to keep any operation under complete control.