Timing milliseconds

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

Hi

I am trying to implement a millisecond timer but it is not giving me the correct result

At program start up I initialise the counter

 

void CounterBInit(char a_Encoder)
{
   InitForEncoder = a_Encoder;

   TCC1.CTRLA = 0x05; //0x05 is divide counter clock by 64.
   TCC1.CTRLB = 0x00;
   TCC1.CTRLC = 0x00;
   TCC1.CTRLD = 0x00;
   TCC1.CTRLE = 0x00;

   TCC1.INTFLAGS = 0x00;

   TCC1.CTRLFSET = 0x00;//does other things but setting LSB to 0 means clock counts up
   TCC1.CTRLGSET = 0x00;
   TCC1.INTCTRLA = 0x03;
   TCC1.INTCTRLB = 0x03;

   TCC1.PER.i = 1;
}

 

The I add an interrupt handler

#pragma interrupt_handler CounterB:iv_TCC1_CCA
void CounterB(void)
{
   //processor 'ticks'
   // tick time is 14.7456MHz/64 = 230.4kH
   Timer = Timer + 1;

   TCC1.CCABUF.i = TCC1.CCABUF.i + 1;

}

 

And I use like so

   for(;;)
   {
      ClearInterrupts();
      timeNow = Timer;
      EnableInterrupts();
      
      if (MyTimer != timeNow)
      {
            MilliSecondsCounter += (timeNow - MyTimer) / TICKTIME;
         MyTimer = timeNow;
      }
      
      if ((MilliSecondsCounter - counter1) >= 1000)
      {
          counter1 = MilliSecondsCounter;
      }
    }

 

But the highlighted line is not called every second as I thought

 

Please can some one help me on this one?

 

Thanks

This topic has a solution.
Last Edited: Thu. Jan 23, 2020 - 03:48 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I see an assumption in that code:

   // tick time is 14.7456MHz/64 = 230.4kH

First is the code really assuming this? (I guess the setting of TICKTIME that is not shown in the excerpt is making this assumption too?)

 

Second how have you proven it really is running at 14.745MHz ?

 

You have posted in the Tiny/Mega forum yet the registers used look more like Xmega so can we conclude this is some kind of AVR-0/AVR-1 chip? They may call them "tiny"/"mega" but they are for all intents and purposes Xmega chips. One thing to note about these chips is that at power on there is typically a /6 on the CPU speed that can only be over-ridden with CCP protection. Often we see threads here where someone is just writing some CTRL register to clear such a division but they have forgotten the required CCP unlock. Perhaps that is your issue?

This reply has been marked as the solution. 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Also since timer is used in both the ISR() and main(), it needs to be declared volatile! 

Jim

 

Click Link: Get Free Stock: Retire early! PM for strategy

share.robinhood.com/jamesc3274
get $5 free gold/silver https://www.onegold.com/join/713...

 

 

 

 

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

Thanks - that did the trick