Instructables
loading
loading

Easy ultrasonic 4-pin sensor monitoring (hc-sr04)

Picture of Easy ultrasonic 4-pin sensor monitoring (hc-sr04)
hcsr04+arduino.png

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;
}

 
Remove these adsRemove these ads by Signing Up
1-40 of 51Next »
akedia422 days ago

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 made it!1 month ago

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);"

IMAG1575.jpg
Giedow (author)  PeterJ71 month ago

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

PeterJ7 Giedow1 month ago

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

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

Giedow (author)  PeterJ71 month ago

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 Giedow1 month ago

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)  PeterJ71 month ago

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 Giedow1 month ago

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)*****************************
PeterJ71 month ago

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.

hazyyrox1 month ago

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

hazyyrox1 month ago

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

ilovenokiac32 months ago

thanks a lot

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

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

djhh3 months ago

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 djhh3 months ago

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.razvi3 months ago

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.razvi3 months ago

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

kumarsrt4 months ago

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)  kumarsrt4 months ago

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!

sthh4 months ago

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

Giedow (author)  sthh4 months ago

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 Giedow4 months ago

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)  sthh4 months ago

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

clabelle1 year ago

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"));

}

temp_817199628.jpg

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

sthh clabelle4 months ago

Awesome bt didnt get it!

tolstoyan2 years ago
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 tolstoyan4 months ago

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

someone did:

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

Giedow (author)  tolstoyan2 years ago
Probably not, wouldn't try it

ahhh but you are wrong my freind tolstoyan is correct that is how i do myne and yes you should hear it i have no clue why but you can anyway you can short them Becouse! if you short them they still have enouph time to jump from the arduino then both ways then into them both (The Echo Pin Practicly Ignores The Input Signal) Then The Trig Pin TAkes That Power Gladly And Actavates The Sensor While Still Dischargeing Intime To Have The Sensor Send Power Back To The Arduino And It Dose This The Whole Time You Want It To Contnue Runing.

AndréanneL10 months ago

Hi! I was wondering if the 3 pin was better than the four pin or is there no big difference between them?

There is difference! 3 pin gives out 4 byte serial output! but 4 pin is not like that.

There is not too much of a difference. Just the fact that it saves one pin on the arduino and that you can use it if giving your robot a wide angle sight or about 4 or more sensors.

Giedow (author)  robobot31128 months ago

Also this was by far the cheapest sensor I could get :)

oh yes. forgot about that

ianyeo19948 months ago

How does one perform this process in reverse? Using a 4-pin sensor code and converting it to 3-pin?

Giedow (author)  ianyeo19948 months ago

"Using a 4-pin sensor code and converting it to 3-pin?"

I did exactly that! I started with the 4 pin code:http://arduino.cc/en/Tutorial/Ping?from=Tutorial.U...

AzkaraWolfe8 months ago

how would i display the serial on an lcd?

1-40 of 51Next »