Subversion Repositories Code-Repo

Rev

Rev 234 | Rev 276 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include "defines.h"
#include "TIMER5.h"

static TIMER5_DATA *timer_data_ptr;

void TIMER5_Init(TIMER5_DATA *data, void (*callback)(void), uint32_t time_us) {
    if (data != NULL) // if ptr is null, use existing data
        timer_data_ptr = data;

    timer_data_ptr->callback_function = callback;

    INTDisableInterrupts();

    T5CON = 0x0;

    // PR5 is 16 bits wide, so we need to determine what pre-scaler to use
    uint16_t time;
    if (time_us < 13107) {
        time = 5 * time_us;
        T5CONSET = 0x0040;         // Prescaler at 1:16
    } else if (time_us < 26214) {
        time = 2.5 * time_us;
        T5CONSET = 0x0050;         // Prescaler at 1:32
    } else if (time_us < 52428) {
        time = 1.25 * time_us;
        T5CONSET = 0x0060;         // Prescaler at 1:64
    } else { // Maximum time_us of 209712
        time = 0.3125 * time_us;
        T5CONSET = 0x0070;         // Prescaler at 1:256
    }

    Nop();
    TMR5 = 0x0;             // Clear timer register
    PR5 = time;             // Load period register
    IPC5SET = 0x0000000D;   // Set priority level = 3, sub-priority level = 1
    IFS0CLR = 0x00100000;   // Clear timer interrupt flag
    IEC0SET = 0x00100000;   // Enable timer interrupt

    INTEnableInterrupts();
}

void TIMER5_Start(void) {
    T5CONSET = 0x8000; // Start timer
}

void TIMER5_Stop(void) {
    T5CONCLR = 0x8000; // Stop timer
}

void __ISR(_TIMER_5_VECTOR, ipl4) __TIMER_5_Interrupt_Handler(void) {
    // Call the saved callback function
    (*timer_data_ptr->callback_function)();

    IFS0CLR = 0x00100000; // Clear the timer interrupt flag
}