Design a site like this with WordPress.com
Get started

Let’s Start with ESP-NOW (ESP8266 NodeMCU with Arduino IDE)

In this article, we’ll show you how you can use ESP-NOW to exchange data between ESP8266 NodeMCU boards programmed with Arduino IDE. ESP-NOW is a connectionless communication protocol developed by Espressif that features short packet transmission and can be used with ESP8266 and ESP32 boards.

//image of esp

//installing esp board link + yt video

Introducing ESP-NOW

The following video shows an introduction to ESP-NOW. This video was recorded for the ESP32, but most concepts also apply to the ESP8266 NodeMCU board.

//video of esp

Stating 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.”

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 ESP8266 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 ESP8266 board sending data to another ESP8266 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.

  • A “master” ESP8266 sending data to multiple ESP8266 “slaves”

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

  • One ESP8266 “slave” receiving data from multiple “masters”

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

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 a two-way communication between boards.

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

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

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

ESP8266: Getting Board MAC Address

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

Each ESP8266 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 ESP8266 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 <ESP8266WiFi.h>

void setup(){
  Serial.begin(115200);
  Serial.println();
  Serial.print("ESP8266 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());
}
 
void loop(){

}

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

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 with ESP8266

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

We’ll send a structure that contains a variable of type charintfloatString 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 ESP8266 #1 and “receiver” to ESP8266 #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 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 most essential ESP-NOW functions:

Function Name and Description
esp_now_init() Initializes ESP-NOW. You must initialize Wi-Fi before initializing
ESP-NOW. Returns 0, if succeed.
esp_now_set_self_role(role) the role can be: ESP_NOW_ROLE_IDLE = 0,
ESP_NOW_ROLE_CONTROLLER, ESP_NOW_ROLE_SLAVE, ESP_NOW_ROLE_COMBO,
 ESP_NOW_ROLE_MAX
esp_now_add_peer(uint8 mac_addr, uint8 role, uint8 channel, uint8 key, uint8 key_len) Call this function to pair a device.
esp_now_send(uint8 mac_address, uint8 data, int len) 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.

ESP8266 NodeMCU Sender Sketch (ESP-NOW)

Here’s the code for the ESP8266 NodeMCU 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.

First, include the ESP8266WiFi.h and espnow.h libraries

/*
 Welcome to GND_TO_VCC!! 
 
*/

#include <ESP8266WiFi.h>
#include <espnow.h>

// REPLACE WITH 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;
  String d;
  bool e;
} struct_message;

// Create a struct_message called myData
struct_message myData;

// Callback when data is sent
void OnDataSent(uint8_t *mac_addr, uint8_t sendStatus) {
  Serial.print("Last Packet Send Status: ");
  if (sendStatus == 0){
    Serial.println("Delivery success");
  }
  else{
    Serial.println("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() != 0) {
    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_set_self_role(ESP_NOW_ROLE_CONTROLLER);
  esp_now_register_send_cb(OnDataSent);
  
  // Register peer
  esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0);
}
 
void loop() {
  // Set values to send
  strcpy(myData.a, "THIS IS A CHAR");
  myData.b = random(1,20);
  myData.c = 1.2;
  myData.d = "Hello";
  myData.e = false;

  // Send message via ESP-NOW
  esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

  delay(2000);
}

ESP8266 NodeMCU Receiver Sketch (ESP-NOW)

Upload the following code to your Esp8266 board.

/*
  Welcome to GND_TO_VCC!! 
*/

#include <ESP8266WiFi.h>
#include <espnow.h>

// 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("Error initializing ESP-NOW");
    return;
  }
  
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info
  esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
  esp_now_register_recv_cb(OnDataRecv);
}

void loop() {
  
}

Testing ESP-NOW Communication

Upload the sender sketch to one board and the receiver sketch to the other board. Don’t forget to insert the receiver MAC address on the sender sketch.

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.

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 in the sender side).

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

Conclusion

In this tutorial you’ve learned how to use ESP-NOW with the ESP8266 NodeMCU board. Now, you can combine the sender and receiver sketch so that you have a two-way communication (each board acting as a server and sender at the same time). You can also use more boards to have a communication between multiple boards.

ESP8266 and ESP32 boards can communicate with each other using ESP-NOW communication protocol. You just need to upload the proper sketches to each board. To learn how to use ESP-NOW with the ESP32, you can read our ESP-NOW getting started guide for the ESP32.

Thanks for reading.

Advertisement

Published by Gnd_To_Vcc

Here to spread my knowledge . Knowledge should always be spread not stored.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: