Problem with TIMER1 CTC mode

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

Hi,

 

I have a problem which I have not been able to solve and it is making me crazy. I am using an interruption to change the width of the PWM pulse in a ATMEGA328P at every cycle. Actually my code seems to be working for a while, but after some cyclic time, the TIMER1 seems not to respond properly (see the photo attached: the high frequency signal is where my code is changing the PWM every cycle, so it is working. But after ~27ms it keeps in the same state for ~32ms. In other words, it stops working for ~32ms and it happens cyclically). Can anyone please help me to find out what is the problem with my code?

 

My timer configuration:

 cli(); //Disable interrupts

 DDRB = (1 << PORTB1); //Set port B1 as output in the in the register DDRB

 TCCR1A = 0;

 TCCR1B = 0;

 TCCR1A |= (1 << COM1A0); 

 TCCR1B |= (1 << WGM12)|(1 << WGM13); //CTC mode, using ICR1

 ICR1 = 511; 

 TIMSK1 |= (1 << OCIE1A); // OCF1A: Timer/Counter1, Output Compare A Match Flag is enabled. Interruption is executed when the TOV1 Flag is set.

 TCCR1B |= (1 << CS11); // clk/8

Sei(); //Enable interrupts

 

Code running in the interruption:

volatile int InterruptionArray [255];

volatile int counter1 = 0;

 

ISR(TIMER1_COMPA_vect)
{

   ICR1 = InterruptionArray [counter1];

   counter1++;

   

   if (counter1>ArraySize)

  {

      counter1=0;

  }

}

 

 

 

 

Attachment(s): 

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

you're probably trying to load a compare value that is less than the timer's current value - thus it has to do a full count cycle to compare match. It takes a finite amount of clock cycles after the last compare to execute the isr, save the processor state then execute your code. In the mean time, your counter has been counting.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
   ICR1 = InterruptionArray [counter1];
   counter1++;

   if (counter1>ArraySize)
     {
      counter1=0;

That is wrong, unless ArraySize is not actually the size of the array, but one less.

Stefan Ernst

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

Thank you Stefan! This was the problem. The error was blinking in front of my eyes, but I could not see it, maybe I am working too much...