Challenge

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

#define TRIG_PIN 2

#define ECHO_PIN 3

void setup() {

  Serial.begin(9600);

  pinMode(TRIG_PIN, OUTPUT);

  pinMode(ECHO_PIN, INPUT);

}

void loop() {

  // Send a short pulse to the trigger pin

  digitalWrite(TRIG_PIN, LOW);

  delayMicroseconds(2);

  digitalWrite(TRIG_PIN, HIGH);

  delayMicroseconds(10);

  digitalWrite(TRIG_PIN, LOW);

  // Measure the duration of the echo pulse

  long duration = pulseIn(ECHO_PIN, HIGH);

  // Calculate the distance in centimeters

  float distance = duration * 0.034 / 2;

  // Print the distance to the serial monitor

  Serial.print("Distance: ");

  Serial.print(distance);

  Serial.println(" cm");

  delay(500);

}

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.