#include <MQTT.h>
#include <DHT.h>
#include <WiFi.h>
#include <NusabotSimpleTimer.h>
#define DHTPIN 2
#define DHTTYPE DHT22
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;
float suhu, kelembaban;
DHT dht(2, DHT22);
int LED = 23;
void connect() {
Serial.print("menghubungkan ke WiFi..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(10);
}
Serial.println("Terhubungkan ke WiFi !");
Serial.print("Menghubungkan ke Broker...");
while (!client.connect("bangoor")) {
Serial.print(".");
}
Serial.println("Terhubung ke Broker");
client.subscribe("bangoor/#");
}
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid, pass);
client.begin("broker.emqx.io", net);
client.onMessage(dataMasuk);
pinMode(23, OUTPUT);
timer.setInterval(5000, kirimData); // Untuk mengirim data setiap 5 detik sekali
connect();
}
void loop() {
client.loop();
timer.run();
}
void dataMasuk(String topic, String data) {
if (topic == "bangoor/led") {
Serial.println(data);
if (data == "Nyala") {
digitalWrite(LED, 1);
} else if (data == "Mati"){
digitalWrite(LED, 0);
}
}
}
void kirimData(){
kelembaban = dht.readHumidity();
suhu = dht.readTemperature();
Serial.print("SUHU = ");
Serial.print(suhu);
Serial.print(" *C ");
Serial.print("KELEMBABAN = ");
Serial.print(kelembaban);
Serial.println(" % ");
client.publish("bangoor/suhu", String(suhu));
client.publish("bangoor/kelembaban", String(kelembaban));
}