current position:Home>Brother Lao Yu takes you to play with esp32:14 and personally make a two-way wireless remote control (I)

Brother Lao Yu takes you to play with esp32:14 and personally make a two-way wireless remote control (I)

2022-04-29 16:57:10Chip home


Today, let's play ESP-NOW.

I believe every kid's shoe is right wireless communication Very interested in , From wireless remote control racing in childhood , To the radio as a student , To all kinds of wireless controlled household appliances after growing up , Mobile phones and other electronic products , Wireless communication allows us to be like in fairy tales Some stunts , It can be done Air separation control , Everyone wants that The remote control is in your own hands .


The essence of wireless remote control is the transmitter Emit electromagnetic waves of a certain frequency get out , The receiver receives and decodes the signal . The air conditioner we often contact , TV , Many remote controls such as fans are infrared , The frequency is mostly 38Khz; The curtain , Garage doors are mostly 315MHz perhaps 433MHz; Abroad have 868MHz、915MHz etc. ; lower than 1Ghz The generic name of Sub 1Ghz, Different countries have different free frequency bands ; The lamp , Mobile phones are mostly used 2.4Ghz Of ,2.4G This frequency band is used more , This band is free to use all over the world , We know WiFi、 bluetooth 、Zigbee The are 2.4Ghz Of ; Of course, NBIOT,2G,4G,5G, long wave , Zhongbo , Equipment with many frequencies such as short wave . Theoretically speaking , At the same power , Low frequency can get better transmission distance , High frequency has better anti-interference performance , Different fields choose the most appropriate communication frequency according to their own characteristics .

Weather station project preview

Let's take a look at our final finished product video introduction :

ESP-NOW summary

ESP-NOW By Espressif A protocol developed , It enables multiple devices to Don't use Wi-Fi Under the circumstances Mutual communication . The protocol is similar to that used in wireless mouse 2.4GHz A wireless connection . therefore , Between devices pairing It needs to be done before they communicate . After pairing , The connection is secure and point-to-point , No need to shake hands , That is, he doesn't look like TCP/IP Wait is a long connection , let me put it another way , It's connectionless , If one of the boards suddenly loses power , After reboot , Will automatically match its connected device to continue communication .


Different from traditional OSI Model ,ESP-NOW Removed some of these layers , Keep only the most basic transport layer , Reduce packet loss delay caused by network congestion , Fast response . Simply speaking ,ESP-NOW Is a fast communication protocol , Can be used in ESP32 Exchange short messages between boards ( At most one time 250 byte ).


ESP-NOW The advantages of

  • Respond quickly : After power on , The device can directly transmit data and control other paired devices without any wireless connection , Response speed in milliseconds ;

  • Long distance communication :ESP-NOW Support long distance communication , The outdoor open distance of onboard antenna can achieve 200 rice +;

  • Multi hop control :ESP-NOW Multi hop control of equipment can be realized , Via unicast 、 Control hundreds of equipment by broadcasting and group control ;

  • New distribution network mode : Provides a division of Wi-Fi And new ways beyond Bluetooth , Configure the network for the first device via Bluetooth , Other devices do not need to be configured SSID/ Password and other information , The first device connected to the network can send this information directly to other devices ;

  • upgrade : Can be used for Firmware upgrade Or the scenario of massive data upgrade ;

  • debugging : In some inconvenient occasions such as high temperature and high pressure , Can receive data from multiple devices , Quickly diagnose equipment faults .

  • Low cost : But with WiFi, Bluetooth, etc ;

  • Security :ESP-NOW use CCMP Method to protect the security of supplier specific action frames , For details, please refer to IEEE Std. 802.11-2012.

ESP-NOW signal communication

One-way communication

A slave sends data to a host

This situation applies to one device sending data to another device in one direction , For example, a slave collects sensor data or sends the switching value to the host .


One master sends data to multiple slaves


A slave receives data from multiple hosts


Two-way communication

The master and slave communicate with each other


Multiple devices communicate with each other


