// This example uses an ESP32 Development Board
// to connect to shiftr.io.
//
// You can check on your device after a successful
// connection here: https://www.shiftr.io/try.
//
// by Joël Gähwiler
// https://github.com/256dpi/arduino-mqtt
#include <WiFi.h>
#include <MQTT.h>
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient net;
MQTTClient client;
unsigned long lastMillis = 0;
int pot;
int led;
void connect() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.print("\nconnecting...");
while (!client.connect("eswoufh487")) {
Serial.print(".");
delay(1000);
}
Serial.println("\nconnected!");
client.subscribe("gedung1/#");
// client.unsubscribe("/hello");
}
void dataDiterima(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
if(topic == "gedung1/lantai19" && payload == "nyala"){
digitalWrite(5, 1);
} else if(topic == "gedung1/lantai19" && payload == "mati"){
digitalWrite(5, 0);
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, pass);
client.begin("broker.emqx.io", net);
client.onMessage(dataDiterima);
connect();
pinMode(5, OUTPUT);
}
void loop() {
client.loop();
delay(10); // <- fixes some issues with WiFi stability
pot = analogRead(34);
if (!client.connected()) {
connect();
}
if (millis() - lastMillis > 1000) {
}
}