# How to set counter for two ultrasonic sensors?

This question has been asked many times in many sites but I am unable to find answer for my problem. I wanted to measure the speed of Vehicle using Ultrasonic sensors. Two sensors are placed along the side of the road and when a vehicle passes in front of first sensor(i.e echo1 is HIGH) then it should start counting until when the vehicle crosses the second sensor(i.e echo2=HIGH). So I will get the time. But I don't know how to set time counter. I searched in Internet a lot and I learnt about millis(). So I wrote code using millis(). But the problem is,it starts counting as the program runs. I also tried using array to save the values and subtract final reading from initial one but I'm unable to do that too. I cannot create large size of arrays. Please help me how do I set timer for it?

• Are you asking how to measure the elapsed time between two events? Feb 15 '17 at 16:53
• Yes. Elasped time between the condition when both the echo pins are high.
– Rima
Feb 15 '17 at 16:54

Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.

This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.

``````#define echo1 3 // Set your echo pins here
#define echo2 4

unsigned long startTime = 0;
unsigned long endTime = 0;

void setup() {
}

void loop() {
// You can do stuff here

// If the first sensor goes off
{
// Remember the time this happened
startTime = millis();
}
// If the second sensor goes off
{
// Remember the time this happened
endTime = millis();
}

// If we have both start and end times
if (0 != startTime && 0 != endTime)
{
unsigned long duration = endTime - startTime;
// Do what you want with "duration"
}

}
``````
• It seems to work. But here the problem is the range of ultrasonic sensor. The sensor can detect the object even up to 300-400 cm so here the sensor cannot work in narrow road as it will detect the objects across the road too and the echo pin will never be at LOW state,if I am not wrong.
– Rima
Feb 15 '17 at 18:02
• Well, that's a different question. Please post one question at a time. It would be worth reading how to ask a good question and then posting a new question. Please consider accepting the answer if it answers the question you asked. Feb 15 '17 at 18:10
• I tried coding according to your given code but the above problem arose so I thought commenting here,if you might have any answer for that.
– Rima
Feb 16 '17 at 2:45