#include <WiFi.h>
#include <PubSubClient.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT broker settings
const char* mqtt_server = "test.mosquitto.org"; // Ganti dengan alamat IP broker MQTT Anda
const int mqtt_port = 1883;
// MQTT topic for distance measurement
const char* topic_distance = "home/distance";
// Pins for HCSR04 sensor
const int trig_pin = 2;
const int echo_pin = 4;
// WiFi client and MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
// Function to measure distance using HCSR04 sensor
float measureDistance() {
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
long duration = pulseIn(echo_pin, HIGH);
float distance = (duration * 0.0343) / 2;
return distance;
}
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Connect to MQTT broker
client.setServer(mqtt_server, mqtt_port);
// Configure pins
pinMode(trig_pin, OUTPUT);
pinMode(echo_pin, INPUT);
}
void loop() {
// Reconnect to MQTT broker if connection is lost
if (!client.connected()) {
Serial.println("Reconnecting to MQTT broker...");
while (!client.connected()) {
if (client.connect("ESP8266Client")) {
Serial.println("Connected to MQTT broker");
} else {
delay(500);
}
}
}
// Measure distance
float distance = measureDistance();
// Publish distance to MQTT topic
char payload[10];
sprintf(payload, "%.2f", distance);
client.publish(topic_distance, payload);
// Wait before measuring again
delay(1000);
}