| 206 |
Kevin |
1 |
#include "defines.h"
|
|
|
2 |
#include "TIMER4.h"
|
|
|
3 |
|
|
|
4 |
static TIMER4_DATA *timer_data_ptr;
|
|
|
5 |
|
| 237 |
Kevin |
6 |
void TIMER4_Init(TIMER4_DATA *data, void (*callback_ms)(void),
|
|
|
7 |
void (*callback_div)(void), uint32_t time_ms) {
|
|
|
8 |
|
| 206 |
Kevin |
9 |
if (data != NULL) // if ptr is null, use existing data
|
|
|
10 |
timer_data_ptr = data;
|
|
|
11 |
|
| 237 |
Kevin |
12 |
// The first callback function will be executed every ms
|
|
|
13 |
timer_data_ptr->callback_function_1 = callback_ms;
|
|
|
14 |
// The second callback function will be executed at the multiplier specified
|
|
|
15 |
timer_data_ptr->callback_function_2 = callback_div;
|
|
|
16 |
timer_data_ptr->divider = time_ms;
|
|
|
17 |
timer_data_ptr->count = 0;
|
| 206 |
Kevin |
18 |
|
|
|
19 |
INTDisableInterrupts();
|
|
|
20 |
|
|
|
21 |
T4CON = 0x0;
|
|
|
22 |
|
| 237 |
Kevin |
23 |
// Set timer to trigger every millisecond
|
|
|
24 |
uint16_t time = 5000;
|
|
|
25 |
T4CONSET = 0x0040; // Prescaler at 1:16
|
| 206 |
Kevin |
26 |
|
|
|
27 |
Nop();
|
|
|
28 |
TMR4 = 0x0; // Clear timer register
|
|
|
29 |
PR4 = time; // Load period register
|
| 237 |
Kevin |
30 |
IPC4SET = 0x00000005; // Set priority level = 1, sub-priority level = 1
|
| 206 |
Kevin |
31 |
IFS0CLR = 0x00010000; // Clear timer interrupt flag
|
|
|
32 |
IEC0SET = 0x00010000; // Enable timer interrupt
|
|
|
33 |
|
|
|
34 |
INTEnableInterrupts();
|
|
|
35 |
}
|
|
|
36 |
|
|
|
37 |
void TIMER4_Start(void) {
|
|
|
38 |
T4CONSET = 0x8000; // Start timer
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
void TIMER4_Stop(void) {
|
|
|
42 |
T4CONCLR = 0x8000; // Stop timer
|
|
|
43 |
}
|
|
|
44 |
|
|
|
45 |
void __ISR(_TIMER_4_VECTOR, ipl4) __TIMER_4_Interrupt_Handler(void) {
|
|
|
46 |
// Call the saved callback function
|
| 264 |
Kevin |
47 |
if (timer_data_ptr->callback_function_1 != NULL)
|
|
|
48 |
(*timer_data_ptr->callback_function_1)();
|
| 206 |
Kevin |
49 |
|
| 237 |
Kevin |
50 |
if (timer_data_ptr->divider != 0 && timer_data_ptr->callback_function_2 != NULL) {
|
|
|
51 |
if (timer_data_ptr->count == timer_data_ptr->divider) {
|
|
|
52 |
(*timer_data_ptr->callback_function_2)();
|
|
|
53 |
timer_data_ptr->count = 0;
|
|
|
54 |
} else {
|
|
|
55 |
timer_data_ptr->count++;
|
|
|
56 |
}
|
|
|
57 |
}
|
|
|
58 |
|
| 206 |
Kevin |
59 |
IFS0CLR = 0x00010000; // Clear the timer interrupt flag
|
|
|
60 |
}
|