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