# Speed measurement with ultrasonic sensor HC-SR04 using the Arduino with an I2C 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 connected to a Raspberry Pi via I2C.

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 I2C connection (Python).

## Calculating the speed

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

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 only once at a time. Since we use an I2C bus with different addresses, we can connect several HC-SR04 sensors to the Arduino. I can transmit this data serially through the different addresses, which allows me to have permanent information available from one sensor. I could also calculate the speed on the Arduino. However, serially I can then transmit either only the speed or the distance. An alternative would be to have the Arduino use two addresses so I can transmit this in parallel. For this I would have to adapt the Arduino Sketch. However, it is more clever that we run our calculation on the Raspberry Pi. We modify our code from the previous example as follows:

```import traceback
import struct
import smbus2
import time

bus = smbus2.SMBus(1)

# This is the address we setup in the Arduino Program

try:
while True:
b1 = []
for byt in range(4):

distance1 = struct.unpack("f", bytearray(b1))[0]

time.sleep(1)

b2 = []
for byt in range(4):

distance2 = struct.unpack("f", bytearray(b2))[0]

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

print(speed)

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

except:
# If something goes wrong
traceback.print_exc()```

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 I2C driver (Python).

Wiki: Drivers/Tutorials/SpeedMeasurementWithUltrasonicSensorHC-SR04ArduinoI2CPython (last edited 2022-11-21 09:13:12 by Michdo93)