// Define constants for the hypersonic sensor pins
const int trigPin = 7;
const int echoPin = 6;
// Define constants for the LED bar graph pins
const int ledPins[] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Configure the hypersonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Configure the LED bar graph pins as OUTPUT
for (int i = 0; i < 10; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
// Trigger the hypersonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the distance from the sensor
long duration = pulseIn(echoPin, HIGH);
int distance = duration / 58; // Convert the duration to distance in centimeters
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Update the LED bar graph based on distance
updateLEDBarGraph(distance);
// Delay before the next reading
delay(500);
}
void updateLEDBarGraph(int distance) {
// Define the distance ranges for different LED colors
int distanceRanges[] = {10, 20, 30, 40, 50, 60, 70, 80, 100, 120};
// Loop through the LED bar graph pins and set their states
for (int i = 0; i < 10; i++) {
if (distance >= distanceRanges[i]) {
digitalWrite(ledPins[i], LOW);
} else {
digitalWrite(ledPins[i], HIGH);
}
}
}