Using the 32-bit Core Timer

One of the features of the PIC32 that I have so far somewhat left out in my “explorations” is the 32-bit Core Timer. This is in fact a piece of the MIPS M4K core itself and is common to all MIPS processors. This makes it a very popular item in typical MIPS literature, but from the PIC32 perspective (and in particular my 8-bitter perspective) this is an odd element that I decided not to focus on. And I don’t mean “odd” in a bad way, it just does not find an equivalent in the traditional Microchip architectures, where all timers are numbered and there is a long legacy and compatibility trail for each one of them. The Core Timer is in fact pretty useful and here I would like to illustrate the most obvious use we have for it…

The Core Timer being attached to the “core” (doh) is fed by the system clock rather than the peripheral bus clock like all other timers. This makes it the natural candidate for all sort of scheduling, benchmarking and self timing applications.

The other peculiar thing about this timer is that it is a 32-bit timer, no need to pair it up like we do with the others (Timer2 and Timer3 or Timer4 and Timer5) and it has a fixed prescaler 1:2.

In other words, when operating at 80MHz, it will be able to provide you with a time interval measurement of up to about 110 seconds with a resolution of 25ns.

To use it, I recommend the standard peripheral libraries: timer.h contains all the macros, prototypes and definitions that you need to know.

In order to use the Core Timer as a real time stopwatch we can define two simple functions: start_timer and read_timer as follows.

void start_timer( void)
{   // resets the core timer count
    WriteCoreTimer( 0);
} // start_timer

double read_timer( void)
{
    unsigned int ui;

    // get the core timer count
    ui = ReadCoreTimer();

    // convert in seconds (1 core tick = 2 SYS cycles)
   return ( ui * 2.0 /FSYS);
} // read_timer

While start_timer()  is pretty straightforward, read_timer() needs a little extra explanation:

  • To read the timer count, use an unsigned int to get access to all 32-bit of the timer
  • To convert the count into a meaningful indication in seconds, we need to divide the count by half of the system clock frequency, but do so in floating point or you will loose a lot of resolution while performing the division. (Note the 2.0 factor that forces the compiler to switch to floating point before the division)
This entry was posted in PIC32, Tips and Tricks. Bookmark the permalink.