how to read TCNT1 on aurdino uno

I want to measure the time elapsed between two pulse on two different interupt pin. My reading is somehow accurate when using micros(). But reading is erratic when using hardware timer TCNT1. When interrupt in one pin timer 1 start and interupt in second pin timer1 stop. Then I am reading Tcnt1. Up to 255 microsecond timing is correct. Prescale is 8.

Perhaps if you post your code?

Please use code tags.

Read this before posting a programming question

How to use this forum

/* 
to measure the time elapsed between two pulse
using arduino uno r3  board and interrupt pin 2(int0)and pin3(int1)
*/
volatile unsigned int timer1_counter;//integer to store the value of timer
volatile boolean state1; 
boolean state2;
void setup()
{
  attachInterrupt(0, starttimer, RISING);//pin2 interrupt
 attachInterrupt(1, stoptimer, RISING);  //pin3 interrupt
 Serial.begin(9600);
 state1=0;
 state2=0;
  
 TCCR1A = 0;//timer1 in normal mode
 TCCR1B = 0;//timer1 in normal mode
 timer1_counter = 0;   
 
 TCNT1 = timer1_counter;  //making intial time counter to zero 
 
}

void starttimer()
{
    TCCR1B |= (1<< CS11);//start the timer with prescaler 8
    
    
}
void stoptimer()
{
    TCCR1B |= (0<< CS11);//stop the timer
    timer1_counter = TCNT1;//read and store the counter value
    
    state1=1; // time measrurement complete
    

}

void loop()
{
 if ((state1==1) and (state2==0)){ //
   Serial.print(timer1_counter);
   state2=1;
 }
}

Moderator edit:
</mark> <mark>[code]</mark> <mark>

</mark> <mark>[/code]</mark> <mark>
tags added.

  if ((state1=1) and (state2=0)){ //

Those are assignment operators '=', not comparison operators '=='.

Changed the code with == but the same problem is coming. Up to 255 counts it comes correctly.beyond that it erratic.

amubgr:

  TCCR1B |= (0 << CS11); //stop the timer

OR-ing with 0 will not set the bit to 0 so that won't stop the timer.

To clear that bit use:

  TCCR1B &= ~(1 << CS11);  //stop the timer

Thanks sir. Actually I was working with mikrobasic compiler. Recently I decided to shift to arduino due to its open support. Now I am learning the syntax. I will try the correct code as suggested by u.