mega328 async interrupts half-speed

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have a project using a mega328. The main clock is the 8 MHz internal, and I have timer 2 running asynchronously with a 32.768 KHz watch crystal.

I have a very simple program that sets up timer 2 in async mode, and adds a timer2 overflow ISR. The prescaler for T2 is /128 (0x05 in TCCR2B).

 

At the overflow interrupt, I toggle a bit line driving an LED. The crystal/prescaler combination should result in an interrupt every second, so the LED should be on for one second, then off for one second, and repeat.

However - the actual interval is TWO seconds. I checked the oscillator frequency with my digital scope, and it gives me 32.8 KHz (close enough) but the output pulse is two seconds.

It is like the prescaler divide ratio is incorrect, but I did not any errata to confirm this.

So, I added a breakpoint and saw that, even though I had never accessed the TCCR2A, the bit 0 position was a 1, indicating a phase-correct PWM setup. Once I cleared TCCR2A as part of the setup, the counting became normal. Is this something that either the Arduino environment does automatically (for the PWM functions) since the sketch was originally imported from an Arduino sketch, or does AS7 do this for some reason? Obviously, the takeaway is that one should ALWAYS make sure that initialization is done as completely as possible, but I've not seen this before, so I didn't check. sad

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

even though I had never accessed the TCCR2A, the bit 0 position was a 1, indicating a phase-correct PWM setup. 

I observed the same recently.

It is better to initialize all used IO registers in Arduino.

It seems one can never be sure what happend in dark corners of Arduino. 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

even though I had never accessed the TCCR2A, the bit 0 position was a 1, indicating a phase-correct PWM setup. 

Is this something that either the Arduino environment does automatically (for the PWM functions)

 Yes.  Unless you replace main(), the Arduino provides main() that calls an init() function that initializes the timers and the ADC (and perhaps other things, so you have to check, or always set complete registers with "=" rather than individual bits with "|="

https://github.com/arduino/Ardui...