1 /**************************************************************************//**
2  * @file     timer.c
3  * @version  V3.00
4  * @brief    Timer Controller(Timer) driver source file
5  *
6  * @copyright SPDX-License-Identifier: Apache-2.0
7  * @copyright Copyright (C) 2021 Nuvoton Technology Corp. All rights reserved.
8  *****************************************************************************/
9 #include "NuMicro.h"
10 
11 
12 /** @addtogroup Standard_Driver Standard Driver
13   @{
14 */
15 
16 /** @addtogroup TIMER_Driver TIMER Driver
17   @{
18 */
19 
20 /** @addtogroup TIMER_EXPORTED_FUNCTIONS TIMER Exported Functions
21   @{
22 */
23 
24 /**
25   * @brief      Open Timer with Operate Mode and Frequency
26   *
27   * @param[in]  timer       The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
28   * @param[in]  u32Mode     Operation mode. Possible options are
29   *                         - \ref TIMER_ONESHOT_MODE
30   *                         - \ref TIMER_PERIODIC_MODE
31   *                         - \ref TIMER_TOGGLE_MODE
32   *                         - \ref TIMER_CONTINUOUS_MODE
33   * @param[in]  u32Freq     Target working frequency
34   *
35   * @return     Real timer working frequency
36   *
37   * @details    This API is used to configure timer to operate in specified mode and frequency.
38   *             If timer cannot work in target frequency, a closest frequency will be chose and returned.
39   * @note       After calling this API, Timer is \b NOT running yet. But could start timer running be calling
40   *             \ref TIMER_Start macro or program registers directly.
41   */
TIMER_Open(TIMER_T * timer,uint32_t u32Mode,uint32_t u32Freq)42 uint32_t TIMER_Open(TIMER_T *timer, uint32_t u32Mode, uint32_t u32Freq)
43 {
44     uint32_t u32Clk = TIMER_GetModuleClock(timer);
45     uint32_t u32Cmpr = 0UL, u32Prescale = 0UL;
46 
47     /* Fastest possible timer working freq is (u32Clk / 2). While cmpr = 2, prescaler = 0. */
48     if(u32Freq > (u32Clk / 2UL))
49     {
50         u32Cmpr = 2UL;
51     }
52     else
53     {
54         u32Cmpr = u32Clk / u32Freq;
55         u32Prescale = (u32Cmpr >> 24);  /* for 24 bits CMPDAT */
56         if (u32Prescale > 0UL)
57             u32Cmpr = u32Cmpr / (u32Prescale + 1UL);
58     }
59 
60     timer->CTL = u32Mode | u32Prescale;
61     timer->CMP = u32Cmpr;
62 
63     return(u32Clk / (u32Cmpr * (u32Prescale + 1UL)));
64 }
65 
66 /**
67   * @brief      Stop Timer Counting
68   *
69   * @param[in]  timer   The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
70   *
71   * @return     None
72   *
73   * @details    This API stops timer counting and disable all timer interrupt function.
74   */
TIMER_Close(TIMER_T * timer)75 void TIMER_Close(TIMER_T *timer)
76 {
77     timer->CTL = 0UL;
78     timer->EXTCTL = 0UL;
79 }
80 
81 /**
82   * @brief      Create a specify Delay Time
83   *
84   * @param[in]  timer       The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
85   * @param[in]  u32Usec     Delay period in micro seconds. Valid values are between 100~1000000 (100 micro second ~ 1 second).
86   *
87   * @retval     TIMER_OK          Delay success, target delay time reached
88   * @retval     TIMER_ERR_TIMEOUT Delay function execute failed due to timer stop working
89   *
90   * @details    This API is used to create a delay loop for u32usec micro seconds by using timer one-shot mode.
91   * @note       This API overwrites the register setting of the timer used to count the delay time.
92   * @note       This API use polling mode. So there is no need to enable interrupt for the timer module used to generate delay.
93   */
TIMER_Delay(TIMER_T * timer,uint32_t u32Usec)94 int32_t TIMER_Delay(TIMER_T *timer, uint32_t u32Usec)
95 {
96     uint32_t u32Clk = TIMER_GetModuleClock(timer);
97     uint32_t u32Prescale = 0UL, u32Delay;
98     uint32_t u32Cmpr, u32Cntr, u32NsecPerTick, i = 0UL;
99 
100     /* Clear current timer configuration */
101     timer->CTL = 0UL;
102     timer->EXTCTL = 0UL;
103 
104     if(u32Clk <= 1000000UL)   /* min delay is 1000 us if timer clock source is <= 1 MHz */
105     {
106         if(u32Usec < 1000UL)
107         {
108             u32Usec = 1000UL;
109         }
110         if(u32Usec > 1000000UL)
111         {
112             u32Usec = 1000000UL;
113         }
114     }
115     else
116     {
117         if(u32Usec < 100UL)
118         {
119             u32Usec = 100UL;
120         }
121         if(u32Usec > 1000000UL)
122         {
123             u32Usec = 1000000UL;
124         }
125     }
126 
127     if(u32Clk <= 1000000UL)
128     {
129         u32Prescale = 0UL;
130         u32NsecPerTick = 1000000000UL / u32Clk;
131         u32Cmpr = (u32Usec * 1000UL) / u32NsecPerTick;
132     }
133     else
134     {
135         u32Cmpr = u32Usec * (u32Clk / 1000000UL);
136         u32Prescale = (u32Cmpr >> 24);  /* for 24 bits CMPDAT */
137         if (u32Prescale > 0UL)
138             u32Cmpr = u32Cmpr / (u32Prescale + 1UL);
139     }
140 
141     timer->CMP = u32Cmpr;
142     timer->CTL = TIMER_CTL_CNTEN_Msk | TIMER_ONESHOT_MODE | u32Prescale;
143 
144     /* When system clock is faster than timer clock, it is possible timer active bit cannot set in time while we check it.
145        And the while loop below return immediately, so put a tiny delay larger than 1 ECLK here allowing timer start counting and raise active flag. */
146     for(u32Delay = (SystemCoreClock / u32Clk) + 1UL; u32Delay > 0UL; u32Delay--)
147     {
148         __NOP();
149     }
150 
151     /* Add a bail out counter here in case timer clock source is disabled accidentally.
152        Prescale counter reset every ECLK * (prescale value + 1).
153        The u32Delay here is to make sure timer counter value changed when prescale counter reset */
154     u32Delay = (SystemCoreClock / TIMER_GetModuleClock(timer)) * (u32Prescale + 1);
155     u32Cntr = timer->CNT;
156     while(timer->CTL & TIMER_CTL_ACTSTS_Msk)
157     {
158         /* Bailed out if timer stop counting e.g. Some interrupt handler close timer clock source. */
159         if(u32Cntr == timer->CNT)
160         {
161             if(i++ > u32Delay)
162             {
163                 return TIMER_ERR_TIMEOUT;
164             }
165         }
166         else
167         {
168             i = 0;
169             u32Cntr = timer->CNT;
170         }
171     }
172     return TIMER_OK;
173 }
174 
175 /**
176   * @brief      Enable Timer Capture Function
177   *
178   * @param[in]  timer       The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
179   * @param[in]  u32CapMode  Timer capture mode. Could be
180   *                         - \ref TIMER_CAPTURE_FREE_COUNTING_MODE
181   *                         - \ref TIMER_CAPTURE_COUNTER_RESET_MODE
182   * @param[in]  u32Edge     Timer capture trigger edge. Possible values are
183   *                         - \ref TIMER_CAPTURE_EVENT_FALLING
184   *                         - \ref TIMER_CAPTURE_EVENT_RISING
185   *                         - \ref TIMER_CAPTURE_EVENT_FALLING_RISING
186   *                         - \ref TIMER_CAPTURE_EVENT_RISING_FALLING
187   *
188   * @return     None
189   *
190   * @details    This API is used to enable timer capture function with specify capture trigger edge \n
191   *             to get current counter value or reset counter value to 0.
192   * @note       Timer frequency should be configured separately by using \ref TIMER_Open API, or program registers directly.
193   */
TIMER_EnableCapture(TIMER_T * timer,uint32_t u32CapMode,uint32_t u32Edge)194 void TIMER_EnableCapture(TIMER_T *timer, uint32_t u32CapMode, uint32_t u32Edge)
195 {
196     timer->EXTCTL = (timer->EXTCTL & ~(TIMER_EXTCTL_CAPFUNCS_Msk | TIMER_EXTCTL_CAPEDGE_Msk)) |
197                     u32CapMode | u32Edge | TIMER_EXTCTL_CAPEN_Msk;
198 }
199 
200 /**
201   * @brief      Disable Timer Capture Function
202   *
203   * @param[in]  timer   The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
204   *
205   * @return     None
206   *
207   * @details    This API is used to disable the timer capture function.
208   */
TIMER_DisableCapture(TIMER_T * timer)209 void TIMER_DisableCapture(TIMER_T *timer)
210 {
211     timer->EXTCTL &= ~TIMER_EXTCTL_CAPEN_Msk;
212 }
213 
214 /**
215   * @brief      Enable Timer Counter Function
216   *
217   * @param[in]  timer       The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
218   * @param[in]  u32Edge     Detection edge of counter pin. Could be ether
219   *                         - \ref TIMER_COUNTER_EVENT_FALLING, or
220   *                         - \ref TIMER_COUNTER_EVENT_RISING
221   *
222   * @return     None
223   *
224   * @details    This function is used to enable the timer counter function with specify detection edge.
225   * @note       Timer compare value should be configured separately by using \ref TIMER_SET_CMP_VALUE macro or program registers directly.
226   * @note       While using event counter function, \ref TIMER_TOGGLE_MODE cannot set as timer operation mode.
227   */
TIMER_EnableEventCounter(TIMER_T * timer,uint32_t u32Edge)228 void TIMER_EnableEventCounter(TIMER_T *timer, uint32_t u32Edge)
229 {
230     timer->EXTCTL = (timer->EXTCTL & ~TIMER_EXTCTL_CNTPHASE_Msk) | u32Edge;
231     timer->CTL |= TIMER_CTL_EXTCNTEN_Msk;
232 }
233 
234 /**
235   * @brief      Disable Timer Counter Function
236   *
237   * @param[in]  timer   The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
238   *
239   * @return     None
240   *
241   * @details    This API is used to disable the timer event counter function.
242   */
TIMER_DisableEventCounter(TIMER_T * timer)243 void TIMER_DisableEventCounter(TIMER_T *timer)
244 {
245     timer->CTL &= ~TIMER_CTL_EXTCNTEN_Msk;
246 }
247 
248 /**
249   * @brief      Get Timer Clock Frequency
250   *
251   * @param[in]  timer   The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
252   *
253   * @return     Timer clock frequency
254   *
255   * @details    This API is used to get the timer clock frequency.
256   * @note       This API cannot return correct clock rate if timer source is from external clock input.
257   */
TIMER_GetModuleClock(TIMER_T * timer)258 uint32_t TIMER_GetModuleClock(TIMER_T *timer)
259 {
260     uint32_t u32Src, u32Clk;
261     const uint32_t au32Clk[] = {__HXT, __LXT, 0UL, 0UL, 0UL, __LIRC, 0UL, __HIRC};
262 
263     if(timer == TIMER0)
264     {
265         u32Src = (CLK->CLKSEL1 & CLK_CLKSEL1_TMR0SEL_Msk) >> CLK_CLKSEL1_TMR0SEL_Pos;
266     }
267     else if(timer == TIMER1)
268     {
269         u32Src = (CLK->CLKSEL1 & CLK_CLKSEL1_TMR1SEL_Msk) >> CLK_CLKSEL1_TMR1SEL_Pos;
270     }
271     else if(timer == TIMER2)
272     {
273         u32Src = (CLK->CLKSEL1 & CLK_CLKSEL1_TMR2SEL_Msk) >> CLK_CLKSEL1_TMR2SEL_Pos;
274     }
275     else      /* Timer 3 */
276     {
277         u32Src = (CLK->CLKSEL1 & CLK_CLKSEL1_TMR3SEL_Msk) >> CLK_CLKSEL1_TMR3SEL_Pos;
278     }
279 
280     if(u32Src == 2UL)
281     {
282         if((timer == TIMER0) || (timer == TIMER1))
283         {
284             u32Clk = CLK_GetPCLK0Freq();
285         }
286         else
287         {
288             u32Clk = CLK_GetPCLK1Freq();
289         }
290     }
291     else
292     {
293         u32Clk = au32Clk[u32Src];
294     }
295 
296     return u32Clk;
297 }
298 
299 /**
300   * @brief This function is used to enable the Timer frequency counter function
301   * @param[in] timer The base address of Timer module. Can be \ref TIMER0 or \ref TIMER2
302   * @param[in] u32DropCount This parameter has no effect in M480 series BSP
303   * @param[in] u32Timeout This parameter has no effect in M480 series BSP
304   * @param[in] u32EnableInt Enable interrupt assertion after capture complete or not. Valid values are TRUE and FALSE
305   * @return None
306   * @details This function is used to calculate input event frequency. After enable
307   *          this function, a pair of timers, TIMER0 and TIMER1, or TIMER2 and TIMER3
308   *          will be configured for this function. The mode used to calculate input
309   *          event frequency is mentioned as "Inter Timer Trigger Mode" in Technical
310   *          Reference Manual
311   */
TIMER_EnableFreqCounter(TIMER_T * timer,uint32_t u32DropCount,uint32_t u32Timeout,uint32_t u32EnableInt)312 void TIMER_EnableFreqCounter(TIMER_T *timer,
313                              uint32_t u32DropCount,
314                              uint32_t u32Timeout,
315                              uint32_t u32EnableInt)
316 {
317     TIMER_T *t;    /* store the timer base to configure compare value */
318 
319     t = (timer == TIMER0) ? TIMER1 : TIMER3;
320 
321     t->CMP = 0xFFFFFFUL;
322     t->EXTCTL = u32EnableInt ? TIMER_EXTCTL_CAPIEN_Msk : 0UL;
323     timer->CTL = TIMER_CTL_INTRGEN_Msk | TIMER_CTL_CNTEN_Msk;
324 
325     return;
326 }
327 
328 /**
329   * @brief This function is used to disable the Timer frequency counter function.
330   * @param[in] timer The base address of Timer module
331   * @return None
332   */
TIMER_DisableFreqCounter(TIMER_T * timer)333 void TIMER_DisableFreqCounter(TIMER_T *timer)
334 {
335     timer->CTL &= ~TIMER_CTL_INTRGEN_Msk;
336 }
337 
338 /**
339   * @brief This function is used to select the interrupt source used to trigger other modules.
340   * @param[in] timer The base address of Timer module
341   * @param[in] u32Src Selects the interrupt source to trigger other modules. Could be:
342   *              - \ref TIMER_TRGSRC_TIMEOUT_EVENT
343   *              - \ref TIMER_TRGSRC_CAPTURE_EVENT
344   * @return None
345   */
TIMER_SetTriggerSource(TIMER_T * timer,uint32_t u32Src)346 void TIMER_SetTriggerSource(TIMER_T *timer, uint32_t u32Src)
347 {
348     timer->TRGCTL = (timer->TRGCTL & ~TIMER_TRGCTL_TRGSSEL_Msk) | u32Src;
349 }
350 
351 /**
352   * @brief This function is used to set modules trigger by timer interrupt
353   * @param[in] timer The base address of Timer module
354   * @param[in] u32Mask The mask of modules (EPWM/BPWM, EADC, DAC and PDMA) trigger by timer. Is the combination of
355   *             - \ref TIMER_TRG_TO_PWM,
356   *             - \ref TIMER_TRG_TO_EADC,
357   *             - \ref TIMER_TRG_TO_DAC, and
358   *             - \ref TIMER_TRG_TO_PDMA
359   * @return None
360   */
TIMER_SetTriggerTarget(TIMER_T * timer,uint32_t u32Mask)361 void TIMER_SetTriggerTarget(TIMER_T *timer, uint32_t u32Mask)
362 {
363     timer->TRGCTL = (timer->TRGCTL & ~(TIMER_TRGCTL_TRGPWM_Msk | TIMER_TRGCTL_TRGDAC_Msk | TIMER_TRGCTL_TRGEADC_Msk | TIMER_TRGCTL_TRGPDMA_Msk)) | u32Mask;
364 }
365 
366 /**
367   * @brief      Reset Counter
368   *
369   * @param[in]  timer       The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
370   *
371   * @retval     TIMER_OK          Timer reset success
372   * @retval     TIMER_ERR_TIMEOUT Timer reset failed
373   *
374   * @details    This function is used to reset current counter value and internal prescale counter value.
375   */
TIMER_ResetCounter(TIMER_T * timer)376 int32_t TIMER_ResetCounter(TIMER_T *timer)
377 {
378     uint32_t u32Delay;
379 
380     timer->CNT = 0UL;
381     /* Takes 2~3 ECLKs to reset timer counter */
382     u32Delay = (SystemCoreClock / TIMER_GetModuleClock(timer)) * 3;
383     while(((timer->CNT&TIMER_CNT_RSTACT_Msk) == TIMER_CNT_RSTACT_Msk) && (--u32Delay))
384     {
385         __NOP();
386     }
387     return u32Delay > 0 ? TIMER_OK : TIMER_ERR_TIMEOUT;
388 }
389 
390 /**
391   * @brief      Enable Capture Input Noise Filter Function
392   *
393   * @param[in]  timer           The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
394   *
395   * @param[in]  u32FilterCount  Noise filter counter. Valid values are between 0~7.
396   *
397   * @param[in]  u32ClkSrcSel    Noise filter counter clock source, could be one of following source
398   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_1
399   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_2
400   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_4
401   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_8
402   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_16
403   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_32
404   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_64
405   *                                 - \ref TIMER_CAPTURE_NOISE_FILTER_PCLK_DIV_128
406   *
407   * @return     None
408   *
409   * @details    This function is used to enable capture input noise filter function.
410   */
TIMER_EnableCaptureInputNoiseFilter(TIMER_T * timer,uint32_t u32FilterCount,uint32_t u32ClkSrcSel)411 void TIMER_EnableCaptureInputNoiseFilter(TIMER_T *timer, uint32_t u32FilterCount, uint32_t u32ClkSrcSel)
412 {
413     timer->CAPNF = (((timer)->CAPNF & ~(TIMER_CAPNF_CAPNFCNT_Msk | TIMER_CAPNF_CAPNFSEL_Msk))
414                     | (TIMER_CAPNF_CAPNFEN_Msk | (u32FilterCount << TIMER_CAPNF_CAPNFCNT_Pos) | (u32ClkSrcSel << TIMER_CAPNF_CAPNFSEL_Pos)));
415 }
416 
417 /**
418   * @brief      Disable Capture Input Noise Filter Function
419   *
420   * @param[in]  timer       The pointer of the specified Timer module. It could be TIMER0, TIMER1, TIMER2, TIMER3.
421   *
422   * @return     None
423   *
424   * @details    This function is used to disable capture input noise filter function.
425   */
TIMER_DisableCaptureInputNoiseFilter(TIMER_T * timer)426 void TIMER_DisableCaptureInputNoiseFilter(TIMER_T *timer)
427 {
428     timer->CAPNF &= ~TIMER_CAPNF_CAPNFEN_Msk;
429 }
430 
431 /*@}*/ /* end of group TIMER_EXPORTED_FUNCTIONS */
432 
433 /*@}*/ /* end of group TIMER_Driver */
434 
435 /*@}*/ /* end of group Standard_Driver */
436