0

I am trying to output something every one second with the following code.

volatile uint64_t timerCounts = 0;
double timenow,pretime;
void setup()
  {
     Serial.begin(19600);
     noInterrupts();
     TCCR2A = TCCR2B = 0;
     TCNT2 = 0;
     OCR2A = 124; //Zero Relative 125
     TCCR2B = B00001101;  //prescaler = 1024
     TIMSK2 |= (1 << OCIE1A);
     interrupts();

     Serial.print("Begin... \n");
  }

  //**********************************************************************
  //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
  //  16Mhz / 125 / 1024 = 125 Hz    0.008s

  ISR(TIMER2_COMPA_vect)
  {
     timerCounts++;
     if (timerCounts == 125){
        Serial.print("1s");
        timerCounts = 0;
     }
  }  // end of TIMER2_COMPA_vect

  void loop()
  {

  }

In the above code, I have set the OCR2A(output compare register) to 124``, which is well below 256(2^8). A user defined counter is also used.

However, when I execute the programme, the interval between consecutive outputs is less than 1 second.

When I change it to timer 1, the interval becomes roughly 1 second. When I change it to timer 0, the interval becomes longer than 1 second.

Anyone knows why?

Thanks.

1 Answer 1

1

OCR2A doesn't do anything because the timer is in 'normal' mode. In normal mode the timer will just count to 256, not 125. Which would mean the you get a serial.print every 2.05s.

You need to use CTC mode. Do this by setting the WGM21 bit to 1.

TCCR2A = _BV(WGM21);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.