#include <WiFi.h>
#include <HTTPClient.h>
#include <ESP32Servo.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String writeApiKey = "116CMM3I1IS8AR9R";
const char* tsServer = "https://api.thingspeak.com/update";
#define SERVO_PIN 12
Servo doorServo;
int doorState = 0;
unsigned long lastTsPost = 0;
const unsigned long TS_INTERVAL_MS = 20000;
String correctPassword = "1234";
String inputPassword = "";
bool countdownActive = false;
int countdownValue = 0;
unsigned long lastCountdown = 0;
void connectWifi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
bool postToThingSpeak(int state) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(tsServer) + "?api_key=" + writeApiKey +
"&field1=" + String(state);
http.begin(url);
int httpCode = http.GET();
Serial.print("[ThingSpeak] HTTP Response: ");
Serial.println(httpCode);
http.end();
return (httpCode == 200);
}
return false;
}
void setup() {
Serial.begin(115200);
doorServo.attach(SERVO_PIN);
doorServo.write(0);
connectWifi();
Serial.println("Masukkan password: ");
}
void loop() {
if (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') {
if (inputPassword.length() > 0) {
if (inputPassword == correctPassword) {
Serial.println("Password benar, pintu terbuka!");
doorState = 1;
doorServo.write(90);
countdownValue = 15;
countdownActive = true;
lastCountdown = millis();
} else {
Serial.println("Password salah, pintu tetap terkunci.");
doorState = 0;
doorServo.write(0);
}
inputPassword = "";
Serial.println("Masukkan password lagi:");
}
} else {
inputPassword += c;
}
}
if (countdownActive && (millis() - lastCountdown >= 1000)) {
Serial.println("Countdown: " + String(countdownValue));
countdownValue--;
lastCountdown = millis();
if (countdownValue < 0) {
Serial.println("Waktu habis, pintu otomatis tertutup!");
doorServo.write(0);
doorState = 0;
countdownActive = false;
}
}
if (millis() - lastTsPost >= TS_INTERVAL_MS) {
postToThingSpeak(doorState);
lastTsPost = millis();
}
}