#include <LiquidCrystal_I2C.h>
#define LDR_PIN A0
// Características do LDR
const float GAMMA = 0.7;
const float RL10 = 50.0;
// Display LCD: endereço 0x27, 20 colunas, 4 linhas
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Referência
const float distanciaRef_cm = 10.0;
float luxRef = -1; // Será definido automaticamente
void setup() {
pinMode(LDR_PIN, INPUT);
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Inicializando...");
delay(2000);
lcd.clear();
}
void loop() {
int analogValue = analogRead(LDR_PIN);
float voltage = analogValue / 1024.0 * 5.0;
float resistance = 2000.0 * voltage / (1.0 - voltage / 5.0); // divisor com 2k
float lux = pow((RL10 * 1000.0 * pow(10, GAMMA)) / resistance, (1.0 / GAMMA));
if (luxRef < 0) {
luxRef = lux; // Salva o lux de referência
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Lux ref: ");
lcd.print(luxRef, 2);
lcd.setCursor(0, 1);
lcd.print("Dist. ref: ");
lcd.print(distanciaRef_cm, 2);
lcd.print("cm");
Serial.println("Lux de referência registrado.");
delay(3000);
return;
}
// Distância estimada com base na Lei do Inverso do Quadrado
float distanciaEstimada = distanciaRef_cm * sqrt(1 / lux);
// Exibe no LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Lux: ");
lcd.print(lux, 1);
lcd.print(" lx");
lcd.setCursor(0, 1);
lcd.print("Dist: ");
lcd.print(distanciaEstimada, 2);
lcd.print(" cm");
lcd.setCursor(0, 2);
lcd.print("Ambiente: ");
if (lux > 50) {
lcd.print("Claro ");
} else {
lcd.print("Escuro");
}
// Exibe no Serial também (opcional)
Serial.print("Lux: ");
Serial.print(lux, 2);
Serial.print(" | Distância estimada: ");
Serial.println(distanciaEstimada, 2);
delay(1000);
}