Timers help needed

void setup() {
 
  pinMode(DETECT, INPUT)
  pinMode(GATE, OUTPUT);

  
  OCR1A = 5;      //initialize the comparator A
  OCR1B=7;//initialize the comparator B
  TIMSK1 = 0x06;    //enable comparator A and B
  TCCR1A = 0x00;    //timer control registers set for
  TCCR1B = 0x00;    //normal operation, timer disabled 
 
  // set up zero crossing interrupt
  attachInterrupt(0,zeroCrossingInterrupt, RISING);    
 }

//Interrupt Service Routines

void zeroCrossingInterrupt(){ //zero cross detect  
   TCCR1B=0x05;   //start timer with divide by 1024 input
  TCNT1 = 0;   //reset timer - count from zero
}

ISR(TIMER1_COMPA_vect){ //comparator match
   PORTB = PORTB | 0b00000010; // Set Pin 8 HIGH
}

ISR(TIMER1_COMPB_vect){ //comparator match
PORTB = PORTB & 0b11111101; // Set Pin 8 LOW
TCCR1B = 0x00;  // Disable Timer
  
}
void loop(){ // sample code to exercise the circuit
        

}

I can easily run above code with Timer 1 however when i use Timer 2 i can't be able to get it work.Any idea on this would be much appreciated.Clock is 16Mh with 1024 prescaler.

The code you posted doesn't compile.

I don’t normally recommend an instructable, but this one is good and includes an example using timer2: https://www.instructables.com/Arduino-Timer-Interrupts/

TCCR1B=0x05;   //start timer with divide by 1024 input

The equivalent of that in Timer2 yields a pre-scaler of 128 instead of 1024 which will give a timer2 clock of 125 KHz

Change it to TCCR2B = 0x07 to get a 1024 prescaler

hzrnbgy:

TCCR1B=0x05;   //start timer with divide by 1024 input

The equivalent of that in Timer2 yields a pre-scaler of 128 instead of 1024 which will give a timer2 clock of 125 KHz

Change it to TCCR2B = 0x07 to get a 1024 prescaler

Thank you everyone for your kind answers. hzrnbgy your are my angel today.I couldn't find it these prescaler in datasheet so figured it out it must have been same with timer1.Everything works perfectly.Hug you.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.