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

210,830

116

60

Published

Introduction: 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

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

4 People Made This Project!

Recommendations

  • Water Contest

    Water Contest
  • Clocks Contest

    Clocks Contest
  • Creative Misuse Contest

    Creative Misuse Contest

60 Discussions

5 cm

5 cm

5 cm

5 cm

5 cm

5 cm

5 cm

1 cm

1 cm

2 cm

1 cm

4 cm

2 cm

2 cm

5 cm

My sensor does not show any value above 5 when placed without any obstruction. When i place something in front it shows the value if it is less than 5.

This is the code I used.

#define trigPin 8

#define echoPin 9

void setup() {

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) / 29.1;

if (distance >= 200 || distance <= 0){

Serial.println("Out of range");

}

else {

Serial.print(distance);

Serial.println(" cm");

}

delay(500);

}

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

1 reply

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

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?

1 reply

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.

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.

2 replies

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.

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?

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

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

1 reply

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

hello

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

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?/

0
user
mzbas

2 years ago

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

0
user
sdtag

2 years ago

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

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?

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.

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.

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

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