Testing Ultrasonic Sensor with Arduino Nano

Recently bought a HC_SR04 sensor for my Arduino and testing it with NewPing library. Main problem was wiring because, I’m using Arduino Nano and there is no internet resources available on how to wire this.


The sensor comes with 4 pins

  1. VCC
  2. Trig
  3. Echo
  4. GND

VCC and GND are for power purposes. Trig is the pin the instruct the sensor to send a ping. Trig  invokes sending 8 cycles of 40KHz audio for a period of not less than 10 microseconds from the transmitter. Then you have Echo that is the detector for the audio.


I have connected the pins in the following way

HC_SR04 Arduino Nano
Trig D3
Echo D2


It is a simple logic. If the distance is less than 5cm, power the LED on.

#include < NewPing.h >

#define TRIGGER_PIN 3 //Trig
#define ECHO_PIN 2    //Echo
#define MAX_DIST 200  //200 centimeter

int led = 13;

void setup() {

void loop() {
  delay(50); //50 millisecond delay
  unsigned int ultrSonic = sonar.ping();

  if ((ultrSonic / US_ROUNDTRIP_CM) < 5) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);

US_ROUNDTRIP_CM is available via NewPing.h file. We use (ultrSonic / US_ROUNDTRIP_CM) operation to convert ping time to distance.

Thats all. Finally output was


2 thoughts on “Testing Ultrasonic Sensor with Arduino Nano

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s