Skip to content

Hardware Timer

Adan edited this page Jul 7, 2020 · 3 revisions

Using the hardware timer

The GP2X as one hardware timer, which is a simple 32-bit unsigned counter that increments by 1 tick every 0.135uS. When the counter reaches 0xFFFFFFFF it overflows back to 0 and continues counting. Some Orcus functions use the timer internally, but do not alter its value.

You can obtain the current timer value by calling timerGet() which simply returns the current tick.

It is possible to set the timer to begin counting at a particular point with timerSet(value), but Orcus provides some utility functions to enable its use without having to do so. Contrary to the warning in the MMSP2 documentation, it is possible to manually assign the value of the counter, however it isn't possible to assign it to the value 0. If you attempt to do so, Orcus will instead set it to start counting from 1.

Counting time since last frame/loop

A common use of the counter may be to figure out how long as elapsed since your main loop was last entered. You can use timerNsSince for this. It takes the value of the timer at the last iteration, and optionally a pointer to a uint32_t which it will update with the current timer value.

uint32_t lastTime = timerGet();
while(true) {
  unsigned int elapsedNs = timerNsSince(lastTime, &lastTime);
  printf("%u ns have elapsed\n", elapsedNs);
}

Timeout

You can also use timerNsSince for timeouts, as if you pass NULL for the second parameter, it will be ignored and won't try to update any variable.

uint32_t startTime = timerGet();
doSomething();
while(somethingHasNotFinished()) {
  if(timerNsSince(startTime, NULL) > 20000000) {
    printf("Something timed out, 20ms\n");
    break;
  }
}

Sleep

You can use the standard usleep and nanosleep functions to pause execution for an arbitrary amount of time. Internally, these call through to timerSleepNs which you can call directly if you wish.

Clone this wiki locally