#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Pin dan tipe sensor
#define DHTPIN 2 // Pin sensor DHT22
#define DHTTYPE DHT22
#define RELAY_PIN 12 // Pin relay untuk mengontrol lampu
#define BUZZER_PIN 10 // Pin buzzer
#define LDR_PIN A0 // Pin untuk sensor LDR
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD 16x2 dengan alamat 0x27
// Simulasi pembacaan sensor gas MQ-2 dengan range 0-350 (bisa lebih)
int readGasValue() {
return random(0, 351); // nilai gas antara 0 sampai 350
}
void setup() {
Serial.begin(9600);
dht.begin();
lcd.init();
lcd.backlight();
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LDR_PIN, INPUT); // Set pin LDR sebagai input
digitalWrite(RELAY_PIN, LOW); // Kipas mati awal
digitalWrite(BUZZER_PIN, LOW); // Buzzer mati awal
randomSeed(analogRead(0)); // Seed random untuk simulasi gas
}
void loop() {
float suhu = dht.readTemperature();
if (isnan(suhu)) {
Serial.println("Gagal membaca sensor DHT!");
delay(3000);
return;
}
int gasValue = readGasValue();
int ldrValue = analogRead(LDR_PIN); // Membaca nilai dari sensor LDR
// Kontrol relay (kipas) berdasarkan suhu
if (suhu > 25.0) {
digitalWrite(RELAY_PIN, HIGH); // Kipas menyala
} else {
digitalWrite(RELAY_PIN, LOW); // Kipas mati
}
// Kontrol buzzer berdasarkan gas (menyala jika gas bocor)
if (gasValue >= 320) {
digitalWrite(BUZZER_PIN, HIGH); // Buzzer aktif
} else {
digitalWrite(BUZZER_PIN, LOW); // Buzzer mati
}
// Tampilan suhu di LCD (tampilan 1)
lcd.clear();
lcd.setCursor(0, 0);
if (suhu > 25.0) {
lcd.print("Suhu Over ");
} else {
lcd.print("Suhu Normal ");
}
lcd.setCursor(0, 1);
lcd.print("Suhu: ");
lcd.print(suhu, 1);
lcd.print(" C");
delay(4000);
// Tampilan gas di LCD (tampilan 2)
lcd.clear();
lcd.setCursor(0, 0);
if (gasValue <= 210) {
lcd.print("Gas Normal ");
} else if (gasValue < 320) {
lcd.print("Waspada ");
} else {
lcd.print("Gas Bocor ");
}
lcd.setCursor(0, 1);
lcd.print("Nilai: ");
lcd.print(gasValue);
lcd.print(" ");
delay(4000);
// Output debug di Serial Monitor
Serial.print("Suhu: ");
Serial.print(suhu, 1);
Serial.print(" C, Gas Nilai: ");
Serial.print(gasValue);
Serial.print(", Relay (Kipas): ");
Serial.print(digitalRead(RELAY_PIN) ? "ON" : "OFF");
Serial.print(", Buzzer: ");
Serial.println(digitalRead(BUZZER_PIN) ? "ON" : "OFF");
// Kontrol relay berdasarkan nilai LDR
if (ldrValue < 500) { // Threshold LDR, sesuaikan sesuai kebutuhan
digitalWrite(RELAY_PIN, HIGH); // Relay menyala (misal untuk lampu)
} else {
digitalWrite(RELAY_PIN, LOW); // Relay mati
}
// Tampilkan nilai LDR di Serial Monitor
Serial.print("Nilai LDR: ");
Serial.println(ldrValue);
delay(3000);
}