Challenge

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

Live batch Preeti mam

#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
// Define inputs and outputs:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

//Begin Serial communication at a baudrate of 9600:
Serial.begin(9600);
}

void loop() {
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);

// Trigger the sensor by setting the trigPin high for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration * 0.034 / 2;

serial.print ("distance: ");

serial.print (distance);

serial.println ("centimeter");

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.