Step 1: The code
So I am going to use the newping library - http://playground.arduino.cc/Code/NewPing
This provides a nice level of sophistication that allows faster pings, and also handles the times when the echo isnt found and stops the library from timing out.
You just need to download it from https://bitbucket.org/teckel12/arduino-new-ping/downloads
and save it locally. I'm using the v1.8
Then go into the Arduino IDE and go Sketch -> Include Library -> Add .ZIP library and load the zip file that you have just loaded and the library is now ready to use.
I wanted to use just one pin for trigger and echo and chose Pin 12 and this is the code I used.
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 12
#define MAX_DISTANCE 400
int cm;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
Serial.println("Ready");
}
void loop() {
delay(35);
int uS = sonar.ping();
Serial.print("Ping: ");
cm = sonar.convert_cm(uS);
Serial.print(cm);
Serial.println("cm");
if (cm <= 7 && cm > 0)
{
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
}
It uses the code library sonar.convert to work out the distance in cm, and there is a check at the end of the loop that turns on the on-board arduino LED on pin 13 if there is something within 7cm range of the sonar module.Wiring it up
So this is very simple, the HC-SR04 has 4 pins and we are using an Arduino Pro-mini 5v
Arduino -- HC-SRO4
Gnd ---------- Gnd
Vcc ----------- Vcc
Echo ---------- Pin 12
Trigger -------- Pin 12
Basically, I just put a jumper link that connects the Echo and Trigger together
So with it all running, the first thing is the serial monitor will print "Ready" then a series of range measurements in cm will be displayed.
One added feature is that when the target in front of the sonar is below 7cm, then the onboard light comes on to show something is near.