Tags

, , , ,

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.

X2dK8

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.

Wring

I have connected the pins in the following way

HC_SR04 Arduino Nano
5V VCC
Trig D3
Echo D2
GND GND

Code

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;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DIST);

void setup() {
  Serial.begin(115200);
}

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

 

Advertisements