#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>

// declarations
int normalizePot(int pin, int minValue);
int mapPot(int normalizedValue);

// constants
const int POTPIN1 = 2;
const int MAXPWMVALUE = 1400;
const int MINPWMVALUE = 2000;
const uint8_t broadcastAddress[] = {0x8C, 0xBF, 0xEA, 0xCC, 0x8E, 0x5C};
//Define the struct that will be sent
typedef struct struct_message {
  int PWMCH1;
  int PWMCH2;
  int PWMCH3;
  int PWMCH4;
} struct_message;
struct_message myData; //declare the struct as myData

esp_now_peer_info_t peerInfo; //create a class object of the ESPNow class

void setup()
{
  // 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;
  }

  // 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;
  }

  Serial.begin(9600);
  pinMode(POTPIN1, INPUT);
}

void loop()
{
  Serial.println(mapPot(normalizePot(POTPIN1, 80))); //call normalizePot and put the output into mapPot then print it

  // Set values to send
  myData.PWMCH1 = mapPot(normalizePot(POTPIN1, 80));
  myData.PWMCH2 = 1000; //test values
  myData.PWMCH3 = 1000;
  myData.PWMCH4 = 1000;
  
  // 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");
  }
}

int mapPot(int normalizedValue){
  return map(normalizedValue, 80, 4095, MINPWMVALUE, MAXPWMVALUE); //map the normalized value to the PWM range
}

int normalizePot(int pin, int minValue) //normalize the pot value to a range of 80 to 4095 instead of 0 to 4095 because the potmeter is at lower values not accurate
{
  int pot = analogRead(pin);

  if (pot <= minValue)
  {
    return 80;
  }
  else
  {
    return pot;
  }
}