#include <WiFi.h>
#include <ThingsBoard.h>
#include <DHTesp.h>
#include <Servo.h>
#include <LiquidCrystal_I2C.h>
// WiFi Setup
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
WiFiClient espClient;
ThingsBoard tb(espClient);
int status = WL_IDLE_STATUS;
// ThingsBoard Setup
#define CURRENT_FIRMWARE_TITLE "TEST"
#define CURRENT_FIRMWARE_VERSION "1.0.0"
#define TOKEN "DWdUSlx91MEqUmu13tn8" //Copy token device dari ThingsBoard
#define THINGSBOARD_SERVER "thingsboard.cloud"
#define LDR_PIN 35
#define POT_PIN 32
#define SRV_PIN 15
// LDR Characteristics
const float GAMMA = 0.7;
const float RL10 = 50;
int ldrValue = 0;
int potValue = 0;
int srvValue = 0;
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void InitWiFi()
{
Serial.println("Connecting to AP ...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
void reconnect() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" Connected to AP");
}
}
void setup() {
Serial.begin(115200);
Serial.println();
myservo.attach(SRV_PIN);
myservo.write(0);
lcd.init();
lcd.backlight();
lcd.clear();
pinMode(LDR_PIN, INPUT);
pinMode(POT_PIN, INPUT);
InitWiFi();
}
void loop() {
delay(1000);
if (WiFi.status() != WL_CONNECTED) {
reconnect();
}
if (!tb.connected()) {
// Connect to the ThingsBoard
Serial.print("Connecting to: ");
Serial.print(THINGSBOARD_SERVER);
Serial.print(" with token ");
Serial.println(TOKEN);
if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
Serial.println("Failed to connect");
return;
}
}
ldrValue = analogRead(LDR_PIN);
float voltage = ldrValue / 4095. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
potValue = analogRead(POT_PIN);
int raindrop = map(potValue, 0, 4095, 0, 1023);
int rainValue = map(raindrop, 0, 1023, 100, 0);
Serial.println("Sending data...");
tb.sendTelemetryFloat("cahaya", lux);
Serial.print("Cahaya : ");
Serial.print(lux);
Serial.println(" lux");
tb.sendTelemetryInt("hujan", rainValue);
Serial.print("Hujan : ");
Serial.print(rainValue);
Serial.println(" %");
lcd.setCursor(0, 0);
lcd.print("Lux : ");
lcd.print(lux);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("Cuaca: ");
if(lux > 30000){
srvValue = 90;
lcd.print("Sgt Terik");
}
else{
myservo.write(0);
if(rainValue < 50){
srvValue = 0;
lcd.print("Tdk Hujan");
}
else if(rainValue >= 50 && rainValue <= 70){
srvValue = 45;
lcd.print("Hujan ");
}
else if(rainValue > 70){
srvValue = 90;
lcd.print("Hjn Deras");
}
}
myservo.write(srvValue);
tb.sendTelemetryInt("atap", srvValue);
Serial.print("Sudut Penutupan Atap : ");
Serial.print(srvValue);
Serial.println(" °");
tb.loop();
}