#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// ====== Konfigurasi Hardware ======
#define LED_PIN 2 // LED di pin D2
#define LDR_PIN A0 // LDR ke A0 (pakai keluaran analog AO)
#define SERIES_RESISTOR 2000 // Nilai resistor seri LDR (Ohm). Ganti ke 10000 jika pakai 10k
// ====== Konstanta Sensor LDR ======
// Model sederhana LDR: lux = (RL10*1000 * 10^GAMMA / R_LDR)^(1/GAMMA)
#define GAMMA 0.7 // Gamma LDR (contoh GL5528 ~ 0.7)
#define RL10 50 // Resistansi LDR pada 10 lux (kΩ)
// ====== LCD I2C ======
LiquidCrystal_I2C lcd(0x27, 20, 4); // Ganti 0x27->0x3F bila perlu, dan 20,4 ke 16,2 jika LCD 16x2
// Ambang lux untuk terang/gelap
float LUX_THRESHOLD = 50.0;
// Tegangan referensi ADC (Uno 5V)
const float VREF = 5.0;
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
lcd.init();
lcd.backlight();
Serial.begin(9600);
Serial.println(F("Mulai: LDR + LCD I2C + LED"));
lcd.setCursor(2, 0);
lcd.print("Sensor Cahaya");
lcd.setCursor(2, 1);
lcd.print("LCD I2C Ready");
delay(1200);
lcd.clear();
}
void loop() {
// ==== Baca analog ====
int analogValue = analogRead(LDR_PIN);
float voltage = analogValue * (VREF / 1023.0);
// Hitung resistansi LDR dari pembagi tegangan:
// Vout = VREF * (R_LDR / (R_LDR + RS))
// => R_LDR = RS * Vout / (VREF - Vout)
float rLdr = SERIES_RESISTOR * voltage / (VREF - voltage);
// Cegah pembagian nol jika sangat gelap/terang
if (rLdr < 1.0) rLdr = 1.0;
// Hitung lux (model perkiraan)
float lux = pow((RL10 * 1000.0 * pow(10.0, GAMMA)) / rLdr, (1.0 / GAMMA));
// ==== Kendali LED ====
bool isBright = (lux > LUX_THRESHOLD);
digitalWrite(LED_PIN, isBright ? LOW : HIGH); // LED nyala saat gelap
// ==== Tampilkan ke Serial ====
Serial.print(F("ADC: ")); Serial.print(analogValue);
Serial.print(F(" V: ")); Serial.print(voltage, 3);
Serial.print(F(" R_LDR(ohm): ")); Serial.print(rLdr, 0);
Serial.print(F(" Lux: ")); Serial.println(lux, 1);
// ==== Tampilkan ke LCD ====
// Baris 1: Lux
lcd.setCursor(0, 0);
lcd.print("Lux: ");
lcd.print(lux, 1);
lcd.print(" "); // padding agar bersih
// Baris 2: Status
lcd.setCursor(0, 1);
lcd.print("Cahaya: ");
if (isBright) {
lcd.print("Terang ");
} else {
lcd.print("Gelap ");
}
// Baris 3: ADC & Volt (opsional informasi)
lcd.setCursor(0, 2);
lcd.print("ADC:");
lcd.print(analogValue);
lcd.print(" V:");
lcd.print(voltage, 2);
lcd.print(" ");
// Baris 4: LED state
lcd.setCursor(0, 3);
lcd.print("LED: ");
lcd.print(isBright ? "OFF (terang)" : "ON (gelap) ");
lcd.print(" ");
delay(300);
}