Our sonar device has 4 pins:

  • +5 (Vcc)
  • Trigger
  • Echo
  • Gnd

 

We apply a very short positive-going pulse to Trigger pin.

The device sends an ultrasonic “ping” and waits for an echo to return.

Then the Echo pin will send us back a pulse, as long as the echo took to return.

So if we measure the echo pulse length, then, knowing speed of sound through air, we can determine how far away the echoing object was.

 

TRIGGER PIN – pin 4

ECHO PIN – pin 6

 

Paste the script below into a blank arduino edit window, and SAVE AS        “sonar”

 

 

 

Script:

 

 

#define TRIGGER_PIN  4
#define ECHO_PIN     6
#define LED         13

void setup()
  {
  Serial.begin(9600);
  Serial.println("Ultrasonic - Sonar - HC-SR04");
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED, OUTPUT);
  }

void loop()
  {
  int cm;
  long microsec = USonic_timing();
  cm = microsec / 70;   // sound speed about 35 uSec/cm in air - Round path 35x2 = 670
  Serial.print("Dist (cm): ");
  Serial.println(cm);

  delay(1000);
  }

long USonic_timing()
    {
    // 0. just be sure we start from low:
    digitalWrite(TRIGGER_PIN, LOW);
    delayMicroseconds(2);

    // 1. pulse the trigger pin high for 10 usec:
    digitalWrite(TRIGGER_PIN, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGGER_PIN, LOW);

    // 2. now measure the length of pulse on echo pin:
    digitalWrite(LED, HIGH);
    long puls = pulseIn(ECHO_PIN, HIGH);
    digitalWrite(LED, LOW);
    return puls;
    }