Nano ATmega328P Timer2 raises Overflow on first tick after initialising and does not advance TCNT2

When I initialise Timer2, set to mode 7 with prescale of 1024 and TOP (OCR2A) of 0xFF and TCNT2 of 0, the timer seems to:

  • wait 64 uS with TCNT2 == 0
  • set TIFR TOV bit
  • wait another 64 uS TCNT2 == 0
  • advance TCNT2 to 1
  • then proceed as expected.

Yes, I am resetting all TIFR2 flags to 0 (by writing '1' to them).

#EDIT# after complaints about 'example too long', and I am changing code to be brutally minimal.

void setup(){
  uint8_t T2C[20] = { 0 };
  uint8_t T2IFR[20] = { 0 };
  uint16_t uSecs[20] = { 0 };
  uint8_t nStep = -1;
  Serial.begin(115200);
  cli();
  TCCR2B = TCCR2A = 0; // this stops clock
  TIFR2 |= _BV(OCF2B) | _BV(OCF2A) | _BV(TOV2);    // clear flags by setting(!) them
  TCCR2B |= (1 << WGM22);
  TCCR2A |= (1 << WGM21) | (1 << WGM20);
  OCR2A = 0xFF; // for TOP;
  TCNT2 = 0;  // init counter NB using 0 seems to A) stay 0 for 2 ticks B) trigger TOV on 2nd of those ticks
  TCCR2B |= 1*_BV(CS22) | 1*_BV(CS21) | 1*_BV(CS20); // b111 = clk/1024 // STARTS TIMER
  sei();
  ++nStep;
  T2C[nStep] = TCNT2;
  T2IFR[nStep] = TIFR2;
  uSecs[nStep] = micros();
  ++nStep;
  delayMicroseconds(80); // it's 64uS per tick; this delay allows the first tick to happen
  T2C[nStep] = TCNT2;
  T2IFR[nStep] = TIFR2;
  uSecs[nStep] = micros();
  Serial.println(F("(o'flo s/b @ 16384 uS)"));
  for(uint8_t ix = 0; ix <= nStep; ++ix){
    Serial.print('['); Serial.print(ix, DEC); Serial.print(F("] δuS>ΣuS:T2C,T2F=δ"));
      Serial.print(uSecs[ix] - uSecs[ix == 0 ? 0 : ix-1], DEC); Serial.print(F(">Σ"));
      Serial.print(uSecs[ix] - uSecs[0], DEC); Serial.print(F(":"));
      Serial.print(T2C[ix], DEC); Serial.print(',');
      Serial.print('x'); Serial.print(T2IFR[ix], HEX);
      Serial.println();
  }
}

void loop(){}

When run, the output is:

