#include <WiFi.h>
#include <MQTT.h>
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient net;
MQTTClient client;
unsigned long lastMillis = 0;
void connect() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.print("\nconnecting...");
while (!client.connect("clientid")) {
Serial.print(".");
delay(1000);
}
Serial.println("\nconnected!");
client.subscribe("testkirim/led"); // untuk kontrol LED
// client.unsubscribe("/hello");
}
void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
if(topic == "testkirim/led"){
if(payload == "on"){
digitalWrite(27, HIGH);
Serial.println("LED Nyala");
} else if(payload == "off"){
digitalWrite(27, LOW);
Serial.println("LED Padam");
} else {
Serial.println("Masukkan 'ON' LED nyala dan 'OFF' LED padam");
}
}
// Note: Do not use the client in the callback to publish, subscribe or
// unsubscribe as it may cause deadlocks when other things arrive while
// sending and receiving acknowledgments. Instead, change a global variable,
// or push to a queue and handle it in the loop after calling `client.loop()`.
}
void setup() {
pinMode(33, INPUT);
pinMode(27, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, pass);
client.begin("broker.emqx.io", net);
client.onMessage(messageReceived);
connect();
}
void loop() {
client.loop();
delay(10); // <- fixes some issues with WiFi stability
if (!client.connected()) {
connect();
}
// publish a message roughly every second.
if (millis() - lastMillis > 1000) {
lastMillis = millis();
int pot = analogRead(33);
// Serial.println(pot);
client.publish("testkirim/pot", String(pot));
}
}