drv_systick.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**************************************************************************//**
  2. *
  3. * @copyright (C) 2020 Nuvoton Technology Corp. All rights reserved.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Change Logs:
  8. * Date Author Notes
  9. * 2020-11-11 Wayne First version
  10. *
  11. ******************************************************************************/
  12. #include "rtthread.h"
  13. #include "NuMicro.h"
  14. #include "drv_sys.h"
  15. #define USE_TIMER 5
  16. /* Concatenate */
  17. #define _CONCAT2_(x, y) x##y
  18. #define CONCAT2(x, y) _CONCAT2_(x, y)
  19. /* Concatenate the macros of timer instance for driver usage. */
  20. #define SYSTICK CONCAT2(TIMER, USE_TIMER)
  21. #define SYSTICK_IRQ CONCAT2(IRQ_TIMER, USE_TIMER)
  22. static void nu_systick_isr(int vector, void *param)
  23. {
  24. rt_tick_increase();
  25. ETIMER_ClearIntFlag(USE_TIMER);
  26. }
  27. void rt_hw_systick_init(void)
  28. {
  29. nu_sys_ipclk_enable(TIMER5CKEN);
  30. nu_sys_ip_reset(TIMER5RST);
  31. // Set timer frequency
  32. ETIMER_Open(USE_TIMER, ETIMER_PERIODIC_MODE, RT_TICK_PER_SECOND);
  33. // Enable timer interrupt
  34. ETIMER_EnableInt(USE_TIMER);
  35. rt_hw_interrupt_install(SYSTICK_IRQ, nu_systick_isr, RT_NULL, "systick");
  36. rt_hw_interrupt_set_priority(SYSTICK_IRQ, IRQ_LEVEL_1);
  37. rt_hw_interrupt_umask(SYSTICK_IRQ);
  38. ETIMER_Start(USE_TIMER);
  39. } /* rt_hw_systick_init */
  40. void rt_hw_us_delay(rt_uint32_t us)
  41. {
  42. rt_uint32_t ticks;
  43. rt_uint32_t told, tnow, tcnt = 0;
  44. rt_uint32_t cmp = ETIMER_GetCompareData(USE_TIMER);
  45. ticks = us * cmp / (1000000 / RT_TICK_PER_SECOND);
  46. told = ETIMER_GetCounter(USE_TIMER);
  47. while (1)
  48. {
  49. /* Timer counter is increment. */
  50. tnow = ETIMER_GetCounter(USE_TIMER);
  51. if (tnow != told)
  52. {
  53. /* 0 -- old === now -------- cmp */
  54. if (tnow > told)
  55. {
  56. tcnt += tnow - told;
  57. }
  58. else
  59. {
  60. /* 0 == now --- old ======== cmp */
  61. tcnt += cmp - told + tnow;
  62. }
  63. told = tnow;
  64. /* Timeout */
  65. if (tcnt >= ticks)
  66. {
  67. break;
  68. }
  69. }
  70. }
  71. } /* rt_hw_us_delay */