#include <WiFi.h>
#include <MQTT.h>
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient net;
MQTTClient client;
void connect() {
rgb(1,0,0);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
rgb(0,1,0);
while (!client.connect("random", "kelasiot", "vwt5TSCSrqqSuqPR")) {
Serial.print(".");
delay(1000);
}
rgb(0,0,1);
client.subscribe("kelasiot/#");
}
void messageReceived(String &topic, String &data) {
if(topic == "kelasiot/lampu"){
if(data == "nyala"){
digitalWrite(33, 1);
} else {
digitalWrite(33, 0);
}
}
}
void setup() {
pinMode(25, OUTPUT);
pinMode(26, OUTPUT);
pinMode(27, OUTPUT);
pinMode(33, OUTPUT);
WiFi.begin(ssid, pass);
client.begin("kelasiot.cloud.shiftr.io", net);
client.onMessage(messageReceived);
connect();
}
void loop() {
client.loop();
delay(10); // <- fixes some issues with WiFi stability
if (!client.connected()) {
connect();
}
}
void rgb(bool merah, bool hijau, bool biru){
digitalWrite(25, merah);
digitalWrite(26, hijau);
digitalWrite(27, biru);
}