#include <LiquidCrystal_I2C.h>
#define BUTTON_PIN 19 // ESP32 pin GIOP16, which connected to button
#define LED_PIN 18 // ESP32 pin GIOP18, which connected to led
#define LDR_PIN 2
int led_state = LOW; // the current state of LED
int button_state; // the current state of button
int last_button_state;
const float GAMMA = 0.7;
const float RL10 = 50;
LiquidCrystal_I2C lcd(0x27, 20, 4);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(33, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // set ESP32 pin to input pull-up mode
pinMode(LED_PIN, OUTPUT); // set ESP32 pin to output mode
button_state = digitalRead(BUTTON_PIN);
pinMode(LDR_PIN, INPUT);
lcd.init();
lcd.backlight();
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
int analogValue = analogRead(LDR_PIN);
float voltage = analogValue / 4096. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
lcd.setCursor(2, 0);
lcd.print("Cuaca: ");
if (lux > 50) {
lcd.print("Cerah");
digitalWrite(33, HIGH);
} else {
lcd.print("Hujan ");
digitalWrite(33, LOW);
}
lcd.setCursor(0, 1);
lcd.print("Lux: ");
lcd.print(lux);
lcd.print(" ");
delay(100);
last_button_state = button_state; // save the last state
button_state = digitalRead(BUTTON_PIN); // read new state
if (last_button_state == HIGH && button_state == LOW) {
Serial.println("The button is pressed");
digitalWrite(33, LOW);
delay(500);
digitalWrite(33, HIGH);
delay(500);
// toggle state of LED
led_state = !led_state;
// control LED arccoding to the toggled state
digitalWrite(LED_PIN, led_state);
}
}