#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>

// WiFi Credentials:
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";

// MQTT Topics
const char* distance_topic = "sensor/ultrasonic/distance";

WiFiClient espClient;
PubSubClient client(espClient);

const int triggpin = 18;
const int echopin = 19;
const int ledPin = 5; // Red LED pin
const float SPEED_OF_SOUND = 0.034;

int distance;
int lastDistance = -1;
long duration;

void setup() {
  Serial.begin(115200);
  pinMode(triggpin, OUTPUT);
  pinMode(echopin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW); // Ensure LED is off at start
  setupWiFi();
  client.setServer(mqtt_server, 1883);
  client.setKeepAlive(60);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  ULSensor();
  if (distance != lastDistance) {
    Serial.print("The distance is: ");
    Serial.print(distance);
    Serial.println(" cm");
    publishDistance(distance);
    lastDistance = distance;
  }
  if (distance > 100) {
    Serial.println("Bin is full! Please empty it!!");
    digitalWrite(ledPin, HIGH); // Turn on red LED
  } else {
    digitalWrite(ledPin, LOW); // Turn off red LED
  }
  delay(1000);
}

void setupWiFi() {
  delay(1000);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("\nConnected to WiFi");
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("espClientDustbinSystem")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void ULSensor() {
  digitalWrite(triggpin, LOW);
  delayMicroseconds(2);
  digitalWrite(triggpin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggpin, LOW);
  duration = pulseIn(echopin, HIGH);
  distance =(duration * SPEED_OF_SOUND / 2) + 1 ;
}

void publishDistance(float distance) {
  char distanceStr[8];
  dtostrf(distance, 1, 2, distanceStr);
  client.publish(distance_topic, distanceStr);
}
Loading
esp32-devkit-v1