#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include "ThingsBoard.h"
#include <PubSubClient.h>
#define LDR A0
const float GAMMA = 0.7; //variable conversi dari tegangan ke lux
const float RL10 = 50;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
#define TOKEN "4916UVhTO5pgtey3xAvs" //Access token of device Display
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);
// WiFi.config(IP, NETWORK, NETMASK, DNS);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("...");
}
Serial.print("\n");
Serial.print("IP address : ");
Serial.print(WiFi.localIP());
Serial.print("\n");
Serial.print("Connect to : ");
Serial.println(ssid);
client.setServer( mqtt_server, 1883); //port 1883 = were using public server (unauthenticated and unencrypted)
// client.setCallback(callback);
}
void loop()
{
if ( !client.connected() )
{
reconnect();
}
getData();
delay(5000);
}
void getData()
{
int analogValue = analogRead(LDR);
float voltage = analogValue / 4095. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
Serial.println(lux);
String payload = "{";
payload += "\"Lux\":";payload += lux;
payload += "}";
char attributes[1000];
payload.toCharArray( attributes, 1000 );
client.publish( "v1/devices/me/telemetry",attributes);
Serial.println( attributes );
}
void reconnect() {
// Loop until we're reconnected
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 ...");
// Attempt to connect (clientId, username, password)
if ( client.connect("3a90f960-1ad1-11ed-b480-cbe4cea4aa70", TOKEN, "") ) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.println( " : retrying in 5 seconds]" );
delay( 500 );
}
}
}