Measuring time between 2 different inputs

Hi everyone,

I have been working on the code for a simple test rig that I was planing to make in the weekend but it didn't go as I expected unfortunately. Basically what I am trying to do is to measure the time between 2 signals and display it on the serial monitor. Let's say the first sensor is triggered at T=0 and the second one is triggered at T=3, the expected output on the screen should be 3.
I did the circuit and I tried couple of different codes but failed eventually.
I am very new and still struggling with the codes but I understand that it won't happen in a day so I still keep working and trying.
I appreciate if you can help me out with this.

Thank you in advance.

Regards
//Kutalp

At the time of the first trigger, save the value of millis() to a variable (of the unsigned long data type). At the time of the second trigger record the value of millis() to a second variable (of the unsigned long data type). Then the time between the 2 events is the second variable minus the first.

Let's say the first sensor is triggered at T=0 and the second one is triggered at T=3, the expected output on the screen should be 3.

Should it be 3, or 4?

It would help if you posted your best effort at coding this. Then we can see how you are thinking and interesting things like how you are planning to detect these "events".

Steve

Depending on the signal speed, micros() is probably better than millis().

I sorted it by searching online, I am putting it here for reference;

unsigned long start, finished, elapsed;

void setup()
{
Serial.begin(9600);
pinMode(4, INPUT); // start INPUT
pinMode(5, INPUT); // stop INPUT
Serial.println("First signal for Start/reset, Second signal for elapsed time");
}

void displayResult()
{
float h,m,s,ms;
unsigned long over;
elapsed=finished-start;
h=int(elapsed/3600000);
over=elapsed%3600000;
m=int(over/60000);
over=over%60000;
s=int(over/1000);
ms=over%1000;
Serial.print("Raw elapsed time: ");
Serial.println(elapsed);
Serial.print("Elapsed time: ");
Serial.print(h,0);
Serial.print("h ");
Serial.print(m,0);
Serial.print("m ");
Serial.print(s,0);
Serial.print("s ");
Serial.print(ms,0);
Serial.println("ms");
Serial.println();
}

void loop()
{
if (digitalRead(4)==HIGH)
{
start=millis();
delay(200); // for debounce
Serial.println("First Signal...");
}
if (digitalRead(5)==HIGH)
{
finished=millis();
delay(200); // for debounce
displayResult();
}
}

1 Like

Those delays for debounce are not doing much. For debounce you read the input, delay a short time and read the input again. If the first and second readings match the state is solid (therefore valid). If not the state is not valid.

Elapsed will never be less than 200ms due to the delay.