Interrupt question

I am trying to set an interrupt on Timer1 for every 500ms.

I have set:

OCR1A = 31249; // 0.5 seconds with prescaler of 256 (2Hz)

TCCR1A |= (1 << WGM12); // Enable CTC

TCCR1B |= (1 << CS12); // Prescaler set to 256

TIMSK1 |= (1 << OCIE1A);

The interrupt runs at 500ms 1st time, but then every 1000ms afterwards. Am I missing something?

volatile byte testInt = 0;

// Start of Setup Function
void setup()
{
  Serial.begin(9600);                      // Sets the serial port baud rate

  // Start Interrupt for Inputs and Outputs
  noInterrupts();                          // Disable Interrupts while setting

  // Interrupt frequency (Hz) = (Arduino clock speed 16,000,000Hz) / (prescaler * (compare match register + 1))

  // Setup for Timer 1
  TCCR1A = 0;// Set entire TCCR1A register to 0 to remove all settings
  TCCR1B = 0;// Same for TCCR1B
  TCNT1  = 0;// Set Counter to 0

  // OCR1A must be < 65536 as Timer 1 is 16-bit
  OCR1A = 31249; // 0.5 seconds with prescaler of 256 (2Hz)

  TCCR1A |= (1 << WGM12);   // Enable CTC

  TCCR1B |= (1 << CS12);    // Prescaler set to 256

  // Enable timer compare interrupt. OCIE1A = Enable the Compare Match Interrupt
  TIMSK1 |= (1 << OCIE1A);

  // Allow Interrupts
  interrupts();
}
// End of Setup Function


// Start of Interrupt Service
ISR(TIMER1_COMPA_vect)
{
  testInt = 1;
}

// Start of Loop
void loop()
{
  if (testInt == 1)
  {
    testInt = 0;

    static unsigned long timepast;

    Serial.print("\r\nTime: ");
    Serial.print((millis() - timepast), DEC);

    timepast = millis();
  }
}
// End of Loop

Maltelec:
I have set:

OCR1A = 31249; // 0.5 seconds with prescaler of 256 (2Hz)

TCCR1A |= (1 << WGM12); // Enable CTC

TCCR1B |= (1 << CS12); // Prescaler set to 256

TIMSK1 |= (1 << OCIE1A);

The interrupt runs at 500ms 1st time, but then every 1000ms afterwards. Am I missing something?

I’d better clear the old register values first before then enabling additional bits in the registers.
CTC mode is enabled by setting a bit in TCCR1B.

  noInterrupts();  // disable global interrupts while setting
  // set up timer with prescaler = 64 and CTC mode
  TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B
  TCCR1B |= (1 << WGM12); // set bit for CTC mode
  TCCR1B |= (1 << CS12);  // set CS12 bit for 256 prescaler
  OCR1A = 31249; // compare value for 0.5 seconds with prescaler of 256 (2Hz)
  // Interrupt frequency (Hz) = (Arduino clock speed 16,000,000Hz) / (prescaler * (compare match register + 1))
  TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
  interrupts(); // enable gloabl interrupts

Edit: One sentence in posting striked out because of user complaint in reply #2.

Hi Jurs

The values are cleared as shown in the code:

TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B

CTC mode is enabled by setting a bit in TCCR1B.

D'oh, so it is. Thanks very much its working now.