Challenge

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

// This code measures the distance of an object using ultrasonic distance sensor (HC-SR04).

// Define the pins for the ultrasonic sensor.

const int triggerPin = 10;

const int echoPin = 11;

// Define the variables for the distance and the sound speed.

float distance;

float soundSpeed = 340; // m/s

// The setup() function runs once when the Arduino is turned on.

void setup() {

// Set the trigger pin as output.

pinMode(triggerPin, OUTPUT);

// Set the echo pin as input.

pinMode(echoPin, INPUT);

}

// The loop() function runs continuously.

void loop() {

// Send a sound wave to the object.

digitalWrite(triggerPin, HIGH);

delayMicroseconds(10);

digitalWrite(triggerPin, LOW);

// Wait for the sound wave to return.

while (digitalRead(echoPin) == LOW);

// Start a timer.

unsigned long startTime = micros();

// Wait for the sound wave to return.

while (digitalRead(echoPin) == HIGH);

// Stop the timer.

unsigned long stopTime = micros();

// Calculate the distance.

distance = (stopTime - startTime) / 2 * soundSpeed / 1000;

// Print the distance to the serial monitor.

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm"

);

// Wait for a second.

delay(1000);

}

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.