#include <ESP32Servo.h>
#include <WiFi.h>
#include <ThingSpeak.h>
#include <NTPClient.h>
#include <time.h>
Servo solarPanel;
#define LDR_PIN 36
const float GAMMA = 0.7;
const float RL10 = 50;
float angle;
const int servoPin = 13;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2670825;
const char *myWriteAPIKey = "MKKCRSALW7KB4CO8";
const int ledPin = 13;
int statusCode;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 19800, 60000);
void setup() {
solarPanel.attach(servoPin);
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(LDR_PIN, INPUT);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
wificonnection();
delay(1500);
timeClient.begin();
}
void wificonnection() {
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
}
void channelupdation() {
if (statusCode == 200) {
Serial.println("Channel update successful.");
} else {
Serial.println("Problem Writing data. HTTP error code: " + String(statusCode));
}
}
void loop() {
int analogValue = analogRead(LDR_PIN);
float voltage = analogValue / 4095.0 * 5.0;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Update time
timeClient.update();
time_t now = timeClient.getEpochTime();
setenv("TZ", "Asia/Kolkata", 1);
tzset();
struct tm *timeinfo = localtime(&now);
int hour = timeinfo->tm_hour;
int minute = timeinfo->tm_min;
int day = timeinfo->tm_mday; // Get the day of the month
int month = timeinfo->tm_mon + 1; // Get the month (0-11, so add 1)
int year = timeinfo->tm_year + 1900; // Get the year since 1900
// Set angle based on time of day
if (hour >= 7 && hour < 11) {
angle = 45;
} else if (hour >= 11 && hour < 14) {
angle = 90;
} else if (hour >= 14 && hour < 17) {
angle = 135;
} else if (hour >= 17 && hour <= 18) {
angle = 179;
} else {
angle = 0;
}
// Adjust angle based on light intensity (lux)
if (lux < 100) {
angle = 0;
} else if (lux < 200) {
angle = 45;
} else if (lux < 400) {
angle = 90;
} else {
angle = 135;
}
solarPanel.write(angle);
Serial.println("Date: " + String(day) + "/" + String(month) + "/" + String(year));
Serial.println("Time: " + String(hour) + ":" + String(minute));
Serial.println("Angle: " + String(angle));
Serial.print("Lux: ");
Serial.println(lux);
Serial.println("Voltage: " + String(voltage));
Serial.println("<-------------------------------->");
// Update ThingSpeak fields
ThingSpeak.setField(1, voltage);
ThingSpeak.setField(2, angle);
ThingSpeak.setField(3, lux);
ThingSpeak.setField(4, hour);
ThingSpeak.setField(5, minute);
ThingSpeak.setField(6, String(day) + "/" + String(month) + "/" + String(year)); // Send date
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
channelupdation();
delay(15000);
}