Home > Projects > Other Projects > Arduino Sketch Read Sonar

Arduino Sketch Read Sonar

Summary of Arduino Sketch Read Sonar


This Arduino sketch measures distance with an HC‑SR04 ultrasonic ranger (TRIG on pin 8, ECHO on pin 7). It sends a 10 μs trigger pulse, times the echo using pulseIn with a timeout, converts duration to centimeters using sound speed, and prints results to the serial console at 9600 baud. If no echo is received within the timeout, it reports No ping. A 30 ms delay allows sensor recovery between measurements.

Parts used in the ReadSonar:

  • Arduino (for example Arduino UNO)
  • HC-SR04 ultrasonic ranger
  • Wires for connections (TRIG to pin 8, ECHO to pin 7, VCC, GND)
  • USB cable for serial console / power

This sketch is used by Exercise: Read Ultrasonic Ranger.

Full Source Code

The full code is all in one file ReadSonar.ino.

// ReadSonar - measure distance using a HC-SR04 or compatible ultrasonic ranger
//
// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
// terms of the BSD 3-clause license as included in LICENSE.
//
// This program assumes that:
//
//  1. A SR04 sonar is connected: as follows: pin 8 is TRIG, pin 7 is ECHO.
//     Note: this sensor has +5V digital outputs can connect directly to the
//     digital input pins on the Arduino UNO.
//
//  2. The serial console on the Arduino IDE is set to 9600 baud communications speed.
//
// Note: this works, but could still use refinement.  The actual module echo
// waveform doesn't quite match the description, there appears to be an initial
// HIGH pulse prior to the LOW during propagation time.  A better solution may
// be to use the NewPing library.

// ================================================================================
// Define constant values.

// The wiring assignment.
const int TRIG_PIN = 8;
const int ECHO_PIN = 7;

// The rated distance limit of the sensor, in cm.
const int MAX_DISTANCE = 450;

// A typical speed of sound, specified in cm/sec.
const long SOUND_SPEED = 34000;

// Determine the maximum time to wait for an echo. The maximum rated distance is
// 4.5 meters; if no echo is received within the duration representing this
// round-trip distance, stop measuring.  The timeout is specified in
// microseconds.
const long TIMEOUT = (2 * MAX_DISTANCE * 1000000)/SOUND_SPEED;

// ================================================================================
// Configure the hardware once after booting up.  This runs once after pressing
// reset or powering up the board.

void setup()
{
  // Initialize the serial UART at 9600 bits per second.
  Serial.begin(9600);

  // Initialize the trigger pin for output.
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);
  
  // Initialize the echo pin for input.
  pinMode(ECHO_PIN, INPUT);
}
// ================================================================================
// Run one iteration of the main event loop.  The Arduino system will call this
// function over and over forever.
void loop()
{
  // Read the distance as an uncalibrated timing value in microseconds.
  long duration = ping_sonar(); // function is defined below

  // If valid, scale into real-world units.
  if (duration > 0) {

    // Convert to a distance.  Note that the speed of sound is specified in
    // cm/sec, so the duration is scaled from microsecondst o seconds.  The
    // factor of 2 accounts for the round-trip doubling the time.
    float distance = (duration * 1e-6 * SOUND_SPEED) / 2;

    Serial.print("Ping: ");
    Serial.print(duration);
    Serial.print(" usec   Distance: ");
    Serial.print(distance);
    Serial.println(" cm");

  } else {
    // if no pulse detected
    Serial.println("No ping.");
  }

  // Allow a little extra time for the sonar to recover.
  delay(30);
}

// ================================================================================
// Ping function to run one measurement cycle using the sonar.  Returns a ping
// travel duration in microseconds, or 0 if no echo was observed.

long ping_sonar(void)
{
  // Generate a short trigger pulse.
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Measure the pulse length
  return pulseIn(ECHO_PIN, HIGH, TIMEOUT);
}

// ================================================================================

Source: Arduino Sketch ReadSonar

Quick Solutions to Questions related to ReadSonar:

  • What pins are used for TRIG and ECHO?
    TRIG is on pin 8 and ECHO is on pin 7 as defined in the sketch.
  • How is the trigger pulse generated?
    The code sets TRIG pin HIGH for 10 microseconds then LOW to generate the trigger pulse.
  • How is the echo measured?
    The sketch uses pulseIn on the ECHO pin to measure the echo pulse length in microseconds with a timeout.
  • How is distance calculated?
    Distance is computed from duration using SOUND_SPEED (34000 cm/s), converting microseconds to seconds and dividing by 2 for round trip.
  • What happens if no echo is received?
    The code prints No ping when pulseIn times out and returns 0.
  • What serial speed should be used?
    The serial console is initialized at 9600 baud in setup.
  • What timeout is used for waiting for an echo?
    TIMEOUT is computed from MAX_DISTANCE (450 cm) and SOUND_SPEED to cover the round-trip time up to that distance.
  • Why is there a delay after each measurement?
    There is a 30 ms delay to allow the sonar to recover between measurements.

About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:
LinkedinTwitter
Scroll to Top