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

9e37dd344b1d28de8cf1c4d1d53d3d76.png

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 .

cfd16b900284ceea13c38cb15ee084c4.png

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 .

08c1e9e92c4bb9e9d61997c4a0a1ce4e.png

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 ).

b785c7fcbac9a91f1df07ecd5207b0ef.png

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 .

69d4db892262fd27c4712c7eeaa8c9d1.png

One master sends data to multiple slaves

2376422965c5dbdd78d425ca24d6c95b.png

A slave receives data from multiple hosts

b8912ce209830ae8f5410ceed7c91558.png

Two-way communication

The master and slave communicate with each other

09c522f4fb0c3b129d0de49c71a0a144.png

Multiple devices communicate with each other

234c9d5fd9391a388ca8e2581a580073.png

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

Hardware

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

Software

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(){
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_STA);
  Serial.println(WiFi.macAddress());
}
 
void loop(){

}

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

793bc1aadd101bedf44c3746b5d684e1.png

initialization ESP-NOW

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

esp_now_init();

Add a paired device

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

esp_now_add_peer();

send data

Send data to paired devices

esp_now_send();

Send data callback function

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

esp_now_register_send_cb();

Receive data callback function

Register a function called when receiving data .

esp_now_register_rcv_cb();

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>

// REPLACE WITH YOUR RECEIVER MAC Address
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
  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);
}

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.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() {

}

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 :

9e1564d49bcd4e0fbf058c3ac67319cb.png

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 :

1、https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/api-reference/network/esp_now.html

2、https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/

3、https://github.com/espressif/esp-now

49565ecda2985ba9b0a3088210bcfbc5.png

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

f2f8a33ca4c5875adae006bab0e4bb0d.png

Have you ever seen 10001000 Encapsulated giant WS2812B LED Do you

ce63d59df11b773f123a67f675b23198.png

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.
https://en.qdmana.com/2022/119/202204291500460462.html

Random recommended