Saturday, 25 July 2026

Plastic Waste Recycling System

Plastic Waste Recycling System Using Microcontroller

♻️ Plastic Waste Recycling System Using Microcontroller

1. Project Title

Microcontroller-Based Smart Plastic Waste Recycling and Sorting System


2. Project Abstract

Plastic waste is one of the major environmental problems because it takes a long time to decompose and can cause serious pollution. The proposed Plastic Waste Recycling System is an automated system designed to collect, detect, sort, and process plastic waste using a microcontroller.

The system uses sensors to detect the presence of plastic waste and automatically separates it from other materials. A conveyor belt transports the waste, while sensors such as an IR sensor, inductive proximity sensor, capacitive sensor, or colour sensor help identify different types of materials. A microcontroller such as Arduino UNO processes the sensor signals and controls motors, servo motors, and indicators.

The system can be extended to include a plastic crushing mechanism, which converts collected plastic waste into small pieces for further recycling. This project reduces manual sorting, improves recycling efficiency, and supports environmental protection.


3. Project Aim

Main Aim

To design and develop an automated microcontroller-based plastic waste recycling system that can detect, sort, and process plastic waste with minimum human effort.

Objectives

  • To detect plastic waste automatically.
  • To separate plastic from other materials.
  • To use a microcontroller for automatic control.
  • To reduce manual waste sorting.
  • To improve plastic recycling efficiency.
  • To crush plastic waste into smaller pieces.
  • To provide a low-cost smart recycling solution.

4. System Description

The system consists of a waste collection section, conveyor belt, sensor detection section, sorting mechanism, and plastic crushing section.

When waste is placed into the input container, a motor-driven conveyor belt moves the waste forward. Sensors detect whether the object is plastic or another material. The Arduino UNO receives the sensor signals and makes a decision.

If the object is detected as plastic, a servo motor or DC motor-controlled mechanism directs it to the plastic collection bin. Other materials are directed to a separate bin.

The collected plastic can then be sent to a crusher mechanism, where rotating blades reduce the plastic into small pieces. These pieces can later be used for further recycling processes.


5. Block Diagram

              ┌──────────────────────┐
              │     Waste Input      │
              │   Plastic + Others   │
              └──────────┬───────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │    Conveyor Belt     │
              │      DC Motor        │
              └──────────┬───────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │   Object Detection   │
              │  IR / Proximity      │
              │  Capacitive Sensor   │
              └──────────┬───────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │    ARDUINO UNO       │
              │    MICROCONTROLLER   │
              └──────┬───────┬───────┘
                     │       │
             Plastic │       │ Other Waste
                     ▼       ▼
          ┌──────────────┐ ┌──────────────┐
          │ Servo Motor  │ │ Reject/Other │
          │ Sorting Arm  │ │ Waste Bin    │
          └──────┬───────┘ └──────────────┘
                 │
                 ▼
          ┌────────────────┐
          │ Plastic Waste  │
          │ Collection Bin │
          └───────┬────────┘
                  │
                  ▼
          ┌────────────────┐
          │ Plastic Crusher│
          │ DC Motor +     │
          │ Blades         │
          └───────┬────────┘
                  │
                  ▼
          ┌────────────────┐
          │ Recycled Small │
          │ Plastic Pieces │
          └────────────────┘

     ┌─────────────┐
     │ Power Supply │
     └──────┬──────┘
            │
            ├── Arduino
            ├── Sensors
            ├── Motor Driver
            └── Motors


6. Components Required

Main Components

No. Component Quantity Purpose
1 Arduino UNO 1 Main microcontroller
2 DC Gear Motor 1 Conveyor belt movement
3 L298N Motor Driver 1 Controls DC motors
4 Servo Motor SG90/MG90S 1–2 Waste sorting mechanism
5 IR Obstacle Sensor 1 Detects waste object
6 Capacitive Proximity Sensor 1 Helps detect non-metal/plastic objects
7 Inductive Proximity Sensor Optional Detects metal objects
8 DC Motor for Crusher 1 Drives crushing mechanism
9 Plastic Crusher Blades 1 set Crushes plastic
10 Conveyor Belt 1 Transports waste
11 LCD 16×2 Display with I2C 1 Displays system status
12 Buzzer 1 Warning/status indication
13 LEDs 2–3 Status indication
14 Push Buttons 2 Start/Stop control
15 12 V DC Power Supply 1 Motor power
16 5 V Buck Converter 1 Provides regulated 5 V
17 Plastic/wood/acrylic frame 1 Mechanical structure
18 Wires and breadboard/PCB As required Connections

7. Recommended Sensor Arrangement

For a simple school or college prototype:

Plastic Detection

Use:

  • IR Sensor → Detects the presence of an object.
  • Capacitive Proximity Sensor → Detects plastic and other non-metallic objects.
  • Inductive Sensor → Detects metal objects.

Basic Decision Logic

Object Detected?
       │
       ▼
Is Metal?
 ┌─────┴─────┐
Yes          No
 │            │
 ▼            ▼
Other       Plastic/
Waste       Non-metal
             │
             ▼
       Sort to Plastic Bin

Note: A basic capacitive sensor can detect many non-metallic materials, not only plastic. For a more advanced project, plastic identification can be improved using multiple sensors, colour sensing, weight sensing, or camera-based AI classification.


8. Schematic Diagram

A. Arduino Sensor Connections

              ┌────────────────────┐
              │    ARDUINO UNO     │
              │                    │
IR Sensor ────┤ D2                 │
Capacitive ───┤ D3                 │
Inductive ────┤ D4                 │
Start Button ─┤ D5                 │
Stop Button ──┤ D6                 │
              │                    │
Servo Motor ──┤ D9                 │
Buzzer ───────┤ D8                 │
Green LED ────┤ D10                │
Red LED ──────┤ D11                │
              │                    │
LCD SDA ──────┤ A4                 │
LCD SCL ──────┤ A5                 │
              │                    │
              │ 5V ────────────────┼── Sensors
              │ GND ───────────────┼── Common Ground
              └────────────────────┘


B. L298N Conveyor Motor Connection

             ARDUINO UNO
                 │
          D7 ────┤ IN1
          D12 ───┤ IN2
                 │
                 ▼
          ┌───────────────┐
          │ L298N DRIVER  │
          │               │
          │ OUT1 ─────────┼──── DC MOTOR
          │ OUT2 ─────────┼──── CONVEYOR
          │               │
          │ 12V ──────────┼──── 12V Supply
          │ GND ──────────┼──── Arduino GND
          └───────────────┘


C. Plastic Crusher Motor Connection

          ┌───────────────┐
          │ Motor Driver  │
          └───────┬───────┘
                  │
                  ▼
          ┌───────────────┐
          │ High Torque   │
          │ DC Motor      │
          └───────┬───────┘
                  │
                  ▼
          ┌────────────────┐
          │ Rotating       │
          │ Crusher Blades │
          └────────────────┘

⚠️ Safety: The crusher mechanism must have a protective cover. Do not operate exposed rotating blades.


9. Example Arduino Pin Configuration

Component Arduino Pin
IR Sensor D2
Capacitive Sensor D3
Inductive Sensor D4
Start Button D5
Stop Button D6
Conveyor Motor IN1 D7
Buzzer D8
Servo Motor D9
Green LED D10
Red LED D11
Conveyor Motor IN2 D12
LCD SDA A4
LCD SCL A5

10. Step-by-Step Project Construction

Step 1: Build the Mechanical Frame

Construct the main frame using:

  • Acrylic sheet
  • Wood
  • PVC
  • Metal frame

Create separate sections for:

Input → Conveyor → Detection → Sorting → Collection → Crushing


Step 2: Build the Conveyor Belt

Install:

  • Two rollers
  • Conveyor belt
  • DC gear motor
  • Motor mounting bracket

The DC motor rotates the roller and moves waste along the belt.


