// Include the Ultrasonic library
#include <Ultrasonic.h>
// Define the pins for the ultrasonic sensor, LEDs, and buzzer
#define TRIGGER_PIN 11
#define ECHO_PIN 12
#define LED_PIN_1 7
#define LED_PIN_2 6
#define LED_PIN_3 5
// Create an Ultrasonic object
Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);
// Define a variable to store the distance measured by the sensor
long distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set LED pins as output
pinMode(LED_PIN_1, OUTPUT);
pinMode(LED_PIN_2, OUTPUT);
pinMode(LED_PIN_3, OUTPUT);
}
void loop() {
// Measure the distance
distance = ultrasonic.read();
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Determine how many LEDs to turn on based on the distance
if (distance < 7) {
blinkLED(LED_PIN_1); // Blink LED 1
digitalWrite(LED_PIN_2, LOW);
digitalWrite(LED_PIN_3, LOW);
} else if (distance >= 7 && distance < 11) {
blinkLED(LED_PIN_1); // Blink LED 1
blinkLED(LED_PIN_2); // Blink LED 2
digitalWrite(LED_PIN_3, LOW);
} else {
blinkLED(LED_PIN_1); // Blink LED 1
blinkLED(LED_PIN_2); // Blink LED 2
blinkLED(LED_PIN_3); // Blink LED 3
}
// Wait for a short time before taking another measurement
delay(500);
}
// Function to blink an LED
void blinkLED(int pin) {
digitalWrite(pin, HIGH); // Turn on the LED
delay(500); // Wait for 500ms
digitalWrite(pin, LOW); // Turn off the LED
delay(500); // Wait for 500ms
}