Pages: [1]   Go Down
Author Topic: Trouble with HC-SR04  (Read 2137 times)
0 Members and 1 Guest are viewing this topic.
Inland Empire, California, US
Offline Offline
Sr. Member
****
Karma: 5
Posts: 274
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I have tried several different examples without any acceptable results. First i tried this sketch:
Code:
#define trigPin 5
#define echoPin 3

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  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);
}
The output from this sketch seems to wander from 45 cm to 70 cm regardless of whether any hard flat surface is within range. Next I tried an example from the new Ping library:
Code:
#include <NewPing.h>

#define SONAR_NUM     1 // Number or sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(5, 3, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
 
};

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  // The rest of your code would go here.
}

void echoCheck() { // If ping received, set the sensor distance to array.
  if (sonar[currentSensor].check_timer())
    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}

void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    Serial.print(i);
    Serial.print("=");
    Serial.print(cm[i]);
    Serial.print("cm ");
  }
  Serial.println();
}
And all I get in output are zeroes. (0=0cm). I can hear it clicking but I'm  beginning to think it may be defective. Any Ideas?
Logged

Switzerland
Offline Offline
Faraday Member
**
Karma: 108
Posts: 5144
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
I can hear it clicking but I'm  beginning to think it may be defective.

Quite a bad sign. I cannot hear my (working) sensor and that's fine because the frequency is 40kHz, more than double of what a human ear is able to detect.

Code:
delayMicroseconds(1000);

This means you're unable to detect anything below 15cm. 200us should be enough for the sensor to send out the signal.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 15
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
I can hear it clicking but I'm  beginning to think it may be defective. Any Ideas?

Mine click, and they work fine.  I don't think clicking is a good sign of a defective unit.

Quote
NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(5, 3, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
 
};

You don't need to set up an array with only one sensor, that may be causing some issues.

I would recommend copying the simplest example in the NewPing files and using that to verify that you can read from the sensor.  Then start to add complexity such as making the sketch time-driven.
Logged

Toledo, OH
Offline Offline
God Member
*****
Karma: 35
Posts: 508
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Next I tried an example from the new Ping library:
Code:
#include <NewPing.h>
.....

And all I get in output are zeroes. (0=0cm). I can hear it clicking but I'm  beginning to think it may be defective. Any Ideas?

You have one sensor you're having a problem with, but you tried using the example sketch that's designed for 15 sensors using interrupts?  Seems like if you're having a problem you should be starting with the basics.  For example, use the Simple NewPing Example Sketch instead.

If that still doesn't work, you should do some basic troubleshooting.  For example, try using different pings (the example sketch above uses pins 12 and 11, use those instead as you may have bad pins on your Arduino).  If it still doesn't work, verify all your jumper cables are connected correctly (there's a diagram at the bottom of the above linked page).  Next, replace your jumper wires with different ones.  I've seen several times now where people are having a problem and they think their sensor is bad, only to find out that their jumper wires are broken (this is quite common).

One thing can be said for sure.  If you use the NewPing library, use the example sketch linked above, use the exact pins in that sketch, and wire the sensor correctly, a good sensor WILL work in all cases.

Also, no reason to open a new thread with an ultrasonic sensor question, you can just ask on the NewPing thread if you're trying to get your sensor to work with NewPing.

Tim
Logged

Arduino - Teensy - Raspberry Pi
My libraries: NewPing - LCDBitmap - toneAC - NewTone - TimerFreeTone

Toledo, OH
Offline Offline
God Member
*****
Karma: 35
Posts: 508
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quite a bad sign. I cannot hear my (working) sensor and that's fine because the frequency is 40kHz, more than double of what a human ear is able to detect.

Even though they produce a 40kHz ping, you can still hear them click.  Some are louder than others, but I can hear every one of my sensors if I get close enough (some are quite loud).  We're not hearing the actual 40kHz ping, there's some type of vibration that's produced that's well within the human audible range.  The clicking isn't even that high of a frequency either, it's probably close to 1kHz.

Tim
Logged

Arduino - Teensy - Raspberry Pi
My libraries: NewPing - LCDBitmap - toneAC - NewTone - TimerFreeTone

Inland Empire, California, US
Offline Offline
Sr. Member
****
Karma: 5
Posts: 274
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks for the input, Tim. I tried the Simple Sketch mentioned in your last post with the same results- "Ping: 0cm".  I double-checked my connections against the diagram using pins 11 and 12 for echo and trigger. Also, I have swapped jumper wires to no avail. Any other suggestions?
Quote
Also, no reason to open a new thread with an ultrasonic sensor question, you can just ask on the NewPing thread if you're trying to get your sensor to work with NewPing.
I feel kinda awkward hijacking a thread with my own personal problem. Time and again, I see moderators telling people to start a new thread.
Logged

Toledo, OH
Offline Offline
God Member
*****
Karma: 35
Posts: 508
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks for the input, Tim. I tried the Simple Sketch mentioned in your last post with the same results- "Ping: 0cm".  I double-checked my connections against the diagram using pins 11 and 12 for echo and trigger. Also, I have swapped jumper wires to no avail. Any other suggestions?

That sketch using my 7 sensors all work perfectly.  So, if you've discounted everything else, (not a pin, not a jumper wire, not a wrong connection, etc.) then it must be the sensor as the sketch and the library are known working.  If you just can't get it working, I would like to have it.  We hear all the time about sensors that don't work, but all that I have work without issue.  My thought is that if I can find a unit that has a problem, I may be able to diagnose the problem and modify the library to work even with sensors that are on the fritz.

Tim
Logged

Arduino - Teensy - Raspberry Pi
My libraries: NewPing - LCDBitmap - toneAC - NewTone - TimerFreeTone

Inland Empire, California, US
Offline Offline
Sr. Member
****
Karma: 5
Posts: 274
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I received a new sensor in the mail today that works just fine. After comparing the two boards, I noticed that capacitor C12 is missing from the top right corner of the board. Any idea what a suitable value is for this capacitor? 
Logged

Offline Offline
Full Member
***
Karma: 2
Posts: 213
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Unfortunately you can't estimate the capacity of a smd-capacitor by size/ footprint.

Is the cap missing on the newly received board? Send it back, don't try to fix it.
If it was the other nonfunctional board, try somtething between 10nF and 100nF .
Logged

It's not my fault when my Posts are full of Errors. This stupid autocorrection from my browser is set up for german grammar.

Offline Offline
Jr. Member
**
Karma: 2
Posts: 69
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

By the way, you should set the trigger to LOW first before setting it to HIGH.  And you don't need 1000 microseconds.   The spec says 10 microseconds will do. http://www.micropik.com/PDF/HCSR04.pdf

Try ch
Code:
void loop() {
  int duration, distance;
  digitalWrite(trigPin, LOW);  //  Added
  delayMicroseconds(2);          // added
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);        // changed to 10
....
Logged

Pages: [1]   Go Up
Jump to: