
//trimite date de la pot legat la +3.3V, GND si GPIO
//bibliografie
//Ref: Random Nerd Tutorials https://randomnerdtutorials.com

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

// adresa MAC a clientului apare astfel CC:50:E3:B6:51:EC
// trebuie introdusa cu sintaxa de mai jos
uint8_t RxMACaddress[] = {0xCC, 0x50, 0xE3, 0xB6, 0x51, 0xEC};

#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#define OLED_ADDR   0x3C
Adafruit_SSD1306 display(-1);

typedef struct TxStruct
{
  int potVal;
  }TxStruct;
  TxStruct sentData;

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) 
{
  Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void setup()
  {
  Serial.begin(9600);

display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);

  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.print("P2P Tx Analog EspNow");
  display.display();
  delay(2000); 

  WiFi.mode(WIFI_STA);
   if(esp_now_init() != ESP_OK)
  {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  esp_now_register_send_cb(OnDataSent);
  esp_now_peer_info_t peerInfo;
  memcpy(peerInfo.peer_addr, RxMACaddress, 6);
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;
   if(esp_now_add_peer(&peerInfo) != ESP_OK)
  {
    Serial.println("Failed to add peer");
    return;
  }
}
void loop()
{
  sentData.potVal = analogRead(A0);

  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.print(" A0=");
  display.print(sentData.potVal);
  display.display();
   esp_err_t result = esp_now_send(RxMACaddress, (uint8_t *) &sentData, sizeof(sentData));
   if (result == ESP_OK) Serial.println("Sent with success");
  else Serial.println("Error sending the data");
   delay(500);
}