Step 3: Install the Sensors

Place the sensors above or beside the conveyor:

        IR Sensor
            │
            ▼
     ┌─────────────┐
     │             │
     │ Conveyor    │
     │   Waste     │
     │             │
     └─────────────┘

The IR sensor detects when waste reaches the detection point.


Step 4: Connect the Arduino UNO

Connect the sensors to the Arduino according to the pin table.

Ensure:

  • All GND connections are common.
  • Sensors receive the correct voltage.
  • Motors are not powered directly from Arduino pins.

Step 5: Connect the Motor Driver

Connect the conveyor motor to the L298N motor driver.

The Arduino sends control signals to the L298N, while the L298N supplies the required current to the motor.

Arduino → Motor Driver → DC Motor


Step 6: Install the Sorting Mechanism

A servo motor can be connected to a sorting arm:

             Plastic
                │
                ▼
       ┌────────────────┐
       │ Servo Sorting  │
       │      Arm       │
       └───────┬────────┘
               │
      ┌────────┴────────┐
      ▼                 ▼
 Plastic Bin       Other Waste Bin

The servo changes its position depending on the sensor result.


Step 7: Install the Plastic Crusher

After plastic enters the plastic collection section:

  1. Plastic is collected.
  2. The crusher motor starts.
  3. Rotating blades crush the plastic.
  4. Small plastic pieces are collected.

For a prototype, a separate push-button can be used to activate the crusher.


Step 8: Install LCD Display

The LCD can display:

PLASTIC RECYCLING
SYSTEM READY

When plastic is detected:

PLASTIC DETECTED
SORTING...

When crushing is active:

CRUSHER RUNNING


11. System Working Flowchart

             START
               │
               ▼
        Initialize System
               │
               ▼
       Start Conveyor Belt
               │
               ▼
        Detect Waste Object
               │
          ┌────┴────┐
          │         │
        No│         │Yes
          │         ▼
          │   Check Material
          │         │
          │    ┌────┴────┐
          │    │         │
          │  Metal     Plastic
          │    │         │
          │    ▼         ▼
          │ Other     Servo Moves
          │ Waste     to Plastic Bin
          │    │         │
          └────┴─────────┘
                    │
                    ▼
          Send Plastic to Crusher
                    │
                    ▼
             Crush Plastic
                    │
                    ▼
              Display Status
                    │
                    ▼
                   STOP


12. Basic Working Sequence

1. Turn ON the system.
        ↓
2. Arduino initializes all sensors.
        ↓
3. Conveyor belt starts.
        ↓
4. Waste reaches the sensor area.
        ↓
5. IR sensor detects the waste.
        ↓
6. Material sensors identify the object.
        ↓
7. Arduino processes the sensor signals.
        ↓
8. Servo motor moves the sorting arm.
        ↓
9. Plastic enters the plastic bin.
        ↓
10. Other materials enter the reject bin.
        ↓
11. Plastic crusher processes the plastic.
        ↓
12. LCD displays system status.


13. Suggested Project Kit Structure

 ┌──────────────────────────────────────────┐
 │              WASTE INPUT                 │
 │         Plastic + Other Materials        │
 └──────────────────┬───────────────────────┘
                    ▼
       ┌─────────────────────────┐
       │      CONVEYOR BELT      │
       │  ─────────────────────  │
       │          ● Waste        │
       └────────────┬────────────┘
                    ▼
             ┌──────────────┐
             │ SENSOR AREA  │
             │ IR + Other   │
             └──────┬───────┘
                    ▼
              ┌────────────┐
              │  ARDUINO   │
              │    UNO     │
              └─────┬──────┘
                    ▼
             ┌──────────────┐
             │ SERVO ARM    │
             │ SORTING UNIT │
             └──────┬───────┘
                ┌───┴────┐
                ▼        ▼
          ┌─────────┐ ┌─────────┐
          │ PLASTIC │ │ OTHER   │
          │   BIN   │ │   BIN   │
          └────┬────┘ └─────────┘
               ▼
        ┌──────────────┐
        │   CRUSHER    │
        │   MOTOR      │
        └──────┬───────┘
               ▼
        ┌──────────────┐
        │ RECYCLED     │
        │ PLASTIC       │
        │ PIECES        │
        └──────────────┘


14. Final Project Working Principle

The Plastic Waste Recycling System automatically transports waste using a conveyor belt. Sensors detect the presence and type of material. The Arduino microcontroller processes the sensor signals and controls the sorting servo motor. Plastic waste is directed to a dedicated collection area and can then be crushed into smaller pieces using a motor-driven crusher. The LCD, LEDs, and buzzer provide system status information.

This project demonstrates the practical use of microcontrollers, sensors, motor control, automation, and environmental technology in a single system.

Best final title:

“Arduino-Based Smart Plastic Waste Sorting and Recycling System Using Sensors and Automated Conveyor Mechanism”



Project kit image

Generated image: Plastic waste recycling system prototype




Description

♻️ Plastic Waste Recycling System – Project Description

The Plastic Waste Recycling System is an automated microcontroller-based system designed to collect, detect, sort, and process plastic waste. The system uses an Arduino UNO microcontroller, sensors, motors, a conveyor belt, and a sorting mechanism to reduce manual waste separation.

When mixed waste is placed into the waste input section, the conveyor belt moves the waste toward the detection area. An IR sensor detects the presence of an object, while additional sensors can help identify plastic and other materials. The Arduino UNO receives the sensor signals and processes the information.

When plastic waste is detected, the Arduino activates a servo motor that moves the sorting arm and directs the plastic into the plastic collection bin. Other materials are directed into a separate waste bin. The collected plastic can then be transferred to a plastic crusher, where a DC motor rotates the crushing mechanism and reduces the plastic into smaller pieces.

The system also includes an LCD display to show the operating status, LEDs for visual indication, and a buzzer for alerts. A motor driver is used to control the conveyor and crusher motors safely.

System Operation

Waste Input
     ↓
Conveyor Belt
     ↓
Object Detection
     ↓
Sensor-Based Identification
     ↓
Arduino UNO Processing
     ↓
Automatic Sorting
     ↓
Plastic Collection
     ↓
Plastic Crushing
     ↓
Small Recyclable Plastic Pieces

Main Advantages

  • Reduces manual waste sorting.
  • Automates plastic waste collection and separation.
  • Demonstrates practical microcontroller applications.
  • Helps improve recycling efficiency.
  • Can be expanded with IoT monitoring and AI-based material recognition.
  • Suitable for a school or college engineering project.

In simple terms, this project combines sensors, Arduino control, motors, conveyor automation, and a crushing mechanism to create a small-scale smart plastic recycling system.

Arduino-Based Smart Dustbin

Arduino-Based Smart Automatic Dustbin with Touchless Lid Opening and Waste-Level Monitoring

Arduino-Based Smart Dustbin

1. Project Title

Arduino-Based Smart Automatic Dustbin with Touchless Lid Opening and Waste-Level Monitoring


2. Project Abstract

The Arduino-Based Smart Dustbin is an automatic waste-management system designed to improve hygiene and convenience. The system uses an Arduino microcontroller, an ultrasonic sensor, and a servo motor to detect a person's hand near the dustbin and automatically open the lid without physical contact.

A second ultrasonic sensor can be used to monitor the waste level inside the dustbin. When the dustbin becomes full, the system can provide an alert using an LED and buzzer. This project demonstrates the practical application of microcontrollers, sensors, automation, and embedded systems in smart waste management.


3. Project Aim

The main aim of this project is:

To design and develop an Arduino-based automatic dustbin that opens its lid without physical contact and indicates when the dustbin is full.

Objectives

  • To provide a touch-free waste disposal system.
  • To automatically open the lid when a person approaches.
  • To monitor the waste level inside the dustbin.
  • To provide a visual or audio alert when the bin is nearly full.
  • To reduce the spread of germs caused by touching dustbin lids.
  • To learn practical applications of an Arduino microcontroller.

