]> rtime.felk.cvut.cz Git - mirosot.git/blob - autodemo/timer3.c
Autodemo updated, timer routeines calculate proper values for given timer period.
[mirosot.git] / autodemo / timer3.c
1 #include <timer3.h>
2 #include <mcu_regs.h>
3 #include <cpu_def.h>
4 #include <system_def.h>
5
6 static volatile timer_t timer;
7
8 static void  timer_isr(void) __attribute__ ((interrupt_handler));
9
10 static void 
11 timer_isr(void)
12 {
13     timer++;
14     //*TPU_TSR3 &= ~TSR2_TCFVm ; //reset overflow flag (clear interrupt)
15     *TPU_TSR3 &= ~TSR3_TCFVm & ~TSR3_TGFAm; //reset overflow and comare match flags
16 }    
17
18 //timer initialisation
19 /*free running counter*/
20 int init_timer3(long long nsec)
21 {
22 #define CPU_CYCLE_NSEC (1000000000/CPU_SYS_HZ)
23   long long timer_tick = CPU_CYCLE_NSEC;
24   int presc_ind = 0;
25   const signed char presc_tab[] = {0,1,2,3,6,5,7,-1};
26   long long nsec_scaled = nsec >> 16;
27   while (presc_ind < 8 &&
28          (timer_tick < nsec_scaled
29           || presc_tab[presc_ind] < 0)) {
30     presc_ind++;
31     timer_tick <<= 2;
32   }
33   if (timer_tick < nsec_scaled)
34     return -1;
35
36
37   *SYS_MSTPCRA &= ~MSTPCRA_TPUm; // power TPU unit
38   
39   *TPU_TCR3 = TCR3_CCLR0m | presc_tab[presc_ind]; //rising edge, cleared by TGA, prescaler is calculated
40   *TPU_TMDR3 =0x00;             // normal mode
41   *TPU_TIOR3L = TIOR3L_IOC1m;   // output 1 at compare match
42   *TPU_TSR3 &= ~TSR3_TCFVm & ~TSR3_TGFAm; //reset overflow and comare match flags
43   //*TPU_TIER3 |=TIER3_TCIEVm;    //enable overflow interrupt
44   *TPU_TIER3 |=TIER3_TGIEAm;    //enable compare match interrupt
45   *TPU_TGR3A = (unsigned)(nsec/timer_tick);
46
47   *TPU_TSTR |=TSTR_CST3m;       //start timer
48   
49   //excptvec_set(EXCPTVEC_TCI3V, timer_isr);  /* handle overflow interrupt */
50   excptvec_set(EXCPTVEC_TGI3A, timer_isr); /* handle TGRA match interrupt */
51   return 0;
52 }
53
54 timer_t get_timer()
55 {
56   return timer;
57 }