/* Modified sketch taken from * Rui Santos, https://randomnerdtutorials.com */ // defines pins numbers int trigPin = 9; //Trigger int echoPin = 10; //Echo long duration, cm; //Time between the emission and reception of the signal int distance; // defines variables void setup() { //Serial Port begin Serial.begin (9600); //Initialize the serial port at a baud rate of 9600 and start serial communication //Define inputs and outputs pinMode(trigPin, OUTPUT); //trigger pin as an output pinMode(echoPin, INPUT); //echo pin as an input } void loop() { // The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor: a HIGH pulse whose // duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance distance= duration*0.034/2; if (distance >= 400 || distance <= 2){ Serial.print("Out of range"); Serial.println(); } else { // Prints the distance on the Serial Monitor Serial.print("Distance, cm: "); Serial.println(distance); } delay(1000); }