4. Project Description

The system consists of two main functions:

Function 1: Automatic Lid Opening

An ultrasonic sensor is installed near the front of the dustbin. When a person's hand comes within a specified distance, the sensor detects the object.

The Arduino then sends a control signal to the servo motor. The servo motor rotates and opens the dustbin lid automatically.

After a few seconds, the lid closes automatically.

Function 2: Waste-Level Monitoring

A second ultrasonic sensor is installed at the top inside the dustbin.

It continuously measures the distance between the sensor and the waste.

  • Low waste level → Normal operation
  • Medium waste level → Warning LED
  • High waste level → Buzzer and full indication

5. Block Diagram

              ┌──────────────────────┐
              │   Object Detection   │
              │  Ultrasonic Sensor 1 │
              └──────────┬───────────┘
                         │
                         ▼
                 ┌───────────────┐
                 │               │
                 │    ARDUINO    │
                 │ MICROCONTROLLER│
                 │               │
                 └───┬─────┬─────┘
                     │     │
          ┌──────────┘     └──────────┐
          ▼                           ▼
 ┌─────────────────┐         ┌──────────────────┐
 │   Servo Motor   │         │ Waste-Level      │
 │ Automatic Lid   │         │ Ultrasonic       │
 │ Opening/Closing │         │ Sensor 2         │
 └─────────────────┘         └────────┬─────────┘
                                      │
                                      ▼
                            ┌─────────────────┐
                            │ Alert System    │
                            │ LED + Buzzer    │
                            └─────────────────┘

                 ┌──────────────────┐
                 │ Power Supply     │
                 │ 5V / USB Supply │
                 └────────┬─────────┘
                          │
                          ▼
                    Arduino System


6. Components Required

No. Component Quantity Purpose
1 Arduino UNO 1 Main microcontroller
2 HC-SR04 Ultrasonic Sensor 2 Object and waste-level detection
3 Servo Motor SG90 1 Opens and closes lid
4 Buzzer 1 Full-bin warning
5 LED 1 or 2 Status indication
6 220 Ω Resistor 1 or 2 LED protection
7 Breadboard 1 Circuit assembly
8 Jumper Wires As required Connections
9 Dustbin with movable lid 1 Mechanical structure
10 5 V USB Power Supply 1 Power source

Optional Components

  • 16×2 LCD with I2C module
  • ESP8266 or ESP32 for IoT monitoring
  • GSM module for SMS alerts
  • OLED display
  • Battery pack

7. Arduino Pin Connections

Ultrasonic Sensor 1 — Object Detection

HC-SR04 Pin Arduino UNO
VCC 5V
GND GND
TRIG D2
ECHO D3

Ultrasonic Sensor 2 — Waste-Level Monitoring

HC-SR04 Pin Arduino UNO
VCC 5V
GND GND
TRIG D4
ECHO D5

Servo Motor

Servo Wire Arduino UNO
Red 5V
Brown/Black GND
Orange/Yellow D9

For a larger servo motor, use an external 5 V power supply. Always connect the external power supply GND to Arduino GND.


Buzzer

Buzzer Pin Arduino UNO
Positive (+) D8
Negative (-) GND

LED

LED Pin Arduino UNO
Anode (+) D7 through 220 Ω resistor
Cathode (-) GND

8. Schematic Diagram

                         +----------------------+
                         |      ARDUINO UNO     |
                         |                      |
      Object Sensor      |                      |
     HC-SR04 #1          |                      |
    +-------------+      |                      |
    | VCC --------|------| 5V                   |
    | GND --------|------| GND                  |
    | TRIG -------|------| D2                   |
    | ECHO -------|------| D3                   |
    +-------------+      |                      |
                         |                      |
      Level Sensor       |                      |
     HC-SR04 #2          |                      |
    +-------------+      |                      |
    | VCC --------|------| 5V                   |
    | GND --------|------| GND                  |
    | TRIG -------|------| D4                   |
    | ECHO -------|------| D5                   |
    +-------------+      |                      |
                         |                      |
      Servo Motor        |                      |
    +-------------+      |                      |
    | Signal ------|------| D9                   |
    | VCC ---------|------| 5V                  |
    | GND ---------|------| GND                  |
    +-------------+      |                      |
                         |                      |
       Buzzer            |                      |
    +-------------+      |                      |
    | + ----------|------| D8                   |
    | - ----------|------| GND                  |
    +-------------+      |                      |
                         |                      |
        LED              |                      |
    D7 ----[220Ω]---->|--| GND                  |
                         +----------------------+


9. Working Principle

Step 1: System Power ON

When power is supplied, the Arduino starts the system and sets the lid to the closed position.

Step 2: Object Detection

The first ultrasonic sensor sends ultrasonic waves.

If a person's hand is detected within approximately 20 cm, the Arduino detects the object.

Step 3: Lid Opening

The Arduino sends a PWM signal to the servo motor.

The servo rotates from approximately:

0° → 90°

The dustbin lid opens.

Step 4: Automatic Closing

After a short delay, the servo motor returns to its original position:

90° → 0°

The lid closes automatically.

Step 5: Waste-Level Detection

The second ultrasonic sensor measures the distance from the top of the dustbin to the waste.

The Arduino calculates the approximate filling condition.

Step 6: Full-Bin Alert

If the waste reaches the defined full level:

  • LED turns ON.
  • Buzzer sounds.
  • The user is notified that the dustbin needs emptying.

10. Step-by-Step Project Construction

Step 1: Prepare the Dustbin

Select a dustbin with a movable lid.

Create a suitable mechanical connection between the lid and the servo motor.

Example:

Servo Motor Horn
       │
       │ Mechanical Link
       ▼
   Dustbin Lid

The servo motor should be firmly fixed to the side of the dustbin.


Step 2: Install Object Detection Sensor

Place Ultrasonic Sensor 1 near the front of the dustbin.

Suggested position:

        Hand
         ↓
    [ HC-SR04 ]
         │
         ▼
     ┌─────────┐
     │         │
     │ Dustbin │
     │         │
     └─────────┘

This sensor detects the user's hand.


Step 3: Install Waste-Level Sensor

Place Ultrasonic Sensor 2 at the top of the dustbin facing downward.

       HC-SR04
          ↓
    ┌───────────┐
    │           │
    │           │
    │   WASTE   │
    │███████████ │
    └───────────┘


Step 4: Connect the Arduino

Connect both ultrasonic sensors according to the pin tables above.

Make sure:

  • All GND pins are connected together.
  • VCC is connected to 5 V.
  • TRIG and ECHO pins are connected correctly.

Step 5: Connect the Servo Motor

Connect the servo signal wire to Arduino D9.

The servo mechanically controls the lid.


Step 6: Connect the LED and Buzzer

Connect:

  • LED to D7 through a 220 Ω resistor.
  • Buzzer positive terminal to D8.
  • All negative terminals to GND.

Step 7: Upload the Program

  1. Open Arduino IDE.
  2. Select Arduino UNO.
  3. Select the correct COM port.
  4. Upload the program.
  5. Test the sensor readings.

11. Basic Arduino Program

#include <Servo.h>

Servo lidServo;

// Object detection sensor
const int trigObject = 2;
const int echoObject = 3;

// Waste-level sensor
const int trigLevel = 4;
const int echoLevel = 5;

// Output devices
const int ledPin = 7;
const int buzzerPin = 8;
const int servoPin = 9;

long duration;
int distance;

void setup() {
  Serial.begin(9600);

  pinMode(trigObject, OUTPUT);
  pinMode(echoObject, INPUT);

  pinMode(trigLevel, OUTPUT);
  pinMode(echoLevel, INPUT);

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  lidServo.attach(servoPin);

  // Initially close the lid
  lidServo.write(0);

  digitalWrite(ledPin, LOW);
  digitalWrite(buzzerPin, LOW);
}

