Subversion Repositories Code-Repo

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
206 Kevin 1
#include <xc.h>
2
#include <plib.h>
3
#include "defines.h"
4
#include "TIMER4.h"
5
 
6
static TIMER4_DATA *timer_data_ptr;
7
 
8
void TIMER4_Init(TIMER4_DATA *data, void (*callback)(void), unsigned int time_us) {
9
    if (data != NULL) // if ptr is null, use existing data
10
        timer_data_ptr = data;
11
 
12
    timer_data_ptr->callback_function = callback;
13
 
14
    INTDisableInterrupts();
15
 
16
    T4CON = 0x0;
17
 
18
    // PR5 is 16 bits wide, so we need to determine what pre-scaler to use
19
    int time;
20
    if (time_us < 13107) {
21
        time = 5 * time_us;
22
        T4CONSET = 0x0040;         // Prescaler at 1:16
23
    } else if (time_us < 26214) {
24
        time = 2.5 * time_us;
25
        T4CONSET = 0x0050;         // Prescaler at 1:32
26
    } else if (time_us < 52428) {
27
        time = 1.25 * time_us;
28
        T4CONSET = 0x0060;         // Prescaler at 1:64
207 Kevin 29
    } else {
30
        time = 0.3125 * time_us;   // Minimum time_us of 209712
206 Kevin 31
        T4CONSET = 0x0070;         // Prescaler at 1:256
32
    }
33
 
34
    Nop();
35
    TMR4 = 0x0;             // Clear timer register
36
    PR4 = time;             // Load period register
37
    IPC4SET = 0x00000011;   // Set priority level = 4, sub-priority level = 1
38
    IFS0CLR = 0x00010000;   // Clear timer interrupt flag
39
    IEC0SET = 0x00010000;   // Enable timer interrupt
40
 
41
    INTEnableInterrupts();
42
}
43
 
44
void TIMER4_Start(void) {
45
    T4CONSET = 0x8000; // Start timer
46
}
47
 
48
void TIMER4_Stop(void) {
49
    T4CONCLR = 0x8000; // Stop timer
50
}
51
 
52
void __ISR(_TIMER_4_VECTOR, ipl4) __TIMER_4_Interrupt_Handler(void) {
53
    // Call the saved callback function
54
    (*timer_data_ptr->callback_function)();
55
 
56
    IFS0CLR = 0x00010000; // Clear the timer interrupt flag
57
}