# Timer2 off by a factor of 2

I have the following code running on an Arduino Nano:

``````volatile int x = 1000;
bool y = 0;
volatile long a = 0;
long b = 0;

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

TCCR2A |= 0;
TCCR2B |= 0x04; //prescaler set to 1/64
OCR2A |= 0xFF;  //this can be adjusted later
TIMSK2 |= 0b10;  //set interrupts
Serial.println(TCCR2B,BIN);

}

void loop() {
// put your main code here, to run repeatedly:

if(y == 1){
Serial.println(a-b);
b = micros();
y=0;
}
}

SIGNAL(TIMER2_COMPA_vect){
if(x==0){
a = micros();
y = 1;
x = 1000;
}

x--;
}
``````

I would expect that with a 16mhz system clock and a divider of 64 that the interrupt should trigger roughly once every millisecond and decrementing a counter down from 1000 should give me an output every second. What I'm getting though is over 2 seconds.

``````2039644
2039644
2039652
2039652
2039652
2039652
2039644
2039644
2039652
2039652
2039652
2039644
2039644
2039652
``````

Thoughts?

Okay I figured it out. I guess the tone() function fiddles with those registers and OR'ing them with a bit mask was leaving some of their bit values. I changed:

``````  TCCR2A |= 0;
TCCR2B |= 0x04; //prescaler set to 1/64
OCR2A |= 0xFF;  //this can be adjusted later
``````

to:

``````  TCCR2A = 0;
TCCR2B = 0x04; //prescaler set to 1/64
OCR2A = 0xFF;  //this can be adjusted later
``````