#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
char PIN_TRIG = 33;
char PIN_ECHO = 35;
char led_red = 23;
char led_green = 18;
// Variables for the duration of the ping and the distance result
long duration;
float distance;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_2593514k";
int PORTNUM = 1883;
void setup_wifi()
{
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED )
{
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Given IP by the router to ESP32 is ");
Serial.println(WiFi.localIP());
}
void connectMQTT()
{
while(!client.connected() )
{
Serial.println("Connecting to MQTT ...");
if (client.connect(espClientName) ) //, mqttUser, mqttPassword) )
{
Serial.println("Connected");
MQTTSubscribe();
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state() );
delay(1500);
}
}
}
void MQTTSubscribe()
{
client.subscribe("DEIOT/6642092K");
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
//client.setCallback(callback);
}
void setup()
{
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(led_green, OUTPUT);
pinMode(led_red, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
duration = pulseIn(PIN_ECHO, HIGH);
distance = (duration*.0343)/2;
// Output the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance >= 300)
{
// On green LED
digitalWrite(led_green, HIGH);
// Off red LED
digitalWrite(led_red, LOW);
client.publish("IOT/CARPARK3", "Available");
}
else
{
// Off green LED
digitalWrite(led_green, LOW);
// On red LED
digitalWrite(led_red, HIGH);
client.publish("IOT/CARPARK3", "Occupied");
}
// Delay before next reading
delay(1000);
}