int getDistance(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;

  return distance;
}

void loop() {

  // Measure distance from user's hand
  int objectDistance = getDistance(trigObject, echoObject);

  // Measure waste level
  int wasteDistance = getDistance(trigLevel, echoLevel);

  Serial.print("Object Distance: ");
  Serial.print(objectDistance);
  Serial.println(" cm");

  Serial.print("Waste Distance: ");
  Serial.print(wasteDistance);
  Serial.println(" cm");

  // Automatic lid opening
  if (objectDistance > 0 && objectDistance < 20) {

    lidServo.write(90);
    delay(3000);

    lidServo.write(0);
    delay(1000);
  }

  // Waste-level monitoring
  if (wasteDistance < 10) {

    // Dustbin is full
    digitalWrite(ledPin, HIGH);

    digitalWrite(buzzerPin, HIGH);
    delay(500);
    digitalWrite(buzzerPin, LOW);

  } else {

    // Dustbin is not full
    digitalWrite(ledPin, LOW);
    digitalWrite(buzzerPin, LOW);
  }

  delay(200);
}


12. Flowchart

              ┌──────────────┐
              │    START     │
              └──────┬───────┘
                     ▼
          ┌────────────────────┐
          │ Initialize Arduino │
          │ Sensors and Servo  │
          └─────────┬──────────┘
                    ▼
          ┌────────────────────┐
          │ Detect Hand/Object │
          └─────────┬──────────┘
                    ▼
          ┌────────────────────┐
          │ Object < 20 cm ?   │
          └──────┬───────┬─────┘
                 │Yes     │No
                 ▼        │
          ┌─────────────┐  │
          │ Open Lid    │  │
          │ Servo = 90° │  │
          └──────┬──────┘  │
                 ▼         │
          ┌─────────────┐  │
          │ Wait 3 Sec  │  │
          └──────┬──────┘  │
                 ▼         │
          ┌─────────────┐  │
          │ Close Lid   │  │
          │ Servo = 0°  │  │
          └──────┬──────┘  │
                 └────┬────┘
                      ▼
             ┌────────────────┐
             │ Measure Waste  │
             │ Level Distance │
             └───────┬────────┘
                     ▼
             ┌────────────────┐
             │ Waste < 10 cm? │
             └──────┬────┬────┘
                    │Yes │No
                    ▼    ▼
              ┌────────┐ ┌────────────┐
              │Buzzer +│ │Normal      │
              │LED ON  │ │Operation   │
              └────┬───┘ └─────┬──────┘
                   └──────┬────┘
                          ▼
                    Repeat Loop


13. Expected Output

Condition System Response
No person nearby Lid remains closed
Hand detected Lid opens automatically
After 3 seconds Lid closes
Bin partially filled Normal operation
Bin almost full LED turns ON
Bin completely full Buzzer alert

14. Advantages

  • Touchless operation
  • Improved hygiene
  • Low-cost project
  • Easy to build
  • Low power consumption
  • Simple Arduino programming
  • Useful for homes, schools, offices, and hospitals

15. Future Enhancements

The project can be upgraded by adding:

IoT Monitoring

Use ESP32 to send the dustbin fill level to a web dashboard.

Mobile Notifications

Send a notification when the dustbin becomes full.

Solar Power

Use a solar panel and battery for outdoor applications.

Automatic Waste Collection

Multiple smart dustbins can send their fill levels to a central monitoring system.

LCD/OLED Display

Display:

Dustbin Status:
EMPTY / HALF FULL / FULL


Recommended Final Project Title

“Arduino-Based Smart Automatic Dustbin with Touchless Lid Control and Waste-Level Monitoring”



Description

Project Description

The Arduino-Based Smart Automatic Dustbin is an intelligent waste-management system designed to improve hygiene, convenience, and cleanliness. The project uses an Arduino UNO microcontroller as the main control unit. An HC-SR04 ultrasonic sensor detects the presence of a person's hand near the dustbin without requiring physical contact.

When an object or hand is detected within a predefined distance, the Arduino processes the sensor signal and activates a servo motor. The servo motor automatically opens the dustbin lid. After a short delay, the lid closes automatically.

A second ultrasonic sensor can be installed inside the dustbin to monitor the waste-filling level. The sensor measures the distance between the top of the dustbin and the waste material. When the waste reaches a specified level, the Arduino activates an LED and buzzer to indicate that the dustbin is full and needs to be emptied.

The system provides a simple, low-cost, and efficient solution for automatic waste disposal. It reduces direct contact with the dustbin, helps improve hygiene, and demonstrates the practical application of microcontrollers, sensors, embedded systems, and automation technology.

Working Summary

Object Detected
       ↓
Ultrasonic Sensor Measures Distance
       ↓
Arduino Processes the Signal
       ↓
Servo Motor Opens the Lid
       ↓
Waste is Deposited
       ↓
Lid Closes Automatically
       ↓
Waste-Level Sensor Checks the Bin
       ↓
LED/Buzzer Alert if the Bin is Full

This project is suitable for homes, schools, offices, hospitals, public places, and smart-city waste-management applications.



Smart Automatic Street Light System Using Microcontroller

Smart Automatic Street Light System Using Microcontroller

1. Project Title

Microcontroller-Based Smart Automatic Street Light Control System Using LDR and PIR Sensor


2. Project Aim

The aim of this project is to design and develop an automatic street light system that controls street lights intelligently according to ambient light conditions and human/vehicle movement.

The system automatically:

  • Turns the street light ON at night.
  • Turns the street light OFF during daytime.
  • Detects movement using a PIR sensor.
  • Operates the light at full brightness when movement is detected.
  • Reduces brightness or turns the light OFF when no movement is detected.
  • Helps to save electrical energy.

3. Project Abstract

The Smart Automatic Street Light System is a microcontroller-based energy-saving system designed to control street lights automatically without manual operation. The system uses an LDR (Light Dependent Resistor) to detect the intensity of surrounding light and a PIR motion sensor to detect the movement of people or vehicles.

During the daytime, the LDR detects sufficient sunlight and the microcontroller keeps the street light switched OFF. During the night, when the light intensity decreases, the microcontroller automatically activates the street light. When motion is detected by the PIR sensor, the street light can operate at full brightness. When no motion is detected for a specific period, the system can reduce the brightness or switch the light OFF.

An Arduino Uno microcontroller is used as the main control unit. The system improves energy efficiency, reduces electricity consumption, and provides automatic and intelligent street lighting.


4. Block Diagram

                 ┌────────────────────┐
                 │   Sunlight / Dark  │
                 └─────────┬──────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ LDR Sensor   │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │              │
                    │              │
                    │   Arduino    │
                    │     Uno      │
                    │              │
                    └──────┬───────┘
                           ▲
                           │
                    ┌──────┴───────┐
                    │              │
                    │ PIR Sensor   │
                    │ Motion Detect│
                    │              │
                    └──────────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ MOSFET /     │
                    │ Relay Driver │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ LED Street   │
                    │ Light        │
                    └──────────────┘

             ┌──────────────────────┐
             │ 5V DC Power Supply   │
             └──────────┬───────────┘
                        │
                        ▼
                    Arduino Uno


5. Components Required

No. Component Quantity Purpose
1 Arduino Uno 1 Main microcontroller
2 LDR Sensor 1 Detects day and night
3 10 kΩ Resistor 1 LDR voltage divider
4 PIR Motion Sensor HC-SR501 1 Detects human/vehicle movement
5 LED Street Light / High-Power LED 1 Lighting output
6 Logic-Level MOSFET, e.g. IRLZ44N 1 Controls high-power LED
7 220 Ω Resistor 1 LED protection, if required
8 5 V Power Supply 1 Powers Arduino and sensors
9 External LED Power Supply 1 Powers high-power street LED
10 Breadboard 1 Prototype circuit
11 Jumper Wires As required Connections
12 Arduino USB Cable 1 Programming

