#include <Arduino.h>
const int trigPin = 12; // Pin connected to the trigger pin of the sensor
const int echoPin = 13; // Pin connected to the echo pin of the sensor
const int ledPin = 2; // Pin connected to the LED
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT);// Set the trigger pin as output
pinMode(echoPin, INPUT); // Set the echo pin as input
pinMode(ledPin, OUTPUT); // Set the LED pin as output
}
void loop() {
long duration, distance; // Define variables for duration and distance
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If the distance is between 4 and 30 cm, turn on the LED, otherwise turn it off
if (distance >= 4 && distance <= 30) {
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
delay(1000); // Wait for a second before taking the next measurement
}