Advertisement
Danixu

ESP-Now send int/long

May 15th, 2021
1,048
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. /*
  2.   Daniel Carrasco
  3.   This and more tutorials at https://www.electrosoftcloud.com/
  4.  
  5.   Example about how to send an int/long variable using ESP_NOW
  6. */
  7.  
  8. #include <esp_now.h>
  9. #include <WiFi.h>
  10.  
  11. // Set the SLAVE MAC Address
  12. uint8_t slaveAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
  13.  
  14. // Callback to have a track of sent messages
  15. void OnSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  16.   Serial.print("\r\nSend message status:\t");
  17.   Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Sent Successfully" : "Sent Failed");
  18. }
  19.  
  20. void setup() {
  21.   // Init Serial Monitor
  22.   Serial.begin(115200);
  23.  
  24.   // Set device as a Wi-Fi Station
  25.   WiFi.mode(WIFI_STA);
  26.  
  27.   // Init ESP-NOW
  28.   if (esp_now_init() != ESP_OK) {
  29.     Serial.println("There was an error initializing ESP-NOW");
  30.     return;
  31.   }
  32.  
  33.   // We will register the callback function to respond to the event
  34.   esp_now_register_send_cb(OnSent);
  35.  
  36.   // Register the slave
  37.   esp_now_peer_info_t slaveInfo;
  38.   memcpy(slaveInfo.peer_addr, slaveAddress, 6);
  39.   slaveInfo.channel = 0;  
  40.   slaveInfo.encrypt = false;
  41.  
  42.   // Add slave        
  43.   if (esp_now_add_peer(&slaveInfo) != ESP_OK){
  44.     Serial.println("There was an error registering the slave");
  45.     return;
  46.   }
  47. }
  48.  
  49. void loop() {
  50.   // Preparing the integer to send
  51.   int shortNumber = 123;
  52.  
  53.   // Is time to send the messsage via ESP-NOW
  54.   esp_err_t result = esp_now_send(slaveAddress, (uint8_t *) &shortNumber, sizeof(int));
  55.    
  56.   if (result == ESP_OK) {
  57.     Serial.println("The integer was sent sucessfully.");
  58.   }
  59.   else {
  60.     Serial.println("There was an error sending the integer.");
  61.   }
  62.   delay(2000);
  63.  
  64.   // Set values to send
  65.   // To simplify the code, we will just set two floats and I'll send it
  66.   long longNumber = 34567;
  67.  
  68.   // Is time to send the messsage via ESP-NOW
  69.   result = esp_now_send(slaveAddress, (uint8_t *) &longNumber, sizeof(long));
  70.    
  71.   if (result == ESP_OK) {
  72.     Serial.println("The long variable was sent sucessfully.");
  73.   }
  74.   else {
  75.     Serial.println("There was an error sending the long variable.");
  76.   }
  77.   delay(2000);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement