#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <Servo.h>
#include <time.h>
// Konfigurasi WiFi dan Blynk
char auth[] = "PZksWAFA9JqzdGvbeflaIWyhtKOX32Xq";
char ssid[] = "Note7";
char pass[] = "12345678";
// Servo dan LDR
Servo servo;
const int ldrPin = 34; // Gunakan pin analog yang sesuai pada ESP32
bool state = true; // Status posisi tirai
bool systemActive = true; // Status sistem aktif/nonaktif
// Waktu
unsigned long previousMillis = 0;
const long interval = 1000; // Interval pembacaan LDR
void setup()
{
Serial.begin(9600);
// Mulai Blynk
Blynk.begin(auth, ssid, pass);
// Inisialisasi Servo
servo.attach(2); // Ganti jika perlu sesuai pin PWM ESP32
pinMode(ldrPin, INPUT);
servo.write(0);
// Atur zona waktu dan sinkronisasi waktu dari NTP
configTime(7 * 3600, 0, "pool.ntp.org", "time.nist.gov"); // GMT+7 (WIB)
while (!time(nullptr)) {
delay(500);
Serial.print(".");
}
Serial.println("Time synchronized");
delay(2000);
}
void loop()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
if (systemActive && isLightControlTime()) {
readLDR();
}
}
Blynk.run();
}
void readLDR()
{
int ldrStatus = analogRead(ldrPin);
Serial.print("LDR: ");
Serial.println(ldrStatus);
if (ldrStatus <= 300 && state == true)
{
servo.write(0);
Serial.println("Servo Closed");
state = false;
}
if (ldrStatus > 300 && state == false)
{
servo.write(180);
Serial.println("Servo Opened");
state = true;
}
}
// Fungsi untuk mengecek apakah waktu saat ini antara 05:00 - 17:00
bool isLightControlTime()
{
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
return true; // Default aktif jika gagal
}
int hour = timeinfo.tm_hour;
return (hour >= 5 && hour < 17); // Aktif dari jam 5 pagi sampai sebelum 5 sore
}
// Blynk kontrol manual
BLYNK_WRITE(V1)
{
if (systemActive) {
servo.write(param.asInt());
}
}
BLYNK_WRITE(V2)
{
if (systemActive) {
servo.write(0);
}
}
BLYNK_WRITE(V3)
{
if (systemActive) {
servo.write(90);
}
}
// Tombol on/off sistem (V4)
BLYNK_WRITE(V4)
{
int btn = param.asInt();
systemActive = (btn == 1);
Serial.println(systemActive ? "System ON" : "System OFF");
}