#include <WiFi.h>
#include <MQTT.h>
#include <NusabotSimpleTimer.h>
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;
#define ledM 26
#define ledH 27
#define ledB 25
#define pot1 32
#define pot2 33
void connect(){
// Menghubungkan ke WiFi
Serial.print("Menghubungkan ke WiFi");
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.println("Berhasil Terhubung ke WiFi");
Serial.print("Menghubungkan ke Broker");
while(!client.connect("588de0ca", "unknowniot", "wpggjnEuuxkLS3JQ")){
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.println("Berhasil Terhubung ke Server");
client.subscribe("aiotblank/affan/led/#", 1);
}
void subscribeData(String &topic, String &data){
if(topic == "aiotblank/affan/led/m"){
digitalWrite(ledM, data.toInt());
}
if(topic == "aiotblank/affan/led/h"){
digitalWrite(ledH, data.toInt());
}
if(topic == "aiotblank/affan/led/b"){
digitalWrite(ledB, data.toInt());
}
}
void publish(){
int potValue1 = analogRead(pot1);
int potValue2 = analogRead(pot2);
Serial.print("Pot 1 : ");
Serial.println(potValue1);
Serial.print("Pot 2 : ");
Serial.println(potValue2);
client.publish("aiotblank/affan/pot1", String(potValue1), true, 1);
client.publish("aiotblank/affan/pot2", String(potValue2), true, 1);
}
void setup() {
pinMode(ledM, OUTPUT);
pinMode(ledH, OUTPUT);
pinMode(ledB, INPUT);
Serial.begin(9600);
WiFi.begin(ssid, pass);
client.begin("unknowniot.cloud.shiftr.io", net);
client.onMessage(subscribeData);
timer.setInterval(1000, publish); // eksekusi publish() setiap 1 detik
connect();
}
void loop() {
delay(10);
client.loop();
timer.run();
delay(10);
}