#include <esp_now.h>
#include <WiFi.h>

// Enter the MAC address of board #1 here.
uint8_t broadcastAddress[] = {0x8c, 0x94, 0xdf, 0x61, 0xda, 0x04};

// Data structure for receiving and sending.
typedef struct struct_message {
    char text[32];
    int counter;
} struct_message;

struct_message myData;       // Information to send
struct_message incomingData; // Received information
int x=10;

esp_now_peer_info_t peerInfo;

// The function is called when data is sent.
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nLatest delivery status: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Sent successfully" : "Send failed");
}

// The function is called when data is submitted.
void OnDataRecv(const esp_now_recv_info *info, const uint8_t *incomingDataRaw, int len) {
  memcpy(&incomingData, incomingDataRaw, sizeof(incomingData));
  Serial.print("--- I received the information from the board.1: ");
  Serial.print(incomingData.text);
  Serial.print(" |number: ");
  Serial.println(incomingData.counter);
}
 
void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  //Getting Started with ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW startup failed.");
    return;
  }

  // Register the Callback function for both incoming and outgoing calls.

esp_now_register_send_cb((esp_now_send_cb_t)OnDataSent);

  

esp_now_register_recv_cb((esp_now_recv_cb_t)OnDataRecv);  
  
  //  Register the board 1 as a Peer.
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
  
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Adding a peer failed.");
    return;
  }
}
 
void loop() {
  //Generate and send data to board 1 every 2 seconds.
  strcpy(myData.text, "Greetings from board number 2.");
   x++;  if(x>100)x=0;
   myData.counter= x;// myData.counter+10;
 
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
  if (result != ESP_OK) {
    Serial.println("An error occurred during data transmission.");
  }

  delay(2000);
}
