Getting Started with ESP-NOW (ESP32 with Arduino IDE)

Learn how to use ESP-NOW to exchange data between ESP32 boards programmed with Arduino IDE. ESP-NOW is a connectionless communication protocol developed by Espressif that features short packet transmission. This protocol enables multiple devices to talk to each other in an easy way.

Getting Started with ESP-NOW (ESP32 with Arduino IDE)

We have other tutorials for ESP-NOW with the ESP32:

Arduino IDE

We’ll program the ESP32 board using Arduino IDE, so before proceeding with this tutorial you should have the ESP32 add-on installed in your Arduino IDE. Follow the next guide:

Note: we have a similar guide for the ESP8266 NodeMCU Board: Getting Started with ESP-NOW (ESP8266 NodeMCU with Arduino IDE)

Introducing ESP-NOW

For a video introduction to ESP-NOW protocol, watch the following (try the project featured in this video):

Stating the Espressif website, ESP-NOW is a “protocol developed by Espressif, which enables multiple devices to communicate with one another without using Wi-Fi. The protocol is similar to the low-power 2.4GHz wireless connectivity (…) . The pairing between devices is needed prior to their communication. After the pairing is done, the connection is safe and peer-to-peer, with no handshake being required.”

ESP-NOW - ESP32 Logo

This means that after pairing a device with each other, the connection is persistent. In other words, if suddenly one of your boards loses power or resets, when it restarts, it will automatically connect to its peer to continue the communication.

ESP-NOW supports the following features:

  • Encrypted and unencrypted unicast communication;
  • Mixed encrypted and unencrypted peer devices;
  • Up to 250-byte payload can be carried;
  • Sending callback function that can be set to inform the application layer of transmission success or failure.

ESP-NOW technology also has the following limitations:

  • Limited encrypted peers. 10 encrypted peers at the most are supported in Station mode; 6 at the most in SoftAP or SoftAP + Station mode;
  • Multiple unencrypted peers are supported, however, their total number should be less than 20, including encrypted peers;
  • Payload is limited to 250 bytes.

In simple words, ESP-NOW is a fast communication protocol that can be used to exchange small messages (up to 250 bytes) between ESP32 boards.

ESP-NOW is very versatile and you can have one-way or two-way communication in different setups.

ESP-NOW One-Way Communication

For example, in one-way communication, you can have scenarios like this:

  • One ESP32 board sending data to another ESP32 board

This configuration is very easy to implement and it is great to send data from one board to the other like sensor readings or ON and OFF commands to control GPIOs.

ESP-NOW One ESP32 board sending data to another ESP32 board

One ESP32 board sending the same or different commands to different ESP32 boards. This configuration is ideal to build something like a remote control. You can have several ESP32 boards around the house that are controlled by one main ESP32 board.

ESP-NOW master ESP32 sending data to multiple ESP32 slaves

This configuration is ideal if you want to collect data from several sensors nodes into one ESP32 board. This can be configured as a web server to display data from all the other boards, for example.

ESP-NOW One ESP32 slave receiving data from multiple masters

Note: in the ESP-NOW documentation there isn’t such thing as “sender/master” and “receiver/slave”. Every board can be a sender or receiver. However, to keep things clear we’ll use the terms “sender” and “receiver” or “master” and “slave”.

ESP-NOW Two-Way Communication

With ESP-NOW, each board can be a sender and a receiver at the same time. So, you can establish two-way communication between boards.

For example, you can have two boards communicating with each other.

ESP-NOW Two-Way Communication between two ESP32 boards

Learn how to: Exchange Sensor Readings with ESP-NOW Two-Way Communication.

You can add more boards to this configuration and have something that looks like a network (all ESP32 boards communicate with each other).

ESP-NOW Communication between multiple ESP32 boards

In summary, ESP-NOW is ideal to build a network in which you can have several ESP32 boards exchanging data with each other.

ESP32: Getting Board MAC Address

To communicate via ESP-NOW, you need to know the MAC Address of the ESP32 receiver. That’s how you know to which device you’ll send the data to.

Each ESP32 has a unique MAC Address and that’s how we identify each board to send data to it using ESP-NOW (learn how to Get and Change the ESP32 MAC Address).

To get your board’s MAC Address, upload the following code.

// Complete Instructions to Get and Change ESP MAC Address: https://RandomNerdTutorials.com/get-change-esp32-esp8266-mac-address-arduino/

#include "WiFi.h"
 
void setup(){
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_STA);
  Serial.println(WiFi.macAddress());
}
 
void loop(){

}

View raw code

After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the ESP32 RST/EN button. The MAC address should be printed as follows:

ESP-NOW ESP32 Getting Board MAC Address

Save your board MAC address because you’ll need it to send data to the right board via ESP-NOW.

ESP-NOW One-way Point to Point Communication

To get you started with ESP-NOW wireless communication, we’ll build a simple project that shows how to send a message from one ESP32 to another. One ESP32 will be the “sender” and the other ESP32 will be the “receiver”.

ESP-NOW One-way Point to Point Communication ESP32

We’ll send a structure that contains a variable of type char, int, float, and boolean. Then, you can modify the structure to send whichever variable types are suitable for your project (like sensor readings, or boolean variables to turn something on or off).

For better understanding, we’ll call “sender” to ESP32 #1 and “receiver” to ESP32 #2.

Here’s what we should include in the sender sketch:

  1. Initialize ESP-NOW;
  2. Register a callback function upon sending data – the OnDataSent function will be executed when a message is sent. This can tell us if the message was successfully delivered or not;
  3. Add a peer device (the receiver). For this, you need to know the receiver MAC address;
  4. Send a message to the peer device.

On the receiver side, the sketch should include:

  1. Initialize ESP-NOW;
  2. Register for a receive callback function (OnDataRecv). This is a function that will be executed when a message is received.
  3. Inside that callback function, save the message into a variable to execute any task with that information.

ESP-NOW works with callback functions that are called when a device receives a message or when a message is sent (you get if the message was successfully delivered or if it failed).

ESP-NOW Useful Functions

Here’s a summary of the most essential ESP-NOW functions:

Function Name and Description
esp_now_init() Initializes ESP-NOW. You must initialize Wi-Fi before initializing ESP-NOW.
esp_now_add_peer() Call this function to pair a device and pass as an argument the peer MAC address.
esp_now_send() Send data with ESP-NOW.
esp_now_register_send_cb() Register a callback function that is triggered upon sending data. When a message is sent, a function is called – this function returns whether the delivery was successful or not.
esp_now_register_rcv_cb() Register a callback function that is triggered upon receiving data. When data is received via ESP-NOW, a function is called.

For more information about these functions read the ESP-NOW documentation at Read the Docs.

ESP32 Sender Sketch (ESP-NOW)

Here’s the code for the ESP32 Sender board. Copy the code to your Arduino IDE, but don’t upload it yet. You need to make a few modifications to make it work for you.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

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

// REPLACE WITH YOUR RECEIVER MAC Address
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

// Structure example to send data
// Must match the receiver structure
typedef struct struct_message {
  char a[32];
  int b;
  float c;
  bool d;
} struct_message;

// Create a struct_message called myData
struct_message myData;

esp_now_peer_info_t peerInfo;

// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
 
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;
  }

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);
  
  // Register peer
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  
  // Add peer        
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    return;
  }
}
 
void loop() {
  // Set values to send
  strcpy(myData.a, "THIS IS A CHAR");
  myData.b = random(1,20);
  myData.c = 1.2;
  myData.d = false;
  
  // Send message via ESP-NOW
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
   
  if (result == ESP_OK) {
    Serial.println("Sent with success");
  }
  else {
    Serial.println("Error sending the data");
  }
  delay(2000);
}

View raw code

How the code works

First, include the esp_now.h and WiFi.h libraries.

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

In the next line, you should insert the ESP32 receiver MAC address.

uint8_t broadcastAddress[] = {0x30, 0xAE, 0xA4, 0x07, 0x0D, 0x64};

In our case, the receiver MAC address is: 30:AE:A4:07:0D:64, but you need to replace that variable with your own MAC address.

Then, create a structure that contains the type of data we want to send. We called this structure struct_message and it contains 4 different variable types. You can change this to send other variable types.

typedef struct struct_message {
  char a[32];
  int b;
  float c;
  bool d;
} struct_message;

Then, create a new variable of type struct_message that is called myData that will store the variables’ values.

struct_message myData;

Create a variable of type esp_now_peer_info_t to store information about the peer.

esp_now_peer_info_t peerInfo;

Next, define the OnDataSent() function. This is a callback function that will be executed when a message is sent. In this case, this function simply prints if the message was successfully delivered or not.

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

In the setup(), initialize the serial monitor for debugging purposes:

