#include <WiFi.h>
#include <PubSubClient.h>
#include <ESP32Servo.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT server details
const char* mqttServer = "test.mosquitto.org"; // Using a public MQTT broker
const int mqttPort = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
// Define pins
int buzzerPin = 14; // Buzzer Pin
int redPin = 32; // RGB Red Pin
int greenPin = 33; // RGB Green Pin
int bluePin = 25; // RGB Blue Pin
int trigPin = 5; // Ultrasonic Trig Pin
int echoPin = 18; // Ultrasonic Echo Pin
int pirPin = 19; // PIR Sensor Pin
int servoPin = 4; // Servo Motor Pin
int tempPin = 34; // NTC Thermistor Pin
const float BETA = 3950; // Beta value of the thermistor
Servo servoMotor; // Create Servo object
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient); // Create MQTT client
// Function to setup GPIO pins
void setupPins() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// Set up ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set up buzzer, temperature sensor pin, and PIR sensor
pinMode(buzzerPin, OUTPUT);
pinMode(tempPin, INPUT);
pinMode(pirPin, INPUT);
// Initialize RGB LED to off
digitalWrite(redPin, HIGH); // Turn off Red
digitalWrite(greenPin, HIGH); // Turn off Green
digitalWrite(bluePin, HIGH); // Turn off Blue
// Attach the servo
servoMotor.attach(servoPin);
// Initialize the servo position (lid closed)
servoMotor.write(0); // Start with the lid closed
}
void setup() {
Serial.begin(115200); // Start Serial communication
setupPins();
setupWiFi();
mqttClient.setServer(mqttServer, mqttPort);
// Initialize RGB LED to off
digitalWrite(redPin, HIGH); // Turn off Red
digitalWrite(greenPin, HIGH); // Turn off Green
digitalWrite(bluePin, HIGH); // Turn off Blue
// Attach the servo
servoMotor.attach(servoPin);
// Initialize the servo position (lid closed)
servoMotor.write(0); // Start with the lid closed
// Setting up analogRead
analogReadResolution(10);
}
void loop() {
// Ensure MQTT is connected
if (!mqttClient.connected()) {
reconnectMQTT();
}
mqttClient.loop(); // Handle MQTT messages
// Fire detection using NTC thermistor
float temperature = readTemperature();
// Check for fire conditions
if (temperature > 50.0) {
digitalWrite(buzzerPin, HIGH); // Fire detected, sound the alarm
tone(buzzerPin, 1000); // Sound the buzzer at 1 kHz
Serial.println("Fire Detected");
} else {
digitalWrite(buzzerPin, LOW); // No fire, buzzer off
noTone(buzzerPin); // Stop the buzzer sound
Serial.println("No fire. Buzzer OFF.");
}
delay(1000); // Run the temperature check every second (adjust if needed)
// Bin level detection with ultrasonic sensor
long distance = readDistance();
publishBinLevel(distance); // Publish bin level to MQTT
// Control RGB LED based on distance
controlRGBLED(distance);
// Motion detection using PIR sensor
int pirState = digitalRead(pirPin);
if (pirState == HIGH) {
openLid(); // Open lid if motion is detected
}
delay(1000); // Wait for a second before the next loop
}
// Function to read temperature from NTC sensor
const int SERIES_RESISTOR = 10000; // 10kΩ resistor
float readTemperature() {
int analogValue = analogRead(tempPin);
float temperature = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
Serial.println("Temperature : ");
Serial.println(temperature);
Serial.println("C");
publishTemperature(temperature); // Publish temperature to MQTT
return temperature;
}
// Function to read distance from ultrasonic sensor
long readDistance() {
long duration;
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2; // Calculate distance in cm
}
// Function to set RGB LED color
void setColor(int red, int green, int blue) {
digitalWrite(redPin, red); // Set red LED value
digitalWrite(greenPin, green); // Set green LED value
digitalWrite(bluePin, blue); // Set blue LED value
}
// Control RGB LED based on distance
void controlRGBLED(long distance) {
if (distance > 40) {
setColor(HIGH, LOW, HIGH); // Green (Low level)
Serial.println("Bin level : LOW");
} else if (distance > 20 && distance <= 40) {
setColor(LOW, LOW, HIGH); // Yellow (Medium level)
Serial.println("Bin level : MEDIUM");
} else {
setColor(LOW, HIGH, HIGH); // Red (High level)
Serial.println("Bin level : HIGH");
}
}
// Function to publish bin level to MQTT
void publishBinLevel(long distance) {
// Assuming the total height of the bin is 60 cm
const float binHeight = 60.0;
// Calculate the percentage of how full the bin is
float binLevelPercentage = 100 - ((distance / binHeight) * 100);
// Ensure the percentage is within the range of 0% to 100%
binLevelPercentage = constrain(binLevelPercentage, 0, 100);
// Convert the percentage to a String for publishing
String binLevel = String(binLevelPercentage);
// Publish the bin level to MQTT
mqttClient.publish("smartgarbage/binLevel", binLevel.c_str(), true); // Retain message
// Print the bin level to the serial monitor
Serial.print("Published bin level: ");
Serial.println(binLevel);
}
// Function to publish temperature to MQTT
void publishTemperature(float temperature) {
String tempString = String(temperature);
mqttClient.publish("smartgarbage/temperature", tempString.c_str(), true); // Retain message
Serial.print("Published temperature: ");
Serial.println(tempString);
}
// Function to open the lid
void openLid() {
servoMotor.write(90); // Open lid
mqttClient.publish("smartgarbage/lidState", "open", true); // Publish lid state
Serial.println("Lid Opened");
delay(5000); // Keep the lid open for 5 seconds
closeLid(); // Close lid after 5 seconds
}
// Function to close the lid
void closeLid() {
servoMotor.write(0); // Close lid
mqttClient.publish("smartgarbage/lidState", "close", true); // Publish lid state
Serial.println("Lid Closed");
}
// Function to set up WiFi connection
void setupWiFi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
// Function to reconnect to MQTT server
void reconnectMQTT() {
// Loop until we're reconnected
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqttClient.connect("ESP32Client")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" trying again in 5 seconds");
delay(5000);
}
}
}