#include <Arduino.h>
#include "WiFi.h"
#include "ThingSpeak.h"

const int potPin = 34;       // Analog input pin for potentiometer (ADC1_CH6)
const int ledPin = 23;       // PWM output pin for LED (GPIO23)
const char* WIFINAME="Wokwi-GUEST";
const char* WIFIPASSWORD="";
const unsigned long my_channel_number=2578701;
const char* api_key="MV384XLXG9N56IGS";

WiFiClient client;

void setup() {
  Serial.begin(115200);            // Initialize serial communication at 115200 baud
  pinMode(potPin, INPUT);          // Set potentiometer pin as input
  pinMode(ledPin, OUTPUT);         // Set LED pin as output
  WiFi.begin( WIFINAME,WIFIPASSWORD);
  while (WiFi.status()!= WL_CONNECTED){
    delay(1000);
    Serial.println("WiFi not connected");
  }
  Serial.println("Wifi connected!");
  ThingSpeak.begin(client);
    
}

void loop() {
  
  int potValue = analogRead(potPin); // Read potentiometer value (0-4095)
  Serial.print("Potentiometer value: ");
  Serial.println(potValue);
  delay(1000);                        // Wait for 1 second
  
  int dutyCycle = map(potValue, 0, 4095, 0, 1024); // Map potentiometer value to PWM duty cycle
  analogWrite(ledPin , dutyCycle);  // Set PWM duty cycle based on potentiometer value
  Serial.print("dutyCycle: ");
  Serial.println(dutyCycle);
  int brightness=map( dutyCycle,0,1024,0,100);
  Serial.print("brightness: ");
  Serial.println(String(brightness)+"%");
  int current=(dutyCycle - 512.0) * (5.0 / 1024.0) / 0.066;
  Serial.print("current: ");
  Serial.println(String(current)+"mA");
  int voltage= (dutyCycle - 512.0) * (5.0 / 1024.0);
  Serial.print("voltage: ");
  Serial.println(String(voltage)+"v");
  int power=current*voltage;
  Serial.print("Power: ");
  Serial.println(String(power)+"mW");


  ThingSpeak.setField(1, voltage);


  ThingSpeak.setField(2,current);
  

  ThingSpeak.setField(3, power);
  

  


  // Write to ThingSpeak
  int status = ThingSpeak.writeFields( my_channel_number, api_key);

  // Check the status of the write operation
  if (status == 200) {
    Serial.println("Data pushed successfully");
  } else {
    Serial.println("Push error: " + String(status));
  }

  Serial.println("--------");

  // Wait for a bit before sending the next value
  delay(10000); // Delay in milliseconds


}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
pot1:GND
pot1:SIG
pot1:VCC
r1:1
r1:2
led1:A
led1:C