Serial.begin(115200);

Set the device as a Wi-Fi station:

WiFi.mode(WIFI_STA);

Initialize ESP-NOW:

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

After successfully initializing ESP-NOW, register the callback function that will be called when a message is sent. In this case, we register for the OnDataSent() function created previously.

esp_now_register_send_cb(OnDataSent);

After that, we need to pair with another ESP-NOW device to send data. That’s what we do in the next lines:

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

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

In the loop(), we’ll send a message via ESP-NOW every 2 seconds (you can change this delay time).

First, we set the variables values as follows:

strcpy(myData.a, "THIS IS A CHAR");
myData.b = random(1,20);
myData.c = 1.2;
myData.d = false;

Remember that myData is a structure. Here we assign the values we want to send inside the structure. For example, the first line assigns a char, the second line assigns a random Int number, a Float, and a Boolean variable.

We create this kind of structure to show you how to send the most common variable types. You can change the structure to send other data types.

Finally, send the message as follows:

esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

Check if the message was successfully sent:

if (result == ESP_OK) {
  Serial.println("Sent with success");
}
else {
  Serial.println("Error sending the data");
}

The loop() is executed every 2000 milliseconds (2 seconds).

delay(2000);

ESP32 Receiver Sketch (ESP-NOW)

Upload the following code to your ESP32 receiver board.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp-now-esp32-arduino-ide/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

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

// Structure example to receive data
// Must match the sender structure
typedef struct struct_message {
    char a[32];
    int b;
    float c;
    bool d;
} struct_message;

// Create a struct_message called myData
struct_message myData;

// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  memcpy(&myData, incomingData, sizeof(myData));
  Serial.print("Bytes received: ");
  Serial.println(len);
  Serial.print("Char: ");
  Serial.println(myData.a);
  Serial.print("Int: ");
  Serial.println(myData.b);
  Serial.print("Float: ");
  Serial.println(myData.c);
  Serial.print("Bool: ");
  Serial.println(myData.d);
  Serial.println();
}
 
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(OnDataRecv);
}
 
void loop() {

}

View raw code

How the code works

Similarly to the sender, start by including the libraries:

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

Create a structure to receive the data. This structure should be the same defined in the sender sketch.

typedef struct struct_message {
  char a[32];
  int b;
  float c;
  bool d;
} struct_message;

Create a struct_message variable called myData.

struct_message myData;

Create a callback function that will be called when the ESP32 receives the data via ESP-NOW. The function is called onDataRecv() and should accept several parameters as follows:

