#include <DHT.h>
#include <ESP32Servo.h>
#define LDR_PIN 34
#define POT_PIN 35
#define TRIG_PIN 5
#define ECHO_PIN 18
#define DHTPIN 15
#define DHTTYPE DHT22
#define LED_HIJAU 27
#define LED_MERAH 14
#define BUZZER_PIN 26
#define SERVO_PIN 25
DHT dht(DHTPIN, DHTTYPE);
Servo myservo;
void setup() {
Serial.begin(115200);
pinMode(LED_HIJAU, OUTPUT);
pinMode(LED_MERAH, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
dht.begin();
myservo.attach(SERVO_PIN);
myservo.write(0);
digitalWrite(LED_HIJAU, HIGH);
digitalWrite(LED_MERAH, LOW);
Serial.println(">>> SIMULASI GREENHOUSE: PERBAIKAN BUZZER <<<");
}
void loop() {
int ldrValue = analogRead(LDR_PIN);
int airRaw = analogRead(POT_PIN);
int airPercent = map(airRaw, 0, 4095, 0, 100);
float t = dht.readTemperature();
float h = dht.readHumidity();
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 20000);
float tanahDistance = (duration == 0) ? 400 : (duration * 0.034 / 2);
bool ldrBahaya = (ldrValue < 500);
bool suhuBahaya = (t < 40);
bool lembapBahaya = (h < 50);
bool airBahaya = (airPercent < 50);
bool tanahBahaya = (tanahDistance < 200);
if (ldrBahaya) {
myservo.write(90);
} else {
myservo.write(0);
}
if (suhuBahaya || lembapBahaya || tanahBahaya) {
digitalWrite(LED_MERAH, HIGH);
digitalWrite(LED_HIJAU, LOW);
} else {
digitalWrite(LED_MERAH, LOW);
digitalWrite(LED_HIJAU, HIGH);
}
if (airBahaya) {
digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(BUZZER_PIN, LOW);
}
Serial.print("LDR:"); Serial.print(ldrValue);
Serial.print(ldrBahaya ? " [!] " : " [V] ");
Serial.print("| T/H:"); Serial.print(t); Serial.print("/"); Serial.print(h);
Serial.print((suhuBahaya || lembapBahaya) ? " [!] " : " [V] ");
Serial.print("| Tanah:"); Serial.print(tanahDistance);
Serial.print(tanahBahaya ? " [!] " : " [V] ");
Serial.print("| Air:"); Serial.print(airPercent); Serial.print("%");
Serial.println(airBahaya ? " [!] ALARM" : " [V]");
delay(1000);
}