gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

DS development > Timers

#133283 - yellowstar - Wed Jul 04, 2007 11:13 pm

I need some help with timers.

How do I use timers, on both processors?

#133288 - Lick - Wed Jul 04, 2007 11:57 pm

Code:
    // Handler
void timer0_handler() {
...
}


int main() {
  // Initialize libnds interrupts system
    irqInit();

  // Set IRQ handler and enable it
    irqSet(IRQ_TIMER0, timer0_handler);
    irqEnable(IRQ_TIMER0);

  // Start timer
    TIMER0_DATA = 0xFFFF - 32768;
    TIMER0_CR = TIMER_ENABLE | TIMER_DIV_1024 | TIMER_IRQ_REQ;

  // Stop timer
    TIMER0_CR = 0;
}


You can also use the same code for TIMER1, TIMER2 and TIMER3.

TIMER_DIV_1024 - TIMER_DIV_256 - TIMER_DIV_64 - TIMER_DIV_1, represent the divider of the frequency in which the timer increments. (These dividers are not dependent on the timer id. For example, all four timers can run at TIMER_DIV_1.) According to Gbatek the timers run at 33554432 Hz. That's 33 million times per second. The TIMERx_DATA value is only 16 bits, so it cannot hold a value large enough to to make a 1 second timer for that clockspeed. Now if you divide the clockspeed by a value of 1024, you'll get 33554432 / 1024 = 32768. That's the amount of increments a timer with TIMER_DIV_1024 will do in a second, and pleasantly it fits inside the 16 bits TIMERx_DATA register.
In the real world you will pick your timer according to the amount of precision you want. And since you only have 4 timers, it's also wise to code your own timer system around a highest precision timer.
_________________
http://licklick.wordpress.com