[code]One way to solve it would be to use millis()/micros() and at the time of pin state changes, recording the millis()/micros() reading. That can be done via interrupts (EINTx or PCINTx) or via polling (dumber way in my view).
#define PULSE_PIN 8
#define TIME() millis() //count to ms. use micros() to count to us
void pulse_init(void) {
pinMode(PULSE_PIN, INPUT);
}
unsigned char pulse_count(unsigned long *p_count) {
static unsigned char pin_prev=0; //previous state of the pin
static unsigned long start_time = TIME();
unsigned long time;
unsigned char tmp=digitalRead(PULSE_PIN);
if (tmp ^ pin_prev) { //pin state has changed
time = TIME(); //record current time
pin_prev = tmp; //save the pin state
if (start_time) { //already in a counting session now
*p_count = time - start_time; //calculate time elapsed
start_time=0; //indicating end of a counting session
return 1; //we have new data
} else { //start of a counting session
start_time = time; //record the start time
return 0; //no count yet
}
} else { //pin state has not changed
return 0; //no new count
}
}
void setup(void) {
Serial.begin(9600);
pulse_init(); //initialize the module
}
unsigned long count;
void loop(void) {
if (pulse_count(&count)) { //new data has arrived
Serial.print("Count = "); Serial.print(count); Serial.println("ms.");
}
}
[/code]
Here pulse_count() returns 1 if new count data is available. Otherwise, 0.
The ultimate approach would be to use the timer capture feature.