Measure time between 2 events

Hi all

I want to measure the time between 2 rising edge pulse using timer interrupt. can anyone help please? thank you in advance!

hi i understand i could do that. but in exact may i know how do i write it?

because i will need to constantly sample rising edge of a signal, and how do i record the time between 2 rising edge?

thanks in advance

how do i record the time between 2 rising edge?

Use the technique described by Delta_G to measure the time 2 occurrences of the input becoming HIGH. See the StateChangeDetection example in the IDE

volatile unsigned long elapsedTimeInMicroseconds = 0;

void ISR() {
    static unsigned long previousTimeInMicroseconds = 0;
    unsigned long time = micros();
    elapsedTimeInMicroseconds = time - previousTimeInMicroseconds;
    previousTimeInMicroseconds = time;
}

void loop() {
    noInterrupts();  // Keep the value from changing as we read it.
    unsigned long interval = elapsedTimeInMicroseconds;
    interrupts();
   Serial.println(interval);
   delay(5000);
}

I was reading about the micros() command and found out that there is a 4microsecond uncertainty.
I was hoping that there was a hardware timer function that wouldnt have that variation. A counter that was armed on one leading edge and disarmed and stopped on the second one. If it has a prescaler of 1us input that should be accurate to a microsecond. Can that be done somehow? My understanding of the chip registers is still vague. I have also tried pulsein(pin8,LOW) + pulsein(pin8,HIGH) not as a single equation of course. But when I program a 20Khz signal to drive this pin I get 20khz or 19.607khz. Nothing else is being run at the same time to interfere. What could be the source of the jitter? I was assuming that pulsein and the clock source are both in hardware once armed they shouldnt vary.

Nemere:
I was reading about the micros() command and found out that there is a 4microsecond uncertainty.
I was hoping that there was a hardware timer function that wouldnt have that variation.

How long is the interval you want to measure?

The datasheet for the microprocessor (Atmega 328 if you are using an Uno) gives all the details about using hardware timers.

...R

kelvinlaujunyi:
Hi all

I want to measure the time between 2 rising edge pulse using timer interrupt. can anyone help please? thank you in advance!

Timer interrupts happen when timer values reach certain values, nothing to do with edges on pins.

You want an external interrupt, ie using attachInterrupt, or maybe pin change interrupts (there's
a library for these I believe).

You can program a timer to count every clock cycle, but interrupt jitter is more than one
clock cycle, so you won't be able to get that precision. If other kinds of interrupt are flying around,
jitter will be many microseconds anyway.