#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include "ThingsBoard.h"
#include <PubSubClient.h>
#define LDR 12
const float GAMMA = 0.7;
const float RL10 = 50;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
#define TOKEN "asjkfhjkhsdkfhsdk" // acces token
const char* mqtt_server = "thingsboard.cloud";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
int status = WL_IDLE_STATUS;
void setup ()
{
Serial.begin(9600);
delay(10);
pinMode(LDR, INPUT);
Serial.print(" Connect to : ");
Serial.println(ssid);
WiFi.begin (ssid, password);
while (WiFi.status() !=WL_CONNECTED);
{
delay(500);
Serial.print("...");
}
Serial.print("/n");
Serial.print("IP Address : ");
Serial.print(WiFi.localIP());
Serial.print("/n");
Serial.println(ssid);
client.setServer( mqtt_server, 1883);
}
void loop ()
{
if ( !client.connected() )
{
reconnect();
}
getData();
delay(5000);
}
void getData()
{
int analogValue = analogRead(LDR);
float voltage = ( analogValue / 4095.) * 3.3;
float resistance = (2000 * voltage / 3.3);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
Serial.println(lux);
String payload = "{";
payload += "\"Intensitas Cahaya\":"; payload += lux ;
payload += "}";
char attributes [1000];
payload.toCharArray (attributes, 1000);
client.publish ( "v1/device/me/telemetry", attributes);
client.publish ( "v1/device/me/attributes", attributes);
Serial.println(attributes);
}
void reconnect () {
while (!client.connected()) {
status = WiFi.status();
if (status != WL_CONNECTED) {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
Serial.print("Connecting to Thingsboard node ...");
if (client.connect("283572395732847"), TOKEN, ""){
Serial.println("[DONE]");
} else {
Serial.print( "[FAILED] [ rc = ");
Serial.println(" : retrying in 5 second]");
delay(5000);
}
}
}