void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {

We copy the content of the incomingData data variable into the myData variable.

memcpy(&myData, incomingData, sizeof(myData));

Now, the myData structure contains several variables inside with the values sent by the ESP32 sender. To access variable a, for example, we just need to call myData.a.

In this example, we simply print the received data, but in a practical application you can print the data on a display, for example.

Serial.print("Bytes received: ");
Serial.println(len);
Serial.print("Char: ");
Serial.println(myData.a);
Serial.print("Int: ");
Serial.println(myData.b);
Serial.print("Float: ");
Serial.println(myData.c);
Serial.print("Bool: ");
Serial.println(myData.d);
Serial.println();

In the setup(), intialize the Serial Monitor.

Serial.begin(115200);

Set the device as a Wi-Fi Station.

WiFi.mode(WIFI_STA);

Initialize ESP-NOW:

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

Register for a callback function that will be called when data is received. In this case, we register for the OnDataRecv() function that was created previously.

esp_now_register_recv_cb(OnDataRecv);

Testing ESP-NOW Communication

Upload the sender sketch to the sender ESP32 board and the receiver sketch to the receiver ESP32 board.

Now, open two Arduino IDE windows. One for the receiver, and another for the sender. Open the Serial Monitor for each board. It should be a different COM port for each board.

This is what you should get on the sender side.

Testing ESP-NOW Communication ESP32 with Arduino IDE Sender

And this is what you should get on the receiver side. Note that the Int variable changes between each reading received (because we set it to a random number on the sender side).

ESP32 ESP-NOW Testing

We tested the communication range between the two boards, and we are able to get a stable communication up to 220 meters (approximately 722 feet) in open field. In this experiment both ESP32 on-board antennas were pointing to each other.

ESP-NOW communication range test ESP32

Wrapping Up

We tried to keep our examples as simple as possible so that you better understand how everything works. There are more ESP-NOW-related functions that can be useful in your projects, like: managing peers, deleting peers, scanning for slave devices, etc… For a complete example, in your Arduino IDE, you can go to File > Examples > ESP32 > ESPNow and choose one of the example sketches.

We hope you’ve found this introduction to ESP-NOW useful. As a simple getting started example, we’ve shown you how to send data as a structure from one ESP32 to another. The idea is to replace the structure values with sensor readings or GPIO states, for example.

Additionally, with ESP-NOW, each board can simultaneously be a sender and receiver. One board can send data to multiple boards and also receive data from multiple boards.

We also have a tutorial about ESP-NOW with the ESP8266: Getting Started with ESP-NOW (ESP8266 NodeMCU with Arduino IDE).

To learn more about the ESP32 board, make sure you take a look at our resources:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

232 thoughts on “Getting Started with ESP-NOW (ESP32 with Arduino IDE)”

  1. Great, we don’t need a WIFI_AP anymore 🙂
    For now, I’m challenging a light handshake protocol between slave and master.
    For my application, the slave must decide the duration of sleep for the master(s). The idea is synchronize all ESP32.

    Reply
  2. hello,
    a simple question: yiu tyitlet this post esp-now-esp32…, but if i’m right the protocol works on esp8266 too: is this correct? is there any difference between esp32 and esp8266?
    regards

    Reply
    • Hi.
      You’re right, ESP-NOW also works with ESP8266.
      However, I haven’t tested this code with the ESP8266. Probably there are some changes that need to be made to make it compatible.
      We’ll write a guide about ESP-NOW with ESP8266 – but we still don’t know when.
      Regards,
      Sara

      Reply
      • can we have both ESP NOW and Wifi running simultaneously? I want to have an esp acting like a slave, receive the message from esp now, and then send it into an MQTT queue via wifi, is this possible?

        Reply
        • Yes.
          It is possible.
          But the ESP32 needs to be set as a wi-fi station and access point at the same time.
          You need to use different wi-fi channels. One for ESP-NOW and other to connect to Wi-Fi.
          I’ll be publishing a tutorial about combining ESP-NOW with Wi-Fi in the next weeks.
          So, stay tuned.
          Regards.
          Sara

          Reply
          • Hi Sara
            I had a quick search but didn’t find it, did this Esp and WiFi tutorial eventuate? else hints? I tried adding a 2 after my ssid/password as I found this on the ESP8266 core website
            WiFi.begin(ssid, password, channel, bssid, connect)
            my slaves are ESP8266 and my master is ESP32 and I’m trying to recieve multiple DHT webserver results.
            thanks Ronni

        • Hi JF,
          It is possible to use an ESP32 to receive the data and send it to the web. I don’t know exactly what you want to do, but I modified the code of this excellent post of this blog and made a project which builts an web server which publishes all the data received by the ESP-NOW protocol.

          This project is available here: https://github.com/dualvim/ESP32CAM_ESPNOW_Sensors_WebServer

          It uses an ESP32, an ESP32-CAM and some sensors.

          I hope that it will help you.
          For Sara and Rui, feel free to use it, once all the code are only modifications based on tons of code that I learned here in the blog. It is yours actually!

          Reply
          • Thanks for sharing that 😀
            We’ll write a tutorial using some of the concepts you address in that project.
            Thank you.
            Regards,
            Sara

      • Hi Sara
        I want to use the controller to broadcast just strings such dog, cat, goat etc to multiple slaves. The commands will activate LEDs accordingly. This is a school project. The codes above do not help, though it connects the boards, Can you help me please with the controller and slave side

        thanks
        sam

        Reply
      • Hi.
        You don’t need to install anything.
        It is included when you install the ESP32 boards in your Arduino IDE.
        Regards,
        Sara

        Reply
  3. With respect to your “ESP32 LoRa Sensor Monitoring with Web Server” project could ESP-NOW be used to setup multiple remotes talking to a single ESP32 server?

    Reply
  4. How about ESP32 to ESP8266 so I can use all of those old 8266 I have? Maybe you could provide a summary of alternative 32 to 8266 networking at this current time in the product development cycle.
    Looking forward to your future developments on this product…

    Reply
    • Hi.
      ESP-NOW communication protocol also works with the ESP8266.
      However, at the moment, I haven’t tested these examples with the ESP8266. So, I don’t know if both boards can use the same code or not.
      Regards,
      Sara

      Reply
    • I have modified the code and now it is working just fine below is the code i used…And the sender is ESP32 while the receiver is ESP8266(nodeMcu).

      extern “C” {
      #include
      #include “user_interface.h”
      }
      #include

      // Structure example to receive data
      // Must match the sender structure
      typedef struct struct_message {
      char a[32];
      int b;
      float c;
      String d;
      bool e;
      } struct_message;

      // Create a struct_message called myData
      struct_message myData;

      // callback function that will be executed when data is received
      void OnDataRecv(uint8_t *mac,uint8_t *incomingData, uint8_t len) {
      memcpy(&myData, incomingData, sizeof(myData));
      Serial.print(“Bytes received: “);
      Serial.println(len);
      Serial.print(“Char: “);
      Serial.println(myData.a);
      Serial.print(“Int: “);
      Serial.println(myData.b);
      Serial.print(“Float: “);
      Serial.println(myData.c);
      Serial.print(“String: “);
      Serial.println(myData.d);
      Serial.print(“Bool: “);
      Serial.println(myData.e);
      Serial.println();
      }

      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() == 0)
      {
      Serial.println(“ESP NOW initialised. . .”);
      }
      else
      {
      Serial.println(“ESP NOW not initialised. . .”);
      ESP.restart();
      delay(1);
      }

      // Once ESPNow is successfully Init, we will register for recv CB to
      // get recv packer info
      esp_now_register_recv_cb(OnDataRecv);
      }
      void loop() {}

      Reply
  5. Hi Sara,
    The source code of the ‘Sender module’ (ESP_NOW_Sender.ino) should be fixed, it is different from the code in the explanations bollow of it.

    Despite this detail, excelent post! I didn’t know this resource and I’m testing it here.
    Congratulations!

    Reply
  6. I definitely want to work with this method. It looks so interesting, and the fact it will reply back is amazing. Random Nerds has the best learning site that I am aware of. I have learned more in a month here, than I have learned in a year from any other site.
    Thank you!!
    Bob D

    Reply
    • Hi Bob.
      Yes, ESP-NOW is a great method to exchange data between boards. And you know if the message was successfully delivered or not.
      Thanks for your nice words.
      Regards,
      Sara

      Reply
  7. Really interesting! A new capability for longer range remote control.
    Definitely one of your best tutorials. The amount of first class info you freely share is admirable.

    Reply
      • Is it possible to extend the range of esp-now by placing another esp between two points that are just out of range of each other? The 2 nodes that are furthest apart need to send and receive data from one another. I’m at wots end trying to figure out a solution to get past my 20 yard shortcoming.

        Reply
        • Further explanation…
          I’m basically trying to create a “I’ve fallen and can’t get up” emergency notification to the other. This is between 2 farmhouses with no internet access. We are about 300 yards from each other. I’ve tried using wifi and ESP-Now but both come up short on distance capabilities. I tried external antennas as well which got me to just shy of being able to connect. The is a tool shed with power about halfway between us and I’m wondering if O can add another node there as a sort of extension or relay.

          Reply
          • Hi Wesley, for this situation that you explained, I believe that will be better for you to use the LoRa radio. This site has some LoRa tutorials too.

  8. Wow, I am very excited about this, it is what I have been looking for to set up networks in my home and on my RV to use when we are on the road seeing our great nation.

    Do you have any idea how much modification it would take to add an M5Stick-c to the network, since it is based on an ESP32, has the built in color screen, and the environmental hat is available for it, using the same chip for reading temp and humidity?

    Perhaps the Heltec ESP32 could be included as well, with it’s built in OLED screen. Just thoughts, this does look extremely useful, thank you so much for the write up and effort put into this project, it could have life changing consequences.

    Reply
    • Hi Jerry.
      Thank you for your nice words.
      The M5Stick-c can be programmed using Arduino IDE, and it uses the ESP32 chip, so you can use the code with that board.
      Then, you just need to know the connections between the peripherals and the board and search for examples that interface those peripherals (the sensors and the display).
      Regards,
      Sara

      Reply
    • I am currently running a Heltec Wireless Stick Lite as the sender with ESP NOW to an M5 Stick C as a receiver with the LCD screen showing data. It works great!! The M5 Stick C has far better reception with its on board antenna. The Heltec board needed a small (3″) wire attached to the 3D on board antenna to get better reception. I needed the Heltec board at the sending end as the M5 didnt have enough pins for my application. Other than that , I prefer the M5 over the Heltec for ease of use.

      Reply
    • Yep, the Heltec WiFi kit 32 works. I am using right now to monitor and display temperatures. Display is the same on both ends, but for the moment I am only sensing temperature on one end. The remote monitor also has a button written in that will control a GPIO on the sensor end, but I am not currently using that function, though it is tested and can be used. (Therefore 2 way communication :)) Timestamped datalogger is the next iteration.

      Reply
  9. I tested ESP NOW with this example and it is very impressive. In my distance tests from outdoors, through two walls to the receiver indoors, I was able to get 40 meters. It is a great alternative to LoRa for point – point closer range communication. Now to get analog sensor readings from sender to receiver …

    Reply
  10. Great post — as usual. 😉

    One thing that concerns me though is the use of 2.4GHz channels. That is, I can see how useful this can be in a field or an open space (as in the picture above) where no WiFi hubs are present. However, if we use the ESP NOW in a home, it will conflict with the current WiFi hub — competing and forcing ‘everybody’ to every-now-and-then drop packages due to collisions. Also, since ESP NOW likely doesn’t have functionalities to auto switch channels, MIMO, etc… the use of the same IEEE802 channels can be a real problem to the current hubs/devices.
    I am saying this because I have noticed in the past that the simple presence of an ESP closer to my home WiFi hub has affected the WiFi hub’s performance — likely, in this case, due to the ‘cheap’ antennas and hardware of the ESPs in general that cause a spread of the channel spectrum (eg. channel 11 in a simple 802.11b/n going, in frequency/spectrum, way over channels 8, 9, 10… 12, 13 14…)

    Reply
  11. It looks to me that it works by sending and receiving low level wireless data frames which I presume are analogous to raw (wired) ethernet frames. That makes me think the station limits are artifacts of the library rather than something baked into the hardware? It also makes me wonder if multi station broadcast would in fact work (with ff:ff:ff:ff:ff:ff as the target address)?

    Reply
      • Hello Sara,

        Is it possible to make a two way communication between multiple ESP32 without setting the MAC addresses and just use FF:FF:FF:FF:FF:FF. Using the confirm message to carry a few data?

        Reply
        • Hi.
          Yes, you can use FF to exchange data between your boards.
          What do you mean by “confirm message to carry a few data?”
          Regards,
          Sara

          Reply
    • You can also use NULL, as in:

      esp_now_send(NULL, (uint8_t *) &myData, sizeof(myData))

      The package will than be sent to all peers added with esp_now_add_peer.

      Reply
  12. Hi sara thanks a lot. And this tutorial is very interesting and very useful for me. Appreciate and thanks again.

    Reply
  13. Hi Sara and Rui
    Just a few days ago I was looking for information on this type of communication between modules. It only works between modules or you can also use the Master with ESP NOW and connect to the Wifi and dump the data on a server or in the cloud? .. Good job … and also beautiful beaches to test the connection distance. ..Thank you

    Reply
    • Hi Carlos.
      Yes, you can use ESP-NOW and Wi-Fi in the same board, in theory.
      However, I didn’t get it working yet. There should be some trick to make it work properly. But, we’re working on that and we’ll publish a tutorial about that subject when we get it working.
      Regards,
      Sara

      P.S. Portugal has a 1,794 km coastline with beautiful beaches. It’s worth a visit, if you have the opportunity, specially the south.
      Regards,
      Sara

      Reply
      • Hi Rui and Sara,
        I figure out hou to connect the ESP32 to the internet and use the ESP-NOW.

        It is a little Akward and I’m really tired, but if you’re interested in my solution, just tell me. I’ll try to upload and share as soon as possible!

        Reply
        • Hi Eduardo.
          If you have that project ready, then share a link to the project GitHub page.
          I’d love to see how you did it. But don’t be in a rush, we have time.
          Regards,
          Sara

          Reply
          • Hi Eduardo.
            Great project! I’ve seen your GitHub page. Very well explained. Thanks for sharing it with us!
            Unfortunately, I was not able to see the project running on that link today 4th February.
            Regards,
            Sara

  14. Hi Sara,

    Great article! But I have a few things to clarify. First, there are several references to using the sender callback function to “know if the message was received,” but, since this is a connectionless protocol, (no “ACK”), the sender can only say that the message was successfully sent. It has no way to know if the message was received, unless the receiver becomes a sender and sends back an “ACK” message. I think that should be clarified in your article.
    Also, in one of your replies, you said that it’s possible to use “ff-ff-ff-ff” as a MAC address to send to multiple receivers… But, in the intro, the article stated that “broadcast is not possible.” Is that because the senders cannot decode and match the “ff-ff-ff-ff” to their own MAC address?
    Also one question: with regards to “registering the sender & receiver,” it seems that all that entails is putting the receiver’s MAC address in the code – – is that correct?
    (But, I’ve forgotten if you need to put the sender’s MAC address in the receiver’s code. If not, I don’t really see how it’s “registering” like when we’re linking two Bluetooth devices. It’s just putting the destination address in the packet, like any other transmission.)
    Thanks again for all the fine (actually awesome) articles!

    Reply
    • Hi Jeff.
      Thanks for your comment.
      I’m not sure if I know how to answer all the questions.
      In the espressif documentation, it says “Call esp_now_send() to send ESP-NOW data and esp_now_register_send_cb to register sending callback function. It will return ESP_NOW_SEND_SUCCESS in sending callback function if the data is received successfully on the MAC layer.” https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/network/esp_now.html#send-esp-now-data But, you’re right, because “t is not guaranteed that application layer can receive the data. ”

      Yes, you can use the FF MAC address to send to all devices and it works. However, in the espressif ESP-NOW “datasheet” they said it doesn’t support broadcast mode: https://www.espressif.com/sites/default/files/documentation/esp-now_user_guide_en.pdf But, maybe this is outdated. I’ll update our article about broadcasting.

      To send a message to a device, you just need to put the receiver MAC address on your code and you don’t need to put the sender MAC address on the receiver code.

      I think that what I’m saying is correct, but tell me if I’m wrong.

      Thanks for your comment.
      Regards,
      Sara

      Reply
  15. Hi Sara,
    very often you refer to address 192.168.4.1 an it works.
    My default addreess of the router is 192.168.1.1

    Which is the reference to the first address?
    Thanks

    Renzo

    Reply
  16. renzo, 192.168.4.1 is the default (gateway address) of the ESP when it is in AP mode. Some applications use 192.168.4.1 to host a web page from which you enter your own home network credentials. The famous ESP-Link bridge application does just that.

    Your default address of 192.168.1.1 is usually the gateway address of your router, it does vary with different routers and some use 192.168.1.254.

    I hope that helps

    Reply
  17. I am using two M5 Stick C , which has an ESP32 Pico chipset. I discovered the above code to get the MAC address doesn’t work on this device.
    I found one that does.

    #include “WiFi.h”

    void setup(){

    Serial.begin(115200);
    delay(500);

    Serial.println();
    Serial.print(“MAC: “);
    Serial.println(WiFi.macAddress());

    }

    void loop(){}

    Hope this helps anyone using M5 Stick C. ( great device by the way)

    Reply
  18. Thank U Rui and Sara,
    I made this project with 100% of success!!!
    Compliments for explanations, videos, pictures and your HUGE patience, availability and endurance

    A hug from Italy
    Renzo (Bologna)

    Reply
  19. “…Additionally, with ESP-NOW, each board can be a sender and receiver at the same time, and one board can send data to multiple boards and also receive data from multiple boards. These topics will be covered in future tutorials, so stay tuned.”

    Hey Rui and Sara: promise me U’ll write soon these “future tutorials” !!!
    Another hug from Italy
    Renzo (Bologna)

    Reply
  20. Hi Sara,
    the idea of JD to make an application in which the slave must decide the duration of sleep for the master(s) is very good.

    But how to do it? As far as I know it is impossible to awake from sleep an ESP8266 with a Wifi signal because simply it can’t receive any signal during sleep.

    Thanks
    Renzo Giurini

    Reply
    • Hi.
      Yes, that’s right.
      But I don’t know the application of his project. Maybe he wants to set up a new sleep time when the ESP32 wakes up from sleep. So, the next time it goes to sleep, it is for a different period of time. I don’t know, I’m just guessing 😀
      Regards,
      Sara

      Reply
  21. I used the sender-sketch for a esp8266 ans the receiver-sketch for a esp32. And both are communicating. A strange thing is that the value “Hello” for the string is not printed in the serial monitor.
    I used the sketches from getting started with ESP-now (one way communication).
    So it is working, yet the stringvalue is not known in the receiver.
    Strange?

    Reply
    • Hi Bert.
      Yes, that’s weird.
      What version of Arduino IDE are you using?
      If it doesn’t work, a workaround is to send the message as a CHAR.
      Regards,
      Sara

      Reply
  22. Sorry, I pressed the Post button too early.
    It is said above in the comments, I should get the library while I installed the ESP8266 boards onto IDE. I did that but the compiler throws me “esp_now.h: No such file or directory” error, so it seems that this is not so.
    I don’t have any ESP32 boards so I did not include them.

    Reply
  23. Hi,
    I’ve made an Arduino IDEe installation from scratch. IDE version is 1.8.12. Then I installed software for ESP8266 Community version 2.6.3 (from the link provided in your tutorial). Compiler still cannot find the esp_now.h.

    Just to see if the same thing happens for ESP32 boards, I installed software esp32 Espresiff Systems version 1.0.4 (also from the link in your corresponding tutorial). I choosed one of ESP32 boards as target and my sketch compiles OK.

    The board for which I am trying to use with ESP-Now is Wemos D1 mini. Is it possible that this board doesn’t support ESP-Now??

    Reply
      • Hi,
        well, I do have an esp2866 board selected. I managed to start web server and also a client with my settings. Just to compile the script, the board doesn’t have to be physically available, so I’ve selected some Adafruit and SparkFun boards – and experienced the same issue —

        Reply
  24. Thanks for this amazing tutorial, I have a little request, would you do a tutorial to how to work with ESP-MESH protocol ? Thanks for you contribution!!

    Reply
    • Hi Jairo.
      Thanks for the suggestion.
      I’ve been thinking about that subject for a while.
      It’s definitely in my to-do list. However, I still don’t know when it will be released. I haven’t started yet.
      Regards,
      Sara

      Reply
  25. Thanks for this great tutorial! I’ve been searching for many hours on the net to find one clean and working code like yours. So thank you!
    I would have a question that I cannot find an answer to yet.
    If I want to send the data shared in my esp-now set-up on a database meaning is it possible to switch the last esp which receives all the data to send them over the internet ?
    Is it possible or I must go with the esp-mesh protocol to do that ?
    Thank you for your time.
    jF

    Reply
    • Hi.
      Yes, you can do that.
      You need to set that ESP32 as a station and access point simultaneously for that to work.
      Regards,
      Sara

      Reply
  26. Hi,

    I want to ask. Can I use different type of ESP32 to do this? I’m using TTGO32-LoRa (as Receiver) and ESP Wroom32 (as Sender). But I didn’t receive anything.

    Thanks.

    Reply
    • Hi.
      It should work with other boards. Because they all have the ESP32 chip.
      I tried with different ESP32 board models, but not those you are mentioning, and it worked fine.
      Regards,
      Sara

      Reply
  27. Fantastic as usual!

    Can I just say, perhaps I read things differently, but I found the following line a bit confusing… “register the callback function that will be called when a message is sent.”

    I find it easier to understand worded thus… “register the callback function that will be called AFTER a message is sent.”

    Reply
  28. Hey, ive got a Problem, the Sender alway says:
    -“Last Packet Send Status: Delivery Fail”
    -“Sent with success”
    and the reciever doesnt get anything….

    Reply
    • Hi Nils.
      That means the sender was able to send the message, but the receiver didn’t get the message.
      Double-check that you’ve properly typed the receiver’s MAC address and that the receiver is relatively close to the sender (so that you’re sure it is not something related to distance).
      Regards,
      Sara

      Reply
  29. Dear Sara can we use esp now with ESP01 since it’s a low cost drive and some time no need to use ESP8266 node mcu or ESP32

    Reply
    • Hi.
      I haven’t experimented with ESP-01.
      But I think it should work. You have to experiment and see what you get.
      Regards,
      Sara

      Reply
  30. Hey guys,
    Great work, as usual.

    Is it possible to put the sender to sleep (light or deep) and have the receiver wake it up somehow to send data, with like a request or something? The sender will be a battery operated device.

    Thanks!

    Reply
    • Hi.
      I don’t know how to do that, and I don’t think it is possible (someone correct me if I’m wrong).
      You can wake up the ESP32 using an external wake-up (via physical GPIO) or have a timer wake-up. So, I don’t think you can wake it up using Wi-Fi or ESP-NOW.
      Regards,
      Sara

      Reply
  31. I m loving this ballistic learning curve I am on, I look at these tutorials and I get them working learning by my errors as I go.

    Then I get these stupid ideas like “I can use the ‘8266 one to many ESP-NOW’ with the ‘ds18b20 code’ and add the ‘oled display’ together “

    And yes I can but boy it’s not easy!

    I am trying to create separate temperature sensors with local displays that I will 3d print enclosures for later. These I will place around my home and garden and have all the data sent back to another that can display ALL the data.

    It’s not going well but thats all part of learning isn’t it. I keep getting tangled as I am finding that simple things like libraries can trip each other up if placed in certain orders.

    I am currently struggling to get the oled to display anything from within the code and although I can get the temperature (as float) across I cant then use it.

    It’s great because it time I go back to your other tutorials I learn a different approach, I am really enjoying the frustration of it

    Cheers Clive

    Reply
  32. Hi Clive,
    I agree totally; I am going back now and starting fresh on an ESP Now tutorial that uses combo mode. I will add the DSS1306 displays, and some code that will track value of a switch condition.
    It is a play on another project I completed, so I know it will work. I just want to re-enforce what I have been learning here at RN by repeating the same concept…but slightly different so I can learn more.
    The good news is I received 5 more WeMos D1, and 3 more ESP8266 modules to experiment with.

    Reply
  33. This is a great page to start with ESP-NOW. I love the community surrounding “RandomNerdTutorials”.
    My hands are burning with new projects in mind.

    Reply
  34. hi Sara
    I´m doing test with esp-now.
    Do you have the code for two ways comunication?
    Is it too different to the one way comunication code?

    regrats and thanks!

    Reply
  35. hello thanks for the tuto
    i have a question
    what about recieving and sending data from multiple esp boards at the same time? i couldnt found the example!

    Reply
      • hi
        yes i want to send and recieve from multiple boards, but they are connected in series not randomly.
        i.e. each board will send to only one board and recieve from only one board
        for example 5 boards:
        board 1 send to B2
        B2 recieve from B1 and send to B3
        B3 recieve from B2 and send to B4
        B4 recieve from B3 and send to B5
        can i do this with esp-now?
        thanks in advance

        Reply
        • Hi.
          Yes.
          You just need to specify to which board you want to send the message.
          You also need to specify that you want to send the received message to the other board.
          Regards,
          Sara

          Reply
  36. Hi Sara and Rui,

    i just discovered a ESP-NOW-Wrapper-library published by user yoursunny on GitHUB. It makes using ESP-NOW much more easier because all the details
    about add-peer etc. are encapsulated inside the library
    here is the link
    https://github.com/yoursunny/WifiEspNow

    I tested the EspNowBroadcast.ino example and it worked right away.
    You just upload this example-code into EVERY ESP-device that shall be part of a ESP-NOW-mesh and press the onboard nodeMCU-button to retrieve the mac-adresses of each device that has the code EspNowBroadcast.ino running.

    best regards Stefan

    Reply
  37. Hi – Great Tutorials

    I have tried the tutorial with an ESP8266 in Wemos D1 boards.

    Unfortunately I’m getting the failure message probably 60% of the time. In the example code communication is every 2 seconds. In my implementation sometimes there are two successful messages in a row but often there are several fails in a row. Often up to five. Thinking there may be conflict with neighbours WiFi my PC etc I added code to turn the LED on/off around the call back function and moved to an open sports field. I didn’t perceive any change in performance – sometimes the LED flashed every 2 seconds but often the delay was longer.

    In terms of communication distance it seemed to communicate up to 100 metres. (I made no attempt to align the antennas)

    For my project 100m communication and updates every 10 seconds will be OK but if it was going to be a commercial product I’m certainly at the limits.

    If anyone has any ideas I’d appreciate it

    All the best for 2021

    John K

    Reply
    • Hi John, a 2 second interval is quite tight. 10 seconds is what I use in testing. I initialize WiFi and ESP NOW at start up, read sensor, transmit, then shut down WiFi/ESP NOW BEFORE!! going into sleep mode. In final product, I read once / three hours. Here is what I’ve built. septicspy.com

      Reply
      • Hi Mitch

        What an interesting project you have.

        In my project initially I used exactly the same code as in the Tutorial with a send every 2 seconds. -I have different Hardware -a WEMOS D1 ESP8266 Board.

        With this set up approximately 2 of every 3 messages at the sender was a failure message. I did try times longer than 2 seconds but did not perceive any difference.

        Cheers

        John K

        Reply
    • A follow up to my previous comment.

      My settings were ‘tools–>Erase Flash–>Only Sketch’

      With “out of the box” ESP8266’s it worked perfectly. I tried it with an update rate of 50mS and there were no failures.

      As per my previous comment with old/pre-used ESP8266’s there was approximately 60% failure rate at 2 second updates.

      Changing settings to ‘tools–>Erase Flash–>Sketch + WiFi Settings’ I did not perceive any difference.

      However with the “old” ESP8266 and ‘tools–>Erase Flash–>All Flash Contents’ everything worked perfectly (tested down to 50mS update rate)

      The range appeared to be about 100m.

      I hope this helps someone else.

      John K

      Reply
      • Does your code have calls of function delay()? Delay() is blocking (almost everything)

        Then this is the reason why receiving fails. As long a s a delay() is executed on the receiverside the microcontroller is unable to receive ESP-NOW-messages
        For receiving ESP-NOW-messages all timing must be done without delay()

        With NON-blocking code I was able to switch an IO-pin ON/OFF through sending ESP-NOW-messages where each message
        sets the IO-pin HIGH next one LOW next one HIGH etc. without any flaws up to a frequency of 500Hz = 2 milliseconds.
        It was possible to do it even faster but with some timing-errors. Which means all pulses where still received but with glitches at every 10 to 20 message.

        best regards Stefan

        Reply
        • Hi Stefan

          I was testing exactly the same code as supplied in the tutorials. With previously used ESP8266 chips and the Arduino IDE set to “Erase Only Sketch” I had a 60% failure rate with a 2 second update (as per original code).

          Using un-used ESP8266s there were NO failures. Also using the ESP8266s that gave the 60% failure rate but changing the Arduino IDE to “Erase ALL Flash Contents” eliminated all the failures.

          Now either set of chips would give 100% pass rate at 50mS update. I didn’t try to go any faster but I suspect the println( ) statements may then be the limiting feature in the code – not the ESP8266s.

          With regard to using delay( ) functions – I never use them – neither do Rui or Shara – as it is a blocking operation. Further delay( ) or millis() will not work in Interrupt Service Routines or Callbacks which are the heart of the ESP8266-NOW example.

          Thanks for your support

          John K.

          Reply
  38. U need to set the arduino ide settings to clear out the sketch “and” the old wifi settings when you upload. I’m not at my pc atm so I can’t recall what the proper terminology is.

    Reply
  39. U need to set the arduino ide settings to clear out the sketch “and” the old wifi settings when you upload. I’m not at my pc atm so I can’t recall what the proper terminology is. This is for response to all who are getting, some but not all, message failures. The esp8266 still has the old wifi settings. This fixed my problems, 0 failures even sending at 50ms intervals.

    Reply
  40. When I connect ESP32 (2 units) to 1 computer, the port is impulsive and only 1 ESP is recognized.
    Is there any way to connect 2 ESPs to 1 computer?

    Reply
  41. Hi, thanks for your tutorial. I tried your tutorial and yes, it’s perfectly working. I got about 500m in open area, by using internal antenna. Better than i expected. I think the range can be improve using external antenna.

    Reply
  42. Hello Sara and Rui,
    I am doing esp-now between an esp32 and an esp8266 and everything is fine except that it is not possible to drive a relay or even the LED_BUILTIN led.
    I manage to control a Pan-Tilt with a PCA9685, but impossible to put digitalWrite (D0, HIGH);
    Do you have an explanation?
    Thank you

    Reply
  43. i dont think it’s possible. Its because both of your esp using the same driver as well as using a single COM PORT.

    Reply
  44. So this seems to be the solution I need but I am a complete noob and need help!

    I need to use two esp01 to create a transmit and receive bridge via serial

    Th commands are sent as lines back and forth for example “N1 G30 Y120”

    Does anyone know how to configure esp now that when it sees on the receive serial it pushes it raw out to the tx on the other esp and vice versa to create the two way link?

    I am at a loss using the two way communication.INO as I do not know what to change in the sensor data example

    Reply
  45. Hello Sara and Rui,

    I’m trying to use OTA which requires me to setup the esp32 as a wifi station. However, I’m hosting an asyncwebserver as well as using ESP Now. It seems that some conflict is happening as ESP Now is no longer working properly when I added the OTA. Are they compatible? Do you have a tutorial where you use all three features?

    Thank you!

    Best regards,
    Joseph

    Reply
  46. Hi Sara,
    I am trying to adapt this code for u8g2 oled display and having problems.
    Can you please adapt this code got this display?
    //regards,jay

    Reply
    • Hi.
      This is what is mentioned in the documentation:
      “Limited encrypted peers. 10 encrypted peers at the most are supported in Station mode; 6 at the most in SoftAP or SoftAP + Station mode;
      Multiple unencrypted peers are supported, however, their total number should be less than 20, including encrypted peers;”
      Regards,
      Sara

      Reply
  47. Hi Ruis and Sara
    Thank you for an excellent tutorial, afraid I’m having an issue and wondered if you could assist? Yesterday (5 Sept 21) this worked just fine on my two ESP32 Node MCU boards, they were talking to each other fine and I moved on to modify the ‘content’ of the messages. However at some point the code stopped working, and I’m getting on the Sender serial monitor the message ‘failed to find peer’. I have reverted right back to the original code on this page, rechecked the MAC address of receiver (which I haven’t changed), and started again from scratch but it doesn’t work any more. The one thing I did notice is that the IDE may have updated the ESP NOW library…is it possible that the code will now not function correctly? Expect if that is the case then other users would find the same issue…could you advise (might also allow you to tweak code on here if needed)? Very grateful for your help, thanks. Alex

    Reply
    • Hi.
      That0s weird.
      Try to send the packet to the following mac Address:
      uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
      See if you get the same results.
      Always double-check that both boards are actually running the code. After uploading press the RST button.
      Regards,
      Sara

      Reply
      • Hi Sara, and sorry I didn’t see your reply before, I set up notifications but despite best efforts it went to junkmail…
        See below second post which seems to have cleared it, from a previous similar fix you posted (thanks!) but I will file this solution away for future reference! Thanks so much for your help.
        Kind regards,
        Alex

        Reply
  48. Hi Ruis and Sara
    Following my earlier query today, I looked back over your responses to similar issues in the 2 way comms page, from a couple years ago, and mimicked the same solution for this issue. It seems to have resolved it, though I don’t know why! THis was the solution you wrote in case any one else can also apply it to same issue:

    “Hi Leo.
    I saw something in a portuguese blog about this issue. I’m not sure if it work, but we can try.
    It suggests that we cut this line from the setup()

    esp_now_peer_info_t peerInfo;
    And past it before the loop() and before the setup().”

    Many thanks

    Alex

    Reply
    • I personally would never expect a compiler to extract the definition of an instance/object from inside any method/function. My opinion is that it should be placed before any code. That is:

      #include ….any library files
      esp_now_peer_info_t peerInfo; //create an instance/object of type esp_now..
      //declare other global variables
      void setup( ) { }
      void loop( ){ }

      One other point – if the object does not have any arguments leave out the brackets as in this example. With the brackets, but no argument(s) the compiler will treat the object as a method/function and then (I seem to recall) the program “worked” but not as expected and it took me a long time to discover my problem.
      Stay safe
      JK

      Reply
      • Thanks John, have made a note as even though the issue has gone away for now, it may well rear its head again. Much obliged.
        Alex

        Reply
  49. I learned something new today. Thank you. Given I’m conceptualising a low power sensor solution this may come in handy as Wifi is very “power hungry”. However if this was an ESP-NOW solution I sell, every sender and receiver would have to be configured manually as part of uploading the firmware as I need to specify the MAC address of the other board, right? Is there a way around this; e.g. generating a virtual MAC address etc.

    Reply
    • Hi.
      You can try to use a Wi-Fi sniffer to get the MAC address of nearby Wi-Fi devices.
      Then, you can modify your code to allow you to select the right MAC address using some kind of interface.
      Regards,
      Sara

      Reply
  50. Hi everyone, Congratulations on your work,
    Without doubt the best site for examples, Great tutorials.

    I tested ESP NOW it’s very impressive.
    I’m thinking about putting several Esp32 and Esp8266 in my house,
    To control windows, lighting, temperature sensors, automatic door etc…
    But,
    Is it okay to use several Esp-Now indoors?
    Will not interfere with the Wifi network?
    Is it safe for health to have lots of Esp-Now indoors?
    Thanks

    Reply
  51. I got an “E (120) ESPNOW: Peer interface is invalid” due to the fact that the peerInfo
    struct contains junk data. Please add ‘memset(&peerInfo, 0, sizeof(peerInfo));’ to initialize
    peerInfo to zeroes:

    // Register peer
    esp_now_peer_info_t peerInfo;
    memset(&peerInfo, 0, sizeof(peerInfo));

    memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    peerInfo.channel = 0;
    peerInfo.encrypt = false;

    OR:

    esp_now_peer_info_t peerInfo = {};

    memcpy(peerInfo.peer_addr, broadcastAddress, 6);
    peerInfo.channel = 0;
    peerInfo.encrypt = false;

    Thanks!

    Reply
  52. Hello and thank you for such great documentation for the ESP32/8266

    I do keep running into a problem though. I have copied both the send and the receive code from this website to trial.

    The send code works with no issue printing to serial “error sending the data”. I however, have not been able to get the Receive code to work. I have tried 2 different boards and even different USB cords yet it will not register or even print to serial. Any suggestions as to what I am doing wrong as I would love to use this product???

    Reply
      • Hey Sara, i wanted to update you on my progress since you were kind enough to actually respond to me. It seems the version of Arduino that i was using had some files stashed in places that as causing problems. I had to totally erase all Arduino files on my c:drive and reinstall the program and it has worked with no issue. I’m not sure exactly what file it was but this is what will as needed to get your examples to work.

        Reply
  53. There is no code showing up for the Rx unit and the Tx unit is saying “error sending the data. If i press the reset button on the Rx unit it prints

    ” rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:2
    load:0x3fff0030,len:1324
    ho 0 tail 12 room 4
    load:0x40078000,len:13480
    ho 0 tail 12 room 4
    load:0x40080400,len:3604
    entry 0x400805f0″

    Reply
  54. I’m wondering if there is any way using ESPNOW that I would be able to turn on an LED when there is a loss in peer connection between 2 ESP32s? I’ve been looking for a function or variable that will work but have yet to find something that will work.

    Thanks in advance

    R

    Reply
  55. Hi,

    Thanks for your Great tutorials.

    Query about the ESP NOW protocol.
    I have one sender and receiver, i am able to send and receive data. I am using an encoder, say it transmits either clockwise or anticlockwise. If i rotate once in clockwise , i am receiving continuously state changes.
    what i require is that it should send data only when the encoder changes the state, otherwise it should not send any data.But the connection should not be affected.
    I hope you understand.

    Thanks
    Sahan

    Reply
  56. I don’t find the library link to the header file esp_now.h

    Is it changed to WiFiEspNow ??

    I googled and there is a WiFiEspNow library.
    Would appreciate if you could revert.

    Reply
  57. Great tutorials. They’ve allowed me to complete a prototype a project that I’ve had in mind for a couple of years.

    Reply
  58. Hi Sara,

    Thank you for all of these tutorials, they really help.
    I do have one thing I can’t quite understand though and I was hoping that you could point me in the right direction, and that is “esp_now.h”, I can’t find this library anywhere, I’ve been through the esp now tutorials here, tutorials on other websites, the arduino ide etc, still nothing.
    I seem to be missing something really obvious as it doesn’t seem to be an issue for anyone else, admittedly I’m still waiting for my boards to arrive (hopefully within the next week or so), but if you know this off the top of your head I’d love to hear the answer.

    Best regards
    Bill

    Reply
    • Hi.
      The espnow.h library comes by default with the ES8266 package for the Arduino IDE.
      For the ESP32, it is esp_now.h.

      You don’t need to install those libraries. They are installed automatically when you install the ESP32 or ESP8266 on Arduino IDE.
      Make sure you have an ESP32 or EPS8266 board selected in Tools > Board when compiling the code.

      Regards,
      Sara

      Regards,
      Sara

      Reply
  59. Hi Sara, can you help me on a project collecting CSI by ESP32. I can collect csi data ,but i can’t visualize the waveforms.

    Reply
  60. Hi Sara, Great tutorial and clear explanations! I was using an ESP32-WROOM-32D as a sender and D1 Mini ESP8266 ESP-12F as receivers. All worked perfectly, until I tried to use ESP32-WROOM-32 as sender. The sender is told to send data from a pin interrupt routine and it fails to send. I am using arduino IDE, board is ESP32 DEV Module. Again code works flawlessly with 32D and not plain 32. As I have several ESP32’s and do not have additional 32D’s it would be great to use my stock of 32’s Thanks in advance John

    Reply
  61. Hi ,

    Thank’s for this great tutorial.
    I hope you can help me for a project.
    i need to send RS485 data from one point to an other wireless.
    i want RS485 to UART modul > ESP32 > datas over the air > ESP32 > UART to RS485 modul.
    is it possible ? (need 115200bauds)

    Reply
    • Hi.
      I never tried it, but yes. I think it should be possible.
      Unfortunately, we don’t have any tutorials covering that exact subject.
      Regards,
      Sara

      Reply
  62. Hi Sara, I have followed and learned a lot from your tutorials. The things that are working for me from your tutorials are as follows:espnow esp32-wroom-32 to esp32-wroom one way comm, esp32wroom to esp8266-12E one way comm. My issue is to get esp32wroom to wemos esp8266 D1 mini one way comm. Depending on the physical wemos boards data gets sent successfully, fails, or intermittently fails. I am using Arduino IDE board ESP32 Dev Module and Lolin (wemos) D1 mini clone. Are there any known issues with this combo? Having 24 of these boards to use in a model railroading project has me looking for an answer. btw I believe the sent data success comes back, however delivery is unsuccessful. 🙁 I can supply code, however it works 100% on one of the boards and other boards are around 20-70% intermittently. makes no sense…

    Reply
    • Hi John.

      I’m not sure, but I think it might be an issue related to the D1 mini boards.
      I had other readers complaining about the same issue on those boards.
      However, I never try them….
      So, I suggest replacing the boards and seeing if you get better results.

      Regards,
      Sara

      Reply
      • Hi Sara,
        Yes out of 24 D1 boards 8 are defective. I send data at a fast pace delay=20 and see either constant success or on the faulty boards intermittent failures. Putting my finger on the antenna area of the D1 board and putting pressure on it the results are almost all success… So the boards are the problem. Thanks for the advice.

        Reply
      • Hey Sara and folks!
        First of all, you web page rocks, Sara! Congrats.
        I’ve just solved the issue about ESP32 Esp d1 mini. It’s about PHY mode (physical layer).

        For some reason, mainly ESP32-WROOM-32D (ESP32-DOWD-V3 or higher) has a different physical rate by default. That causes trouble when ESP32 send data to ESP8266EX because this board can’t receive due to the radio frequency.

        That’s the solution:
        On ESP32 firmware you have to declare on main function:
        WiFi.mode(WIFI_AP_STA);
        esp_wifi_start();
        esp_now_init();
        esp_wifi_config_espnow_rate(WIFI_IF_STA, WIFI_PHY_RATE_54M);

        No extra libs it is necessary! ASAP I will post the example code, including a DEBUG testing, on my GitHub and share with you all.

        ESP-IDF from espressif helps me a lot – https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv415wifi_phy_rate_t.

        I hope this trick can help lots of people 🙂

        Reply
        • Hi.
          Thank you so much for sharing this. It is indeed very useful.
          I had no idea of how to sort it out.
          Thank you.
          Regards,
          Sara

          Reply
  63. Greetings,
    I really like your website and you have a lot of great info on the ESP32.

    Trying to setup a sender and receiver based on the codes above and I am having problems with inserting the MAC address:

    // REPLACE WITH YOUR RECEIVER MAC Address
    uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

    I get errors like the one below.

    error: invalid digit “8” in octal constant

    It seems to not like the MAC Address I type in.

    Any thoughts on what I am doing wrong?

    Regards David B

    Reply
  64. awesome lessons all around!!!!
    thanks for sharing

    i have AI Thinker and WEMOS D1 MINI – everything seems to be working fine for now but i want to revise the project to send partial structure data
    i am trying ESP_NOW Combo on both units
    for example:
    myData.a
    myData.b
    myData.c
    myData.d

    i want to send only ‘myData.a, .b, & .c’ from AI thinker to WEMOS
    and only send ‘myData.d’ from WEMOS to AI Thinker

    is that possible and do you have a lesson on how or point me in right direction, please???

    Reply
  65. Hi Sara,
    I want to send data from several sensors,in a range of about 10 meters, ie temp, garage door etc to a central receiver and to show data on a display.
    It is possible with ESPnow?
    Regards
    Renzo

    Reply
  66. Hi, I just have a couple of doubts
    Can ESP NOW and MQTT be implemented at the same time (of course with different boards) and can esp now be used to send command from master to slave board to turn something off or on?
    Thanks in advance

    Reply
  67. I am using ESP Now to send a temperature reading every 4 minutes to the receiver. Is there a way to configure the receiver to flag if it hasn’t received a reading for say 10 minutes?

    Reply
  68. So unfortunate that I am seeing this website now. I have been struggling with how to transmit MPU6050 accelerometer data using espnow. Sara, could you give some inputs on this?

    Reply
  69. Just as a learning curve…I am reading that using integer is not best practice because the same code compiled of a 32 bit machine vs a 64 bit machine can cause issues. I have been converting my code from “int” to “uint8_t” so far so good.
    When it comes to this line…void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
    I coverted all my code and had an error with the “uint8_t” seems it has to be a zero.
    The people who write the ESP library are much better than myself, so I was wondering why they reverted back to an “int”…yet the internet is full of things like..don’t use strings and dont use int.
    TIA

    Reply
    • typo..void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
      “Seems the “int len” has to be an “int” and fails if a “uint8_t” is used

      Reply
  70. First of all, congratulations on a job well done!
    Are there any examples that allow the extension of the wifi network (esp_now)? I very simply have to insert one or more esp32 “repeters” between master and slave to try to overcome physical obstacles (walls or whatever).
    Thanks anyway and congratulations again

    Reply
  71. Bonjour
    J’utilise 2 esp32 avec le protocole ESPNOW, cela fonctionne bien
    , mais au delà de 5mètres à l’intérieur, plus de transfert de données.
    Dois je utiliser des ESP avec antenne?
    Merci et surtout félicitations pour votre travail….une véritable source d’informations

    Reply
  72. Sara and team
    Great tutorial as usual. I have been trying to send 2 different structs from the same module to a single second module. Google was not helpful, but this worked.
    Sender:
    typedef struct relay_message {
    int message; //set to 0 for relay
    int relay_num;
    bool on_off;
    };
    // Create a struct_message called myRelayData
    relay_message myRelayData;

    //seperate struct for on/off
    typedef struct onoff_message {
    int message; //set to 1 for onOff
    int valve_num;
    int on_hour;
    int on_minute;
    int duration;
    };
    // Create a struct_message called myData
    onoff_message onOffData;

    Then have 2 routines to send the data, these are the same as yours, one for each struct.

    Receiver:
    Define the structs as above, then add
    int messageType;
    Here is the clever bit (well not that clever)
    // callback function that will be executed when data is received
    void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
    memcpy(&messageType, incomingData, sizeof(messageType));
    switch (messageType) {
    case 0: //relay on off
    memcpy(&myRelayData, incomingData, sizeof(myRelayData));
    doSomthingWithRelayData (myRelayData);
    break;
    case 1: //set time on and duration
    memcpy(&onOffData, incomingData, sizeof(onOffData));
    doSomthingWithOnOffData (onOffData);
    break;
    }
    }

    Feel free to use if of any interest.

    Reply
  73. Hi Sara and Rui,
    great instruction, i had it working in 30 minutes, nice.
    I just tried it for fun, probaly I can use it in future projects.
    Kind Regards
    Otto

    Reply
  74. Hi there, is force pressure sensor 602 compatible with esp now? because I seem to not to be able to have the readings of the sensor working correctly as I insert the codes for esp now. Meanwhile without the esp now codes the sensor is working fine. Kindly help me with this, thank you!

    Reply
      • Hi, I have tried possible variable types but did not work and I found out that as I type in the WiFi.mode(WIFI_STA); into the void setup, it began to malfunctioning the pressure sensor.

        Do you have any idea on what is happening?

        Here is my codes:

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

        #define fsrpin 14
        #define SS_PIN 5
        #define RST_PIN 22

        MFRC522 mfrc522(SS_PIN, RST_PIN);
        byte validUid[] = {0x90, 0x6A, 0x6F, 0x20};

        double fsrreading;
        int car1;
        bool access1;

        uint8_t broadcastAddress[] = {0x08, 0xB6, 0x1F, 0x3D, 0x29, 0xF4};
        typedef struct struct_message {
        bool access1;
        int car1;
        } struct_message;
        struct_message myData;
        esp_now_peer_info_t peerInfo;

        void setup() {
        Serial.begin(115200);
        SPI.begin();
        mfrc522.PCD_Init();
        pinMode(fsrpin, INPUT);

        WiFi.mode(WIFI_STA);
        }

        void loop() {

        if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
        // Check if the UID of the card matches the valid UID
        if (memcmp(mfrc522.uid.uidByte, validUid, mfrc522.uid.size) == 0) {
        access1 = true;
        Serial.println(access1);
        delay(100);
        }
        // Halt PICC and stop encryption
        mfrc522.PICC_HaltA();
        mfrc522.PCD_StopCrypto1();
        }

        fsrreading = analogRead(fsrpin);
        if(fsrreading > 0){
        car1 = car1+1;
        }
        Serial.println(fsrreading);//*
        //Serial.print(“Reading = “);
        //
        Serial.println(fsrreading);
        delay(300);
        }

        Reply
          • Hi Sara, I managed to tackle it out by trying different GPIO pins and I guess ADC1 should be used instead of ADC2. However, Im not sure regarding the reason why it works like that. Btw, thank you for your help! Appreciate it.

            By any chance, do you know whether it is possible to run the esp32 cores parallelly but with an ability to overlap or cancel the occuring delay of an LED (say in the defaut void loop) with a condition form the second core.
            So, it will be like:
            In the void loop, the led1 is on, with a delay of lets say 5 sec. Then, in the loop2, as the MFRC522 granted an access, it will directly turn the led1 off, regardless of the delay of the led1 in vood loop condition.

          • Hi.
            It’s because using ADC2 pins interferes with the Wi-Fi functions. That’s why I asked about the GPIOs you were using.

            Yes, that is possible. I think you need to use semaphores. But, I’m not very familiar with that subject.

            Regards,
            Sara

          • I see, thanks for the information. Oh, I heard of semaphores. No problem, I’ll try to learn it. Thanks a lot Sara!

  75. Try formatting your code. That helps show things up. Add print statements to see what is going on
    How can anyone debug your code for you, when there is only part of the code.

    Reply
  76. Hello,
    I have a problem with esp-now. The controllers only communicate if they are powered/all/ via the computer’s USB. If they are externally powered, for example from a battery… there is no communication. What could be the reason?

    Reply
    • WiFi requires significant power – are your batteries powerful enough?
      I have several units set up around a model railway track and I am using voltage regulators from the track to generate the 5V for the ESP8266.

      Reply
    • It’s installed by default with the ESP32 core on the Arduino IDE.
      Just make sure you have an ESP32 board selected in Tools > Board.
      Regards,
      Sara

      Reply
  77. Hi Sara ,

    I’m confused by the memcpy command …

    “memcpy(&myData, incomingData, sizeof(myData)); ”

    Surely when the memcpy occurs – the myData is null and therefore doesn’t have any size – where as incomingData does have a size. So why aren’t you ( and Rui ) using sizeof(incomingData) ?

    Thanks for being such valuable contributors to the ESP world.

    Reply
  78. Hello Sara,
    Great tutorials on ESP NOW. Thank You.
    I have successfully completed a Sensor to Remote Receiver project that works great when the two TTGO- T-Display devices are relatively close together but the Sensor/Sender can’t quite reach the receiver reliably when it’s placed out in the garage of my house where I need it.

    I understand that it’s possible to extend the ESP NOW range by reducing its Wifi data rate, and that by default it’s set to 54MBit, however if you can set it to the more robust 802.11n ( as many routers do dynamically) The data rate can be reduced to 2 or a 1Mbit rate and extended the range dramatically. Unfortunately I don’t know how to do this with the Arduino IDE 2.10, as it’s (I hear) possible to do with the ESP IDF.
    so: Presently when I try with this :
    // Set ESP32 as a Wi-Fi Station
    WiFi.mode(WIFI_STA);

    wifi_config_t wifi_config;
    esp_wifi_get_config(WIFI_IF_STA, &wifi_config);
    wifi_config.sta.listen_interval = 3;
    wifi_config.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL;
    wifi_config.sta.threshold.rssi = -127;
    wifi_config.sta.threshold.authmode = WIFI_AUTH_OPEN;
    wifi_config.sta.pmf_cfg.capable = true;
    wifi_config.sta.pmf_cfg.required = false;
    wifi_config.sta.bssid_set = 0;
    esp_wifi_set_config(WIFI_IF_STA, &wifi_config);

    // Set the WiFi protocol to 802.11b for longer range
    esp_wifi_set_protocol(ESP_IF_WIFI_STA, WIFI_PROTOCOL_11B);

    I get:” Compilation error: cannot convert ‘esp_interface_t’ to ‘wifi_interface_t'” on this last line.

    So my question is this: .. is there a way to use the Arduino IDE 2.10.x to extent the range of ESP NOW without having to use an external antenna .. or switching to use of the ESP IDF so I can switch to the more robust 802.11n protocol?
    Thanks in Advance.. jimS

    Reply
    • Hi.
      I’m sorry, but I’m not familiar with those functions.
      Usually, you can use ESP IDF functions with the Arduino IDE. Try to check if you’re using the latest version of the ESP32 boards installation. Then, check that if you’re using the latest ESP IDF functions so that everything is compatible.
      Regards,
      Sara

      Reply
  79. hey sarra,
    I’m doing a flower recognition with edge impulse FOMO on esp32 cam.
    the recognition is on the esp32cam and the output is on the serial monitor. with the help of esp_now and your tutorial, i wanna make it the server and send the data to another esp32 as a client to display the flower’s name in an LCD on the esp32. tell me if it is possible or not and can you please help me with the code ? this is the esp32cam code :

    #define MAX_RESOLUTION_VGA 1

    /**
    * Run Edge Impulse FOMO model on the Esp32 camera
    */

    // replace with the name of your library
    #include <SCopt_inferencing.h>
    #include “esp32cam.h”
    #include “esp32cam/tinyml/edgeimpulse/FOMO.h”

    using namespace Eloquent::Esp32cam;

    Cam cam;
    TinyML::EdgeImpulse::FOMO fomo;

    void setup() {
    Serial.begin(115200);
    delay(3000);
    Serial.println(“Init”);

    cam.aithinker();
    cam.highQuality();
    cam.highestSaturation();
    cam.vga();

    while (!cam.begin())
    Serial.println(cam.getErrorMessage());

    }

    void loop() {
    if (!cam.capture()) {
    Serial.println(cam.getErrorMessage());
    delay(1000);
    return;
    }

    // run FOMO model
    if (!fomo.detectObjects(cam)) {
    Serial.println(fomo.getErrorMessage());
    delay(1000);
    return;
    }

    // print found bounding boxes
    if (fomo.hasObjects()) {
    Serial.printf("Found %d objects in %d millis\n", fomo.count(), fomo.getExecutionTimeInMillis());

    fomo.forEach([](size_t ix, ei_impulse_result_bounding_box_t bbox) {
    Serial.print(" > BBox of label ");
    Serial.print(bbox.label);
    Serial.print(" at (");
    Serial.print(bbox.x);
    Serial.print(", ");
    Serial.print(bbox.y);
    Serial.print("), size ");
    Serial.print(bbox.width);
    Serial.print(" x ");
    Serial.print(bbox.height);
    Serial.println();

    });
    }
    else {
    Serial.println("No objects detected");
    }

    }

    Reply
    • Hi.
      I’m not familiar with that library. So, I’m not sure if it is compatible with ESP-NOW.
      In theory, I think you can combine both features.

      Regards,
      Sara

      Reply
  80. Hello
    I want to ask is it possible to transmit messages with ESP32 NOW?
    If it is possible to use the above program code directly?

    Reply
  81. Hi,
    thanks for this tutorial, I just tried this in platformio and ran into one little problem, the compiler was throwing an error on the receiver part and I had to change the OnDataRecv function like this to make it work:

    void OnDataRecv(const esp_now_recv_info * mac, const unsigned char *incomingData, int len){
    instead of
    void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {

    Uli

    Reply
  82. Hey Sara,
    thanks for the great tutorial! Everything works great but there is one thing I don’t understand about the code:
    the “esp_now_register_send_cb(OnDataSent)” function only gets called in the setup part of the program but in the serial monitor I get the delivery information in every loop. Is the esp_now_register_send_cb() automatically called when esp_now_send() is called? Thanks for your help!
    All the best,
    Marco

    Reply
  83. Are there libraries that pack larger objects into the data, like breaking an image into 250-byte parts and sending each one until the entire image is transmitted? Of course, this would need a smart ACK, eg, some sort of ID per block so that retransmission of missed data is possible.

    Basically, the lib would implement TCP using ESP-NOW, and compare all the outgoing blocks to incoming ACKs.

    Reply
  84. Is there any way of broadcasting from a master board to unidentified slave(s), ie without a mac address for the slave?
    Reason: I have 6 boards which could be swapped around at any time. Having to update mac addresses at each change is a (admittedly small) pain.

    I guess I could list all boards and have the master run that through a loop until a reply is received. A bit hefty though.

    Regards

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.