/*
ESP32 Distance Sensor
WARNING: In a real circuit you'll need level shifters
between the ESP32 and the active components!!!!
Wokwi | questions
LuckybossX2 [UE], Monday, June 15, 2026 12:08 PM
my project is The Sea Trash Collection Project uses an ESP32 microcontroller
as the main controller, HC-SR04 ultrasonic sensors to detect floating waste,
DC motors controlled by an L298N motor driver to move the boat on water,
a servo motor to operate the collection net, LEDs and a buzzer for status
and alerts, an LCD display with potentiometer for information display,
and a mobile application for real-time monitoring and control.
Together, these components form an intelligent autonomous system designed
to detect, navigate, and collect marine waste to help reduce ocean pollution
https://wokwi.com/projects/466907431854771201?gh=1
*/
#include <LiquidCrystal.h>
#include <ESP32Servo.h>
// HC-SR04
#define TRIG_PIN 33
#define ECHO_PIN 32
// Servo
#define SERVO_PIN 19
// Buzzer
#define BUZZER_PIN 21
// LEDs
#define GREEN_LED 23
#define RED_LED 22
// LCD: RS, E, D4, D5, D6, D7
LiquidCrystal lcd(13, 12, 14, 27, 26, 25);
Servo net;
int trashCount = 0;
float getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0)
return 999;
return duration * 0.0343 / 2;
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
pinMode(RED_LED, OUTPUT);
net.attach(SERVO_PIN);
net.write(0);
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("SeaGuardian");
lcd.setCursor(0, 1);
lcd.print("Starting...");
delay(2000);
lcd.clear();
digitalWrite(GREEN_LED, HIGH);
}
void loop() {
float distance = getDistance();
Serial.print("Distance: ");
Serial.println(distance);
lcd.setCursor(0, 0);
lcd.print("Dist:");
lcd.print((int)distance);
lcd.print(" cm ");
lcd.setCursor(0, 1);
lcd.print("Trash:");
lcd.print(trashCount);
lcd.print(" ");
// إذا كانت النفايات قريبة
if (distance < 15) {
digitalWrite(GREEN_LED, LOW);
digitalWrite(RED_LED, HIGH);
tone(BUZZER_PIN, 1000);
// فتح الشبكة
net.write(90);
delay(1500);
// إغلاق الشبكة
net.write(0);
noTone(BUZZER_PIN);
trashCount++;
delay(1000);
}
else {
digitalWrite(GREEN_LED, HIGH);
digitalWrite(RED_LED, LOW);
noTone(BUZZER_PIN);
}
delay(300);
}