/*
Photoresistor (LDR) Analog Demo
Copyright (C) 2021 Uri Shaked.
https://wokwi.com/arduino/projects/305193627138654786
*/
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define LDR_PIN 2
// LDR Characteristics
const float GAMMA = 0.7;
const float RL10 = 50;
Servo servo;
int servoPosition = 0;
bool isShutterDown = false;
const int relayPin = 13;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
pinMode(LDR_PIN, INPUT);
lcd.init();
lcd.backlight();
servo.attach(0);
servo.write(0);
}
float getLux() {
int analogValue = analogRead(A0);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
return lux;
}
void loop() {
float lux = getLux();
lcd.setCursor(0, 0);
lcd.print("Room: ");
lcd.setCursor(0, 1);
lcd.print("Lux: ");
lcd.print(lux);
lcd.print(" ");
if (lux > 10000) {
digitalWrite(relayPin, LOW);
lcd.print("Shutter down");
if (!isShutterDown) {
for (servoPosition = 0; servoPosition <= 180; servoPosition += 1) {
servo.write(servoPosition);
delay(15);
}
isShutterDown = true;
}
} else {
lcd.print("Shutter up");
if (isShutterDown) {
for (servoPosition = 180; servoPosition >= 0; servoPosition -= 1) {
servo.write(servoPosition);
delay(15);
}
isShutterDown = false;
}
if (lux < 3000) {
digitalWrite(relayPin, HIGH);
} else {
digitalWrite(relayPin, LOW);
}
}
delay(100);
}