#include <WiFi.h>
#include <ESP32Servo.h>
#include <time.h>
const int servoPin = 18; // Pin to connect the servo
const int ldrPin = 34; // Pin to connect the LDR (Analog input)
Servo myServo; // Create a Servo object
// WiFi credentials
const char* ssid = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char* password = ""; // Replace with your WiFi Password
// Time zone settings
const char* timeServer = "pool.ntp.org"; // NTP server
const long gmtOffset_sec = 3600; // Set time zone offset in seconds
const int daylightOffset_sec = 3600; // Daylight saving offset
void setup() {
Serial.begin(115200); // Initialize serial communication
myServo.attach(servoPin); // Attach the Servo to the defined pin
Serial.begin(115200);
setTime(2022, 12, 6, 10, 30, 5); // Set to December 6, 2022, 17:30:05
// LDR pin setup
pinMode(ldrPin, INPUT); // Set the LDR pin as an input
// WiFi connection
WiFi.begin(ssid, password); // Connect to WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("WiFi connected.");
// Initialize NTP
configTime(gmtOffset_sec, daylightOffset_sec, timeServer);
}
void setTime(int yr, int month, int mday, int hr, int minute, int sec) {
struct tm tm;
tm.tm_year = yr - 1900; // Year since 1900
tm.tm_mon = month - 1; // Month from 0 to 11
tm.tm_mday = mday; // Day of the month
tm.tm_hour = hr; // Hour
tm.tm_min = minute; // Minute
tm.tm_sec = sec; // Second
time_t t = mktime(&tm); // Convert to time_t
struct timeval now = { .tv_sec = t };
settimeofday(&now, NULL); // Set the current time
}
void loop() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
delay(1000);
return;
}
int hour = timeinfo.tm_hour; // Get current hour
int minute = timeinfo.tm_min; // Get current minute
int angle = 0; // Initialize the servo angle
// Read LDR value
int ldrValue = analogRead(ldrPin); // Read the value from the LDR
Serial.print("LDR value: ");
Serial.println(ldrValue); // Output the LDR value to the Serial Monitor
// Check if the LDR value is above the threshold (200)
if (ldrValue > 200) {
// Determine servo angle based on the time
if (hour == 7 && minute == 0) {
angle = 40; // 7 AM
}
else if (hour == 10 && minute == 0) {
angle = 90; // 10 AM
}
else if (hour == 15 && minute == 0) { // 3 PM
angle = 150;
}
else if (hour == 18 && minute == 0) { // 6 PM
angle = 180;
}
else if (hour == 19 && minute == 0) { // 7 PM
angle = 0; // Reset
}
if (angle != 0) { // Change servo position if an angle is set
myServo.write(angle); // Set the servo position
Serial.print("Servo angle set to: ");
Serial.println(angle); // Output the angle to the Serial Monitor
delay(1000); // Delay to avoid rapid changes
}
} else {
Serial.println("LDR value below threshold, servo not adjusted.");
}
delay(10000); // Wait before the next check (10 seconds)
}