Use of Timer 2 in Arduino UNO

float value = 98; 

void setup() 
{
  // put your setup code here, to run once:
Serial.begin(9600);

  noInterrupts();                       // disable all interrupts
  
  TCCR2A = 0;
  TCCR2B = 0;

  TCNT2 = value;                        // preload timer
  TCCR2B |= (1<<CS22)|(1<<CS21)|(1<<CS20);    // 1024 prescaler 
  TIMSK2 |= (1 << TOIE2);               // enable timer overflow interrupt ISR
  interrupts();                         // enable all interrupts


}


void loop() 
{
  // put your main code here, to run repeatedly:
Serial.println("LOOP");
delay(1000);
}

ISR(TIMER2_OVF_vect)                    // interrupt service routine for overflow
{
  TCNT2 = value;                                // preload timer
  Serial.println("ISR");
  //delay(1000);
}

Iam beginner with arduino and learning Interrupts , Stuck at a point while doing my project , I want to know how to use timer 2 for interrupt , i wrote a small peace of code , after every 10ms i want to monitor a sensor input . But it is always in the ISR and once in ~1.5 sec it is going to loop() . Whats wrong with the code?

What do you know about your code and the timer? I'm too lazy to figure out the timer mode, source of TOP etc., what's your intent?

I guess that TOP is set to zero (OCR2A?), resulting in 16/1024 MHz timer clock if the prescaler is really set to 1024.

Regardless of the mode, the TCNT register should be set only after everything else.

Good job using code tags on your first post. :slight_smile:

I can’t confirm your issue. When I run your code as provided, I see 100 instances of “ISR” between each printing of “LOOP”.

Printing from within an ISR is not a good practice.There can be issues if output buffers overflow. Try increasing your baud rate to 115200.

Here’s a slight modification of your sketch which uses better coding practices and does not print from the ISR, and uses a millis timer instead of delay in loop().

byte value = 98;
volatile boolean flagComplete = false;

void setup()
{
  Serial.begin(9600);
  noInterrupts();                       // disable all interrupts
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = value;                        // preload timer
  TCCR2B |= (1 << CS22) | (1 << CS21) | (1 << CS20); // 1024 prescaler
  TIMSK2 |= (1 << TOIE2);               // enable timer overflow interrupt ISR
  interrupts();                         // enable all interrupts
}

void loop()
{
  static unsigned long startMillis = millis();
  if (millis() - startMillis >= 1000) //change this time to 500 and see two printings of "LOOP" for 100 timer interrupts
  {
    startMillis = millis();
    Serial.println("LOOP");
  }

  if (flagComplete)
  {
    Serial.println("100 counts in ISR");
    flagComplete = false;
  }
}

ISR(TIMER2_OVF_vect)                    // interrupt service routine for overflow
{
  static byte count = 0;
  count++;
  if (count == 100)
  {
    flagComplete = true;
    count = 0;
  }
  TCNT2 = value;// preload timer
}