#include <ESP32Servo.h>
#include <LiquidCrystal_I2C.h>
#include "DHTesp.h"
const int ldrPin = 32;
const int ledPin = 18;
const int ledPin2 = 19;
int servoPin = 26; // select the input pin for LDR
Servo servoMotor;
LiquidCrystal_I2C lcd(0x27,20,4);
DHTesp dht;
#define dhtPin 5
int pos = 90;
float temperature = 0;
float humidity = 0;
const float GAMMA = 0.7;
const float RL10 = 50;
String status = "";
void layar (float temp, float hum, float lux, String status){
lcd.setCursor(0,0); lcd.print("Lux : "); lcd.setCursor(6,0); lcd.print(lux);
lcd.setCursor(0,1); lcd.print("Temp: "); lcd.setCursor(6,1); lcd.print(temp);
lcd.setCursor(0,2); lcd.print("Hum : "); lcd.setCursor(6,2); lcd.print(hum);
lcd.setCursor(0,3); lcd.print(status);
}
void setup() {
Serial.println(F("DHTxx test!"));
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ldrPin, INPUT);
Serial.begin(115200);
servoMotor.attach(servoPin);
dht.setup(dhtPin, DHTesp::DHT22);
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.print("--> WELCOME <--");
delay(3000);
lcd.clear();
}
void loop() {
// float vout = analogRead(ldrPin);
// float ldrOut = vout;
int analogValue = analogRead(ldrPin);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// lux >50 light else dark
TempAndHumidity data = dht.getTempAndHumidity();
float temp = data.temperature;
float hum = data.humidity;
// String status = String("Awalan");
// layar(temp, hum, lux, status);
if (lux >= 50) {
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, LOW);
Serial.print("Opening the curtain");
String status = String("Opening the curtain");
layar(temp, hum, lux, status);
Serial.println(lux);
if (pos < 180){
for (pos = 0; pos <= 180; pos += 1) {
servoMotor.write(pos);
delay(50);
}
}
else{
pos=180;
servoMotor.write(pos);
delay(1000);
}
}
else if (lux < 50){
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, HIGH);
Serial.print("Closing the curtain");
String status = String("Closing the curtain");
layar(temp, hum, lux, status);
Serial.println(lux);
if (pos > 0){
for (pos = 180; pos >= 0; pos -= 1) {
servoMotor.write(pos);
delay(50);
}
}
else{
pos=0;
servoMotor.write(pos);
delay(1000);
}
}
else{
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
Serial.print("Wrong call");
String status = String("Wrong call");
layar(temp, hum, lux, status);
pos=90;
servoMotor.write(pos);
delay(random(1000));
}
// layar(temp, hum, ldrOut, status);
}