Optional Components

  • LCD 16×2 display
  • OLED display
  • RTC module
  • ESP8266/ESP32 for IoT monitoring
  • Solar panel
  • Battery
  • Rain sensor
  • Ultrasonic sensor

6. System Working Principle

The project works in the following sequence:

Daytime

  1. The LDR receives strong sunlight.
  2. The LDR output value indicates bright conditions.
  3. Arduino detects daytime.
  4. The street light remains OFF.
Bright Light → LDR Detects Day → Arduino → Street Light OFF


Nighttime Without Movement

  1. The LDR detects darkness.
  2. Arduino turns the street light ON.
  3. If no motion is detected by the PIR sensor, the light can operate at reduced brightness.
Darkness → LDR Detects Night → Arduino
                         ↓
                  No Movement
                         ↓
                 Low Brightness


Nighttime With Movement

  1. The LDR detects darkness.
  2. The PIR sensor detects a person or vehicle.
  3. Arduino receives the motion signal.
  4. The street light operates at full brightness.
Darkness + Motion Detected
             ↓
         Arduino
             ↓
      Full Brightness


7. Schematic Diagram

Basic Connection Diagram

                    +5V
                     │
                     │
                 ┌───┴───┐
                 │  LDR  │
                 └───┬───┘
                     │
                     ├────────────── A0
                     │
                 ┌───┴───┐
                 │ 10kΩ  │
                 │Resistor│
                 └───┬───┘
                     │
                    GND


       PIR SENSOR HC-SR501

       VCC ─────────────── 5V
       GND ─────────────── GND
       OUT ─────────────── D2


       ARDUINO UNO

       D9 ──────────────── Gate
                              │
                              ▼
                         ┌────────┐
                         │ MOSFET │
                         └───┬────┘
                             │
                             │ Drain
                             ▼
                       LED STREET LIGHT
                             │
                             │
                            GND

       MOSFET Source ─────── GND


8. Arduino Pin Connection Table

Component Component Pin Arduino Pin
LDR Voltage Divider Output A0
LDR VCC 5V
LDR Resistor Other side GND
PIR Sensor VCC 5V
PIR Sensor GND GND
PIR Sensor OUT D2
MOSFET Gate Gate D9
MOSFET Source Source GND
LED Street Light Positive External +V
LED Street Light Negative MOSFET Drain

Important

For a high-power LED street light, do not power the LED directly from an Arduino GPIO pin. Use a suitable:

  • MOSFET driver
  • LED driver circuit
  • External power supply

9. Step-by-Step Construction

Step 1: Prepare the Arduino Uno

Connect the Arduino Uno to your computer using the USB cable.

The Arduino will be the main controller that receives:

  • LDR sensor input
  • PIR sensor input

and controls:

  • Street light output

Step 2: Connect the LDR Sensor

The LDR is used to detect light intensity.

Connection

5V ─── LDR ───┬─── A0
              │
             10kΩ
              │
             GND

The junction between the LDR and the 10 kΩ resistor is connected to:

Arduino A0

Function

  • Bright light → one range of analog values
  • Darkness → another range of analog values

The Arduino reads the value using:

analogRead(A0);


Step 3: Connect the PIR Sensor

The PIR sensor detects movement.

Connections

PIR VCC  → Arduino 5V
PIR GND  → Arduino GND
PIR OUT  → Arduino Digital Pin 2

The PIR output will be:

HIGH → Motion detected
LOW  → No motion


Step 4: Connect the MOSFET

The MOSFET works as an electronic switch.

Connections

Arduino D9 → MOSFET Gate
MOSFET Source → GND
MOSFET Drain → LED Negative
LED Positive → External Power Supply Positive

A common ground must be connected:

Arduino GND ─── External Power Supply GND


Step 5: Connect the Street Light

For a simple demonstration, you can use an LED.

For a real street light, use a suitable high-power LED module with an appropriate driver.

Basic Concept

External +V
    │
    ▼
LED Street Light
    │
    ▼
MOSFET Drain
    │
MOSFET Source
    │
   GND


10. Control Logic

The control algorithm is:

START
  │
  ▼
Read LDR Value
  │
  ▼
Is it Daytime?
 ┌───────────────┐
 │               │
YES             NO
 │               │
 ▼               ▼
Light OFF    Read PIR Sensor
                  │
                  ▼
          Is Motion Detected?
             ┌────────┴────────┐
             │                 │
            YES               NO
             │                 │
             ▼                 ▼
       Full Brightness    Low Brightness
             │                 │
             └────────┬────────┘
                      │
                      ▼
                  Repeat


11. Example Arduino Program

// Smart Automatic Street Light System
// Arduino Uno + LDR + PIR + MOSFET

const int LDR_PIN = A0;
const int PIR_PIN = 2;
const int LIGHT_PIN = 9;

int ldrValue;
int pirState;

int darknessThreshold = 500;

void setup() {
  pinMode(PIR_PIN, INPUT);
  pinMode(LIGHT_PIN, OUTPUT);

  Serial.begin(9600);

  analogWrite(LIGHT_PIN, 0);
}

void loop() {

  // Read LDR value
  ldrValue = analogRead(LDR_PIN);

  // Read PIR motion sensor
  pirState = digitalRead(PIR_PIN);

  Serial.print("LDR Value: ");
  Serial.print(ldrValue);

  Serial.print(" | PIR: ");
  Serial.println(pirState);

  // Night condition
  if (ldrValue < darknessThreshold) {

    // Motion detected
    if (pirState == HIGH) {
      analogWrite(LIGHT_PIN, 255);
      Serial.println("Night + Motion: Full Brightness");
    }

    // No motion
    else {
      analogWrite(LIGHT_PIN, 80);
      Serial.println("Night + No Motion: Low Brightness");
    }
  }

  // Day condition
  else {
    analogWrite(LIGHT_PIN, 0);
    Serial.println("Daytime: Light OFF");
  }

  delay(500);
}


12. How the Program Works

LDR Reading

ldrValue = analogRead(LDR_PIN);

This reads the light intensity from the LDR circuit.


PIR Reading

pirState = digitalRead(PIR_PIN);

This checks whether motion is detected.


Night Detection

if (ldrValue < darknessThreshold)

The Arduino checks whether the environment is dark.

The value:

darknessThreshold = 500;

may need to be adjusted according to your LDR circuit.


Full Brightness

analogWrite(LIGHT_PIN, 255);

This produces maximum PWM output.


Low Brightness

analogWrite(LIGHT_PIN, 80);

This reduces the brightness.


Light OFF

analogWrite(LIGHT_PIN, 0);

This switches the street light OFF.


13. Testing Procedure

Test 1: Daylight Test

  1. Place the LDR under bright light.
  2. Open the Serial Monitor.
  3. Check the LDR value.
  4. The street light should turn OFF.

Test 2: Darkness Test

  1. Cover the LDR with your hand.
  2. Check the LDR value.
  3. The system should detect night.
  4. The street light should turn ON at low brightness.

Test 3: Motion Test

  1. Keep the LDR covered.
  2. Move in front of the PIR sensor.
  3. The PIR output becomes HIGH.
  4. The street light should turn to full brightness.

14. Advantages

  • Automatic operation
  • Saves electrical energy
  • Reduces manual control
  • Uses low-cost components
  • Easy to expand
  • Improves street-light efficiency
  • Can be powered using solar energy
  • Suitable for smart-city applications

15. Applications

  • Roads and highways
  • Residential streets
  • College and school campuses
  • Parking areas
  • Industrial areas
  • Rural roads
  • Smart-city infrastructure
  • Solar street-light systems

16. Future Enhancements

The project can be upgraded with:

IoT Monitoring

Use ESP32 to monitor:

  • Light status
  • Power consumption
  • Fault conditions

Solar Power

