#include <WiFi.h>
#include <PubSubClient.h>
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
int echopin = 5;
int trigpin =15;
int Time;
int Distance;
static char strDistance[10] = {0};
void setup()
{
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", "");
client.setServer("broker.emqx.io", 1883);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
Serial.begin(9600);
}
void mqttReconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(clientId)) {
Serial.println(" connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
mqttReconnect();
}
client.loop();
digitalWrite(trigpin, LOW);
digitalWrite(trigpin, HIGH);
digitalWrite(trigpin, LOW);
Time =pulseIn(echopin,HIGH);
Distance= Time * 0.0341/2;
sprintf(strDistance, "%d", Distance);
Serial.println(strDistance);
client.publish("topicName/distance", strDistance);
}