// Include the necessary libraries
#include <Arduino.h>
// Define the pins for the ultrasonic sensor
const int trigPin = 2;
const int echoPin = 4;
// Define the pin for the LED
const int ledPin = 14;
// Define the maximum distance in centimeters
const int maxDistance = 500;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the trigger pin as an output
pinMode(trigPin, OUTPUT);
// Set the echo pin as an input
pinMode(echoPin, INPUT);
// Set the LED pin as an output
pinMode(ledPin, OUTPUT);
}
void loop() {
// Trigger the ultrasonic sensor by sending a 10 microsecond 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);
// Convert the duration to distance in centimeters
int distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.println(distance);
// Check if the distance is greater than 300cm
if (distance > 300) {
// Turn on the LED
digitalWrite(ledPin, HIGH);
} else {
// Turn off the LED
digitalWrite(ledPin, LOW);
}
// Delay before taking the next measurement
delay(1000);
}