// Define pins for ultrasonic sensor
const int trigPin = 9;
const int echoPin = 10;
// Define pins for LEDs
const int redLED = 2;
const int blueLED = 3;
const int yellowLED = 4;
const int greenLED = 5;
// Variable for distance measurement
long duration;
int distance;
// Container depth in cm (adjusted to 400 cm)
const int containerDepth = 400; // Maximum depth of the container in cm
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLED, OUTPUT);
pinMode(blueLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
}
void loop() {
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo response
duration = pulseIn(echoPin, HIGH);
// Calculate distance
distance = duration * 0.034 / 2;
// Calculate percentage
int percentage = map(distance, containerDepth, 0, 0, 100);
// Clamp percentage to 0-100 range
if (percentage < 0) percentage = 0;
if (percentage > 100) percentage = 100;
// Display percentage in Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, Percentage: ");
Serial.print(percentage);
Serial.println("%");
// Control LEDs based on percentage
if (percentage <= 25) {
setLEDs(HIGH, LOW, LOW, LOW); // Red LED
} else if (percentage <= 50) {
setLEDs(LOW, HIGH, LOW, LOW); // Blue LED
} else if (percentage <= 75) {
setLEDs(LOW, LOW, HIGH, LOW); // Yellow LED
} else {
setLEDs(LOW, LOW, LOW, HIGH); // Green LED
}
// Delay for stability
delay(500);
}
// Function to control LEDs
void setLEDs(int red, int blue, int yellow, int green) {
digitalWrite(redLED, red);
digitalWrite(blueLED, blue);
digitalWrite(yellowLED, yellow);
digitalWrite(greenLED, green);
}