Introduction: Easy Ultrasonic 4-pin Sensor Monitoring (hc-sr04)

Picture of Easy Ultrasonic 4-pin Sensor Monitoring (hc-sr04)

hello Instructables,
I have had some trouble with my cheap ultrasonic sensor (hc-sr04) and today I found a really easy solution.
It is a really simple edit of the normal 3pin code.

I added the 4 int's to the beginning of the code, so you can changes the arduino pins very easily.

The new code(4pin):

int vcc = 2; //attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; //attach pin 4 to Echo
int gnd = 5; //attach pin 5 to GND

void setup() {

pinMode (vcc,OUTPUT);
pinMode (gnd,OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}

void loop()
{
digitalWrite(vcc, HIGH);
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(trig, OUTPUT);
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(5);
digitalWrite(trig, LOW);

// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echo,INPUT);
duration = pulseIn(echo, HIGH);

// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);

Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();

delay(100);
}

long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PI...
return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}

Step 1: 3-pin Code

Picture of 3-pin Code

Code
/* Ping))) Sensor
 
   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.
    
   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping
  
   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe

   This example code is in the public domain.

*/

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

Step 2: Trouble With the Sensor/troubleshooting

So there have been many questions about failing sensors and no output. Here are some solutions.

1) Dubble check the connection.

2) check your power source: Sometimes usb connections or 9v batteries do not deliver enough power for sensors and motors/servos. So check the output with only the sensor before you upload your final code. A bigger battery might come in handy too.

3) Use other ports: First of try using a different usb port on your computer and restart the program. Second of try using other pins to attach the sensor to the arduino

Comments

prathik98 (author)2017-07-18

after using 2,3,4,5 pins which pin should i use for led considering in my case pins 9 to 13 are occupied too

Giedow (author)prathik982017-07-22

A LED can be connected from any of the digital ports using a 220 ohm resistor to the ground pin (or LOW digital pin)

More info here:
https://www.arduino.cc/en/Tutorial/Blink

Medina NualartM (author)2017-07-20

Searching for other example projects i found that this one is the only that doesn't require a breadboard, so i wonder, why bothering using a breadboard when you can simply connect it like this example? Is there something wrong with connecting the senspr directly to the arduino?

Giedow (author)Medina NualartM2017-07-22

Most of the time a breadboard is used to make assembly easier (there is more room on a breadboard and it uses power rails) and to get more current than the I/O ports can deliver (for example when using a servo or multiple sensors).

Also some say connecting the sensor directly to the I/O will damage the sensor (see MitchellB30's comment), but I doubt this and I haven't had any issues with this.

MitchellB30 (author)2017-03-25

the four-pin is just plain wrong. You can't power sensors over digital I/O of arduino boards. Digital I/O pins aren't rated for enough current to power most sensors, you run the risk of damaging one or both devices. Use the 5V and GND pins, they're there for a reason.

MitchellB30 (author)MitchellB302017-03-25

After reviewing the specs for the ultrasonic sensor, the sensor only draws 15 of the 20mA max for arduino digital I/O pins. That said, its a dumb idea to power sensors off of Digital I/O and hope you down blow up your microcontroller. ploease, don't do this.

Giedow (author)MitchellB302017-07-22

Thanks for the warning, but according to the arduino website the output current is only 20mA. This might be a problem for long term use, but certainly won't damage the sensor in the sort term. Furthermore, I have never had any issue with this.

Also isn't the output current equal to the current "requested" by the sensor?

californiakayaker (author)2017-01-13

There is a project where I'd like to use the 4 pin (I have) instead of a 3 pin .

The code for the other project is here.

https://www.instructables.com/id/Voice-activated-Ro...

I'm just beginning to learn how to code and don't feel comfy enough to change it.

/*

This program is based off the demonstration of the Emic 2 module by
Joe Grand [www.grandideastudio.com]

*/
#include

#define rxPin 2 // Serial input (connects to Emic 2 SOUT)
#define txPin 3 // Serial output (connects to Emic 2 SIN)

// set up a new serial port
SoftwareSerial emicSerial = SoftwareSerial(rxPin, txPin);
const int pingPin = 7;
long int duration, distanceInches, distanceCm;
byte LimitCm= 30;
byte ledPin = 12;

long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}



void setup() // Set up code called once on start-up
{
// define pin modes
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
pinMode(ledPin,OUTPUT);

// set the data rate for the SoftwareSerial port
emicSerial.begin(9600);

/*
When the Emic 2 powers on, it takes about 3 seconds for it to successfully
intialize. It then sends a ":" character to indicate it's ready to accept
commands. If the Emic 2 is already initialized, a CR will also cause it
to send a ":"
*/
emicSerial.print('\n'); // Send a CR in case the system is already up
while (emicSerial.read() != ':'); // When the Emic 2 has initialized and is ready, it will send a single ':' character, so wait here until we receive it
delay(10); // Short delay
emicSerial.flush(); // Flush the receive buffer
}

void loop() // Main code, to run repeatedly
{
//check distance with Ping)))
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

distanceInches = microsecondsToInches(duration);
distanceCm = microsecondsToCentimeters(duration);


check();
delay(100);

}

void check()
{
if (distanceCm > 30)
{
emicSerial.print('S');
emicSerial.print();
emicSerial.print('\n');
while (emicSerial.read() != ':');
}
if (distanceCm < 30)
{

emicSerial.print('S');
emicSerial.print("object detected. Fire.");
emicSerial.print('\n');
while (emicSerial.read() != ':');

digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);

}
}

IMadeIt Approved

lafeo_007 (author)2016-11-04

Can I use the sensor to send a message.

Eg: Can I use the trig. to send a message and then, use the echo. on the other sensor to receive that message?

PLEASE REPLY.. It's urgent

FlyingDrMike (author)lafeo_0072016-12-07

Sorry no. The so called echo is not an echo of the transmitted pulse. Also the transmitted pulse is fixed at 8 cycles at 40kHz. The echo line goes high when the pulse is sent and stays high until the first echo is received. So distance is measured from the duration of the echo pulse. The arduino devices are however a cheap source of ultrasonic Tx/Rx. Also the LM324 quad amp that is used to detect the return might be used to monitor the received signal without too many mods. There is a very good analysis of the HC-SR04 at:

http://uglyduck.ath.cx/ep/archive/2014/01/Making_a...

Mike

modsbyus made it! (author)2016-12-06

Thanks for the write up!

salmasaleh (author)2016-11-17

hello

hoe can i use four of HC_SR04 to detect the shortest distance of an object? with the Arduino

BillA9 made it! (author)2016-05-09

I built the hc-sr04 version, but modified it to use float data type for the variables inches and cm. Then changed microsecondsToInches and Centimeters to return a float and to divide by 74.0 instead of 74 or 29.0 instead of 29 - this causes a floating divide instead of a integer divide.

rshonk made it! (author)2015-12-05

I put a little different twist on it. but thank you for the insperation.

ChibuikeO1 (author)2015-12-04

hello, please i have a problem. My arduino keeps tripping off any time i connect the GND of the HCSR04 with the GND of my microcontroller. the ardunio uno micro controller keeps tripping off and i have tried this on two different micro-controller. the micro controller is powered by my laptop usb port. any idea how i can fix this problem?/

mzbas (author)2015-11-22

the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc. You will need the NewPing library which is far better.

A working code:

#include <NewPing.h>

#define TRIGGER_PIN 12

#define ECHO_PIN 11

#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {

Serial.begin(9600);

}

void loop() {

delay(50);

unsigned int uS = sonar.ping();

pinMode(ECHO_PIN,OUTPUT);

digitalWrite(ECHO_PIN,LOW);

pinMode(ECHO_PIN,INPUT);

Serial.print("Ping: ");

Serial.print(uS / US_ROUNDTRIP_CM);

Serial.println("cm");

}

link: http://forum.arduino.cc/index.php?topic=55119.15

NewPing link: http://playground.arduino.cc/Code/NewPing

PeterJ7 made it! (author)2015-06-03

Ive noticed that if I've aimed the sensor at something a long way away I start receiving 0cm, scrolls until I restart.

Reading the comments in the code again, I'm guessing the sensor is stuck sending HIGH to the trigger pin as the HIGH duration is the length of time from send to receive... but it doesnt receive as its too far away.

If I tap the sensor or table in front of it it seems to kick it off again.

Is there any way around this? Or rather, I know I want to write an "If duration is longer than 1 second, restart " but no idea how or where to add it yet.

"// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);"

mzbas (author)PeterJ72015-11-22

the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc. You will need the NewPing library which is far better.

A working code:

#include <NewPing.h>

#define TRIGGER_PIN 12

#define ECHO_PIN 11

#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {

Serial.begin(9600);

}

void loop() {

delay(50);

unsigned int uS = sonar.ping();

pinMode(ECHO_PIN,OUTPUT);

digitalWrite(ECHO_PIN,LOW);

pinMode(ECHO_PIN,INPUT);

Serial.print("Ping: ");

Serial.print(uS / US_ROUNDTRIP_CM);

Serial.println("cm");

}

link: http://forum.arduino.cc/index.php?topic=55119.15

NewPing link: http://playground.arduino.cc/Code/NewPing

Giedow (author)PeterJ72015-06-03

Please tell me if it works or what works, so I can add it to the troubleshooting. Good luck

PeterJ7 (author)Giedow2015-06-03

Still not sure whats happening because (see last post) and I added an ELSE to show when it was over a certain duration, and it can come back from that. It somehow dies when its pointed a certain distance away.

if (duration <= 15000)
{
// Display results
Serial.print("Distance is ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
Serial.println(duration);
delay(500);
} //end if
else
{
Serial.print("uh oh, I cant see that far!");
Serial.println();
delay(500);
}

----------------------------
Distance is 159cm
9272
Distance is 159cm
9271
uh oh, I cant see that far!
Distance is 160cm
9322
Distance is 160cm
9322
uh oh, I cant see that far!
uh oh, I cant see that far!
uh oh, I cant see that far!
uh oh, I cant see that far!
uh oh, I cant see that far!
uh oh, I cant see that far!
Distance is 160cm
9281
Distance is 160cm
9307

-----------------------------

erikma1 (author)PeterJ72015-11-20

Peter - was running into the same problem
of the sensor getting "stuck" - I debugged by digitialRead()-ing the
Echo pin value before sending the digital pulse and afterward. What I
found was that the Echo pin was staying HIGH all the time when you point
it far away and get it stuck; when it's operating normally the pin is
zero to start with. I updated the code above a bit: Before
digitalWrite(trig, LOW) I call resetPingSensorIfStuck() which looks
like:

// When the sensor gets aimed at "nothing" (too far away for a return) it can get
// "stuck". If you flick one of the "eyes" on the sensor it wakes up. We can get around this
// by resetting the Echo pin to zero manually. Typically this should be called
// just before sending the pulse via Trig.
void resetPingSensorIfStuck()
{
int echoValue = digitalRead(echo);
if (echoValue != 0) {
pinMode(echo, OUTPUT);
digitalWrite(echo, LOW);
pinMode(echo, INPUT);
}
}

Giedow (author)PeterJ72015-06-03

As far as I can tell this is normal. As the sound generated by the trigger gets further away it gets less intense, so there will be a point where the echo can not be distinct from random noise.

PeterJ7 (author)Giedow2015-06-03

I worked out why the delay is ignored.
There is a default of 1 second before pulseIn gives up listening.
http://www.arduino.cc/en/Reference/PulseIn

Id really like to understand though how to restart the whole process once it dies.

Thanks for the help so far. Ill post back if I work it out! :)

Giedow (author)PeterJ72015-06-03

I guess it would be something like this:

pinMode(echo,INPUT);
duration = pulseIn(echo, HIGH);

if(duration<=VALUE){

Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();

}

delay(100);

}

Where VALUE would be the duration in seconds at the max range. You can test this by replacing the part after duration=pulseIn(.....); with Serial.println(duration);

PeterJ7 (author)Giedow2015-06-03

Thanks for the reply!

This (1) is the serial monitor output I get just before I point the sensor at the ceiling at work (can you tell im busy at work?).

The ceiling is way higher that 400cm which I believe is the max range of the HC-SR04?

I added the IF statement (3) and end up getting this (2) but still get the repeating 0cm after pointing at far away objects. The delay(500) goes out of the window too, it takes 2 or 3 seconds before it outputs the next 0cm

If I give it a flick then it does restart (4). Resetting the arduino and closing/reopening the serial monitor does nothing either. Pulling the power (USB) and re-plugging does work.

Confused!

*(4)********************
Distance is 0cm
0
Distance is 0cm
0
Distance is 0cm
0
FLICK!!!
Distance is 159cm
9245
Distance is 158cm
9221
Distance is 159cm
9223
Distance is 158cm
9221
*(4)*********************
*(3)********************************
if (duration <= 20000)
{
// Display results
Serial.print("Distance is ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
Serial.println(duration);
delay(500); //print line after every delay
} //end if
*(3)*************************
*(2)*************************
Distance is 269cm
15622
Distance is 269cm
15646
Distance is 268cm
15601
Distance is 271cm
15745
Distance is 271cm
15719
Distance is 238cm
13837
Distance is 0cm
0
Distance is 0cm
0
*(2)************************
*(1)******************
Distance is 389cm
22586
Distance is 418cm
24283
Distance is 417cm
24209
Distance is 417cm
24218
Distance is 0cm
0
Distance is 0cm
0
Distance is 0cm
0
*(1)*****************************
sdtag (author)2015-10-12

I am using a HC-SR04 hooked up to a Arduino Nano. I have it mounted on my quad-copter (drone) to control the retractable landing gear. I have it set to 3 feet and it works reliably when closer than 3 feet to the ground. My problem is when it is flying, the sensor is "seeing" my rotor wash from the props and generating false triggers. When my quad is up high flying, the landing gear goes up and down at random.

I think I need to look at the distance, wait a second and look again. If the two answers match, then perform an action. My problem is I'm not a programmer. Can anyone give me a clue or just do it for me?

Here is my code that I stole so far. Any help will be greatly appreciated and I promise I won't spy on you with my drone. :) Thanks in advance

#include <Servo.h>

Servo servoLeft;
Servo servoRight;
#define echoPin 2
#define trigPin 3

void setup() {
servoLeft.attach(5);
servoRight.attach(6);
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 74; // 74=inches 29=cm
if (distance < 36) { // 160cm=5' 62cm=2' 60"=5' 24"=2'
servoLeft.write(80);
servoRight.write(90); //LANDING
}
else {
servoLeft.write(180);
servoRight.write(0); //FLYING
}
delay(2000);
}

rogercanda (author)2015-07-19

I have a confusion with HC-SR04. I tried your code and it works very well. I got the output on the Serial Monitor just fine. The problem is, when I take out the trig pin (detach) from pin 3. I still got the reading just fine? I thought that the TRIG is for sending pulse and the ECHO is for receiving pulse. Somebody please explain what is the case here?

akedia4 (author)2015-06-11

Hey, This was great help. Thanks!


However, I have a question about the use of the pulseIn function here. Aduino Documentauin tells me that this function starts timing when the pin gets a high signal, and then stops timing when the pin gets a low signal. So in our context it will record the ‘duration’ as the time between when it started hearing the reflected sound, and when it stopped hearing the reflected sound. But I don't think that is what we want. That duration will always be 10 microsecond, since that was the length of our pulse (assuming that any obstacle is further than 5 sound-microseconds). Don't we want something that starts timing whn the signal is first sent, and then stops timing when the signal is first received? I may be wrong. The code works perfectly, but it doesn't make theoretical sense to me.

PeterJ7 (author)2015-06-03

Thanks for this! :)
I found that I was getting 0 inch and 0CM but going through a breadboard and hooking Ground to Ground (instead of pin 5) and VCC to 5V (instead of pin 2) I started to get readings! Might help other people trying this?!
Not sure my readings are all that accurate at the moment but im already late for work. ;) Ill take a look at the code/calculations and the actual sensor etc and see if there is a reason for it and maybe fudge the calculation to match my sensor.

hazyyrox (author)2015-05-07

is it the connection fault or some kind of noise error??

hazyyrox (author)2015-05-07

why do i get zero reading from ultrasonic sensors???

ilovenokiac3 (author)2015-04-30

thanks a lot

wmada (author)2015-04-29

hey wondering why my robot runs into walls still. i changed distance from 40cm to 20 cm any thoughts?

csmith183 (author)2015-04-17

Ok I made it and implemented the code however It won't display anything, Is there something with my sensor?

djhh (author)2015-03-21

i used this code and the sensor will give me correct data for a bit but then it will stop for a seconds then only output 0in and 0cm once per second any idea what could be causing this? thank you

cfletcher32 (author)djhh2015-03-26

is it possible that you did not define your pin modes for your echo and trig pins?

Your trig pin mode should be output and your echo pin mode should be input

hannan.razvi (author)2015-03-10

hey guys it works fine but the problem is when i upload the program on to the board it shows zero cm although the intensity of the 0cm changes as i get a obstacle in front of the hc-sr04 but it still shows 0cm .any help would be really appreciated thank you in advance

Giedow (author)hannan.razvi2015-03-10

If you have a cheap arduino the ground pins may not be connected, so try an other ground pin.

Try dubble checking the connections, is it hooked up correctly?

otherwhise the arduino or the sensor might be broken, so try an other senser or an other arduino or at least other pin(make sure to change them in de code too).

Good luck

kumarsrt (author)2015-02-21

hello sir can im doing obstacle avoidance robot with vacuum cleaning robot.im need to use 3 ultrasonic HC-SR04 sensors in front of the robot.can i connect VCC and Gnd pin directly to the regulated 5V from IC7805 will affect the working of sensors.if not is there any way to connect 3 sensors

Giedow (author)kumarsrt2015-02-22

You can just use the normal 5v and GND pins on the arduino. Just connect all 5v pins on the sensors to the 5v on the board, do the same for the GND. If you do this you can leave the two "pinmode" and the "digitalWrite(2, HIGH);" lines out.

I just used these so I could plug the sensor directly into the arduino.

Also if the sensors do not work properly try connecting them to another 5v powersupply as the current on the arduino may not be sufficient to power sensors and motors. Good luck!

sthh (author)2015-02-14

my module iz not working properly, is there any solution to fixed it, anyone plz help....

Giedow (author)sthh2015-02-14

I could be anything. Can you be more specific?

Also try dubble checking the connections and the code and if you have an other arduino try that one.

sthh (author)Giedow2015-02-15

Actually my sensor HC-SR04 iz not working, i doubt whether it is damage or not! is there any method to repair it or nt, and bundle of thanx 4 ur response

Giedow (author)sthh2015-02-15

I dont think repairing is an option. You could try to remove the calculations from the code, so it displays the direct signal. "serial.println(duration)"

Other whise ask it on a forum like reddit.com/r/arduino

Good luck

clabelle (author)2014-06-02

I would do it this way, cause pulseIn() hang the system for a certain time and interrupt does not.

Code:

#define broche_Trig 12
#define broche_Echo 3
#define broche_Piezo 8

volatile unsigned long last_detection = 0;
unsigned long last_detection2 = 0;
const int Ping_interval = 150;

const double k_Mach = 29.4117647;

int duration;
double distance;

void setup() {

  attachInterrupt(1, got_echo, FALLING);
  
  pinMode(broche_Trig, OUTPUT);
  pinMode(broche_Echo, INPUT);

  Serial.begin (115200);
  
}

void loop() {
  
  if(millis() - last_detection >= Ping_interval) {
  
    digitalWrite(broche_Trig, HIGH);
    delayMicroseconds(5);
    digitalWrite(broche_Trig, LOW);
    last_detection = millis();   
    last_detection2 = micros();
    
  }
  
  
}

void got_echo(){
  
     duration = micros() - last_detection2 ;
     distance = (0.5  *(duration / k_Mach)) - 8  ; // - 8 ???
     Serial.println((String)distance + F(" cm"));

}

clabelle (author)clabelle2014-06-02

ahah I got this code from my BF Frederic Plante. ;)

sthh (author)clabelle2015-02-14

Awesome bt didnt get it!

tolstoyan (author)2013-01-16

can i just short the echo and trig pin in the ultra sonic sensor so that i dont have to changed anything in the code?

sthh (author)tolstoyan2015-02-14

ya u can short trig pulse but cant echo b/c it depends upon module!

diy_bloke (author)tolstoyan2014-09-13

someone did:

https://www.instructables.com/id/Hack-an-HC-SR04-to-a-3-pin-sensor/