Speed measurement with IR sensor GP2Y0A02YKOF (Python)

This tutorial guides you through calculating a relative velocity by using the distance measurement of the GP2Y0A02YKOF infrared sensor over the time.

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 infrared distance sensor can do no more. Therefore, first read Speed measurement with IR sensor GP2Y0A02YKOF (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

We change our code from the previous example as follows:

```import spidev
import time

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz=1000000

val = spi.xfer2([1,(8+channel)<<4,0])
data = ((val[1]&3) << 8) + val[2]

return data

if __name__ == "__main__":
dist1 = (16.2537 * v1**4 - 129.893 * v1**3 + 382.268 * v1**2 - 512.611 * v1 + 301.439) * 0.01

time.sleep(1)