(o'flo s/b @ 16384 uS)
[0] δuS>ΣuS:T2C,T2F=δ0>Σ0:0,x0
[1] δuS>ΣuS:T2C,T2F=δ80>Σ80:0,x1

Second line ends in x0 which indicates the TOV is not set
Third line ends in x1 which indicates that TOV is set

Why don't you start with a simple example sketch first, illustrating your problem

I thought timer 2 wasn't available on a 32u4.

Also you should really turn interrupts off while setting up the registers or the results can be unpredictable

My not-so-simple example prints voluminous data of Timer2 registers, both data values and interpretation of those values, to assist me (and hopefully others) to see what I mean.

The output, with microsecond stamped snapshots, shows TCNT2 not incrementing properly, and TOV2 being set at first tick instead of at TOP tick.

i could just dump a bunch of hex values, but that then requires pawing over the hundreds of pages of ATmega328P datasheet to see what those hex values mean

My understanding of the timers is that the moment the timer clock is turned off (with TCCR2B = 0), that timer 'freezes' until the clock is restarted.

BTW you may note that I do 'Serial.flush();' every now and then to remove communication interrupts from stuffing up my timings.

But it is completely unreadable to most. Partly because you did not use <code> tags but i suspect blockquotes, and partly because there isn't an empty line between functions and loads of compiler directives. Keep in mind that the timer functions as it should, but you most likely have made a mistake somewhere.

A more appropriate method of ensuring nothing happens until you say so, is to turn off interrupts. The method of turning off the timer is usually done from within an ISR, which disables interrupts as well.

My suggestion is to clean up your code and reduce it down to a basic example first, and add all of the test results thereafter separately.

This code completely masks any errors, and you're unlikely to get any help if you insist on using it.
I'd recommend using an example that only starts a timer and handles an interrupt. I think the entire code should be no more than 20 lines long.

The whole point of this code is that it does NOT use ANY interrupts. I have a requirement for CPU-intensive signal processing so need minimal overheads in getting elapsed time between events. I got a shock when I analysed the multi-microsecond ISR overheads merely in pushing and popping registers. Getting the elapsed time is reduced to merely checking that if TOV2 is set then return 0xFF, otherwise return TCNT2; this gives 64uS ticks up to 16mS. And all that in a handful of inline instructions that's quicker than setting up an ISR. BTW I have been writing interrupt routines and operating systems since the 1970's.

Does that include the lines for setting up the seven Timer2 registers? Do I put them all in one one line? And i see complaints about no lines between function definitions.

If you are trying to start a timer in a non-standard way, then, even more so, remove all unnecessary things from the code. You especially need to show a minimal example so that those helping you can understand your idea.

Considering that you don't need anything other than starting the timer, not even an interrupt, then 20 lines will be enough even if you add 2 lines between the functions.

Pleas seek competent advice on how to programme an ATmega328P timer. Did you know you can select more than a handful of prescale values? And choose from multiple PWM, counter, modes? Select alternative TOP values? Select 510 ticks for 8 bit timer before Overflow flag is set?

BTW I have reposted a sub-40 line example to hopefully keep you & others happy.

This I have done with an edit to my first post. I've also added cli() & sei() to keep pedantics happy.
Same (but shorter) results, of course, but now requires reading the datasheet to see which bit of which register is the TOV2 flag. Or is this something that Arduino purists already know?

Please explain why all this bits multiplied on one?

Compare to your line above in code:

Never done this again - do not edit your previous posts if it already answered by somebody.
By doing this, you disrupt the flow of the discussion and, in principle, this are considered disrespectful to other correspondents.
If you want to change the code, paste it in a new message.

This allows an easy way to pick different prescale values; the code shown os for prescaler 7. If I want to change to use prescaler 5 then I change code to

TCCR2B |= 1*_BV(CS22) | 0*_BV(CS21) | 1*_BV(CS20);

Using your alternative to pick prescaler 5 would be

TCCR2B |= _BV(CS22) | _BV(CS20);

which to me is not clear at all.

As for the alternative line you quote, that is selecting 3 (somewhat) unrelated flags - compareA, compare B, and overflow.

There is a different , more often used way to write this

TCCR2B |= (1 << CS22) | ( 0 << CS21) | (1 << CS20);

So far,

  • I have received no answers that address the issue I am having,
  • some answers contain factually incorrect information,
  • I thought that the barrage of 'too complicated' comments meant that I should start over.

As far as I see, you didn't formulated the issue you experiencing after changing the code.

the issue is that, according to my reading of the Atmel datasheet, TOV2 is being incorrectly set and TCNT2 is not being incremented on the first clock tick. This is mentioned in both the topic header and post preamble before the example code. That issue has not changed.

Did you tried to log next tick steps?
As I see, you have the arrays for counter and flag for 20 elements.

Both of these constructs are potentially wrong, and always misleading, because logical ORing with zero does not unset a bit that might already be set in the register.

TCCR2B |= 1\*\_BV(CS22) | 0\*\_BV(CS21) | 1\*\_BV(CS20);

TCCR2B |= (1 << CS22) | ( 0 << CS21) | (1 << CS20);

That is why it is recommended to start setting up the timer by resetting the registers to zero.
The same we can see in the OP code: