 # Calculating time in a specified period

I just need to calculate the exact time according to my sensors feedback values. For example when values are greater then 10 i want to start the clock and end it when value is smaller then 5. And get the value of time tick in that period. How do i do that ?

Save the millis() value at the start and end. Compare the two values to get the elapsed time in milliseconds.

UKHeliBob:
Save the millis() value at the start and end. Compare the two values to get the elapsed time in milliseconds.

So something like this ?

#define echoPin 6
#define trigPin 7

int maximumRange = 50;
int minimumRange = 0;

void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
time = pulseIn(echoPin, HIGH);
distance= time/29.1/2;
if(distance> 50)
{
int time2 = millis();
while(distance >= 20)
go_forward(50);
int time3 = millis();
}
int real_time = millis3-millis2;
}

I just write a random code. But the logic is this right ?

Declare all of your timing variable as unsigned long to avoid problems with rollover of millis() and to ensure that the calculations are correct as that is the data type returned by millis()

``````   while(distance >= 20)
go_forward(50);
``````

This won't work as distance will never be updated in the while loop. It looks like you need to use if instead of while to detect the end of timing event.