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

207,687

115

72

Posted

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

  • Epilog Challenge 9

    Epilog Challenge 9
  • Sew Warm Contest 2018

    Sew Warm Contest 2018
  • Paper Contest 2018

    Paper Contest 2018
user

We have a be nice policy.
Please be positive and constructive.

Tips

Questions

60 Comments

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

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?

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.

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