macca-nz

ESP_NOW_FIX

Jan 23rd, 2024 (edited)
1,311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.33 KB | Source Code | 0 0
  1. #include <esp_now.h>
  2. #include <WiFi.h>
  3.  
  4. #define LED_BUILTIN 4  //GPIO4 Flash
  5.  
  6. unsigned long previousMillis = 0;  // will store last time LED was updated
  7.  
  8. const long interval = 1000;                                           // interval at which to blink
  9. uint8_t broadcastAddress[] = { 0x98, 0xCD, 0xAC, 0x31, 0x59, 0xBC };  // Mac address for reciver board
  10.  
  11. bool ledState = 0;
  12.  
  13. typedef struct struct_message {  // struct to hold variables to send
  14.   char info[32];
  15.   float _temp;
  16.   bool _ledState;
  17. } struct_message;
  18.  
  19. struct_message myData;
  20. esp_now_peer_info_t peerInfo;  // variable to hold mac/channel info to connect
  21.  
  22.  
  23. // Serial print after each packet sent
  24. void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  25.   Serial.print("Last Data Status:  ");
  26.   Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Success" : "Fail");
  27. }
  28.  
  29. void setup() {
  30.   Serial.begin(115200);       // start serial @115200
  31.   WiFi.mode(WIFI_STA);        // set wifi to station mode
  32.   if (esp_now_init() != 0) {  // if esp_now fails to initaite
  33.     Serial.println("ESP FAILED TO INITATE");
  34.     ESP.restart();  // restart esp
  35.     return;         // exit
  36.   }
  37.   esp_now_register_send_cb(OnDataSent);  //
  38.  
  39.   memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  40.   peerInfo.channel = 0;
  41.   peerInfo.encrypt = false;
  42.  
  43.   if (esp_now_add_peer(&peerInfo) != ESP_OK) {
  44.     Serial.println("Failed to connect to Peer");
  45.     ESP.restart();
  46.   }
  47.   pinMode(LED_BUILTIN, OUTPUT);
  48. }
  49. void loop() {
  50.   unsigned long currentMillis = millis();
  51.  
  52.   Serial.print("currentMillis : ");
  53.   Serial.println(currentMillis);
  54.  
  55.   // if elapsed time is greater the interval
  56.   if (currentMillis - previousMillis >= interval) {
  57.     previousMillis = currentMillis;  // reset timer to 0
  58.     digitalWrite(LED_BUILTIN, ledState = !ledState);  // toggle led on/off
  59.       Serial.println(ledState ? "Led is ON" : "Led is OFF");
  60.    
  61.     // data to be sent
  62.     strcpy(myData.info, "esp32");         // display board name
  63.     myData._ledState = ledState;      // ledstate
  64.     myData._temp = random(1.00, 100.00);  // temps
  65.  
  66.     esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&myData, sizeof(myData));
  67.     if (result == ESP_OK) {
  68.       Serial.println("SENT WITH SUCCESS");
  69.       delay(1000);
  70.     } else {
  71.       Serial.println("SEND FAILED");
  72.       delay(2000);
  73.     }
  74.   }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment