Challenge

Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)

#define echo 8 //defining macros at pin-8 echo pulse

#define trig 9 //defining macro at pin-9 triggering

long duration; //declaration of global variable duration with long data type

int distance; //declaration of global variable distance with long data type

void setup() {

pinMode (trig, OUTPUT); //setting trig pin as output

pinMode (echo, INPUT); //setting echo pin as input

Serial.begin(9600);

}

void loop() {

digitalWrite(trig, LOW); //clear the output pin

delayMicroseconds (2); //wait for 2microsec

digitalWrite(trig, HIGH); //setting output pin to High

delayMicroseconds (10); //delay of 10microsec

digitalWrite(trig, LOW); //clear the output pin

duration = pulseIn (echo, HIGH); //Returning time in microsec

distance = duration*0.034/2; //formula used distance=(sound_speed*time)/2. where time=pulse duration=10microsec and sound_speed=340m/s=0.034cm/microsec.

Serial.print("distance: ");

Serial.print(distance);

Serial.println(" centimeter");

}

Output

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.