#include <WiFi.h>
#include <MQTT.h>
WiFiClient net;
MQTTClient client;
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
const char brokerName[] = "broker.emqx.io";
const char clientID[] = "client-001";
const char subTopic[] = "kelasiot/#";
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 16;
void setup() {
pinMode(pinRed, OUTPUT);
pinMode(pinGreen, OUTPUT);
pinMode(pinBlue, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid, pass);
client.begin(brokerName, net);
client.onMessage(subscribe);
connect();
}
void loop() {
client.loop();
if (!client.connected()) {
connect();
}
delay(10);
}
void subscribe(String &topic, String &data) {
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Subscribe Data: ");
Serial.println(data);
Serial.println();
}
void rgb(bool red, bool green, bool blue) {
digitalWrite(pinRed, red);
digitalWrite(pinGreen, green);
digitalWrite(pinBlue, blue);
}
void connect() {
rgb(1,0,0); // Merah
while (WiFi.status() != WL_CONNECTED) {
delay(500);
rgb(1,0,0); rgb(0,1,0); // Kuning
}
delay(1000);
rgb(0,1,0); // Hijau
while (!client.connect(clientID)) {
delay(500);
}
delay(1000);
rgb(0,0,1); // Biru
client.subscribe(subTopic, 1); // Subscribe dengan QoS 1
}