#include <WiFi.h>
#include <HTTPClient.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Buat Koneksi ke WiFi Wokwi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String token = "BBUS-SLh7Ee4Kr65S9F5FZWsLCxxvDaYaL8";
char mqttBroker[] = "stem.ubidots.com";
// Label device dan Variabel
String DEVICE_LABEL = "esp32_ijal";
String temperatureVarLabel = "suhu";
String buzzerVarLabel = "led";
WiFiClient ubidots;
PubSubClient client(ubidots);
#define ONE_WIRE_BUS 13
const int buzzerpin = 4;
const float max_temp = 30.0;
float tempC;
int buzzer;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void wifiInit();
void callback(char* topic, byte* payload, unsigned int length);
void sendData();
void reconnect();
void setup(void)
{
wifiInit();
client.setServer(mqttBroker, 1883);
client.setCallback(callback);
pinMode(buzzerpin, OUTPUT);
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
sensors.begin();
reconnect();
}
void loop(void)
{
if (!client.connected()) {
reconnect();
}
client.loop();
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
Serial.println("DONE");
tempC = sensors.getTempCByIndex(0);
if (tempC != DEVICE_DISCONNECTED_C)
{
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(tempC);
if (tempC > max_temp) {
digitalWrite(buzzerpin, HIGH);
buzzer = 1;
Serial.println("Buzzer ON!");
} else {
digitalWrite(buzzerpin, LOW);
buzzer = 0;
Serial.println("Buzzer OFF!");
}
}
else
{
Serial.println("Error: Could not read temperature data");
}
sendData();
delay(1000);
}
void wifiInit() {
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Waiting for WiFi connection...");
}
Serial.println("WiFi connected");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
Serial.print("Message from Ubidots: ");
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println(message);
}
void sendData() {
Serial.println("Sending data to Ubidots...");
if (client.connect("ESP32", token.c_str(), "")) {
String payload = "{\"" + temperatureVarLabel + "\": " + tempC + ",\"" + buzzerVarLabel + "\": "+ buzzer +"}";
client.publish((String("/v1.6/devices/") + DEVICE_LABEL).c_str(), payload.c_str());
Serial.println("Data sent!");
} else {
Serial.println("Connection to server failed");
}
}
void reconnect() {
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
if (client.connect("ESP32", token.c_str(), "")) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect, rc=");
Serial.print(client.state());
Serial.println(" try again in 2 seconds");
delay(2000);
}
}
}