Arduino And Sensors Part I

You can divide Arduino add ons to two categories. First one are shields that are going to connect in the Arduino GPIO and be stacked on top of each other. Some examples are: The other kind of add ons are sensors that are not part of a shield. For example: The sensor that we are going to use today, however, is the SainSmart HC-SR04 Ranging Detector Mod Distance Sensor (Blue) sensor. Here are some images of that sensor
  • HCSR04 Front View
  • HCSR04 Back View
  • HCSR04 Side View

The HCSR04, unlike the Parallax Ping Sensor, has 4 pings:

  • VCC+ - the 5V rail
  • Trigger - this is what sends the sound initially
  • Echo - this is what receives the sound back
  • GND - Ground rail

The process that you will need to do with this sensor is fairly simple. First step you send a high to the trigger pin. Than you will wait for echo to become High as well. That will give you the duration the sound travel. Knowing the speed of sound you can convert that to distance with the time.

So I didn't want to write the same code over and over again on each project that I want to use, or if I want to use more than one Ping sensor within the same project.
Therefore, i have created an Arduino Library that will do all we need to get the distance. You can download the library here: HCSR04.zip After the download finishes, you will need to extract the zip file under your Arduino folder -> libraries. If you have the Arduino IDE session you will need to close it and restart it to pick up the new library.

Here is a sample code that you can find in the downloadable zip file above.

#include <HCSR04.h>
// Constructor
// HCSR04(Echo,Trigger,IsInches)
// HCSR04(pinNumber,pinNumber, boolean)
HCSR04 ping = HCSR04(10,11,true)

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    Serial.print("Distance in Inches:");
    Serial.println(ping.Distance());
}

Here is how the connection to the Ping sensor and the Arduino board

  • Ping Board Example
  • Ping Connections
  • Arduino Board Connections

You can download the manual here