Pages: [1]   Go Down
Author Topic: Help with ultrasonic module HC-SR04  (Read 453 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,

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:
#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);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin,HIGH);
   distance = (duration/2) / 29.1;

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

I copy-pasted it directly from a tutorial, and tried several delays for the trigpin high signal. I keep getting this as output:
Code:
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 smiley-grin
Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 180
Posts: 8103
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Pages: [1]   Go Up
Jump to: