#include <WiFi.h>
#include <MQTT.h>
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient net;
MQTTClient client;
int ldr;
void setup() {
pinMode(32, OUTPUT);
pinMode(33, INPUT);
WiFi.begin(ssid, pass);
client.begin("broker.emqx.io", net);
Serial.begin(9600);
client.onMessage(terima);
Serial.print("menghubungkan ke wifi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("Berhasil terhubung ke Wifi");
Serial.print("\nMenghubungkan ke server");
while (!client.connect("123-gas")) {
Serial.print(".");
delay(1000);
}
Serial.println("berhasil terhubung ke server");
client.subscribe("kelasiotmalam/#");
}
void loop() {
client.loop();
ldr = analogRead(33);
delay(100);
client.publish("kelasiotmalam/ldr", String(ldr));
}
void terima(String &topic, String &payload){
if(topic == "kelasiotmalam/lampu"){
if(payload == "nyala"){
digitalWrite(32, 0);
} else {
digitalWrite(32, 1);
}
}
}