ESP-NOW Perfect for building a Small networks , You can make multiple ESP32 Data exchange between .


The basic demonstration does not need to add other peripherals , Just connect the board to the serial port assistant and observe .


Get the of the board MAC Address

ESP-NOW It's through MAC Address as the unique identification of different devices Of , Like different devices ID It's the same size , Of course, we can automatically pair by scanning pairing , Here, in order to show the principle of the program , Let's start with the most basic way , First, get the information of the host device through the following code MAC Address .

#include "WiFi.h"
void setup(){
void loop(){


Get the name of the host MAC After the address , Let's write it down .


initialization ESP-NOW

initialization ESP-NOW, Must be initialized before this function call WiFi.


Add a paired device

Call this function to pair the device , take MAC Address , passageway , Encrypt information, etc .


send data

Send data to paired devices


Send data callback function

Register a function called when sending data , This function will return whether the message was sent successfully .


Receive data callback function

Register a function called when receiving data .


There are other functions , We'll talk about it when we need it .

Complete sender

We will print the previously MAC Save the address , Replace the broadcastAddress Array . In the code , First, we define a structure , Contains several different types of data variables , This is the data we want to send , stay setup() Set first in WiFi Working in STA Pattern , And then call esp_now_init() initialization , Add the information of the paired device , Simply configure the send callback function , Whether the print was sent successfully , Main function , Every time 2 Send data once per second .esp_now_send Return whether to send out , The callback function shows whether it is successfully sent to the receiver .

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

uint8_t broadcastAddress[] = {0x8C, 0xCE, 0x4E, 0xA6, 0x73, 0x74};

// 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
  // Set device as a Wi-Fi Station

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

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  // Register peer
  memcpy(peerInfo.peer_addr, broadcastAddress, 6); = 0;  
  peerInfo.encrypt = false;
  // Add peer        
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
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");

Complete receiving procedure

Receiving is similar to sending , It is also necessary to define a data structure like the sender , Used to save the received data , Create a receive callback function , When data is received , Call this function , Save the data to a structure variable , Then print it out .

#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.print("Char: ");
  Serial.print("Int: ");
  Serial.print("Float: ");
  Serial.print("Bool: ");
void setup() {
  // Initialize Serial Monitor
  // Set device as a Wi-Fi Station

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


Burn the above sending and receiving programs to two boards , The one-way transmission of data is realized , Let's take a look at the serial port print data of the receiver :


This is the simplest case , Everyone to ESP-NOW First there is one. Simple understanding , About ESP-NOW Management equipment , Delete device , Scan slave device , Automatic pairing, etc , In the next issue , Assign an assignment , You can add a button at the sending end , The receiver adds a LED etc. , You can realize the of a remote control Demo 了 , Go and try it .

Next section , We will actually do a small project , Add the following functions :

  • Multiple host , Multiple Slave ;

  • Press and hold the key of slave machine to trigger to enter Broadcast mode , Release WIFI The signal , When the host is powered on , It will scan WIFI Signal and Automatic pairing ;

  • After pairing , The master and slave will MAC The address is automatically Write storage space , The next time you start, you don't have to re pair ;

  • Two slaves can control two on the host by pressing the key LED The lamp , The master can also control two slave computers at the same time LED The lamp ;

  • The two slaves are Collect temperature, humidity and air pressure data , Transfer to host ;

  • The host will display the data on the local display screen , While connecting WiFi after , Can pass Web View sensor data in real time at the end ;

  • The indicator light shows the connection status .

Thank you for your , About ESP32 Learning from , I hope you all. Enjoy! Those who want to learn together can join the fan group through the chip House official account .

Reference material :





Brother Lao Yu will show you around ESP32,12 This basic tutorial has been updated , Next is the advanced tutorial


Have you ever seen 10001000 Encapsulated giant WS2812B LED Do you


A great peripheral driver library ! be based on STM32F4

Welcome to share 、 Collection 、 give the thumbs-up 、 Looking at

copyright notice
author[Chip home],Please bring the original link to reprint, thank you.

Random recommended