Distance measurement with Arduino sensor HC-SR04 US-015

Presents sensors provide distance measurement using ultrasound. The sensor sends out a wave, which after reflection from the obstacle, it returns to him. Computing the time between transmission and reception of the pulse, we can determine the distance to the object.

 

We will need the following items:

 

Connect the sensor with Arduino:

The sensor using the Arduino you should connect the layout as follows:

 

Pin BH1750 Pin Arduino
VCC 5 V
GND GND
TRIG 2
ECHO

3

 

Connection diagram of ultrasonic sensor with Arduino Uno.

Program for Arduino

In the example, we used the following code:

 

  1. int Trig = 2; //pin 2 of Arduino is connected to the contact sensor Trigger
  2. int Echo = 3; //Arduino pin 3 is connected to the contact sensor Echo
  3. int CM; //distance in cm
  4. long TIME; //duration of the reverse pulse in the uS
  5.  
  6. void setup()
  7. {
  8. Serial.begin(9600); //inicjalizaja monitor serial port
  9. pinMode(Trig, OUTPUT); //setting Arduino pin 2 as output
  10. pinMode(Echo, INPUT); //setting pin 3 in Arduino as input
  11.  
  12. Serial.println("Test of spacing");
  13. }
  14.  
  15. void loop()
  16. {
  17. pomiar_odleglosci(); //measure the distance
  18. Serial.print("Distance: "); //display results on the screen in a loop every 200 MS
  19. Serial.print(CM);
  20. Serial.println(" cm");
  21. delay(200);
  22. }
  23.  
  24. void pomiar_odleglosci ()
  25. {
  26. digitalWrite(Trig, LOW); //setting the high status on 2 uS pulse inicjalizujacy - see the documentation
  27. delayMicroseconds(2);
  28. digitalWrite(Trig, HIGH); //setting the high position for 10 uS pulse inicjalizujacy - see the documentation
  29. delayMicroseconds(10);
  30. digitalWrite(Trig, LOW);
  31. digitalWrite(Echo, HIGH);
  32. TIME = pulseIn(Echo, HIGH);
  33. CM = DURATION / 58; //width of the reflected pulse in the uS divided by 58 is the distance in centimeters - see the documentation
  34. }

 

To calculate the distance to the object, the response time is common to 58 (according to the documentation). Why so much? This value is derived by the formula:

 

TIME / [1/(0.34 / 2 )/10]

 

  • the value in square brackets is equal to 58:
    • 0.34 - wave velocity in m/MS (340 m/sec) divided by 2 (since the wave has come a long way in the two sides).
    • In addition, all safely by 10 to change millimetres to centimeters

 

The result of the program can be viewed on the serial monitor:

 

A screenshot of the serial monitor.

Botland.store - shop for makers!