#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int TRIG_PIN = 5; // Pin connected to ultrasonic sensor TRIG
const int ECHO_PIN = 18; // Pin connected to ultrasonic sensor ECHO
const int LDR_PIN = 34; // Pin connected to LDR (light sensor)
const char* ssid = "Wokwi-GUEST"; // Your Wi-Fi SSID
const char* password = ""; // Your Wi-Fi Password
const char* mqtt_server = "broker.hivemq.com"; // MQTT Broker
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastDistMsg = 0; // Variable for ultrasonic reading interval
unsigned long lastLdrMsg = 0; // Variable for LDR reading interval
float distance = 0; // Distance variable for ultrasonic sensor
long duration; // Duration for ultrasonic sensor pulse
// LCD setup using I2C
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD display address, columns, rows
// Setup function for WiFi and MQTT
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// Callback for incoming MQTT messages
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// Reconnect to the MQTT server if disconnected
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected");
client.publish("/ThinkIOT/Publish", "Welcome");
client.subscribe("/ThinkIOT/Subscribe");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
// Function to determine waste level based on ultrasonic sensor distance
String determineWasteLevel(long distance) {
const long MAX_HEIGHT = 30; // Example: Change this based on actual container height in cm
float fillPercentage = ((float)(MAX_HEIGHT - distance) / MAX_HEIGHT) * 100;
if (fillPercentage < 20) {
return "Waste Bin is full!";
} else if (fillPercentage >= 20 && fillPercentage < 40) {
return "Waste Bin is almost full.";
} else if (fillPercentage >= 40 && fillPercentage < 60) {
return "Waste Bin is halfway full.";
} else if (fillPercentage >= 60 && fillPercentage < 80) {
return "Waste Bin is nearly empty.";
} else {
return "Waste Bin is Empty.";
}
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
// Initialize LCD
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight for better visibility
lcd.clear(); // Clear the LCD
lcd.print("Connecting..."); // Display initial message
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
// Read distance data from ultrasonic sensor every 1 second
if (now - lastDistMsg > 1000) {
lastDistMsg = now;
// Send trigger pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure duration of pulse
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2; // Calculate distance in cm
// Send the raw distance data to Node-RED
String distanceStr = String(distance);
client.publish("/ThinkIOT/distance", distanceStr.c_str()); // Sending the distance data to Node-RED
// Output to Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Determine waste level and message for display
String wasteLevelMessage = determineWasteLevel(distance);
// Display the waste level message on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" cm");
lcd.setCursor(0, 1);
lcd.print(wasteLevelMessage);
}
// Read LDR data (light sensor) every 2 seconds
if (now - lastLdrMsg > 2000) {
lastLdrMsg = now;
int ldrValue = analogRead(LDR_PIN);
// Adjust the backlight of the LCD based on LDR value
if (ldrValue < 1000) {
lcd.noBacklight(); // Low light -> turn off the backlight
} else {
lcd.backlight(); // Sufficient light -> turn on the backlight
}
// Output to Serial Monitor
Serial.print("LDR Value: ");
Serial.println(ldrValue);
}
}