For this project we will use the ultrasonic sensor and Arduino to measure distance. Copy and paste the sketch below and upload it to the Arduino. The video below uses an LCD display but we will use the serial monitor option of the IDE. So for this project connect your sensor and in the Arduino IDE click on TOOLS and SERIAL MONITOR. The serial monitor will show the distance an object is from the sensor.
SKETCH
const int trigPin=4;
const int echoPin=2;
long duration;
int distance;
void setup (){
pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);
Serial.begin (9600);
}
void loop () {
digitalWrite (trigPin, LOW);
delayMicroseconds (2);
digitalWrite (trigPin, HIGH);
delayMicroseconds (10);
digitalWrite (trigPin, LOW);
duration = pulseIn (echoPin, HIGH);
distance= duration*0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
}