ReadSonar Arduino Sketch

This sketch is used by Exercise: Read Ultrasonic Ranger.

Full Source Code

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

  1// ReadSonar - measure distance using a HC-SR04 or compatible ultrasonic ranger
  2//
  3// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
  4// terms of the BSD 3-clause license as included in LICENSE.
  5//
  6// This program assumes that:
  7//
  8//  1. A SR04 sonar is connected: as follows: pin 8 is TRIG, pin 7 is ECHO.
  9//     Note: this sensor has +5V digital outputs can connect directly to the
 10//     digital input pins on the Arduino UNO.
 11//
 12//  2. The serial console on the Arduino IDE is set to 9600 baud communications speed.
 13//
 14// Note: this works, but could still use refinement.  The actual module echo
 15// waveform doesn't quite match the description, there appears to be an initial
 16// HIGH pulse prior to the LOW during propagation time.  A better solution may
 17// be to use the NewPing library.
 18
 19// ================================================================================
 20// Define constant values.
 21
 22// The wiring assignment.
 23const int TRIG_PIN = 8;
 24const int ECHO_PIN = 7;
 25
 26// The rated distance limit of the sensor, in cm.
 27const int MAX_DISTANCE = 450;
 28
 29// A typical speed of sound, specified in cm/sec.
 30const long SOUND_SPEED = 34000;
 31
 32// Determine the maximum time to wait for an echo. The maximum rated distance is
 33// 4.5 meters; if no echo is received within the duration representing this
 34// round-trip distance, stop measuring.  The timeout is specified in
 35// microseconds.
 36const long TIMEOUT = (2 * MAX_DISTANCE * 1000000)/SOUND_SPEED;
 37
 38// ================================================================================
 39// Configure the hardware once after booting up.  This runs once after pressing
 40// reset or powering up the board.
 41
 42void setup()
 43{
 44  // Initialize the serial UART at 9600 bits per second.
 45  Serial.begin(9600);
 46
 47  // Initialize the trigger pin for output.
 48  pinMode(TRIG_PIN, OUTPUT);
 49  digitalWrite(TRIG_PIN, LOW);
 50  
 51  // Initialize the echo pin for input.
 52  pinMode(ECHO_PIN, INPUT);
 53}
 54// ================================================================================
 55// Run one iteration of the main event loop.  The Arduino system will call this
 56// function over and over forever.
 57void loop()
 58{
 59  // Read the distance as an uncalibrated timing value in microseconds.
 60  long duration = ping_sonar(); // function is defined below
 61
 62  // If valid, scale into real-world units.
 63  if (duration > 0) {
 64
 65    // Convert to a distance.  Note that the speed of sound is specified in
 66    // cm/sec, so the duration is scaled from microsecondst o seconds.  The
 67    // factor of 2 accounts for the round-trip doubling the time.
 68    float distance = (duration * 1e-6 * SOUND_SPEED) / 2;
 69
 70    Serial.print("Ping: ");
 71    Serial.print(duration);
 72    Serial.print(" usec   Distance: ");
 73    Serial.print(distance);
 74    Serial.println(" cm");
 75
 76  } else {
 77    // if no pulse detected
 78    Serial.println("No ping.");
 79  }
 80
 81  // Allow a little extra time for the sonar to recover.
 82  delay(30);
 83}
 84
 85// ================================================================================
 86// Ping function to run one measurement cycle using the sonar.  Returns a ping
 87// travel duration in microseconds, or 0 if no echo was observed.
 88
 89long ping_sonar(void)
 90{
 91  // Generate a short trigger pulse.
 92  digitalWrite(TRIG_PIN, HIGH);
 93  delayMicroseconds(10);
 94  digitalWrite(TRIG_PIN, LOW);
 95
 96  // Measure the pulse length
 97  return pulseIn(ECHO_PIN, HIGH, TIMEOUT);
 98}
 99
100// ================================================================================