#include <WiFi.h>
#include <HTTPClient.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
// Untuk sensor PIR
#define PIR_PIN 14
int PIR_state = LOW;
int PIR_val = 0;
// Untuk sensor LDR
#define LDR_PIN 34
const float GAMMA = 0.7;
const float RL10 = 50;
int LDR_val;
float lux;
// Untuk connect WiFi & API
const char ssid[] = "Wokwi-GUEST";
const char password[] = "";
String serverName = "https://api.thingspeak.com/update?api_key=NLBEAVPAK2TO2GXM&";
// Untuk perhitungan milis
int interval = 1000;
unsigned long previousMillis = 0;
long lastTime = 0;
long timeOverlay = 500;
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
WiFi.begin(ssid, password);
LCD.init();
LCD.backlight();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("-");
}
Serial.println("");
Serial.println("ESP 32 connected");
LCD.setCursor(0,0);
LCD.print("ESP 32 connected");
Serial.println(WiFi.localIP());
delay(2000);
LCD.setCursor(0,0);
LCD.print(" JULIAN A.W ");
LCD.setCursor(0,1);
LCD.print(" 2440065264 ");
delay (500);
LCD.clear();
LCD.setCursor(0,0);
LCD.print(" UASPOSI ");
LCD.setCursor(0,1);
LCD.print(" START ");
delay (500);
LCD.clear();
}
void loop() {
unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
if(WiFi.status() == WL_CONNECTED) {
// Deteksi & Perhitungan kecerahan
LDR_val = analogRead(LDR_PIN);
float voltage = LDR_val / 4095. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Deteksi Jarak PIR
PIR_val = digitalRead(PIR_PIN);
LCD.clear();
LCD.setCursor(0,0);
LCD.print("Cahaya: ");
LCD.print(String(lux));
if (PIR_val == LOW) {
if (PIR_state == LOW) {
LCD.setCursor(0,1);
LCD.print("TIDAK TERDETEKSI");
delay(1000);
LCD.setCursor(0,1);
LCD.print(" GERAKAN ");
PIR_state = HIGH;
}
} else {
if (PIR_state == HIGH) {
LCD.setCursor(0,1);
LCD.print(" TERDETEKSI ");
delay(1000);
LCD.setCursor(0,1);
LCD.print(" GERAKAN ");
PIR_state = LOW;
}
}
sendData(lux, PIR_state);
} else {
Serial.println("WiFi Disconnected");
}
previousMillis = millis();
}
}
void sendData(int lux, bool PIR_state) {
HTTPClient http;
String url = serverName + "field1=" + lux + "&field2=" + PIR_state;
http.begin(url.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.print("HTTP Response Code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error Code: ");
Serial.println(httpResponseCode);
}
http.end();
}