Skip to content
Ryan Summers edited this page Oct 19, 2015 · 9 revisions

Timer Example

This page contains information describing the provided timer example. Examples can be located in the example folder within the repository.


/********************************************************
 *   File Name: timer_ex.c
 *
 *   Description:
 *              Main file
 *
 *
 *********************************************************/

/*************************************************************************
 System Includes
 ************************************************************************/
#include "sublibinal.h"
#include "sublibinal_config.h"

//forward declarations
void timer_callback();

/*************************************************************************
 Main Function
 ************************************************************************/
int main(void) {

    //structures for configuring peripherals
    Timer_Config timer_config = {0};
    
    //Configure our output pin, PB3
    ANSELBbits.ANSB3 = 0; //digital pin
    TRISBbits.TRISB3 = 0; //output

    //setup peripherals
    timer_config.frequency = 1; //Have the timer trigger at a rate of 1Hz
    timer_config.pbclk = 15000000; //The peripheral bus clock is configured to operate at 15MHz
    timer_config.which_timer = Timer_1; //Use Timer 1
    timer_config.callback = &timer_callback; //Hand a callback function for the ISR
    timer_config.enabled = 1; //Enable the Timer
    initialize_Timer(timer_config); //Initialize the timer module
 
    //Global interrupt enable. Do this last!
	enable_Interrupts();

    while (1) {
        //background tasks here, if necessary
    }

    return 0;
}

void timer_callback(void)
{
    //toggle a pin
    LATBINV = 1<<3;
    
}

This example demonstrates how to configure and initialize a timer. There are a number of key steps to note. When the program initializes the Timer_Config structure, it initializes the entire structure to 0 by calling Timer_Config timer_config = {0};. This ensures that parameters are always nonzero if explicitly set. The next portion of code fills out the configuration for the structure. The frequency is set to 1000, which means the timer interrupt will occur 1000 times per second, or 1 KHz. A callback function is also supplied for the timer_callback() function. That means every time an interrupt occurs, this function will be executed.
The end result of this program is the toggling of pin PB0 1000 times per second.

top

Clone this wiki locally