// Define the pins for ultrasonic sensor
const int trigPin = 2;
const int echoPin = 3;
// Variables for calculating distance
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set trigPin as OUTPUT and echoPin as INPUT
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Send a short ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
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 100cm
if (distance < 100) {
// Perform the desired action
// Replace the following line with your desired action
Serial.println("Object is too close!");
}
delay(500); // Delay before the next measurement
}