int trigPin = 3; // sends out signal
int echoPin = 2; // Receives signals
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// READ THE RESULTS
int duration = pulseIn(echoPin, HIGH); // measuring the time it takes
// for the signal to return
Serial.print(" Distance in cm: ");
Serial.println(duration/58); // converts to cm
Serial.print("Distance in inches: ");
Serial.print(duration/148); // converts to inches
if (duration / 50 < 100)
{
Serial.println(" You are too close "); // if closer then 100cm
}
else if ((duration / 50 > 100) & (duration / 58 < 400))
{
Serial.println(" you are in range "); // if in between 100-400cm than is prints ot you are in range
}
else if (duration / 50 > 400)
{
Serial.println(" you are too far "); // if farther then 400cm
}
delay(1000);
}