#define TRIG_PIN 9
#define ECHO_PIN 10
#define RED_LED_PIN 3 // Define the pin for the red LED
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RED_LED_PIN, OUTPUT); // Set red LED pin as OUTPUT
}
void loop() {
long duration;
float distance;
// Trigger the ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the pulse duration
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
distance = (duration * 0.034) / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than 20 centimeters (20 cm)
if (distance < 20) {
digitalWrite(RED_LED_PIN, HIGH); // Turn on the red LED
} else {
digitalWrite(RED_LED_PIN, LOW); // Turn off the red LED
}
delay(1000); // Delay for 1 second before the next reading
}