Using the ultrasound sensor HC SR04

My first foray into Ardunio programming is to implement a robot based upon the Arduino Motor shield and some sensors – starting with the HC SR04.

In this case I want a sensor that will tell me the distance from objects, so hopefully the robot will not go around smashing into walls etc. This is where the HC SR04 comes in.

The HC SR04 has four pins. We simply connect the VCC pin to the 5V pin on the Arduino, the GND to the Arduino’s ground pin and then we’re left with two other pins.

The trigger and echo pins are digital pins, the idea being we send a 10 microsecond pulse to the trigger pin and the module will send back (via the echo pin) a value whose duration we can use to calculate the distance “pinged”. But we don’t just read the digital pin, we instead use the pulseIn function.

I’m indebted to others who have kindly supplied information on how to program this sensor, I’ve added references at the bottom of this post. I’m writing this post simply to detail the steps and code I successfully used to get this working. The referenced posts are definitely the best posts for full information on this sensor, hardware connections and code.

Here’s a simple C++ class (header and source) for handling this sensor

#ifndef _ULTRASOUND_h
#define _ULTRASOUND_h

#if defined(ARDUINO) && ARDUINO >= 100
   #include "Arduino.h"
#else
   #include "WProgram.h"
#endif

class Ultrasound
{
private:
	int triggerPin;
	int echoPin;

public:

	void init(int tiggerPin, int echoPin);
	long ping();
};

#endif

and the corresponding source

#include "Ultrasound.h"

void Ultrasound::init(int triggerPin, int echoPin)
{
   this->triggerPin = triggerPin;
   this->echoPin = echoPin;

   pinMode(triggerPin, OUTPUT);
   pinMode(echoPin, INPUT);
}

long Ultrasound::ping()
{
   digitalWrite(triggerPin, LOW);
   delayMicroseconds(2);
   digitalWrite(triggerPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(triggerPin, LOW);

   long duration = pulseIn(echoPin, HIGH);
   long distance = (duration / 2) / 29.1;
   // >= 200 or <= 0 are error values, or out of range
   return distance >= 200 || distance <= 0 ? -1 : distance;
}

References

Ultrasonic Ranging Module HC – SR04
Simple Arduino and HC-SR04 Example
Complete Guide for Ultrasonic Sensor HC-SR04