#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27, 20, 4); // Alamat I2C LCD: 0x27, dengan 20 karakter dan 4 baris.

const int ldrPins[] = {A0, A1, A2, A3}; // Pin analog untuk 4 LDR.
float calibrationFactors[4] = {1.0, 1.0, 1.0, 1.0}; // Faktor kalibrasi awal untuk 4 LDR.

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
// Define the Keymap
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the Rows of the keypad pin 8, 7, 6, 5 respectively
byte colPins[COLS] = {5, 4, 3, 2}; //connect to the Columns of the keypad pin 4, 3, 2, 1 respectively

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 

void setup() {
  lcd.init();           // Inisialisasi LCD.
  lcd.backlight();      // Aktifkan pencahayaan LCD.
  lcd.setCursor(0, 0);
  lcd.print("Mengukur Cahaya");

  // Inisialisasi serial monitor (opsional).
  Serial.begin(9600);
}

void loop() {
  float luxReadings[4];

  for (int i = 0; i < 4; i++) {
    int rawReading = analogRead(ldrPins[i]);
    luxReadings[i] = rawReading * calibrationFactors[i];
  }

  float totalLux = luxReadings[0] + luxReadings[1] + luxReadings[2] + luxReadings[3];

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("candela: ");
  lcd.print(totalLux, 2);

  // Menampilkan hasil pengukuran pada serial monitor (opsional).
  Serial.print("Total Lux: ");
  Serial.println(totalLux, 2);

  char key = customKeypad.getKey();

  if (key == 'A') {
    // Masuk ke mode kalibrasi.
    calibrateLDRs();
  }

  delay(1000); // Tunggu satu detik sebelum mengukur lagi.
}

void calibrateLDRs() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Enter Calib Factor");

  for (int i = 0; i < 4; i++) {
    lcd.setCursor(0, i + 1);
    lcd.print("LDR");
    lcd.print(i + 1);
    lcd.print(": ");
    calibrationFactors[i] = readFloatFromKeypad();
  }
}

float readFloatFromKeypad() {
  String input = "";
  char key;
  
  while (true) {
    key = customKeypad.getKey();
    if (key) {
      if (key == '#') {
        return input.toFloat();
      } else {
        input += key;
        lcd.print(key);
      }
    }
  }
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
ldr1:VCC
ldr1:GND
ldr1:DO
ldr1:AO
ldr2:VCC
ldr2:GND
ldr2:DO
ldr2:AO
ldr3:VCC
ldr3:GND
ldr3:DO
ldr3:AO
ldr4:VCC
ldr4:GND
ldr4:DO
ldr4:AO
keypad1:R1
keypad1:R2
keypad1:R3
keypad1:R4
keypad1:C1
keypad1:C2
keypad1:C3
keypad1:C4
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL