// Include the required libraries
#include <esp_now.h>
#include <WiFi.h>

uint8_t broadcastAddress[] = { 0xa0, 0xdd, 0x6c, 0x86, 0x15, 0x44 };

// Variables for reading the potentiometer value from the joystick, and mapping it to a different number.
int potPin = 35;
int potValue = 0;
int mappedPotValue = 0;

// Variables for the millis() function, used instead of delay() so that the rest of the program isn't interrupted.
unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 250;  //This is the delay between messages sent to the reciever ESP32, in milliseconds.

// Structure of the data that is passed between the two ESP32 development boards.
typedef struct struct_message {
  int a;
} struct_message;

struct_message myData;

esp_now_peer_info_t peerInfo;

// Provides status to Serial output.
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("\r\nPrevious Packet Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Command Sent Successfully" : "Command Delivery Failed");
}

void setup() {
  // Initialize the Serial Monitor
  Serial.begin(115200);
  // Set the device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);
  // Initialize ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  // Establishe and register the connection with the reciever ESP32
  esp_now_register_send_cb(OnDataSent);
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;
  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }
}

void loop() {
  // Read the currently value of single-axis joystick as a potentiometer.
  potValue = analogRead(potPin);

  // Transform the joystick readings into a different number scale.
  mappedPotValue = map(potValue, 0, 4095, -100, 100);

  // Package the motor speed command to be sent. 
  myData.a = mappedPotValue;

  // Send the motor speed command to the reciever ESP32 every 250 msec.
  currentMillis = millis();
  if (currentMillis - startMillis >= period)  
  {
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&myData, sizeof(myData));

    if (result == ESP_OK) {
      Serial.println("Command Sent");
    } else {
      Serial.println("Error. Command Not Sent");
    }
    startMillis = currentMillis;
  }
}