input capture

hi guys…thanks in advance
i have been trying to calculate the timeperiod of a square wave generator and for this i am using input capture from the pin 8 of arduino uno
i am trying to capture the value of TCNT1 through ICR1 at the first positive edge and the second positive edge and the by subtracting it, i get the timeperiod (i.e t2-t1, time between consecutive positive pulses)
my code is

int sampleperiod=1000;
volatile unsigned int t1,t2; //timer values at consecutive positive edges
int capturepin=8; //icp pin for arduino uno
volatile int index=0; // to calulate only 2 edges time...
float timeperiod;
byte prescalebits=B010;
float precision=0.5; //time for one tick=prescale/frequency
 // Serial.println(t2);

void setup()
void loop()
Serial.print("time in us=");

my code is not working, help required.
thanks again


  • Indent consistently, or use Tools->Auto Format to make your code more readable.
  • Tell us what it does. The phrase, “my code is not working,” lacks descriptive power.

I see a couple of things that will keep this code from doing what you want:

This  TCCR1B=prescalebits;starts Timer1 using the prescaler you’ve selected. However, it’s followed by this  TCCR1B=1<<ICES1;which sets the input capture edge select bit to 1, and stops the timer. With the timer stopped, ICR1 will always have the same value. I don’t think that’s what you wanted.

Thisif(index=2)sets index to 2, and then tests it to see if its something other than zero. The test always passes, so it prints the values and waits a second. However, with Timer1 stopped, t1 is always the same as t2, and the elapsed time always reports zero. I don’t think that’s what you wanted, either.

The input signal will presumably continue toggling while the sketch delays between samples. The input capture interrupt isn’t disabled, so index will likely be something big, and t1 and t2 will already be set, when the system comes out of delay. Looking for equality with 2 will lead to disappointment. You may want to examine of managing the capture interrupt between samples, or alternative ways of writing the ISR, to avoid that condition.

brother as much i have studied i have seen that ICES1 is a R/W bit..
if we write "high", we get the interrupt at positive edge and for "low", we get interrupt call at negative edge...
so what is the point of timer to stop..
please explain