[Documentation] [TitleIndex] [WordIndex

Speed measurement with ultrasonic sensor HC-SR04 using the Arduino with a serial connection (Python)

This tutorial guides you through calculating a relative velocity by using the distance measurement of the HC-SR04 sensor over the time. The HC-SR04 is wired to an Arduino. The Arduino is serial connected to a Raspberry Pi.

In order to be able to measure a speed at all, we must first be able to measure a distance to an object. Ultimately, the ultrasonic sensor can do no more. Therefore, first read Distance measurement with ultrasonic sensor HC-SR04 using the Arduino with a serial connection (Python).

Calculating the speed

Let's take another closer look at the triangle from the previous chapter:

https://lastminuteengineers.b-cdn.net/wp-content/uploads/arduino/Distance-Speed-Time-Formula-Triangle.png

So we need

Speed = Distance / Time

However, we do not want to go to the speed of sound now and check whether there is a deviation here.

I will show you how to measure the speed of movement of an object using this sensor. For that purpose we need to take two distance measurements in a short time apart and we have:

distance2 - distance1 = distance speed at a given time

If we make the measurements in a time period of 1 second, then we get the speed of movement of the object in cm/s.

When the object is moving in the opposite direction, the speed represented on the display has a negative sign.

Programming the speed measurement

The serial write/read has a disadvantage. You can exchange data bidirectionally, but you can only exchange data once at a time. This means that I would have difficulties to connect several HC-SR04 sensors to the Arduino. Because I could only transmit the data from one at a time serially and in ROS we actually want to have the information from one sensor permanently. If we now want to calculate the speed, then we do not do this on the Arduino, but on our Raspberry Pi. We change our code from the previous example as follows:

import traceback
import serial_float
import sys
import struct

try:
    # Initialise serial port
    ser = serial_float.Serial('/dev/ttyUSB0', 115200)
    running = True

    while running:
        # read a line from serial port
        bites1 = ser.read(4)
        distance1 = struct.unpack('f', bites1)[0] * 0.01
        
        time.sleep(1)

        bites2 = ser.read(4)
        distance2 = struct.unpack('f', bites2)[0] * 0.01

        speed = (distance2 - distance1) / 1.0   # m/s

        # Output line from serial
        sys.stdout.write(speed)

except KeyboardInterrupt:
    # User stopped
    print("\nBye...")

except:
    # If something goes wrong
    traceback.print_exc()
finally:
    running = False

Now that we know what we can measure with the HC-SR04 and how, we can write our driver and wrap it in ROS in the next chapter. Please read for this Writing your HC-SR04 serial driver (Python).


2024-12-21 12:14