Add:

Solar Panel → Charge Controller → Battery → LED Street Light

Fault Detection

The system can detect:

  • LED failure
  • Overcurrent
  • Low battery
  • Cable failure

Automatic Brightness Control

Use PWM to control the LED brightness based on:

  • Ambient light
  • Motion
  • Time of day

17. Final Project Summary

LDR SENSOR
     │
     ▼
Detect Day/Night
     │
     ▼
   ARDUINO UNO
     ▲
     │
PIR MOTION SENSOR
     │
     ▼
Detect Movement
     │
     ▼
MOSFET DRIVER
     │
     ▼
LED STREET LIGHT

Final System Operation

Daytime → Light OFF

Night + No Motion → Low Brightness

Night + Motion Detected → Full Brightness

This is a strong Microcontroller Systems course project because it demonstrates sensor interfacing, analog input, digital input, PWM output, transistor/MOSFET switching, and embedded control logic in one practical application.

Tuesday, 21 July 2026

AI-Based Smart Water Leakage Detection and Alert System

``` AI-Based Smart Water Leakage Detection and Alert System ```
```

AI-Based Smart Water Leakage Detection and Alert System

ESP32 + IoT + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak Cloud Dashboard


AI-Powered ESP32 Agentic IoT n8n Automation Telegram Alerts Cloud Dashboard ```
```

1. Complete Project Overview

The AI-Based Smart Water Leakage Detection and Alert System is an intelligent Agentic IoT platform designed to detect water leakage, abnormal water consumption, pipe bursts, continuous water flow, and unusual water usage.

The ESP32 acts as the main IoT controller. It collects data from water flow sensors, leakage sensors, temperature sensors, and optional water-level sensors.

The collected data is transmitted through Wi-Fi to a PHP IoT API, n8n automation workflow, ThingSpeak cloud dashboard, Google Sheets, and an AI Agent.

When the AI Agent detects a possible water leakage, the system automatically generates Telegram text alerts, voice notifications, data logs, and maintenance alerts.

```
```

2. Main Project Objectives

Water Leakage Detection

Detect abnormal water flow and physical water leakage.

AI-Based Analysis

Analyze sensor data and calculate leakage probability.

Telegram Notification

Send instant Telegram alerts when leakage is detected.

Voice Notification

Automatically generate and send voice alerts.

Cloud Monitoring

Display real-time data using ThingSpeak.

Historical Data

Store sensor information in Google Sheets.

```
```

3. Complete System Architecture

```

+-------------------------------------------------------------+
|                     WATER PIPELINE                          |
|                                                             |
|        +----------------+       +----------------+          |
|        | Water Flow     |       | Water Leakage  |          |
|        | Sensor         |       | Sensor         |          |
|        +--------+-------+       +--------+-------+          |
|                 |                         |                |
+-----------------+-------------------------+----------------+
|
v
+------------------------+
|        ESP32            |
|                        |
| Sensor Reading         |
| Wi-Fi Communication    |
| Local Alarm             |
+-----------+------------+
|
+-----------+------------+
|                        |
v                        v
+---------------+       +------------------+
| PHP IoT API   |       | ThingSpeak Cloud |
+-------+-------+       +------------------+
|
v
+---------------+
| MySQL Database|
+-------+-------+
|
v
+---------------+
| IoT Webpage   |
| Dashboard     |
+---------------+

ESP32
|
v
n8n Webhook
|
v
AI Agent
|
+------------------+
|                  |
v                  v
Telegram Alert   Google Sheets
|
v
Voice Notification 
```

4. Hardware Components List

Component Quantity Purpose
ESP32 DevKit V1 1 Main IoT controller
YF-S201 Water Flow Sensor 1 or more Measures water flow
Water Leakage Sensor 1 or more Detects physical water presence
DS18B20 Temperature Sensor 1 Measures pipe temperature
HC-SR04 Ultrasonic Sensor Optional Measures tank water level
Buzzer 1 Local warning
Red LED 1 Leakage indication
Green LED 1 Normal operation indication
OLED Display 1 Local data display
5V Power Supply 1 Power source
Waterproof Enclosure 1 Protects electronics
```
```

5. ESP32 Pin Configuration

ESP32 Pin Component
GPIO 27 Water Flow Sensor Signal
GPIO 34 Leakage Sensor Analog Output
GPIO 4 DS18B20 Temperature Sensor
GPIO 5 Buzzer
GPIO 2 Red LED
GPIO 15 Green LED
GPIO 21 OLED SDA
GPIO 22 OLED SCL
```
```

6. Circuit Schematic Diagram

                     +----------------------+
                     |        ESP32         |
                     |                      |
                     | GPIO27 <-------------| FLOW SENSOR
                     |                      |
                     | GPIO34 <-------------| LEAK SENSOR
                     |                      |
                     | GPIO4  <-------------| DS18B20
                     |                      |
                     | GPIO5  --------------> BUZZER
                     |                      |
                     | GPIO2  --------------> RED LED
                     |                      |
                     | GPIO15 --------------> GREEN LED
                     |                      |
                     | GPIO21 <-------------> OLED SDA
                     | GPIO22 <-------------> OLED SCL
                     |                      |
                     | 3.3V ---------------> SENSOR VCC
                     | GND ----------------> COMMON GROUND
                     +----------------------+

   +------------------+
   | WATER FLOW SENSOR|
   +------------------+
      VCC  ----------> ESP32 VCC
      GND  ----------> ESP32 GND
      SIGNAL --------> GPIO27


   +------------------+
   | LEAK SENSOR      |
   +------------------+
      VCC  ----------> ESP32 VCC
      GND  ----------> ESP32 GND
      ANALOG --------> GPIO34


   +------------------+
   | DS18B20 SENSOR   |
   +------------------+
      VCC  ----------> 3.3V
      GND  ----------> GND
      DATA ----------> GPIO4
Electrical Safety:

Water and electricity must be properly isolated. Use waterproof connectors, insulated wiring, low-voltage DC power, fuse protection, and a waterproof enclosure.

```
```

7. Complete System Flowchart

START
Initialize ESP32, Sensors and Wi-Fi
Read Water Flow Sensor
Read Leakage Sensor
Calculate Flow Rate and Total Water Consumption
Is Abnormal Flow or Leakage Detected?
Send Data to PHP API, n8n and ThingSpeak
AI Agent Analyzes Sensor Data
Calculate Leakage Probability
If Critical: Telegram Alert + Voice Notification
Store Data in Google Sheets and MySQL
Update IoT Dashboard
Repeat Continuously
```
```

8. Water Leakage Detection Logic

Continuous Flow Detection

```

IF flow_rate > minimum_flow
AND flow continues for a long duration
AND no expected water usage is detected

THEN

```
Possible Water Leakage

Sudden Water Flow Detection

```

Previous Flow = 0 L/min

Current Flow = 20 L/min

IF sudden_flow_change > threshold

THEN

```
Possible Pipe Burst

Physical Leakage Sensor Detection

```

IF leak_sensor_value > threshold

THEN

```
Immediate Water Leakage Alert
```
```

9. Complete ESP32 Source Code


```

#include 
#include 
#include 
#include 

const char* WIFI_SSID =
"YOUR_WIFI_NAME";

const char* WIFI_PASSWORD =
"YOUR_WIFI_PASSWORD";

const char* SERVER_URL =
"http://YOUR_SERVER_ADDRESS/water-leakage/api/receive_data.php";

const char* THINGSPEAK_API_KEY =
"YOUR_THINGSPEAK_WRITE_API_KEY";

const char* THINGSPEAK_URL =
"http://api.thingspeak.com/update";

#define FLOW_SENSOR_PIN 27
#define LEAK_SENSOR_PIN 34
#define TEMP_SENSOR_PIN 4
#define BUZZER_PIN 5
#define RED_LED_PIN 2
#define GREEN_LED_PIN 15

OneWire oneWire(TEMP_SENSOR_PIN);

DallasTemperature temperatureSensor(
&oneWire
);

volatile unsigned long pulseCount = 0;

float flowRate = 0.0;

float totalLiters = 0.0;

float temperature = 0.0;

unsigned long lastTime = 0;

unsigned long lastSendTime = 0;

const float FLOW_CALIBRATION = 7.5;

const float MIN_LEAK_FLOW = 0.5;

const unsigned long LEAK_TIME_LIMIT =
300000;

unsigned long continuousFlowStart = 0;

void IRAM_ATTR pulseCounter()
{
pulseCount++;
}

void setup()
{
Serial.begin(115200);

```
pinMode(
    FLOW_SENSOR_PIN,
    INPUT_PULLUP
);

pinMode(
    LEAK_SENSOR_PIN,
    INPUT
);

pinMode(
    BUZZER_PIN,
    OUTPUT
);

pinMode(
    RED_LED_PIN,
    OUTPUT
);

pinMode(
    GREEN_LED_PIN,
    OUTPUT
);

digitalWrite(
    BUZZER_PIN,
    LOW
);

digitalWrite(
    RED_LED_PIN,
    LOW
);

digitalWrite(
    GREEN_LED_PIN,
    HIGH
);

temperatureSensor.begin();

attachInterrupt(
    digitalPinToInterrupt(
        FLOW_SENSOR_PIN
    ),
    pulseCounter,
    RISING
);

WiFi.begin(
    WIFI_SSID,
    WIFI_PASSWORD
);

while (
    WiFi.status()
    != WL_CONNECTED
)
{
    delay(500);

    Serial.print(".");
}

Serial.println();

Serial.println(
    "WiFi Connected"
);

Serial.println(
    WiFi.localIP()
);

lastTime = millis();
```

}

void loop()
{
readFlowData();

```
readTemperature();

detectLeakage();

if (
    millis()
    -
    lastSendTime
    >=
    30000
)
{
    sendDataToPHP();

    sendDataToThingSpeak();

    lastSendTime =
    millis();
}

delay(1000);
```

}

void readFlowData()
{
unsigned long currentTime =
millis();

```
if (
    currentTime
    -
    lastTime
    >=
    1000
)
{
    noInterrupts();

    unsigned long pulses =
    pulseCount;

    pulseCount = 0;

    interrupts();

    flowRate =
    pulses
    /
    FLOW_CALIBRATION;

    float litersPerSecond =
    flowRate
    /
    60.0;

    totalLiters +=
    litersPerSecond;

    Serial.print(
        "Flow Rate: "
    );

    Serial.print(
        flowRate
    );

    Serial.println(
        " L/min"
    );

    lastTime =
    currentTime;
}
```

}

void readTemperature()
{
temperatureSensor.requestTemperatures();

```
temperature =
temperatureSensor.getTempCByIndex(
    0
);
```

}

void detectLeakage()
{
int leakValue =
analogRead(
LEAK_SENSOR_PIN
);

```
bool physicalLeakDetected =
leakValue > 1500;

bool continuousFlow =
flowRate > MIN_LEAK_FLOW;

if (
    continuousFlow
)
{
    if (
        continuousFlowStart
        ==
        0
    )
    {
        continuousFlowStart =
        millis();
    }
}

else
{
    continuousFlowStart =
    0;
}

bool longContinuousFlow =
continuousFlowStart > 0
&&
millis()
-
continuousFlowStart
>
LEAK_TIME_LIMIT;

if (
    physicalLeakDetected
    ||
    longContinuousFlow
)
{
    digitalWrite(
        RED_LED_PIN,
        HIGH
    );

    digitalWrite(
        GREEN_LED_PIN,
        LOW
    );

    digitalWrite(
        BUZZER_PIN,
        HIGH
    );

    Serial.println(
        "POSSIBLE WATER LEAKAGE"
    );
}

else
{
    digitalWrite(
        RED_LED_PIN,
        LOW
    );

    digitalWrite(
        GREEN_LED_PIN,
        HIGH
    );

    digitalWrite(
        BUZZER_PIN,
        LOW
    );
}
```

}

void sendDataToPHP()
{
if (
WiFi.status()
!=
WL_CONNECTED
)
{
return;
}

```
HTTPClient http;

http.begin(
    SERVER_URL
);

http.addHeader(
    "Content-Type",
    "application/json"
);

String jsonData =
"{";

jsonData +=
"\"device_id\":\"ESP32_WATER_001\",";

jsonData +=
"\"flow_rate\":"
+
String(flowRate)
+
",";

jsonData +=
"\"total_liters\":"
+
String(totalLiters)
+
",";

jsonData +=
"\"temperature\":"
+
String(temperature)
+
",";

jsonData +=
"\"leak_sensor\":"
+
String(
    analogRead(
        LEAK_SENSOR_PIN
    )
);

jsonData +=
"}";

int httpCode =
http.POST(
    jsonData
);

Serial.println(
    httpCode
);

http.end();
```

}

void sendDataToThingSpeak()
{
if (
WiFi.status()
!=
WL_CONNECTED
)
{
return;
}

```
HTTPClient http;

String url =
String(
    THINGSPEAK_URL
)
+
"?api_key="
+
THINGSPEAK_API_KEY
+
"&field1="
+
String(
    flowRate
)
+
"&field2="
+
String(
    totalLiters
)
+
"&field3="
+
String(
    temperature
)
+
"&field4="
+
String(
    analogRead(
        LEAK_SENSOR_PIN
    )
);

http.begin(
    url
);

int httpCode =
http.GET();

Serial.println(
    httpCode
);

http.end();
```

} 
```

10. PHP and MySQL Backend Architecture

```

water-leakage/

├── index.php

├── dashboard.php

├── config.php

├── api/

│   ├── receive_data.php

│   ├── get_latest_data.php

│   └── get_history.php

├── database/

│   └── water_leakage.sql

├── css/

│   └── style.css

└── js/

```
└── dashboard.js
```
```

11. MySQL Database


```

CREATE DATABASE water_leakage;

USE water_leakage;

CREATE TABLE sensor_data (

```
id INT AUTO_INCREMENT PRIMARY KEY,

device_id VARCHAR(100),

flow_rate FLOAT,

total_liters FLOAT,

temperature FLOAT,

leak_sensor INT,

leakage_status VARCHAR(50),

ai_probability FLOAT,

created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
```

); 
```

12. PHP Configuration File


```

connect_error
)
{
die(
"Database connection failed"
);
}

?> 
```

13. PHP ESP32 API


```


"error",

```
        "message" =>
        "Invalid JSON data"
    ]
);

exit;
```

}

$device_id =
$data["device_id"]
??
"UNKNOWN";

$flow_rate =
floatval(
$data["flow_rate"]
??
0
);

$total_liters =
floatval(
$data["total_liters"]
??
0
);

$temperature =
floatval(
$data["temperature"]
??
0
);

$leak_sensor =
intval(
$data["leak_sensor"]
??
0
);

$leakage_status =
"NORMAL";

if (
$flow_rate > 0.5
&&
$leak_sensor > 1500
)
{
$leakage_status =
"POSSIBLE_LEAKAGE";
}

$sql =
"
INSERT INTO sensor_data
(
device_id,
flow_rate,
total_liters,
temperature,
leak_sensor,
leakage_status
)
VALUES (?, ?, ?, ?, ?, ?)
";

$stmt =
$conn->prepare(
$sql
);

$stmt->bind_param(
"sdddis",

```
$device_id,

$flow_rate,

$total_liters,

$temperature,

$leak_sensor,

$leakage_status
```

);

$stmt->execute();

echo json_encode(
[
"status" =>
"success",

```
    "leakage_status" =>
    $leakage_status
]
```

);

?> 
```

14. n8n Automation Workflow

```

ESP32
|
v
Webhook
|
v
Receive JSON
|
v
Calculate Leakage Risk
|
v
AI Agent
|
v
Leakage Probability
|
v
IF Risk >= 60%
|
+---------------------+
|                     |
v                     v
Telegram Alert      Google Sheets
|                     |
v                     v
Voice Alert          Data Logging
|
v
Maintenance Action 
```

n8n Workflow JSON


```

{
"name":
"AI Water Leakage Detection",

```
"nodes":
[

    {
        "name":
        "ESP32 Webhook",

        "type":
        "n8n-nodes-base.webhook",

        "parameters":
        {
            "path":
            "water-leakage",

            "httpMethod":
            "POST"
        }
    },

    {
        "name":
        "Calculate Leakage Risk",

        "type":
        "n8n-nodes-base.code",

        "parameters":
        {
            "jsCode":
            "const data = $json.body || $json;

            let risk = 0;

            if (data.flow_rate > 0.5)
            {
                risk += 25;
            }

            if (data.leak_sensor > 1500)
            {
                risk += 50;
            }

            if (data.flow_rate > 5)
            {
                risk += 25;
            }

            return [{
                json: {
                    ...data,
                    leakage_probability: risk,
                    timestamp:
                    new Date().toISOString()
                }
            }];"
        }
    },

    {
        "name":
        "Leakage Detected?",

        "type":
        "n8n-nodes-base.if",

        "parameters":
        {
            "condition":
            "leakage_probability >= 60"
        }
    },

    {
        "name":
        "Telegram Alert",

        "type":
        "n8n-nodes-base.telegram",

        "parameters":
        {
            "text":
            "WATER LEAKAGE ALERT"
        }
    },

    {
        "name":
        "Google Sheets Log",

        "type":
        "n8n-nodes-base.googleSheets",

        "parameters":
        {
            "operation":
            "append"
        }
    }

]
```

} 
```

15. Telegram Bot Setup

  1. Open Telegram.
  2. Search for BotFather.
  3. Send: /start
  4. Send: /newbot
  5. Enter the bot name.
  6. Enter a unique bot username.
  7. Copy the generated bot token.
  8. Configure the token inside n8n.
Example Telegram Alert
```

WATER LEAKAGE DETECTED

Device:
ESP32_WATER_001

Flow Rate:
5.8 L/min

Leakage Probability:
94%

Action:
Inspect the water pipeline immediately. 
```
```
```

16. Voice Notification Automation

```

Leakage Detected
|
v
AI Creates Alert Text
|
v
Text-to-Speech Service
|
v
Generate Audio File
|
v
Telegram Send Voice Message 
```

Example voice message:

Warning. Possible water leakage has been detected. The current flow rate is 5.8 liters per minute. Please inspect the water pipeline immediately.
```
```

17. Google Sheets Integration

Create a Google Sheet with the following columns:

Column Description
Timestamp Event time
Device ID ESP32 device identity
Flow Rate Current water flow
Total Liters Total water consumption
Temperature Pipe temperature
Leak Sensor Leakage sensor value
AI Probability Leakage probability
AI Decision Normal or Leakage
```
```

18. ThingSpeak Cloud Dashboard Setup

Field Data
Field 1 Flow Rate
Field 2 Total Water Consumption
Field 3 Temperature
Field 4 Leakage Sensor
Field 5 AI Leakage Probability
Field 6 Daily Consumption Prediction
```
```

19. AI Leakage Detection Logic

```

Current Flow Rate
+
Historical Average Flow
+
Flow Duration
+
Time of Day
+
Leak Sensor Value
+
Daily Water Consumption
|
v
AI Agent Analysis
|
v
Leakage Probability
|
+----------------------+
|                      |
v                      v
Normal Usage            Possible Leakage
|                      |
v                      v
Data Logging             Telegram Alert
|
v
Voice Alert 
```

Example AI Decision

Flow Rate: 5.8 L/min

Time: 02:30 AM

Historical Average: 0.2 L/min

Leakage Probability: 94%

Recommendation: Immediately inspect the main water pipeline.

```
```

20. AI Water Consumption Prediction

```

Average Daily Consumption

=

## Total Water Used

Number of Days 
```
```

IF current_usage

>

historical_average
*
1.5

THEN

HIGH CONSUMPTION ALERT 
```

Example

```

Historical Average = 800 Liters

Threshold = 800 x 1.5

Threshold = 1200 Liters

Current Consumption = 1500 Liters

Result:

ABNORMAL WATER CONSUMPTION 
```

21. Complete End-to-End Data Flow

```

Water Flow
|
v
Flow Sensor
|
v
ESP32
|
+--------------------> Local Buzzer
|
+--------------------> PHP API
|                            |
|                            v
|                      MySQL Database
|                            |
|                            v
|                      IoT Web Dashboard
|
+--------------------> ThingSpeak
|
+--------------------> n8n Webhook
|
v
AI Agent
|
v
Leakage Probability
|
+-------------+-------------+
|             |             |
v             v             v
Telegram      Voice Alert    Google Sheets
Message       Audio Alert    Data Logging 
```

22. Step-by-Step Installation

Step 1: Hardware Installation

Connect the water flow sensor, leakage sensor, temperature sensor, buzzer, LEDs, and optional ultrasonic sensor to the ESP32.

Step 2: ESP32 Programming

Install Arduino IDE and ESP32 board support. Install required libraries. Configure Wi-Fi and API credentials. Upload the ESP32 program.

Step 3: Web Server Setup

Install Apache, PHP, and MySQL. Copy the project files to the server. Create the water_leakage database.

Step 4: API Testing

Send test JSON data to the PHP API and confirm that the data is inserted into the MySQL database.

Step 5: n8n Configuration

Configure the webhook, AI Agent, IF condition, Telegram node, voice notification node, and Google Sheets node.

Step 6: ThingSpeak Configuration

Create a ThingSpeak channel and configure the required fields.

Step 7: Complete Testing

Test normal flow, small leakage, continuous flow, and pipe burst conditions.

```
```

23. Testing Procedure

Test Input Expected Result
Normal Condition Flow = 0 Normal Status
Small Leakage Low Continuous Flow Warning Alert
Major Leakage High Flow Telegram + Voice Alert
Pipe Burst Sudden Very High Flow Critical Alert
```
```

24. Security Recommendations

Never expose Wi-Fi passwords, Telegram bot tokens, ThingSpeak API keys, database passwords, or AI API keys inside public source code.

Use environment variables, server-side configuration, HTTPS, authentication, and encrypted credentials.

```
```

25. Future Enhancements

Automatic Water Valve Control

Add a relay and solenoid valve. Automatically close the main water supply when critical leakage is detected.

Multiple ESP32 Nodes

Install sensors in kitchens, bathrooms, gardens, tanks, and industrial pipelines.

Predictive Maintenance

Predict pipe degradation, repeated leakage, increasing water usage, and possible future failures.

Mobile Application

Create Android, iOS, Flutter, or React Native applications.

AI Voice Assistant

Ask the AI system: "Is there any water leakage?"

```
```

26. Final Project Summary

This project combines ESP32, IoT sensors, Wi-Fi, PHP, MySQL, n8n automation, AI Agent technology, Telegram notifications, voice alerts, Google Sheets, and ThingSpeak cloud monitoring.

The result is an intelligent Agentic IoT water management platform capable of monitoring water flow, detecting leakage, analyzing abnormal usage, predicting consumption, and automatically notifying users.

```
```

27. Recommended Final Project Title

AI-Powered Agentic IoT-Based Smart Water Leakage Detection and Predictive Water Consumption Monitoring System Using ESP32, n8n Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak Cloud Dashboard

```
```

AI-Based Smart Water Leakage Detection and Alert System

ESP32 | AI Agent | Agentic IoT | n8n | Telegram Voice Alerts | Google Sheets | ThingSpeak

Smart Water Monitoring System 🚀

```