#include <WiFi.h>
#include <PubSubClient.h>
#define LDR 35
const float GAMMA = 0.7;
const float RL10 = 50;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
#define DEVICEID "DEV636e54ebbb3df65488"
#define TOKEN "18465f56af5e96c3"
const char* mqtt_server = "mqtt.telkomiot.id";
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.print("Connect to : ");
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. * 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 += "\"Intensitas Cahaya\":";payload += lux;
payload += "}";
char telemetry[1000];
payload.toCharArray( telemetry, 1000 );
client.publish("v2.0/pubs/APP636e118d6bdf765263/DEV636e54ebbb3df65488",telemetry);
Serial.println( telemetry );
}
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 server node ...");
if ( client.connect("DEV636e54ebbb3df65488","18465f56af5c944f", "18465f56af5e96c3")) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.println( " : retrying in 5 seconds]" );
delay( 500 );
}
}
}