const int trigPin = 9; // Trig pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
const int led1Pin = 12; // Pin for the first LED
const int led2Pin = 13; // Pin for the second LED
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Trigger the ultrasonic sensor to send a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters (speed of sound is 343 m/s or 0.0343 cm/microsecond)
int distance = duration * 0.0343 / 2;
// Print the distance on the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Control LEDs based on the distance measured
if (distance < 20) {
// If the distance is less than 20 cm, turn on both LEDs
digitalWrite(led1Pin, HIGH);
digitalWrite(led2Pin, HIGH);
} else {
// If the distance is 20 cm or more, turn off both LEDs
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
}
// Wait for a short duration before taking the next measurement
delay(1000);
}