Measuring delay between two pulses using millis() and micros()

I am using Arduino Uno board for my project. What I am trying to do is to read the delay between two pulses. A set of pulses are generated using an Arduino Mega board. The delay between each pulse is set to 1 s (1000 ms).

In Arduino Uno I am using the attachinterrupt with the 3rd pin (ISR 1) to detect the rising edge of the pulses. When the first rising edge is detected I am keeping the time using micros() or millis() to a variable (t1) and when the 2nd rising edge is detected again I keep the time using micros() or millis() to another variable (t2).

After that took the difference between (t1 and t2) to get the delay time.
delay = t2 - t1;

Problem is,

When I was using millis() to keep the times for t1 and t2, I got delay values like 1005 ms, 1004 ms, etc. which are almost equal to 1000 ms delay (which is actual delay between the pulses).

When I was using micros() to do the same task the delay values I got are fluctuates a lot and after converting all those values to ms, those are not same as the values I got using millis(). The values I got using micros() are as follows.

658904 us

Can you please help to figure out what is happening in here.

Perhaps you should show us your sketch.

.

Hi there,

The code I am using is mentioned below.

#define RX 3

int unsigned flag1=0, flag2 = 0, flag3 = 0;
unsigned long t1 = 0, t2 = 0, t3 = 0;

void setup(){
Serial.begin(115200);
pinMode(RX, INPUT);
digitalWrite(3,HIGH);
attachInterrupt(1, ISR1, RISING);
}

void loop(){

}

void ISR1(){

flag1++;
if(flag1==2){
t1 = micros();
detachInterrupt(digitalPinToInterrupt(3));
for (int i=0;i<800;i++) {
delay(1);
}
flag2 = 1;
attachInterrupt(1, ISR1, RISING);
}
if((flag2==1) &&(flag1==4)){
t2 = micros();
detachInterrupt(digitalPinToInterrupt(3));
for(int i=0;i<800;i++){
delay(1);
}
flag3 = 1;
attachInterrupt(1, ISR1, RISING);
}
if((flag3==1) &&(flag1==6)){
t3 = micros();
detachInterrupt(digitalPinToInterrupt(3));
for(int i=0;i<800;i++){
delay(1);
}

Serial.print(t1);
Serial.print(" ");
Serial.print(t2);
Serial.print(" ");
Serial.print(t3);
Serial.print(" 1 ");
Serial.print(t2 - t1);
Serial.print(" 2 ");
Serial.println(t3 - t2);

flag1 = 0;
flag2 = 0;
flag3 = 0;
t1 = 0;
t2 = 0;
t3 = 0;
attachInterrupt(1, ISR1, RISING);
}
}

Please tell me the mistake I have done when taking the microseconds readings.

Change your ISR to make it much shorter. Perhaps

void ISR1() {
   pulseMicros = micros();
   newPulse = true;
}

and do all the other calculations in loop() with if (newPulse == true) {

...R

Time to read about interrupts:

Robin2:

Thank you very much for your help and it is working. :slight_smile: :slight_smile: :slight_smile: :slight_smile:

Dear All:

Thank you very much for your valuable ideas and advises. :slight_smile: :slight_smile: :slight_smile: :slight_smile: :slight_smile: