Home Wiki Electricity & Electrons ESP32 and Wireless Connectivity: A Smart Sensor Connected to the Network
Electricity & Electrons

ESP32 and Wireless Connectivity: A Smart Sensor Connected to the Network

ESP32: A Microcontroller With Built-In WiFi and Bluetooth

The ESP32 by Espressif integrates WiFi 802.11 b/g/n and Bluetooth 4.2 into a low-cost microcontroller. Its dual-core 240 MHz processor, 520 KB SRAM, and rich peripherals make it ideal for industrial IoT while costing under five dollars.

In factories, the ESP32 serves as a wireless sensor node — reading temperature, vibration, and current from equipment, then transmitting data to a central server via WiFi. Key specs for industrial use: 12-bit ADC with 18 channels, multiple UART/SPI/I2C interfaces, deep sleep at 10 microamps, and -40 to +85 degrees Celsius operating range.

Setting Up the Development Environment: ESP-IDF or Arduino

ESP-IDF is the official SDK based on FreeRTOS — recommended for industrial applications. Arduino framework offers simpler APIs for prototyping.

# Install ESP-IDF
mkdir -p ~/esp && cd ~/esp
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf && ./install.sh esp32
source export.sh

# Build and flash
idf.py create-project sensor_node
cd sensor_node
idf.py set-target esp32
idf.py build && idf.py flash monitor

Connecting to a WiFi Network

Factory WiFi requires robust reconnection logic. Metal structures cause reflections, motors create RF interference, and access points may restart.

#include "esp_wifi.h"
#include "esp_event.h"
#include "nvs_flash.h"

static void wifi_event_handler(void *arg, esp_event_base_t base,
                               int32_t id, void *data) {
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED)
        esp_wifi_connect();  // Auto-reconnect
}

void wifi_init(void) {
    nvs_flash_init();
    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);
    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
                               wifi_event_handler, NULL);

    wifi_config_t wifi_cfg = {
        .sta = { .ssid = "Factory-Floor-5G",
                 .password = "industrial_key" },
    };
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg);
    esp_wifi_start();
    esp_wifi_connect();
}

Industrial firmware should also implement exponential backoff, local data buffering during outages, and static IP to avoid DHCP delays.

MQTT Protocol: The Language of Industrial IoT

MQTT uses publish/subscribe where sensor nodes publish to named topics and interested clients subscribe. A broker routes messages between all parties.

Topics follow factory hierarchy: factory/line-1/press-01/temperature. QoS levels: 0 (fire and forget), 1 (at least once, standard for sensors), 2 (exactly once, for commands).

Sending Sensor Data to the Server via MQTT

#include "mqtt_client.h"
#include "cJSON.h"

static esp_mqtt_client_handle_t mqtt_client;

void mqtt_init(void) {
    esp_mqtt_client_config_t cfg = {
        .broker.address.uri = "mqtt://192.168.1.100:1883",
        .credentials.client_id = "sensor-node-01",
    };
    mqtt_client = esp_mqtt_client_init(&cfg);
    esp_mqtt_client_start(mqtt_client);
}

void publish_sensor_data(float temp, float humidity) {
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, "temperature", temp);
    cJSON_AddNumberToObject(json, "humidity", humidity);
    cJSON_AddNumberToObject(json, "timestamp", esp_timer_get_time());

    char *payload = cJSON_PrintUnformatted(json);
    esp_mqtt_client_publish(mqtt_client,
        "factory/line-1/node-01/env", payload, 0, 1, 0);
    free(payload);
    cJSON_Delete(json);
}

Practical Example: An IIoT Node Sending Temperature and Humidity Every 10 Seconds

This complete example reads a DHT22 sensor and publishes to MQTT every 10 seconds with automatic reconnection.

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "dht.h"

#define DHT_GPIO  GPIO_NUM_4
#define TAG       "IIoT-Node"

void sensor_publish_task(void *params) {
    float temperature, humidity;
    while (1) {
        if (dht_read_float_data(DHT_TYPE_AM2301, DHT_GPIO,
                &humidity, &temperature) == ESP_OK) {
            ESP_LOGI(TAG, "Temp=%.1fC Hum=%.1f%%", temperature, humidity);
            publish_sensor_data(temperature, humidity);
        } else {
            ESP_LOGW(TAG, "DHT read failed, retrying next cycle");
        }
        vTaskDelay(pdMS_TO_TICKS(10000));
    }
}

void app_main(void) {
    wifi_init();
    vTaskDelay(pdMS_TO_TICKS(3000));
    mqtt_init();
    vTaskDelay(pdMS_TO_TICKS(2000));
    xTaskCreate(sensor_publish_task, "SensorPub", 4096, NULL, 5, NULL);
    ESP_LOGI(TAG, "IIoT sensor node running");
}

On the server side, platforms like Dr. Machine aggregate sensor data from dozens of ESP32 nodes into a unified monitoring dashboard with alerts and analytics.

Summary

The ESP32 combines a dual-core processor with integrated WiFi and Bluetooth, making it ideal for industrial IoT nodes. ESP-IDF provides a production-grade development framework on FreeRTOS. WiFi connectivity requires robust reconnection for harsh factory RF environments. MQTT is the standard IIoT protocol using publish/subscribe topics that map naturally to factory hierarchies. Sensor data is published as JSON with configurable QoS levels. The next lesson brings everything together in a complete industrial monitoring project with STM32, Modbus, and PCB design.

ESP32 WiFi MQTT IIoT wireless sensor-node المتحكم اللاسلكي واي فاي عقدة المستشعر إنترنت الأشياء الاتصال البيانات