#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
#define TRIGGER_PIN 7
#define ECHO_PIN 6
#define RED_LED 8
#define YELLOW_LED 9
#define GREEN_LED 10
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 20, 4); // Alamat I2C LCD dapat berbeda
void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RED_LED, OUTPUT);
pinMode(YELLOW_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
dht.begin();
lcd.init();
lcd.backlight();
}
void loop() {
// Membaca suhu dan kelembaban dari sensor DHT22
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Membaca jarak dari sensor ultrasonik HC-SR04
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
float distance = pulseIn(ECHO_PIN, HIGH) / 58.2; // Mengonversi waktu ke jarak (cm)
// Menampilkan data suhu dan jarak pada LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Suhu: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Kelembaban: ");
lcd.print(humidity);
lcd.print(" %");
lcd.setCursor(0, 2);
lcd.print("Jarak: ");
lcd.print(distance);
lcd.print(" cm");
// Mengatur LED berdasarkan jarak
if (distance > 300) {
digitalWrite(GREEN_LED, HIGH);
digitalWrite(YELLOW_LED, LOW);
digitalWrite(RED_LED, LOW);
} else if (distance > 100 && distance <= 300) {
digitalWrite(GREEN_LED, LOW);
digitalWrite(YELLOW_LED, HIGH);
digitalWrite(RED_LED, LOW);
} else {
digitalWrite(GREEN_LED, LOW);
digitalWrite(YELLOW_LED, LOW);
digitalWrite(RED_LED, HIGH);
}
delay(2000); // Menunggu 2 detik sebelum membaca ulang
}