Go Down

Topic: Help with ultrasonic module HC-SR04 (Read 961 times) previous topic - next topic



I just started with an Ardiuno Uno, and I'm trying to connect an ultrasonic module. It should be pretty simple, but for some reason it isn't working. I'm pretty sure it's properly connected (I use have a sensor board) and I'm using the following code:

Code: [Select]

#define trigPin 9
#define echoPin 8

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

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin,HIGH);
   distance = (duration/2) / 29.1;

  Serial.print("duration: ");
  Serial.print("distance: ");
  Serial.println(" cm");

I copy-pasted it directly from a tutorial, and tried several delays for the trigpin high signal. I keep getting this as output:
Code: [Select]

duration: 10138
distance: 174 cm
duration: 10142
distance: 174 cm
duration: 10098
distance: 173 cm

While it should be more like 10 cm. And the duration doesn't seem to change when I change the distance to the object.
Also, the 29.1 in the distance formula should somehow relate to the speed of sound, but I have no clue how.

Can you help me out? Thanks :D


The speed of sound is 340.29 meters per second.  That's 34029 cm/sec  34.029 cm/ms .034029 cm/us.  Invert to get 29.387 microseconds per cm.  Divide your round-trip microsecond value by 59 to get one-way cm.

My guess is that there is something wrong with the transmitter or receiver of that unit and it is not seeing the echo at all.  The numbers you are getting correspond roughly with the stated 4-meter range of the sensor.  I think the receiver is timing out at maximum range.
Send Bitcoin tips to: 1G2qoGwMRXx8az71DVP1E81jShxtbSh5Hp

Go Up