Hi all,

I just started to program with Arduino, and while I was testing timer1 interrupt, I have the next problem: the interrupt routine is executed twice, and the only way for having a only execution, is setting an one logic in the timer1 interrupt flag. Hence I know the solution, I don’t know where is the problem, because datasheet says, when the timer1 interrupt routine is totally executed, automatically the flag is set to one.

This is the code:

int cont =0;

void setup()
   DDRD = 0x20; 

   OCR1A = 15624;

   TCCR1A &= ~(1 << WGM11);
   TCCR1A &= ~(1 << WGM10);
   TCCR1B &= ~(1 << WGM13);
   TCCR1B |= (1 << WGM12);
   // Mode 4, CTC on OCR1A

   TIMSK1 |= (1 << OCIE1A);
   TIMSK1 &= ~(1 << OCIE1B);
   TIMSK1 &= ~(1 << ICIE1);
   TIMSK1 &= ~(1 << TOIE0);
   //Set interrupt on compare match
   TCCR1B &= ~(1 << CS11);
   TCCR1B |= (1 << CS12) | (1 << CS10);
   // set prescaler to 1024 and start the timer
   // enable interrupts

   // action to be done every 1 sec
   if(PORTD == 0x20)
      PORTD &= ~(1 << PORTD5);
      PORTD |= (1 << PORTD5);
[color=red]   TIFR1 |= (1 << OCF1A);
[/color]    TCNT1=0;

void loop()

I hope you guys have the answer.


First off, you cannot use serial in an ISR. http://www.gammon.com.au/forum/?id=11488

The fact that you have Serial.print() in the ISR (which you should not) may mean that another interrupt has stacked up before the first one is complete and then executes the instant the first interrupt finishes.


Please edit your post, select the code, and put it between [code][/code] tags.

You can do that by hitting the # button above the posting area.

How to use this forum


What Robin2 and LarryD said.

The interrupt flag may have already been set. You can clear it in advance:

 TIFR1 |= bit (OCF1A);    // clear interrupt flag

Before you wait for the interrupt. No point doing it where you had it.

I've had success using the serial port from within an ISR by writing only one byte directly to the port, UDR0. It's fairly limited and the baud rate and interrupt frequency also have to be considered. Generally it's a better idea to save the value and then use Serial.print from within loop(). You could do that with your variable "cont". I believe that you would want to make it volatile if you're going to do that.