June 17, 2025
EspNow protocol

EspNow protocol

In the rapidly evolving landscape of the Internet of Things (IoT), efficient communication protocols are essential for seamless device interaction. One such innovative protocol is ESP-NOW, developed by Espressif for their ESP32 and ESP8266 microcontrollers. This article delves into the key features, advantages, and applications of ESP-NOW, illustrating why it’s becoming a popular choice among developers and hobbyists alike.

What is ESP-NOW?

ESP-NOW is a wireless communication protocol that enables low-power, low-latency data exchange between devices without the need for a traditional Wi-Fi connection. It operates over the 2.4 GHz band, allowing devices to communicate directly with one another in a peer-to-peer manner. This is particularly advantageous for IoT applications where devices often need to share small amounts of data quickly and efficiently.

Key Features of ESP-NOW

  • Low Power Consumption: One of the standout features of ESP-NOW is its ability to facilitate communication while consuming minimal power. This is crucial for battery-operated devices, making ESP-NOW an excellent choice for energy-sensitive applications.
  • No Need for Wi-Fi Router: ESP-NOW allows for direct communication between devices, eliminating the need for a Wi-Fi network or router. This not only simplifies setup but also enhances reliability, especially in environments where Wi-Fi signals may be weak or unreliable.
  • Support for Multiple Devices: ESP-NOW can handle multiple peer devices simultaneously. Each ESP32 or ESP8266 can communicate with up to 20 other devices, making it suitable for larger networks of sensors or actuators.
  • Encryption Support: Security is paramount in IoT applications. ESP-NOW supports encryption to protect data being transmitted between devices, ensuring that sensitive information remains secure from potential intrusions.
  • Simple Implementation: The protocol is relatively easy to implement, with straightforward APIs provided in the ESP-IDF (Espressif IoT Development Framework) and Arduino IDE, allowing developers to get started quickly.

Getting Started with ESP-NOW

To implement ESP-NOW, you’ll need an ESP32 or ESP8266 development board. Here’s a simple outline to get you started:

  1. Set Up Your Development Environment: Install the Arduino IDE or ESP-IDF on your computer.
  2. Include Necessary Libraries: For Arduino, include the esp_now.h library to utilize ESP-NOW functionality.
  3. Mac address : To Get the mac addresses of Sender and receiver
  4. Initialize ESP-NOW: Use the provided APIs to initialize ESP-NOW and set up your devices to communicate.
  5. Send and Receive Data: Implement callback functions to send and receive messages between devices, handling encryption and data formats as needed.

Getting the Mac address

Before we start sending and receiving the data over EspNow protocol we will need Mac address of esp devices. Here is simple code that we can to print the mac address of esp device .

#include <WiFi.h>
#include <esp_wifi.h>

void readMacAddress(){
  uint8_t baseMac[6];
  esp_err_t ret = esp_wifi_get_mac(WIFI_IF_STA, baseMac);
  if (ret == ESP_OK) {
    Serial.printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
                  baseMac[0], baseMac[1], baseMac[2],
                  baseMac[3], baseMac[4], baseMac[5]);
  } else {
    Serial.println("Failed to read MAC address");
  }
}

void setup(){
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  WiFi.STA.begin();

  Serial.print("[DEFAULT] ESP32 Board MAC Address: ");
  readMacAddress();
}
 
void loop(){

}

Run this code and not down the mac address for each device .

Sending the data using EspNow:

Now that we have mac address of receiver we can start sending data . i have connected Aht-20 (temp & humidity) sensor but you can use dht-11 to esp32 module .

#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>
#include <AHT20.h>

// REPLACE WITH RECEIVER MAC Address
uint8_t broadcastAddress[] = {0xb0,0xd0,0x10,0xab,0xf4,0x14};


struct DataPacket {
    int device_id;
    float temperature;
    float humidity;
} dataPacket;

struct DataRec {
    unsigned long timeDelay;
} datarecv;

unsigned long lastTime = 0;
unsigned long timerDelay = 2000;  // send readings timer

// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
    Serial.print("Last Packet Send Status: ");
    if (status == ESP_NOW_SEND_SUCCESS) {
        Serial.println("Delivery success");
    } else {
        Serial.println("Delivery fail");
    }
}

// Callback function when data is received
void OnDataRecv(const esp_now_recv_info_t *recv_info, const uint8_t *incomingData, int len) {
    memcpy(&datarecv, incomingData, sizeof(datarecv));
    Serial.print("Received time delay: ");
    Serial.println(datarecv.timeDelay);
    timerDelay = datarecv.timeDelay;
}

AHT20 aht20;

