#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <ESP32Servo.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <math.h>
// ============================================================
// E-WASTE MONITOR - ESP32 + PYTHONANYWHERE API
// Device ID: EWB001
// ============================================================
// ---------------- WIFI AND SERVER ----------------
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const char* API_HOST = "https://ewaste2027.pythonanywhere.com";
const char* DEVICE_ID = "EWB001";
// setInsecure() is for initial testing only.
// Use certificate validation for production.
// ---------------- PIN DEFINITIONS ----------------
const int motorRelayPin = 18;
const int greenLedPin = 27;
const int redLedPin = 32;
const int buzzerPin = 26;
const int ultrasonicTrigPin = 25;
const int ultrasonicEchoPin = 33;
const int dhtPin = 4;
const int dhtType = DHT22;
const int servoPin = 13;
const int servoLidShutterPin = 19;
const int pirSensorPin = 23;
const int lcdSdaPin = 21;
const int lcdSclPin = 22;
// ---------------- LCD ----------------
const int lcdAddress = 0x27;
const int lcdColumns = 16;
const int lcdRows = 2;
LiquidCrystal_I2C lcd(
lcdAddress,
lcdColumns,
lcdRows
);
// ---------------- SENSOR OBJECTS ----------------
DHT dht(dhtPin, dhtType);
Servo ultrasonicServo;
Servo lidShutterServo;
// ---------------- SERVO ANGLES ----------------
const int servoAngleOne = 0;
const int servoAngleTwo = 30;
const int servoAngleThree = 90;
const int lidClosedAngle = 0;
const int lidOpenAngle = 90;
// ---------------- DISTANCE CALIBRATION ----------------
const float distanceOffsetAtZero = 0.0;
const float distanceOffsetAtThirty = 0.0;
const float distanceOffsetAtNinety = 0.0;
// ---------------- TIMING ----------------
const unsigned long stabilizationTime = 5000;
const unsigned long servoMoveDelay = 800;
const unsigned long ultrasonicDelay = 100;
const unsigned long measurementInterval = 10000;
const unsigned long lidOpenDuration = 5000;
const unsigned long apiPollInterval = 3000;
const unsigned long wifiRetryInterval = 10000;
// ---------------- BIN CONFIGURATION ----------------
const float binHeightCm = 30.0;
const float lowLevelPercentage = 40.0;
const float mediumLevelPercentage = 75.0;
// ---------------- ULTRASONIC ----------------
const int ultrasonicSamples = 5;
const unsigned long ultrasonicTimeout = 30000;
// ---------------- OUTPUT POLARITY ----------------
// true = LOW activates relay
// false = HIGH activates relay
const bool relayActiveLow = true;
// Wokwi PIR output is normally HIGH on motion.
const bool pirActiveHigh = true;
// ---------------- BIN LEVEL ----------------
enum BinLevel {
LEVEL_LOW,
LEVEL_MEDIUM,
LEVEL_FULL,
LEVEL_UNKNOWN
};
struct MeasurementData {
float rawDistanceAtZero;
float rawDistanceAtThirty;
float rawDistanceAtNinety;
float distanceAtZero;
float distanceAtThirty;
float distanceAtNinety;
float averageDistance;
float fillPercentage;
float temperature;
float humidity;
BinLevel binLevel;
};
MeasurementData measurementData = {
-1, -1, -1,
-1, -1, -1,
-1, -1,
-1, -1,
LEVEL_UNKNOWN
};
// ---------------- GLOBAL STATE ----------------
unsigned long lastMeasurementTime = 0;
unsigned long lastApiPollTime = 0;
unsigned long lastWiFiRetryTime = 0;
bool lidIsOpen = false;
bool pirMotionHandled = false;
bool remoteOpenPending = false;
unsigned long lidOpenedAt = 0;
// ============================================================
// RELAY CONTROL
// ============================================================
void setRelay(bool state) {
if (relayActiveLow) {
digitalWrite(motorRelayPin, state ? LOW : HIGH);
} else {
digitalWrite(motorRelayPin, state ? HIGH : LOW);
}
}
// ============================================================
// PIR SENSOR
// ============================================================
bool isPirMotionDetected() {
int state = digitalRead(pirSensorPin);
if (pirActiveHigh) {
return state == HIGH;
}
return state == LOW;
}
// ============================================================
// LCD MESSAGE
// ============================================================
void displayLidMessage(
const char* firstLine,
const char* secondLine
) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(firstLine);
lcd.setCursor(0, 1);
lcd.print(secondLine);
}
// ============================================================
// LID CONTROL - NON-BLOCKING
// Both PIR and server commands use this function.
// ============================================================
void requestLidOpen(const char* source) {
if (lidIsOpen) {
Serial.println("LID: Already open; ignoring trigger");
return;
}
lidIsOpen = true;
lidOpenedAt = millis();
Serial.print("LID OPEN SOURCE: ");
Serial.println(source);
lidShutterServo.write(lidOpenAngle);
displayLidMessage("Opening Lid...", source);
}
// ============================================================
// LID CONTROLLER
// ============================================================
void handleLidShutter() {
bool motionDetected = isPirMotionDetected();
// One trigger per continuous motion event.
if (motionDetected && !pirMotionHandled) {
pirMotionHandled = true;
requestLidOpen("PIR Motion");
}
if (!motionDetected) {
pirMotionHandled = false;
}
// Remote command received from the server.
if (remoteOpenPending) {
remoteOpenPending = false;
requestLidOpen("IoT Form");
}
// Close automatically after the configured duration.
if (lidIsOpen &&
millis() - lidOpenedAt >= lidOpenDuration) {
lidShutterServo.write(lidClosedAngle);
lidIsOpen = false;
Serial.println("LID: Closed");
displayLidMessage("Lid Closed", "System Ready");
}
}
// ============================================================
// WIFI CONNECTION
// ============================================================
void connectWiFi() {
if (WiFi.status() == WL_CONNECTED) {
return;
}
Serial.print("Connecting to Wi-Fi: ");
Serial.println(WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
unsigned long startTime = millis();
while (WiFi.status() != WL_CONNECTED &&
millis() - startTime < 10000) {
handleLidShutter();
delay(50);
}
if (WiFi.status() == WL_CONNECTED) {
Serial.print("Wi-Fi connected. IP: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("Wi-Fi connection pending; retry later.");
}
}
// ============================================================
// BIN LEVEL HELPERS
// ============================================================
const char* getLevelName(BinLevel level) {
switch (level) {
case LEVEL_LOW:
return "LOW";
case LEVEL_MEDIUM:
return "MEDIUM";
case LEVEL_FULL:
return "FULL";
default:
return "UNKNOWN";
}
}
const char* getOutputName(BinLevel level) {
switch (level) {
case LEVEL_LOW:
return "GREEN LED";
case LEVEL_MEDIUM:
return "GREEN+RED LED";
case LEVEL_FULL:
return "RED LED + ALERT";
default:
return "SENSOR ERROR";
}
}
BinLevel determineBinLevel(float fillPercentage) {
if (!isfinite(fillPercentage) ||
fillPercentage < 0 ||
fillPercentage > 100) {
return LEVEL_UNKNOWN;
}
if (fillPercentage < lowLevelPercentage) {
return LEVEL_LOW;
}
if (fillPercentage < mediumLevelPercentage) {
return LEVEL_MEDIUM;
}
return LEVEL_FULL;
}
// ============================================================
// BUZZER
// ============================================================
void activateBuzzer(int beepCount, int beepDuration) {
for (int i = 0; i < beepCount; i++) {
digitalWrite(buzzerPin, HIGH);
delay(beepDuration);
digitalWrite(buzzerPin, LOW);
delay(beepDuration);
}
}
// ============================================================
// ULTRASONIC DISTANCE
// ============================================================
float readUltrasonicDistance() {
digitalWrite(ultrasonicTrigPin, LOW);
delayMicroseconds(3);
digitalWrite(ultrasonicTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(ultrasonicTrigPin, LOW);
unsigned long duration = pulseIn(
ultrasonicEchoPin,
HIGH,
ultrasonicTimeout
);
if (duration == 0) {
return -1.0;
}
float distance = duration * 0.0343 / 2.0;
if (distance <= 0 || distance > 400) {
return -1.0;
}
return distance;
}
float getStableDistance() {
float totalDistance = 0;
int validReadings = 0;
for (int i = 0; i < ultrasonicSamples; i++) {
float distance = readUltrasonicDistance();
if (distance > 0) {
totalDistance += distance;
validReadings++;
}
handleLidShutter();
delay(ultrasonicDelay);
}
if (validReadings == 0) {
return -1.0;
}
return totalDistance / validReadings;
}
// ============================================================
// SERVO CALIBRATION
// ============================================================
float getAngleOffset(int angle) {
if (angle == servoAngleOne) {
return distanceOffsetAtZero;
}
if (angle == servoAngleTwo) {
return distanceOffsetAtThirty;
}
if (angle == servoAngleThree) {
return distanceOffsetAtNinety;
}
return 0.0;
}
float moveServoAndMeasure(int angle, float &rawDistance) {
ultrasonicServo.write(angle);
unsigned long start = millis();
while (millis() - start < servoMoveDelay) {
handleLidShutter();
delay(10);
}
rawDistance = getStableDistance();
if (rawDistance < 0) {
return -1.0;
}
float correctedDistance =
rawDistance + getAngleOffset(angle);
if (correctedDistance < 0) {
correctedDistance = 0;
}
if (correctedDistance > 400) {
correctedDistance = 400;
}
return correctedDistance;
}
// ============================================================
// MEASUREMENT CALCULATIONS
// ============================================================
float calculateAverageDistance(
float distanceOne,
float distanceTwo,
float distanceThree
) {
float total = 0;
int count = 0;
if (distanceOne >= 0) {
total += distanceOne;
count++;
}
if (distanceTwo >= 0) {
total += distanceTwo;
count++;
}
if (distanceThree >= 0) {
total += distanceThree;
count++;
}
if (count == 0) {
return -1.0;
}
return total / count;
}
float calculateFillPercentage(float averageDistance) {
if (!isfinite(averageDistance) ||
averageDistance < 0 ||
binHeightCm <= 0) {
return -1.0;
}
float filledHeight = binHeightCm - averageDistance;
filledHeight = constrain(
filledHeight,
0.0f,
binHeightCm
);
return (filledHeight / binHeightCm) * 100.0;
}
// ============================================================
// DHT22
// ============================================================
void readDhtSensor() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
measurementData.humidity = -1;
measurementData.temperature = -1;
Serial.println("ENV: Temperature/Humidity error");
return;
}
measurementData.humidity = humidity;
measurementData.temperature = temperature;
Serial.printf(
"ENV: Temperature=%.1f C, Humidity=%.1f%%\n",
temperature,
humidity
);
}
// ============================================================
// WASTE STABILIZATION
// ============================================================
void stabilizeWaste() {
Serial.println("STABILIZING WASTE");
displayLidMessage("Stabilizing", "Waste...");
setRelay(true);
unsigned long start = millis();
while (millis() - start < stabilizationTime) {
handleLidShutter();
delay(20);
}
setRelay(false);
displayLidMessage("Stabilization", "Completed");
}
// ============================================================
// PERFORM BIN MEASUREMENT
// ============================================================
void performWasteMeasurement() {
Serial.println();
Serial.println("========== BIN SCAN ==========");
measurementData.distanceAtZero =
moveServoAndMeasure(
servoAngleOne,
measurementData.rawDistanceAtZero
);
measurementData.distanceAtThirty =
moveServoAndMeasure(
servoAngleTwo,
measurementData.rawDistanceAtThirty
);
measurementData.distanceAtNinety =
moveServoAndMeasure(
servoAngleThree,
measurementData.rawDistanceAtNinety
);
measurementData.averageDistance =
calculateAverageDistance(
measurementData.distanceAtZero,
measurementData.distanceAtThirty,
measurementData.distanceAtNinety
);
measurementData.fillPercentage =
calculateFillPercentage(
measurementData.averageDistance
);
measurementData.binLevel =
determineBinLevel(
measurementData.fillPercentage
);
Serial.printf(
"Distance 0 degrees: %.2f cm\n",
measurementData.distanceAtZero
);
Serial.printf(
"Distance 30 degrees: %.2f cm\n",
measurementData.distanceAtThirty
);
Serial.printf(
"Distance 90 degrees: %.2f cm\n",
measurementData.distanceAtNinety
);
Serial.printf(
"Average distance: %.2f cm\n",
measurementData.averageDistance
);
if (measurementData.fillPercentage >= 0) {
Serial.printf(
"Bin fill: %.1f%%\n",
measurementData.fillPercentage
);
} else {
Serial.println("Bin fill: SENSOR ERROR");
}
Serial.printf(
"Bin status: %s\n",
getLevelName(measurementData.binLevel)
);
Serial.printf(
"Indicator: %s\n",
getOutputName(measurementData.binLevel)
);
}
// ============================================================
// INDICATORS
// ============================================================
void updateIndicators() {
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, LOW);
digitalWrite(buzzerPin, LOW);
switch (measurementData.binLevel) {
case LEVEL_LOW:
digitalWrite(greenLedPin, HIGH);
break;
case LEVEL_MEDIUM:
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, HIGH);
activateBuzzer(1, 150);
break;
case LEVEL_FULL:
digitalWrite(redLedPin, HIGH);
activateBuzzer(3, 200);
break;
default:
digitalWrite(redLedPin, HIGH);
activateBuzzer(2, 100);
break;
}
}
// ============================================================
// LCD DISPLAY FUNCTIONS
// ============================================================
void displayLevel() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("LEVEL:");
lcd.print(getLevelName(measurementData.binLevel));
lcd.setCursor(0, 1);
if (measurementData.fillPercentage >= 0) {
lcd.print("Fill:");
lcd.print((int)measurementData.fillPercentage);
lcd.print("%");
} else {
lcd.print("Sensor Error");
}
delay(1200);
}
void displayEnvironment() {
lcd.clear();
lcd.setCursor(0, 0);
if (measurementData.temperature >= 0) {
lcd.print("Temp:");
lcd.print(measurementData.temperature, 1);
lcd.print((char)223);
lcd.print("C");
} else {
lcd.print("Temp:ERROR");
}
lcd.setCursor(0, 1);
if (measurementData.humidity >= 0) {
lcd.print("Hum:");
lcd.print(measurementData.humidity, 0);
lcd.print("%");
} else {
lcd.print("Hum:ERROR");
}
delay(1200);
}
void displayDistances() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("0:");
if (measurementData.distanceAtZero >= 0) {
lcd.print(measurementData.distanceAtZero, 1);
} else {
lcd.print("ERR");
}
lcd.print(" 30:");
if (measurementData.distanceAtThirty >= 0) {
lcd.print(measurementData.distanceAtThirty, 1);
} else {
lcd.print("ERR");
}
lcd.setCursor(0, 1);
lcd.print("90:");
if (measurementData.distanceAtNinety >= 0) {
lcd.print(measurementData.distanceAtNinety, 1);
} else {
lcd.print("ERR");
}
lcd.print("cm");
delay(1200);
}
void displayMainStatus() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("E-WASTE:");
lcd.print(getLevelName(measurementData.binLevel));
lcd.setCursor(0, 1);
lcd.print("F:");
if (measurementData.fillPercentage >= 0) {
lcd.print((int)measurementData.fillPercentage);
lcd.print("%");
} else {
lcd.print("ERR");
}
lcd.print(" T:");
if (measurementData.temperature >= 0) {
lcd.print((int)measurementData.temperature);
lcd.print("C");
} else {
lcd.print("--");
}
delay(1200);
}
// ============================================================
// COMPLETE MEASUREMENT CYCLE
// ============================================================
void runMeasurementCycle() {
Serial.println();
Serial.println("==============================");
Serial.println("E-WASTE MONITORING CYCLE");
Serial.println("==============================");
readDhtSensor();
stabilizeWaste();
performWasteMeasurement();
updateIndicators();
displayLevel();
displayEnvironment();
displayDistances();
displayMainStatus();
}
// ============================================================
// SERVER API INTEGRATION
//
// GET /api/iot/update?deviceId=EWB001&fullpercentage=72
//
// Checks the JSON response for:
// "openLid": true
// ============================================================
void pollServerAndReportLevel() {
if (WiFi.status() != WL_CONNECTED) {
return;
}
if (!isfinite(measurementData.fillPercentage) ||
measurementData.fillPercentage < 0 ||
measurementData.fillPercentage > 100) {
Serial.println("API: No valid bin reading to upload");
return;
}
int fill = constrain(
(int)roundf(measurementData.fillPercentage),
0,
100
);
WiFiClientSecure client;
// TESTING ONLY: this disables certificate verification.
client.setInsecure();
HTTPClient http;
String url = String(API_HOST) +
"/api/iot/update?deviceId=" +
DEVICE_ID +
"&fullpercentage=" +
String(fill);
http.setConnectTimeout(5000);
http.setTimeout(5000);
if (!http.begin(client, url)) {
Serial.println("API: HTTPS initialization failed");
return;
}
Serial.print("API GET: ");
Serial.println(url);
int httpCode = http.GET();
if (httpCode > 0) {
String response = http.getString();
Serial.printf("API HTTP status: %d\n", httpCode);
Serial.print("API response: ");
Serial.println(response);
if (httpCode >= 200 && httpCode < 300) {
// Locate the openLid JSON property.
int keyPosition = response.indexOf("\"openLid\"");
if (keyPosition >= 0) {
int colonPosition =
response.indexOf(':', keyPosition);
if (colonPosition >= 0) {
String value =
response.substring(colonPosition + 1);
value.trim();
if (value.startsWith("true") &&
(value.length() == 4 ||
value.charAt(4) == ',' ||
value.charAt(4) == '}' ||
value.charAt(4) == ' ')) {
remoteOpenPending = true;
Serial.println(
"API: OPEN LID COMMAND RECEIVED"
);
}
}
}
Serial.printf("Server fill reading: %d%%\n", fill);
Serial.printf(
"Local bin level: %s\n",
getLevelName(measurementData.binLevel)
);
}
} else {
Serial.print("API request error: ");
Serial.println(
HTTPClient::errorToString(httpCode)
);
}
http.end();
}
// ============================================================
// STARTUP
// ============================================================
void showStartupMessage() {
displayLidMessage("E-WASTE MONITOR", "Initializing...");
delay(1500);
displayLidMessage("Smart Waste Bin", "System Ready");
delay(1500);
lcd.clear();
}
// ============================================================
// SETUP
// ============================================================
void setup() {
Serial.begin(115200);
delay(500);
Serial.println();
Serial.println("==============================");
Serial.println("SMART E-WASTE MONITOR");
Serial.println("==============================");
pinMode(motorRelayPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ultrasonicTrigPin, OUTPUT);
pinMode(ultrasonicEchoPin, INPUT);
// PIR sensors normally idle LOW.
pinMode(pirSensorPin, INPUT);
setRelay(false);
digitalWrite(greenLedPin, LOW);
digitalWrite(redLedPin, LOW);
digitalWrite(buzzerPin, LOW);
digitalWrite(ultrasonicTrigPin, LOW);
Wire.begin(lcdSdaPin, lcdSclPin);
lcd.init();
lcd.backlight();
dht.begin();
// Ultrasonic scanning servo: GPIO 13.
ultrasonicServo.setPeriodHertz(50);
int scanAttached =
ultrasonicServo.attach(servoPin, 500, 2400);
if (scanAttached == 0) {
Serial.println("ERROR: Scan servo attach failed");
} else {
ultrasonicServo.write(servoAngleOne);
}
// Lid servo: GPIO 19.
lidShutterServo.setPeriodHertz(50);
int lidAttached =
lidShutterServo.attach(
servoLidShutterPin,
500,
2400
);
if (lidAttached == 0) {
Serial.println("ERROR: Lid servo attach failed");
} else {
lidShutterServo.write(lidClosedAngle);
}
showStartupMessage();
Serial.println("PIR input: GPIO 23");
Serial.println("Scanning servo: GPIO 13");
Serial.println("Lid servo: GPIO 19");
Serial.println("Device ID: EWB001");
connectWiFi();
// Trigger first measurement immediately.
lastMeasurementTime =
millis() - measurementInterval;
// Allow immediate first API poll after measurement.
lastApiPollTime = millis();
}
// ============================================================
// MAIN LOOP
// ============================================================
void loop() {
// Keep lid handling responsive between operations.
handleLidShutter();
unsigned long now = millis();
// Reconnect Wi-Fi when needed.
if (WiFi.status() != WL_CONNECTED &&
now - lastWiFiRetryTime >= wifiRetryInterval) {
lastWiFiRetryTime = now;
connectWiFi();
}
// Poll server for remote lid commands and upload readings.
if (now - lastApiPollTime >= apiPollInterval) {
lastApiPollTime = now;
pollServerAndReportLevel();
}
// Periodic sensor measurements.
if (now - lastMeasurementTime >= measurementInterval) {
lastMeasurementTime = now;
runMeasurementCycle();
// Immediately upload the newly measured value.
pollServerAndReportLevel();
lastApiPollTime = millis();
}
delay(10);
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4