How to interface the HC-SR04 ultrasonic ranging module to Arduino

If you are sourcing an ultrasonic ranging module, the HC-SR04 is a good choose . Its stable performance and high ranging accuracy  make it a popular module in electronic market.

Specifications:

  • power supply        :  5V DC
  • quiescent current :  <=2mA
  • effectual angle     :  <= 15°
  • ranging distance  :  3 cm – 400 cm
  • resolution             :  0.3 cm



There are 4 pins out of the module : VCC , Trig, Echo, GND . So it’s a very easy interface for controller to use it ranging. 

 

  • Pull the Trig pin to high level  for more than 10us impulse, so the module starts ranging;
  • If you find an object in front , Echo pin will be high level, and based on the different distance, it will take the different duration of high level. 
  • Compute the distance: Distance = ((Duration of high level)*(Sonic :340m/s))/2

Here you are a simple sketch, to work with it you must connect the hc-sr04 to your arduino board using the following scheme:

 


/*
 * Define the pins you want to use as trigger and echo.
 */

#define ECHOPIN 2        // Pin to receive echo pulse
#define TRIGPIN 3        // Pin to send trigger pulse

/*
 * setup function
 * Initialize the serial line (D0 & D1) at 115200.
 * Then set the pin defined to receive echo in INPUT 
 * and the pin to trigger to OUTPUT.
 */
 
void setup()
{
  Serial.begin(115200);
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
}

/*
 * loop function.
 * 
 */
void loop()
{
  // Start Ranging
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);
  // Compute distance
  float distance = pulseIn(ECHOPIN, HIGH);
  distance= distance/58;
  Serial.println(distance);
  delay(200);
}


We have some of these sensors, if you are interested take a look here.

 

Gg1