Measuring distance in metres using the Arduino and HC-SR04 rangefinder

Same circuit as example in previous post!

//
// Another HC-SR04 rangefinder example for Arduino Nano
// Written by Ted Burke, last updated 13-2-2019
//
// Arduino pins:
//
//    D2 is an output for an indicator LED
//    D5 is an input for the rangefinder's echo pin
//    D6 is an output for the rangefinder's trigger pin
//
 
void setup()
{
  pinMode(2, OUTPUT); // LED
  pinMode(6, OUTPUT); // trigger pin

  // Open a serial connection to display the distance measurements
  Serial.begin(9600);
}
 
void loop()
{
  // Declare variables
  unsigned long tus; // time of flight in microseconds
  double c = 340.0;  // speed of sound in metres per second
  double d;          // distance to object in metres
  
  // Set trigger pulse
  digitalWrite(6, HIGH); // set TRIG to 5V
  delayMicroseconds(200);
  digitalWrite(6, LOW); // set TRIG to 0V

  // Use the pulseIn Arduino function to measure the duration
  // of the echo pulse in microseconds
  tus = pulseIn(5, HIGH, 50000);

  // Calculate the distance in metres
  d = tus * (c / 2e6);

  // Print out the distance over the serial connection
  // To view the printed text, open the "Tools" menu in
  // the Arduino IDE and select "Serial Monitor".
  Serial.print("distance = ");
  Serial.print(d);
  Serial.println(" metres");
 
  // Leave some time before loop function
  // runs again to allow any ultrasound
  // in the room to die away before next
  // measurement. Otherwise, successive
  // pulses will get mixed up!
  delay(100);
}

Here’s how it looks in the Serial Monitor:


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s