#include <Wire.h>
#include <MPU6050.h>
#include <LiquidCrystal_I2C.h>
MPU6050 mpu;
// Pin LDR, Relay, LED, dan Buzzer
const int LDR_PIN = 34; // Pin LDR
const int RELAY_PIN = 32; // Pin Relay
const int LED_PIN = 15; // Pin LED
const int BUZZER_PIN = 2; // Pin Buzzer
// Inisialisasi LCD I2C dengan alamat 0x27 dan ukuran 16x2
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Inisialisasi I2C dan MPU6050
Wire.begin(21, 22); // SDA: 21, SCL: 22 untuk ESP32
lcd.begin(16, 2);
lcd.backlight(); // Pastikan backlight LCD aktif
lcd.print("LCD OK!");
delay(1000);
mpu.initialize();
if (!mpu.testConnection()) {
Serial.println("MPU6050 tidak terhubung!");
while (1);
}
}
void loop() {
// Membaca nilai LDR
int ldrValue = analogRead(LDR_PIN);
int lux = map(ldrValue, 0, 4095, 0, 2000);
// Membaca suhu dari MPU6050
int rawTemp = mpu.getTemperature();
float tempC = rawTemp / 340.0 + 36.53;
// **Tampilkan suhu & kondisi gelap/terang di LCD dan Serial Monitor**
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Suhu: ");
lcd.print(tempC, 1);
lcd.print(" C");
Serial.print("Suhu: ");
Serial.print(tempC, 1);
Serial.println(" C");
lcd.setCursor(0, 1);
if (lux < 500) {
lcd.print("Terang");
Serial.println("Kondisi: Terang");
digitalWrite(LED_PIN, LOW);
digitalWrite(RELAY_PIN, LOW);
noTone(BUZZER_PIN);
} else {
lcd.print("Gelap");
Serial.println("Kondisi: Gelap");
for (int i = 0; i < 5; i++) { // Buzzer dan LED berkedip berirama
digitalWrite(LED_PIN, HIGH);
digitalWrite(RELAY_PIN, HIGH);
tone(BUZZER_PIN, 1000);
delay(300);
digitalWrite(LED_PIN, LOW);
digitalWrite(RELAY_PIN, LOW);
noTone(BUZZER_PIN);
delay(300);
}
}
delay(1000);
// Membaca akselerasi mentah
int16_t ax_raw, ay_raw, az_raw;
mpu.getAcceleration(&ax_raw, &ay_raw, &az_raw);
// **Konversi ke g (gravitasi bumi)**
float ax = ax_raw / 16384.0;
float ay = ay_raw / 16384.0;
float az = az_raw / 16384.0;
// **Tampilkan nilai akselerasi X, Y, Z di LCD dan Serial Monitor**
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Ax:");
lcd.print(ax, 2);
lcd.print(" Ay:");
lcd.print(ay, 2);
lcd.setCursor(0, 1);
lcd.print("Az:");
lcd.print(az, 2);
Serial.print("X: ");
Serial.print(ax, 2);
Serial.print(" Y: ");
Serial.print(ay, 2);
Serial.print(" Z: ");
Serial.println(az, 2);
delay(2000);
}