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


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.


  • 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()
  pinMode(ECHOPIN, INPUT);

 * loop function.
void loop()
  // Start Ranging
  digitalWrite(TRIGPIN, LOW);
  digitalWrite(TRIGPIN, HIGH);
  digitalWrite(TRIGPIN, LOW);
  // Compute distance
  float distance = pulseIn(ECHOPIN, HIGH);
  distance= distance/58;

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



You may also like...

7 Responses

  1. raphael says:

    Hey guys 
    I'am Brazilian so sorry for english. I had been studing the header file of the library and i discovered a way to make the library work again well on the IDE 1.0.1 of arduino. inside de header file and the .cpp archive you just need to replace de library included wprogram.h for the library Arduino.h and them the your life will become prety simple.

  2. admin says:

    Thank you for this tip

  3. Justin says:

    What is the unit for the distance?(Centimeters, Millimeters, etc.)

  4. admin says:

    I have not a sensor now, but for that I remember the output should be in millimeters

  5. Edwin says:

    Just made some tests. and it looks like it's cm.
    also it get nothing under 2 cm …

  6. Nicu FLORICA says:

    very simple and good article, I followed the steps and am very pleased.. In addition, I connected a LCD display

  7. doss says:

    can i use the current output from sensor for other purpose. how

Leave a Reply

Your email address will not be published. Required fields are marked *