delaying pulses

i am using arduino nano and hc-sr04 ultrasonic sensor to measure speed of a car. i plan to take the difference of distances taken at different time, hence by making a delay in turning on the pins.

(distance1 - distance2)/delay = speed

it gives me distances and the delta almost accurately, but the speed remained 0.

any help :o :o

Let's see a complete example with full code.

What data types are the variables ?

speed is float
the rest are integer values

test2.ino (1.03 KB)

I am sorry to be picky, but the formula that you say you are having problems with does not appear in the program that you posted

  objectsSpeed = deltaS / 1000;

Because of 'integer math' the expression will return a 'long'. deltaS less than 1000 will return 0.

You can force it to 'float' like this:

  objectsSpeed = deltaS / 1000.0;

Actually, the formula appears here

  cm1 = (duration*0.034)/02;
...
  cm2 = duration*0.034/2;
...
  deltaS = cm1 - cm2;
...
  objectsSpeed = deltaS/1000;

All these variables are declared as long, so the division is integer division and you lose the accuracy. You should use

 objectsSpeed = deltaS/1000.0;

For better accuracy, declare all variables as floats :

long duration;
float cm1, cm2, deltaS;

and do

cm1 = ((float)duration*0.034)/2.0;
...
cm2 = ((float)duration*0.034)/2.0;

Since you are using a delay of 1000ms between distance measurements, the distance traveled is already giving the speed in cm/second. Using cm/ms as the units of speed doesn't seem very useful, since that will give a maximum speed of 0.40cm/ms if you travel the entire 400cm range of the ultrasonic sensor during the one second interval. It would also be helpful if you printed out more decimal places, since anything less than 5cm/second will show as 0.00

thanks it is working now