Arduino Ultrasonic Distance Measurement Tutorial with Code

Ultrasonic Sensor

Ultrasonic waves are sound waves that exceed the limits of human hearing, with a vibration frequency above 20 kHz. When working, the ultrasonic sensor converts between voltage and ultrasonic waves. When the ultrasonic sensor emits ultrasonic waves, the probe converts voltage into ultrasonic waves and emits them. When receiving ultrasonic waves, the receiving probe converts the ultrasonic waves back into voltage and sends it back to the microcontroller chip. Ultrasonic waves have advantages such as high vibration frequency, short wavelength, small diffraction, good directionality, and the ability to propagate in a directed manner for reflection lines. Additionally, the energy consumption of ultrasonic sensors is low, which is beneficial for distance measurement. In medium to long-distance measurements, the accuracy and directionality of ultrasonic sensors are significantly better than infrared sensors, although they are slightly more expensive.

The ultrasonic transmitter emits ultrasonic waves in a certain direction while starting a timer. The ultrasonic waves propagate through the air and return immediately upon encountering an obstacle. The ultrasonic receiver stops the timer as soon as it receives the reflected wave. The speed of sound in air is 340 m/s, and based on the recorded time t, the distance s from the emission point to the obstacle can be calculated as: s = 340 m/s × t / 2. This is known as the time-of-flight distance measurement method. This experiment displays the distance measured by ultrasonic waves through the serial port.

Arduino Ultrasonic Distance Measurement Tutorial with Code

The data interface of the HC-SR04 ultrasonic distance measurement module is shown in the above image, and the connection method with Arduino Uno is as follows: VCC connects to +5V, GND connects to ground, Trig connects to digital I/O interface 5 (can be other), Echo connects to digital I/O interface 4 (can be other).

Key Points:

pulseIn(): Used to detect the pulse width of the high and low levels output from the pin.

pulseIn(pin, value)

pulseIn(pin, value, timeout)

Pin— The pin that needs to read the pulse

Value — The type of pulse to read, HIGH or LOW

Timeout — The timeout period in microseconds, data type is unsigned long.

Usage and timing diagram:

Arduino Ultrasonic Distance Measurement Tutorial with Code

1. Use Arduino to send a high-level signal of at least 10 μs to the Trig pin of the SR04 to trigger the distance measurement function;

2. After triggering, the module will automatically send 8 ultrasonic pulses at 40KHz and automatically detect if there is a returned signal. This step will be completed automatically by the module.

3. If there is a returned signal, the Echo pin will output a high level, and the duration of the high level is the time taken for the ultrasonic wave to travel from emission to return. At this point, we can use the pulseIn() function to obtain the distance measurement result and calculate the actual distance to the measured object.

Arduino Ultrasonic Distance Measurement Tutorial with Code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

/*

  Date:2014.10.24

  Function: Measure distance using the SR04 ultrasonic sensor and display the measured distance value via serial port

  Method: 1. Use Arduino to send a high-level signal of at least 10μs to the Trig pin of the SR04 to trigger the distance measurement function;

        2. After triggering, the module will automatically send 8 ultrasonic pulses at 40KHz and automatically detect if there is a returned signal.

        This step will be completed automatically by the module.

        3. If there is a returned signal, the Echo pin will output a high level, and the duration of the high level is the time taken for the ultrasonic wave to travel from emission to return.

        At this point, we can use the pulseIn() function to obtain the distance measurement result and calculate the actual distance to the measured object.

*/

// Set the pins connected to the SR04

const int TrigPin = 2; 

const int EchoPin = 3;

const int LedPin = 17;

float distance; 

void setup()                 // Initialize serial communication and connect the pins for SR04

{       

     Serial.begin(9600); 

      pinMode(TrigPin, OUTPUT);

     pinMode(TrigPin, OUTPUT);  

     pinMode(EchoPin, INPUT);  // Set the pin to input mode to read pulse width

    Serial.println("Ultrasonic sensor:");

} 

void loop() 

{ 

    // Generate a 10us high pulse to trigger TrigPin 

    digitalWrite(LedPin,HIGH); 

    delayMicroseconds(2); 

    digitalWrite(TrigPin,HIGH); 

    delayMicroseconds(10);

    digitalWrite(TrigPin,LOW); 

    // Detect pulse width and calculate distance

    distance = pulseIn(EchoPin,HIGH);

    Serial.print(distance);

    Serial.print("ms");

    distance = distance/58; 

    distance = (int(distance*100.0))/100.0; // Keep two decimal places 

    Serial.print(".....distance is:");

    Serial.print(distance); 

    Serial.print("cm"); 

    Serial.println(); 

    delay(1000);  

}

Leave a Comment

×