void setup() {
    // Init Serial Monitor
    Serial.begin(115200);

    // Set device as a Wi-Fi Station
    WiFi.mode(WIFI_STA);

    // Init ESP-NOW
    if (esp_now_init() != ESP_OK) {
        Serial.println("Error initializing ESP-NOW");
        return;
    }

    // Register send and receive callback functions
    esp_now_register_send_cb(OnDataSent);
    esp_now_register_recv_cb(OnDataRecv);

    // Register peer
    esp_now_peer_info_t peerInfo;
    memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    peerInfo.channel = 0;  
    peerInfo.encrypt = false;

    if (esp_now_add_peer(&peerInfo) != ESP_OK) {
        Serial.println("Failed to add peer");
        return;
    }

    Wire.begin(); // Join I2C bus
    // Check if the AHT20 will acknowledge
    if (aht20.begin() == false) {
        Serial.println("AHT20 not detected. Please check wiring. Freezing.");
        while (1);
    }
    Serial.println("AHT20 acknowledged.");
}

void loop() {
    if ((millis() - lastTime) > timerDelay) {
        float humidity = aht20.getHumidity();
        float temperature = aht20.getTemperature();

        dataPacket.temperature = temperature;
        dataPacket.humidity = humidity;
        dataPacket.device_id = 50;

        esp_now_send(broadcastAddress, (uint8_t *)&dataPacket, sizeof(dataPacket));

        lastTime = millis();
    }
}

Explanation :

  • The only functions which are important in this code are onDataSent and onDataRecev . These callback functions are called when data is either sent or received and rest of the code is self explanatory.

Receiving the data using EspNow:

If you have not set up esp receiver or if receiver esp device is down then the above sender code will print “Delivery fail” message on the serial console. Lets fix that by setting up the receiver.

#include <esp_now.h>
#include <WiFi.h>

struct DataPacket {
  int device_id;
  float temperature;
  float humidity;
};


// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *data, int len) {

  DataPacket receivedData;
  memcpy(&receivedData, data, sizeof(receivedData));
  Serial.print("S,");
  Serial.print(receivedData.device_id);
  Serial.print(",");
  Serial.print(receivedData.temperature);
  Serial.print(",");
  Serial.print(receivedData.humidity);
  Serial.print(",");
  Serial.println("P");
}
 
void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  
  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info
  esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv));
}
 
void loop() {

}

Explanation :

In this when data is received then “OnDataRecv” function is fired . Then we starting separating the data from the structure object and print it on the serial console .

ESP-NOW vs Bluetooth Protocol

After exploring the ESP-NOW protocol, one important question to consider is how it compares to Bluetooth as both protocols are supported by same esp32 devices .

Both ESP-NOW and Bluetooth are wireless communication protocols commonly used in IoT applications, but they have distinct characteristics and use cases. Here’s a comparison of the two:

FeatureESP-NOWBluetooth
RangeDepends on various conditions , but it is better than bluetooth. Typically 10-100 meters, with some versions reaching longer distances
EncryptionSupports basic encryption for secure communicationProvides robust encryption and authentication mechanisms
Setup ComplexitySimple setup with minimal configuration neededMore complex, often requires pairing and device discovery
Connection TypePeer-to-peer communication without a central hubCan connect to multiple devices via a master-slave architecture
LatencyLow latency, making it suitable for real-time applicationsSlightly higher latency, but still suitable for most applications
Power ConsumptionModerate power consumption,Low power consumption, ideal for battery-operated devices
InterferenceOperates on the 2.4 GHz band; susceptible to interference from Wi-FiAlso operates on the 2.4 GHz band; can experience interference from other Bluetooth devices
Device CompatibilityPrimarily designed for ESP32 and ESP8266 devicesWidely supported across various devices, including smartphones, tablets, and computers
Network ScalabilityCan communicate with up to 20 devices simultaneouslySupports connections with multiple devices but can be more complex to manage
Use CasesIoT sensor networks, home automation, remote controlWearable devices, audio streaming, smartphone connectivity

Summary

  • ESP-NOW is best suited for applications that require low-power, low-latency communication between multiple devices in a local network, particularly when simplicity and direct peer-to-peer communication are key.
  • Bluetooth, especially BLE, is ideal for applications that involve connecting to consumer devices (like smartphones) or require robust security and authentication features.

The choice between ESP-NOW and Bluetooth largely depends on the specific requirements of your project, such as range, power consumption, and the complexity of device interactions.

Conclusion

ESP-NOW is a powerful and flexible protocol that enhances communication capabilities in the IoT ecosystem. Its low power consumption, ease of use, and ability to operate without a traditional Wi-Fi infrastructure make it an appealing choice for developers looking to create efficient and scalable IoT applications. As the demand for interconnected devices continues to grow, protocols like ESP-NOW will play a crucial role in shaping the future of IoT communication. Whether you’re a seasoned developer or just starting, exploring ESP-NOW could open up new possibilities for your projects.

Leave a Reply

Your email address will not be published. Required fields are marked *