#include <WiFi.h>
#include <PubSubClient.h>
#define WIFISSID "Wokwi-GUEST"
#define PASSWORD ""
#define TOKEN "BBUS-jaHdvIu5yMf01cUqxCZiSBgHDOryaC"
#define MQTT_CLIENT_NAME "Notifikasi"
#define VARIABLE_LABEL "button"
#define DEVICE_LABEL "esp32"
#define BUZZER_VARIABLE_LABEL "buzzer"
const char *mqtt_server = "industrial.api.ubidots.com";
const int mqtt_port = 1883;
const int buttonPin = 2; // Pin tempat tombol tekan terhubung
const int buzzerPin = 13; // Pin tempat buzzer terhubung
bool isBuzzerOn = false; // Variabel untuk melacak status bunyi buzzer
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(buttonPin, INPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(115200);
connectToWiFi();
client.setServer(mqtt_server, mqtt_port);
}
void connectToWiFi() {
WiFi.begin(WIFISSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void connectToMQTT() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
Serial.println("Connected to MQTT");
// Convert String to const char* using c_str()
client.subscribe((String("/v1.6/devices/") + DEVICE_LABEL + "/" + VARIABLE_LABEL).c_str());
client.subscribe((String("/v1.6/devices/") + DEVICE_LABEL + "/" + BUZZER_VARIABLE_LABEL).c_str());
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Trying again in 5 seconds...");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
connectToMQTT();
}
client.loop();
if (digitalRead(buttonPin) == HIGH) {
// Tombol ditekan
Serial.println("Pesanan di table 1..!!");
if (!isBuzzerOn) {
// Buzzer belum aktif, aktifkan
tone(buzzerPin, 1000); // Frekuensi buzzer (1 kHz)
isBuzzerOn = true;
delay(10000);
} else {
noTone(buzzerPin); // Matikan suara buzzer
isBuzzerOn = false;
}
// Kirim status tombol ke Ubidots
String ubidotsTopicButton = "/v1.6/devices/" + String(DEVICE_LABEL);
String payloadButton = String("{\"") + VARIABLE_LABEL + "\": " + (digitalRead(buttonPin) == HIGH ? "1" : "0") + "}";
client.publish(ubidotsTopicButton.c_str(), payloadButton.c_str());
String ubidotsTopicBuzzer = "/v1.6/devices/" + String(DEVICE_LABEL);
String payloadBuzzer = String("{\"") + BUZZER_VARIABLE_LABEL + "\": " + (isBuzzerOn ? "1" : "0") + "}";
client.publish(ubidotsTopicBuzzer.c_str(), payloadBuzzer.c_str());
// Tunggu sementara agar tidak mendeteksi multiple presses
delay(500);
}
}