#include <WiFi.h>
#include <ThingSpeak.h>
#define SECRET_SSID "Wokwi-GUEST"
#define SECRET_PASS ""
#define SECRET_CH_ID 1951119
#define SECRET_WRITE_APIKEY "NBA9HIGIJYSUV1PQ"
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
int keyIndex = 0;
WiFiClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;

// LDR Characteristics
const float GAMMA = 0.7;
const float RL10 = 50;


void setup() {
  Serial.begin(115200);
  while (!Serial){
    ;
  }
  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);
}


void loop() {
  if(WiFi.status() !=WL_CONNECTED)
  {
    Serial.print("Attempting to connect the SSID: ");
    Serial.println(SECRET_SSID);
    while(WiFi.status() != WL_CONNECTED)
    {
      WiFi.begin(ssid,pass);
      Serial.print(".");
      delay(5000);
    }
    Serial.print("\nConnected.");
  }

  int analogValue = analogRead(34);
  float voltage = analogValue / 4096. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  Serial.print("Analog Value = "); 
  Serial.println(voltage);
  Serial.print("Lux Value = ");
  Serial.println(lux);

  ThingSpeak.setField(1, voltage);
  ThingSpeak.setField(2, lux);

  int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  if(x == 200)
  {
    Serial.println("Channel update successfull");
  }
  else
  {
    Serial.println("Problem updating Channel. HTTP error code" +String(x));

  }
  delay(15000);
}