#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ThingsBoard.h>
#include "DHTesp.h"
const int DHT_PIN = 15;
const int LDR_PIN = 36;
const int PIR_PIN = 26;
const float GAMMA = 0.7;
const float RL10 = 50;
int val = 0;
int pirState = LOW;
int motionDetect = 0;
// Deklarasi Variable dan Konstanta
String wifiSSID = "Wokwi-GUEST";
String wifiPassword = "";
DHTesp dhtSensor;
// Thingsboard Credential
String tbHost = "thingsboard.cloud";
String tbToken = "n1vNuHYCMsvcWWimoS2t";
WiFiClient client;
ThingsBoard tb(client);
// Deklarasi Fungsi
void connectWifi();
String randTemp();
String randHum();
void tbReconnect();
void setup()
{
Serial.begin(9600);
connectWifi();
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}
void loop()
{
if (!tb.connected())
{
tbReconnect();
}
float temp = randTemp().toDouble();
float hum = randHum().toDouble();
float lx = randLux().toDouble();
float motion = randMotion().toDouble();
Serial.println("Sending data to Thingsboard");
tb.sendTelemetryFloat("temperature", temp);
tb.sendTelemetryFloat("humidity", hum);
tb.sendTelemetryFloat("light", lx);
if (motion == 1.0){
tb.sendTelemetryString("motion", "motion detected");
}else{
tb.sendTelemetryString("motion", "motion not detected");
}
tb.loop();
delay(1000);
}
String randTemp()
{
TempAndHumidity data = dhtSensor.getTempAndHumidity();
return String(data.temperature);
}
String randHum()
{
TempAndHumidity data = dhtSensor.getTempAndHumidity();
return String(data.humidity);
}
String randLux()
{
float LDR_val = analogRead(LDR_PIN);
float voltage = LDR_val / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
return String(lux);
}
String randMotion()
{
int analogValue = analogRead(A0);
val = digitalRead(PIR_PIN);
if(val == HIGH){
if (pirState == LOW) {
motionDetect = 1;
pirState = HIGH;
}
}else{
if (pirState == HIGH) {
motionDetect = 0;
pirState = LOW;
}
}
return String(motionDetect);
}
void tbReconnect()
{
while (!tb.connected())
{
if (WiFi.status() != WL_CONNECTED)
{
connectWifi();
}
Serial.println("connecting to thingsboard ... ");
if (tb.connect(tbHost.c_str(), tbToken.c_str()))
{
Serial.println("Thingsboard Connected!");
}
else
{
Serial.println("Thingsboard connection failed");
Serial.println("Retrying in 5 seconds...");
delay(5000);
}
}
}
void connectWifi()
{
Serial.println("Connecting To Wifi");
WiFi.begin(wifiSSID.c_str(), wifiPassword.c_str());
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println("Wifi Connected");
Serial.println(WiFi.SSID());
Serial.println(WiFi.RSSI());
Serial.println(WiFi.macAddress());
Serial.println(WiFi.localIP());
Serial.println(WiFi.gatewayIP());
Serial.println(WiFi.dnsIP());
}