// Define pins for HC-SR04
const int trigPin = 18;
const int echoPin = 19;
// Variable to store the duration of sound wave travel
long duration;
// Variable to store the calculated distance
int distance;
void setup() {
// Begin serial communication at a baud rate of 115200:
pinMode(12, OUTPUT);
Serial.begin(115200);
// Set the trigPin as an OUTPUT:
pinMode(trigPin, OUTPUT);
// Set the echoPin as an INPUT:
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin HIGH for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
// Speed of sound wave divided by 2 (there and back) in cm:
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor:
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if(distance>=350)
{
digitalWrite(12, LOW);
Serial.println("OBJECT NEARER");
}
else if(distance>=150)
{
digitalWrite(12, HIGH);
Serial.println("OBJECT IS LONGER");
}
// Wait for 100 milliseconds before taking the next measurement
delay(100);
}