app_timer.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. /* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved.
  2. *
  3. * The information contained herein is property of Nordic Semiconductor ASA.
  4. * Terms and conditions of usage are described in detail in NORDIC
  5. * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
  6. *
  7. * Licensees are granted free, non-transferable use of the information. NO
  8. * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
  9. * the file.
  10. *
  11. */
  12. #include "app_timer.h"
  13. #include <stdlib.h>
  14. #include "nrf.h"
  15. #include "nrf_soc.h"
  16. #include "app_error.h"
  17. #include "nrf_delay.h"
  18. #include "app_util_platform.h"
  19. #include "sdk_common.h"
  20. #define RTC1_IRQ_PRI APP_IRQ_PRIORITY_LOW /**< Priority of the RTC1 interrupt (used for checking for timeouts and executing timeout handlers). */
  21. #define SWI_IRQ_PRI APP_IRQ_PRIORITY_LOW /**< Priority of the SWI interrupt (used for updating the timer list). */
  22. // The current design assumes that both interrupt handlers run at the same interrupt level.
  23. // If this is to be changed, protection must be added to prevent them from interrupting each other
  24. // (e.g. by using guard/trigger flags).
  25. STATIC_ASSERT(RTC1_IRQ_PRI == SWI_IRQ_PRI);
  26. #define MAX_RTC_COUNTER_VAL 0x00FFFFFF /**< Maximum value of the RTC counter. */
  27. #define APP_HIGH_USER_ID 0 /**< User Id for the Application High "user". */
  28. #define APP_LOW_USER_ID 1 /**< User Id for the Application Low "user". */
  29. #define THREAD_MODE_USER_ID 2 /**< User Id for the Thread Mode "user". */
  30. #define RTC_COMPARE_OFFSET_MIN 3 /**< Minimum offset between the current RTC counter value and the Capture Compare register. Although the nRF51 Series User Specification recommends this value to be 2, we use 3 to be safer.*/
  31. #define MAX_RTC_TASKS_DELAY 47 /**< Maximum delay until an RTC task is executed. */
  32. #ifdef NRF51
  33. #define SWI_IRQn SWI0_IRQn
  34. #define SWI_IRQHandler SWI0_IRQHandler
  35. #elif defined NRF52
  36. #define SWI_IRQn SWI0_EGU0_IRQn
  37. #define SWI_IRQHandler SWI0_EGU0_IRQHandler
  38. #endif
  39. /**@brief Timer node type. The nodes will be used form a linked list of running timers. */
  40. typedef struct
  41. {
  42. uint32_t ticks_to_expire; /**< Number of ticks from previous timer interrupt to timer expiry. */
  43. uint32_t ticks_at_start; /**< Current RTC counter value when the timer was started. */
  44. uint32_t ticks_first_interval; /**< Number of ticks in the first timer interval. */
  45. uint32_t ticks_periodic_interval; /**< Timer period (for repeating timers). */
  46. bool is_running; /**< True if timer is running, False otherwise. */
  47. app_timer_mode_t mode; /**< Timer mode. */
  48. app_timer_timeout_handler_t p_timeout_handler; /**< Pointer to function to be executed when the timer expires. */
  49. void * p_context; /**< General purpose pointer. Will be passed to the timeout handler when the timer expires. */
  50. void * next; /**< Pointer to the next node. */
  51. } timer_node_t;
  52. STATIC_ASSERT(sizeof(timer_node_t) == APP_TIMER_NODE_SIZE);
  53. /**@brief Set of available timer operation types. */
  54. typedef enum
  55. {
  56. TIMER_USER_OP_TYPE_NONE, /**< Invalid timer operation type. */
  57. TIMER_USER_OP_TYPE_START, /**< Timer operation type Start. */
  58. TIMER_USER_OP_TYPE_STOP, /**< Timer operation type Stop. */
  59. TIMER_USER_OP_TYPE_STOP_ALL /**< Timer operation type Stop All. */
  60. } timer_user_op_type_t;
  61. /**@brief Structure describing a timer start operation. */
  62. typedef struct
  63. {
  64. uint32_t ticks_at_start; /**< Current RTC counter value when the timer was started. */
  65. uint32_t ticks_first_interval; /**< Number of ticks in the first timer interval. */
  66. uint32_t ticks_periodic_interval; /**< Timer period (for repeating timers). */
  67. void * p_context; /**< General purpose pointer. Will be passed to the timeout handler when the timer expires. */
  68. } timer_user_op_start_t;
  69. /**@brief Structure describing a timer operation. */
  70. typedef struct
  71. {
  72. timer_user_op_type_t op_type; /**< Id of timer on which the operation is to be performed. */
  73. timer_node_t * p_node;
  74. union
  75. {
  76. timer_user_op_start_t start; /**< Structure describing a timer start operation. */
  77. } params;
  78. } timer_user_op_t;
  79. STATIC_ASSERT(sizeof(timer_user_op_t) <= APP_TIMER_USER_OP_SIZE);
  80. STATIC_ASSERT(sizeof(timer_user_op_t) % 4 == 0);
  81. /**@brief Structure describing a timer user.
  82. *
  83. * @details For each user of the timer module, there will be a timer operations queue. This queue
  84. * will hold timer operations issued by this user until the timer interrupt handler
  85. * processes these operations. For the current implementation, there will be one user for
  86. * each interrupt level available to the application (APP_HIGH, APP_LOW and THREAD_MODE),
  87. * but the module can easily be modified to e.g. have one queue per process when using an
  88. * RTOS. The purpose of the queues is to be able to have a completely lockless timer
  89. * implementation.
  90. */
  91. typedef struct
  92. {
  93. uint8_t first; /**< Index of first entry to have been inserted in the queue (i.e. the next entry to be executed). */
  94. uint8_t last; /**< Index of last entry to have been inserted in the queue. */
  95. uint8_t user_op_queue_size; /**< Queue size. */
  96. timer_user_op_t * p_user_op_queue; /**< Queue buffer. */
  97. } timer_user_t;
  98. STATIC_ASSERT(sizeof(timer_user_t) == APP_TIMER_USER_SIZE);
  99. STATIC_ASSERT(sizeof(timer_user_t) % 4 == 0);
  100. /**@brief User id type.
  101. *
  102. * @details In the current implementation, this will automatically be generated from the current
  103. * interrupt level.
  104. */
  105. typedef uint32_t timer_user_id_t;
  106. #define CONTEXT_QUEUE_SIZE_MAX (2)
  107. static uint8_t m_user_array_size; /**< Size of timer user array. */
  108. static timer_user_t * mp_users = NULL; /**< Array of timer users. */
  109. static timer_node_t * mp_timer_id_head; /**< First timer in list of running timers. */
  110. static uint32_t m_ticks_latest; /**< Last known RTC counter value. */
  111. static uint32_t m_ticks_elapsed[CONTEXT_QUEUE_SIZE_MAX]; /**< Timer internal elapsed ticks queue. */
  112. static uint8_t m_ticks_elapsed_q_read_ind; /**< Timer internal elapsed ticks queue read index. */
  113. static uint8_t m_ticks_elapsed_q_write_ind; /**< Timer internal elapsed ticks queue write index. */
  114. static app_timer_evt_schedule_func_t m_evt_schedule_func; /**< Pointer to function for propagating timeout events to the scheduler. */
  115. static bool m_rtc1_running; /**< Boolean indicating if RTC1 is running. */
  116. static bool m_rtc1_reset; /**< Boolean indicating if RTC1 counter has been reset due to last timer removed from timer list during the timer list handling. */
  117. #ifdef APP_TIMER_WITH_PROFILER
  118. static uint8_t m_max_user_op_queue_utilization; /**< Maximum observed timer user operations queue utilization. */
  119. #endif
  120. #define MODULE_INITIALIZED (mp_users != NULL)
  121. #include "sdk_macros.h"
  122. /**@brief Function for initializing the RTC1 counter.
  123. *
  124. * @param[in] prescaler Value of the RTC1 PRESCALER register. Set to 0 for no prescaling.
  125. */
  126. static void rtc1_init(uint32_t prescaler)
  127. {
  128. NRF_RTC1->PRESCALER = prescaler;
  129. NVIC_SetPriority(RTC1_IRQn, RTC1_IRQ_PRI);
  130. }
  131. /**@brief Function for starting the RTC1 timer.
  132. */
  133. static void rtc1_start(void)
  134. {
  135. NRF_RTC1->EVTENSET = RTC_EVTEN_COMPARE0_Msk;
  136. NRF_RTC1->INTENSET = RTC_INTENSET_COMPARE0_Msk;
  137. NVIC_ClearPendingIRQ(RTC1_IRQn);
  138. NVIC_EnableIRQ(RTC1_IRQn);
  139. NRF_RTC1->TASKS_START = 1;
  140. nrf_delay_us(MAX_RTC_TASKS_DELAY);
  141. m_rtc1_running = true;
  142. }
  143. /**@brief Function for stopping the RTC1 timer.
  144. */
  145. static void rtc1_stop(void)
  146. {
  147. NVIC_DisableIRQ(RTC1_IRQn);
  148. NRF_RTC1->EVTENCLR = RTC_EVTEN_COMPARE0_Msk;
  149. NRF_RTC1->INTENCLR = RTC_INTENSET_COMPARE0_Msk;
  150. NRF_RTC1->TASKS_STOP = 1;
  151. nrf_delay_us(MAX_RTC_TASKS_DELAY);
  152. NRF_RTC1->TASKS_CLEAR = 1;
  153. m_ticks_latest = 0;
  154. nrf_delay_us(MAX_RTC_TASKS_DELAY);
  155. m_rtc1_running = false;
  156. }
  157. /**@brief Function for returning the current value of the RTC1 counter.
  158. *
  159. * @return Current value of the RTC1 counter.
  160. */
  161. static __INLINE uint32_t rtc1_counter_get(void)
  162. {
  163. return NRF_RTC1->COUNTER;
  164. }
  165. /**@brief Function for computing the difference between two RTC1 counter values.
  166. *
  167. * @return Number of ticks elapsed from ticks_old to ticks_now.
  168. */
  169. static __INLINE uint32_t ticks_diff_get(uint32_t ticks_now, uint32_t ticks_old)
  170. {
  171. return ((ticks_now - ticks_old) & MAX_RTC_COUNTER_VAL);
  172. }
  173. /**@brief Function for setting the RTC1 Capture Compare register 0, and enabling the corresponding
  174. * event.
  175. *
  176. * @param[in] value New value of Capture Compare register 0.
  177. */
  178. static __INLINE void rtc1_compare0_set(uint32_t value)
  179. {
  180. NRF_RTC1->CC[0] = value;
  181. }
  182. /**@brief Function for inserting a timer in the timer list.
  183. *
  184. * @param[in] timer_id Id of timer to insert.
  185. */
  186. static void timer_list_insert(timer_node_t * p_timer)
  187. {
  188. if (mp_timer_id_head == NULL)
  189. {
  190. mp_timer_id_head = p_timer;
  191. }
  192. else
  193. {
  194. if (p_timer->ticks_to_expire <= mp_timer_id_head->ticks_to_expire)
  195. {
  196. mp_timer_id_head->ticks_to_expire -= p_timer->ticks_to_expire;
  197. p_timer->next = mp_timer_id_head;
  198. mp_timer_id_head = p_timer;
  199. }
  200. else
  201. {
  202. timer_node_t * p_previous;
  203. timer_node_t * p_current;
  204. uint32_t ticks_to_expire;
  205. ticks_to_expire = p_timer->ticks_to_expire;
  206. p_previous = mp_timer_id_head;
  207. p_current = mp_timer_id_head;
  208. while ((p_current != NULL) && (ticks_to_expire > p_current->ticks_to_expire))
  209. {
  210. ticks_to_expire -= p_current->ticks_to_expire;
  211. p_previous = p_current;
  212. p_current = p_current->next;
  213. }
  214. if (p_current != NULL)
  215. {
  216. p_current->ticks_to_expire -= ticks_to_expire;
  217. }
  218. p_timer->ticks_to_expire = ticks_to_expire;
  219. p_timer->next = p_current;
  220. p_previous->next = p_timer;
  221. }
  222. }
  223. }
  224. /**@brief Function for removing a timer from the timer queue.
  225. *
  226. * @param[in] timer_id Id of timer to remove.
  227. */
  228. static void timer_list_remove(timer_node_t * p_timer)
  229. {
  230. timer_node_t * p_previous;
  231. timer_node_t * p_current;
  232. uint32_t timeout;
  233. // Find the timer's position in timer list.
  234. p_previous = mp_timer_id_head;
  235. p_current = p_previous;
  236. while (p_current != NULL)
  237. {
  238. if (p_current == p_timer)
  239. {
  240. break;
  241. }
  242. p_previous = p_current;
  243. p_current = p_current->next;
  244. }
  245. // Timer not in active list.
  246. if (p_current == NULL)
  247. {
  248. return;
  249. }
  250. // Timer is the first in the list
  251. if (p_previous == p_current)
  252. {
  253. mp_timer_id_head = mp_timer_id_head->next;
  254. // No more timers in the list. Reset RTC1 in case Start timer operations are present in the queue.
  255. if (mp_timer_id_head == NULL)
  256. {
  257. NRF_RTC1->TASKS_CLEAR = 1;
  258. m_ticks_latest = 0;
  259. m_rtc1_reset = true;
  260. }
  261. }
  262. // Remaining timeout between next timeout.
  263. timeout = p_current->ticks_to_expire;
  264. // Link previous timer with next of this timer, i.e. removing the timer from list.
  265. p_previous->next = p_current->next;
  266. // If this is not the last timer, increment the next timer by this timer timeout.
  267. p_current = p_previous->next;
  268. if (p_current != NULL)
  269. {
  270. p_current->ticks_to_expire += timeout;
  271. }
  272. }
  273. /**@brief Function for scheduling a check for timeouts by generating a RTC1 interrupt.
  274. */
  275. static void timer_timeouts_check_sched(void)
  276. {
  277. NVIC_SetPendingIRQ(RTC1_IRQn);
  278. }
  279. /**@brief Function for scheduling a timer list update by generating a SWI interrupt.
  280. */
  281. static void timer_list_handler_sched(void)
  282. {
  283. NVIC_SetPendingIRQ(SWI_IRQn);
  284. }
  285. /**@brief Function for executing an application timeout handler, either by calling it directly, or
  286. * by passing an event to the @ref app_scheduler.
  287. *
  288. * @param[in] p_timer Pointer to expired timer.
  289. */
  290. static void timeout_handler_exec(timer_node_t * p_timer)
  291. {
  292. if (m_evt_schedule_func != NULL)
  293. {
  294. uint32_t err_code = m_evt_schedule_func(p_timer->p_timeout_handler, p_timer->p_context);
  295. APP_ERROR_CHECK(err_code);
  296. }
  297. else
  298. {
  299. p_timer->p_timeout_handler(p_timer->p_context);
  300. }
  301. }
  302. /**@brief Function for checking for expired timers.
  303. */
  304. static void timer_timeouts_check(void)
  305. {
  306. // Handle expired of timer
  307. if (mp_timer_id_head != NULL)
  308. {
  309. timer_node_t * p_timer;
  310. timer_node_t * p_previous_timer;
  311. uint32_t ticks_elapsed;
  312. uint32_t ticks_expired;
  313. // Initialize actual elapsed ticks being consumed to 0.
  314. ticks_expired = 0;
  315. // ticks_elapsed is collected here, job will use it.
  316. ticks_elapsed = ticks_diff_get(rtc1_counter_get(), m_ticks_latest);
  317. // Auto variable containing the head of timers expiring.
  318. p_timer = mp_timer_id_head;
  319. // Expire all timers within ticks_elapsed and collect ticks_expired.
  320. while (p_timer != NULL)
  321. {
  322. // Do nothing if timer did not expire.
  323. if (ticks_elapsed < p_timer->ticks_to_expire)
  324. {
  325. break;
  326. }
  327. // Decrement ticks_elapsed and collect expired ticks.
  328. ticks_elapsed -= p_timer->ticks_to_expire;
  329. ticks_expired += p_timer->ticks_to_expire;
  330. // Move to next timer.
  331. p_previous_timer = p_timer;
  332. p_timer = p_timer->next;
  333. // Execute Task.
  334. if (p_previous_timer->is_running)
  335. {
  336. p_previous_timer->is_running = false;
  337. timeout_handler_exec(p_previous_timer);
  338. }
  339. }
  340. // Prepare to queue the ticks expired in the m_ticks_elapsed queue.
  341. if (m_ticks_elapsed_q_read_ind == m_ticks_elapsed_q_write_ind)
  342. {
  343. // The read index of the queue is equal to the write index. This means the new
  344. // value of ticks_expired should be stored at a new location in the m_ticks_elapsed
  345. // queue (which is implemented as a double buffer).
  346. // Check if there will be a queue overflow.
  347. if (++m_ticks_elapsed_q_write_ind == CONTEXT_QUEUE_SIZE_MAX)
  348. {
  349. // There will be a queue overflow. Hence the write index should point to the start
  350. // of the queue.
  351. m_ticks_elapsed_q_write_ind = 0;
  352. }
  353. }
  354. // Queue the ticks expired.
  355. m_ticks_elapsed[m_ticks_elapsed_q_write_ind] = ticks_expired;
  356. timer_list_handler_sched();
  357. }
  358. }
  359. /**@brief Function for acquiring the number of ticks elapsed.
  360. *
  361. * @param[out] p_ticks_elapsed Number of ticks elapsed.
  362. *
  363. * @return TRUE if elapsed ticks was read from queue, FALSE otherwise.
  364. */
  365. static bool elapsed_ticks_acquire(uint32_t * p_ticks_elapsed)
  366. {
  367. // Pick the elapsed value from queue.
  368. if (m_ticks_elapsed_q_read_ind != m_ticks_elapsed_q_write_ind)
  369. {
  370. // Dequeue elapsed value.
  371. m_ticks_elapsed_q_read_ind++;
  372. if (m_ticks_elapsed_q_read_ind == CONTEXT_QUEUE_SIZE_MAX)
  373. {
  374. m_ticks_elapsed_q_read_ind = 0;
  375. }
  376. *p_ticks_elapsed = m_ticks_elapsed[m_ticks_elapsed_q_read_ind];
  377. m_ticks_latest += *p_ticks_elapsed;
  378. m_ticks_latest &= MAX_RTC_COUNTER_VAL;
  379. return true;
  380. }
  381. else
  382. {
  383. // No elapsed value in queue.
  384. *p_ticks_elapsed = 0;
  385. return false;
  386. }
  387. }
  388. /**@brief Function for handling the timer list deletions.
  389. *
  390. * @return TRUE if Capture Compare register must be updated, FALSE otherwise.
  391. */
  392. static bool list_deletions_handler(void)
  393. {
  394. timer_node_t * p_timer_old_head;
  395. uint8_t user_id;
  396. // Remember the old head, so as to decide if new compare needs to be set.
  397. p_timer_old_head = mp_timer_id_head;
  398. user_id = m_user_array_size;
  399. while (user_id--)
  400. {
  401. timer_user_t * p_user = &mp_users[user_id];
  402. uint8_t user_ops_first = p_user->first;
  403. while (user_ops_first != p_user->last)
  404. {
  405. timer_user_op_t * p_user_op = &p_user->p_user_op_queue[user_ops_first];
  406. // Traverse to next operation in queue.
  407. user_ops_first++;
  408. if (user_ops_first == p_user->user_op_queue_size)
  409. {
  410. user_ops_first = 0;
  411. }
  412. switch (p_user_op->op_type)
  413. {
  414. case TIMER_USER_OP_TYPE_STOP:
  415. // Delete node if timer is running.
  416. timer_list_remove(p_user_op->p_node);
  417. break;
  418. case TIMER_USER_OP_TYPE_STOP_ALL:
  419. // Delete list of running timers, and mark all timers as not running.
  420. while (mp_timer_id_head != NULL)
  421. {
  422. timer_node_t * p_head = mp_timer_id_head;
  423. p_head->is_running = false;
  424. mp_timer_id_head = p_head->next;
  425. }
  426. break;
  427. default:
  428. // No implementation needed.
  429. break;
  430. }
  431. }
  432. }
  433. // Detect change in head of the list.
  434. return (mp_timer_id_head != p_timer_old_head);
  435. }
  436. /**@brief Function for updating the timer list for expired timers.
  437. *
  438. * @param[in] ticks_elapsed Number of elapsed ticks.
  439. * @param[in] ticks_previous Previous known value of the RTC counter.
  440. * @param[out] p_restart_list_head List of repeating timers to be restarted.
  441. */
  442. static void expired_timers_handler(uint32_t ticks_elapsed,
  443. uint32_t ticks_previous,
  444. timer_node_t ** p_restart_list_head)
  445. {
  446. uint32_t ticks_expired = 0;
  447. while (mp_timer_id_head != NULL)
  448. {
  449. timer_node_t * p_timer;
  450. timer_node_t * p_timer_expired;
  451. // Auto variable for current timer node.
  452. p_timer = mp_timer_id_head;
  453. // Do nothing if timer did not expire
  454. if (ticks_elapsed < p_timer->ticks_to_expire)
  455. {
  456. p_timer->ticks_to_expire -= ticks_elapsed;
  457. break;
  458. }
  459. // Decrement ticks_elapsed and collect expired ticks.
  460. ticks_elapsed -= p_timer->ticks_to_expire;
  461. ticks_expired += p_timer->ticks_to_expire;
  462. // Timer expired, set ticks_to_expire zero.
  463. p_timer->ticks_to_expire = 0;
  464. // Remove the expired timer from head.
  465. p_timer_expired = mp_timer_id_head;
  466. mp_timer_id_head = p_timer->next;
  467. // Timer will be restarted if periodic.
  468. if (p_timer->ticks_periodic_interval != 0)
  469. {
  470. p_timer->ticks_at_start = (ticks_previous + ticks_expired) & MAX_RTC_COUNTER_VAL;
  471. p_timer->ticks_first_interval = p_timer->ticks_periodic_interval;
  472. p_timer->next = *p_restart_list_head;
  473. *p_restart_list_head = p_timer_expired;
  474. }
  475. }
  476. }
  477. /**@brief Function for handling timer list insertions.
  478. *
  479. * @param[in] p_restart_list_head List of repeating timers to be restarted.
  480. *
  481. * @return TRUE if Capture Compare register must be updated, FALSE otherwise.
  482. */
  483. static bool list_insertions_handler(timer_node_t * p_restart_list_head)
  484. {
  485. timer_node_t * p_timer_id_old_head;
  486. uint8_t user_id;
  487. // Remember the old head, so as to decide if new compare needs to be set.
  488. p_timer_id_old_head = mp_timer_id_head;
  489. user_id = m_user_array_size;
  490. while (user_id--)
  491. {
  492. timer_user_t * p_user = &mp_users[user_id];
  493. // Handle insertions of timers.
  494. while ((p_restart_list_head != NULL) || (p_user->first != p_user->last))
  495. {
  496. timer_node_t * p_timer;
  497. if (p_restart_list_head != NULL)
  498. {
  499. p_timer = p_restart_list_head;
  500. p_restart_list_head = p_timer->next;
  501. }
  502. else
  503. {
  504. timer_user_op_t * p_user_op = &p_user->p_user_op_queue[p_user->first];
  505. p_user->first++;
  506. if (p_user->first == p_user->user_op_queue_size)
  507. {
  508. p_user->first = 0;
  509. }
  510. p_timer = p_user_op->p_node;
  511. if ((p_user_op->op_type != TIMER_USER_OP_TYPE_START) || p_timer->is_running)
  512. {
  513. continue;
  514. }
  515. p_timer->ticks_at_start = p_user_op->params.start.ticks_at_start;
  516. p_timer->ticks_first_interval = p_user_op->params.start.ticks_first_interval;
  517. p_timer->ticks_periodic_interval = p_user_op->params.start.ticks_periodic_interval;
  518. p_timer->p_context = p_user_op->params.start.p_context;
  519. if (m_rtc1_reset)
  520. {
  521. p_timer->ticks_at_start = 0;
  522. }
  523. }
  524. // Prepare the node to be inserted.
  525. if (
  526. ((p_timer->ticks_at_start - m_ticks_latest) & MAX_RTC_COUNTER_VAL)
  527. <
  528. (MAX_RTC_COUNTER_VAL / 2)
  529. )
  530. {
  531. p_timer->ticks_to_expire = ticks_diff_get(p_timer->ticks_at_start, m_ticks_latest) +
  532. p_timer->ticks_first_interval;
  533. }
  534. else
  535. {
  536. uint32_t delta_current_start;
  537. delta_current_start = ticks_diff_get(m_ticks_latest, p_timer->ticks_at_start);
  538. if (p_timer->ticks_first_interval > delta_current_start)
  539. {
  540. p_timer->ticks_to_expire = p_timer->ticks_first_interval - delta_current_start;
  541. }
  542. else
  543. {
  544. p_timer->ticks_to_expire = 0;
  545. }
  546. }
  547. p_timer->ticks_at_start = 0;
  548. p_timer->ticks_first_interval = 0;
  549. p_timer->is_running = true;
  550. p_timer->next = NULL;
  551. // Insert into list
  552. timer_list_insert(p_timer);
  553. }
  554. }
  555. return (mp_timer_id_head != p_timer_id_old_head);
  556. }
  557. /**@brief Function for updating the Capture Compare register.
  558. */
  559. static void compare_reg_update(timer_node_t * p_timer_id_head_old)
  560. {
  561. // Setup the timeout for timers on the head of the list
  562. if (mp_timer_id_head != NULL)
  563. {
  564. uint32_t ticks_to_expire = mp_timer_id_head->ticks_to_expire;
  565. uint32_t pre_counter_val = rtc1_counter_get();
  566. uint32_t cc = m_ticks_latest;
  567. uint32_t ticks_elapsed = ticks_diff_get(pre_counter_val, cc) + RTC_COMPARE_OFFSET_MIN;
  568. if (!m_rtc1_running)
  569. {
  570. // No timers were already running, start RTC
  571. rtc1_start();
  572. }
  573. cc += (ticks_elapsed < ticks_to_expire) ? ticks_to_expire : ticks_elapsed;
  574. cc &= MAX_RTC_COUNTER_VAL;
  575. rtc1_compare0_set(cc);
  576. uint32_t post_counter_val = rtc1_counter_get();
  577. if (
  578. (ticks_diff_get(post_counter_val, pre_counter_val) + RTC_COMPARE_OFFSET_MIN)
  579. >
  580. ticks_diff_get(cc, pre_counter_val)
  581. )
  582. {
  583. // When this happens the COMPARE event may not be triggered by the RTC.
  584. // The nRF51 Series User Specification states that if the COUNTER value is N
  585. // (i.e post_counter_val = N), writing N or N+1 to a CC register may not trigger a
  586. // COMPARE event. Hence the RTC interrupt is forcefully pended by calling the following
  587. // function.
  588. rtc1_compare0_set(rtc1_counter_get()); // this should prevent CC to fire again in the background while the code is in RTC-ISR
  589. nrf_delay_us(MAX_RTC_TASKS_DELAY);
  590. timer_timeouts_check_sched();
  591. }
  592. }
  593. else
  594. {
  595. // No timers are running, stop RTC
  596. rtc1_stop();
  597. }
  598. }
  599. /**@brief Function for handling changes to the timer list.
  600. */
  601. static void timer_list_handler(void)
  602. {
  603. timer_node_t * p_restart_list_head = NULL;
  604. uint32_t ticks_elapsed;
  605. uint32_t ticks_previous;
  606. bool ticks_have_elapsed;
  607. bool compare_update;
  608. timer_node_t * p_timer_id_head_old;
  609. #ifdef APP_TIMER_WITH_PROFILER
  610. {
  611. unsigned int i;
  612. for (i = 0; i < APP_TIMER_INT_LEVELS; i++)
  613. {
  614. timer_user_t *p_user = &mp_users[i];
  615. uint8_t size = p_user->user_op_queue_size;
  616. uint8_t first = p_user->first;
  617. uint8_t last = p_user->last;
  618. uint8_t utilization = (first <= last) ? (last - first) : (size + 1 - first + last);
  619. if (utilization > m_max_user_op_queue_utilization)
  620. {
  621. m_max_user_op_queue_utilization = utilization;
  622. }
  623. }
  624. }
  625. #endif
  626. // Back up the previous known tick and previous list head
  627. ticks_previous = m_ticks_latest;
  628. p_timer_id_head_old = mp_timer_id_head;
  629. // Get number of elapsed ticks
  630. ticks_have_elapsed = elapsed_ticks_acquire(&ticks_elapsed);
  631. // Handle list deletions
  632. compare_update = list_deletions_handler();
  633. // Handle expired timers
  634. if (ticks_have_elapsed)
  635. {
  636. expired_timers_handler(ticks_elapsed, ticks_previous, &p_restart_list_head);
  637. compare_update = true;
  638. }
  639. // Handle list insertions
  640. if (list_insertions_handler(p_restart_list_head))
  641. {
  642. compare_update = true;
  643. }
  644. // Update compare register if necessary
  645. if (compare_update)
  646. {
  647. compare_reg_update(p_timer_id_head_old);
  648. }
  649. m_rtc1_reset = false;
  650. }
  651. /**@brief Function for enqueueing a new operations queue entry.
  652. *
  653. * @param[in] p_user User that the entry is to be enqueued for.
  654. * @param[in] last_index Index of the next last index to be enqueued.
  655. */
  656. static void user_op_enque(timer_user_t * p_user, uint8_t last_index)
  657. {
  658. p_user->last = last_index;
  659. }
  660. /**@brief Function for allocating a new operations queue entry.
  661. *
  662. * @param[in] p_user User that the entry is to be allocated for.
  663. * @param[out] p_last_index Index of the next last index to be enqueued.
  664. *
  665. * @return Pointer to allocated queue entry, or NULL if queue is full.
  666. */
  667. static timer_user_op_t * user_op_alloc(timer_user_t * p_user, uint8_t * p_last_index)
  668. {
  669. uint8_t last;
  670. timer_user_op_t * p_user_op;
  671. last = p_user->last + 1;
  672. if (last == p_user->user_op_queue_size)
  673. {
  674. // Overflow case.
  675. last = 0;
  676. }
  677. if (last == p_user->first)
  678. {
  679. // Queue is full.
  680. return NULL;
  681. }
  682. *p_last_index = last;
  683. p_user_op = &p_user->p_user_op_queue[p_user->last];
  684. return p_user_op;
  685. }
  686. /**@brief Function for scheduling a Timer Start operation.
  687. *
  688. * @param[in] user_id Id of user calling this function.
  689. * @param[in] timer_id Id of timer to start.
  690. * @param[in] timeout_initial Time (in ticks) to first timer expiry.
  691. * @param[in] timeout_periodic Time (in ticks) between periodic expiries.
  692. * @param[in] p_context General purpose pointer. Will be passed to the timeout handler when
  693. * the timer expires.
  694. * @return NRF_SUCCESS on success, otherwise an error code.
  695. */
  696. static uint32_t timer_start_op_schedule(timer_user_id_t user_id,
  697. timer_node_t * p_node,
  698. uint32_t timeout_initial,
  699. uint32_t timeout_periodic,
  700. void * p_context)
  701. {
  702. uint8_t last_index;
  703. timer_user_op_t * p_user_op = user_op_alloc(&mp_users[user_id], &last_index);
  704. if (p_user_op == NULL)
  705. {
  706. return NRF_ERROR_NO_MEM;
  707. }
  708. p_user_op->op_type = TIMER_USER_OP_TYPE_START;
  709. p_user_op->p_node = p_node;
  710. p_user_op->params.start.ticks_at_start = rtc1_counter_get();
  711. p_user_op->params.start.ticks_first_interval = timeout_initial;
  712. p_user_op->params.start.ticks_periodic_interval = timeout_periodic;
  713. p_user_op->params.start.p_context = p_context;
  714. user_op_enque(&mp_users[user_id], last_index);
  715. timer_list_handler_sched();
  716. return NRF_SUCCESS;
  717. }
  718. /**@brief Function for scheduling a Timer Stop operation.
  719. *
  720. * @param[in] user_id Id of user calling this function.
  721. * @param[in] timer_id Id of timer to stop.
  722. *
  723. * @return NRF_SUCCESS on successful scheduling a timer stop operation. NRF_ERROR_NO_MEM when there
  724. * is no memory left to schedule the timer stop operation.
  725. */
  726. static uint32_t timer_stop_op_schedule(timer_user_id_t user_id, timer_node_t * p_node)
  727. {
  728. uint8_t last_index;
  729. timer_user_op_t * p_user_op = user_op_alloc(&mp_users[user_id], &last_index);
  730. if (p_user_op == NULL)
  731. {
  732. return NRF_ERROR_NO_MEM;
  733. }
  734. p_user_op->op_type = TIMER_USER_OP_TYPE_STOP;
  735. p_user_op->p_node = p_node;
  736. user_op_enque(&mp_users[user_id], last_index);
  737. timer_list_handler_sched();
  738. return NRF_SUCCESS;
  739. }
  740. /**@brief Function for scheduling a Timer Stop All operation.
  741. *
  742. * @param[in] user_id Id of user calling this function.
  743. */
  744. static uint32_t timer_stop_all_op_schedule(timer_user_id_t user_id)
  745. {
  746. uint8_t last_index;
  747. timer_user_op_t * p_user_op = user_op_alloc(&mp_users[user_id], &last_index);
  748. if (p_user_op == NULL)
  749. {
  750. return NRF_ERROR_NO_MEM;
  751. }
  752. p_user_op->op_type = TIMER_USER_OP_TYPE_STOP_ALL;
  753. p_user_op->p_node = NULL;
  754. user_op_enque(&mp_users[user_id], last_index);
  755. timer_list_handler_sched();
  756. return NRF_SUCCESS;
  757. }
  758. /**@brief Function for handling the RTC1 interrupt.
  759. *
  760. * @details Checks for timeouts, and executes timeout handlers for expired timers.
  761. */
  762. void RTC1_IRQHandler(void)
  763. {
  764. // Clear all events (also unexpected ones)
  765. NRF_RTC1->EVENTS_COMPARE[0] = 0;
  766. NRF_RTC1->EVENTS_COMPARE[1] = 0;
  767. NRF_RTC1->EVENTS_COMPARE[2] = 0;
  768. NRF_RTC1->EVENTS_COMPARE[3] = 0;
  769. NRF_RTC1->EVENTS_TICK = 0;
  770. NRF_RTC1->EVENTS_OVRFLW = 0;
  771. // Check for expired timers
  772. timer_timeouts_check();
  773. }
  774. /**@brief Function for handling the SWI interrupt.
  775. *
  776. * @details Performs all updates to the timer list.
  777. */
  778. void SWI_IRQHandler(void)
  779. {
  780. timer_list_handler();
  781. }
  782. uint32_t app_timer_init(uint32_t prescaler,
  783. uint8_t op_queues_size,
  784. void * p_buffer,
  785. app_timer_evt_schedule_func_t evt_schedule_func)
  786. {
  787. int i;
  788. // Check that buffer is correctly aligned
  789. if (!is_word_aligned(p_buffer))
  790. {
  791. return NRF_ERROR_INVALID_PARAM;
  792. }
  793. // Check for NULL buffer
  794. if (p_buffer == NULL)
  795. {
  796. mp_users = NULL;
  797. return NRF_ERROR_INVALID_PARAM;
  798. }
  799. // Stop RTC to prevent any running timers from expiring (in case of reinitialization)
  800. rtc1_stop();
  801. m_evt_schedule_func = evt_schedule_func;
  802. // Initialize users array
  803. m_user_array_size = APP_TIMER_INT_LEVELS;
  804. mp_users = p_buffer;
  805. // Skip user array
  806. p_buffer = &((uint8_t *)p_buffer)[APP_TIMER_INT_LEVELS * sizeof(timer_user_t)];
  807. // Initialize operation queues
  808. for (i = 0; i < APP_TIMER_INT_LEVELS; i++)
  809. {
  810. timer_user_t * p_user = &mp_users[i];
  811. p_user->first = 0;
  812. p_user->last = 0;
  813. p_user->user_op_queue_size = op_queues_size;
  814. p_user->p_user_op_queue = p_buffer;
  815. // Skip operation queue
  816. p_buffer = &((uint8_t *)p_buffer)[op_queues_size * sizeof(timer_user_op_t)];
  817. }
  818. mp_timer_id_head = NULL;
  819. m_ticks_elapsed_q_read_ind = 0;
  820. m_ticks_elapsed_q_write_ind = 0;
  821. #ifdef APP_TIMER_WITH_PROFILER
  822. m_max_user_op_queue_utilization = 0;
  823. #endif
  824. NVIC_ClearPendingIRQ(SWI_IRQn);
  825. NVIC_SetPriority(SWI_IRQn, SWI_IRQ_PRI);
  826. NVIC_EnableIRQ(SWI_IRQn);
  827. rtc1_init(prescaler);
  828. m_ticks_latest = rtc1_counter_get();
  829. return NRF_SUCCESS;
  830. }
  831. uint32_t app_timer_create(app_timer_id_t const * p_timer_id,
  832. app_timer_mode_t mode,
  833. app_timer_timeout_handler_t timeout_handler)
  834. {
  835. // Check state and parameters
  836. VERIFY_MODULE_INITIALIZED();
  837. if (timeout_handler == NULL)
  838. {
  839. return NRF_ERROR_INVALID_PARAM;
  840. }
  841. if (p_timer_id == NULL)
  842. {
  843. return NRF_ERROR_INVALID_PARAM;
  844. }
  845. if (((timer_node_t*)*p_timer_id)->is_running)
  846. {
  847. return NRF_ERROR_INVALID_STATE;
  848. }
  849. timer_node_t * p_node = (timer_node_t *)*p_timer_id;
  850. p_node->is_running = false;
  851. p_node->mode = mode;
  852. p_node->p_timeout_handler = timeout_handler;
  853. return NRF_SUCCESS;
  854. }
  855. /**@brief Function for creating a timer user id from the current interrupt level.
  856. *
  857. * @return Timer user id.
  858. */
  859. static timer_user_id_t user_id_get(void)
  860. {
  861. timer_user_id_t ret;
  862. STATIC_ASSERT(APP_TIMER_INT_LEVELS == 3);
  863. switch (current_int_priority_get())
  864. {
  865. case APP_IRQ_PRIORITY_HIGH:
  866. ret = APP_HIGH_USER_ID;
  867. break;
  868. case APP_IRQ_PRIORITY_LOW:
  869. ret = APP_LOW_USER_ID;
  870. break;
  871. default:
  872. ret = THREAD_MODE_USER_ID;
  873. break;
  874. }
  875. return ret;
  876. }
  877. uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context)
  878. {
  879. uint32_t timeout_periodic;
  880. timer_node_t * p_node = (timer_node_t*)timer_id;
  881. // Check state and parameters
  882. VERIFY_MODULE_INITIALIZED();
  883. if (timer_id == 0)
  884. {
  885. return NRF_ERROR_INVALID_STATE;
  886. }
  887. if (timeout_ticks < APP_TIMER_MIN_TIMEOUT_TICKS)
  888. {
  889. return NRF_ERROR_INVALID_PARAM;
  890. }
  891. if (p_node->p_timeout_handler == NULL)
  892. {
  893. return NRF_ERROR_INVALID_STATE;
  894. }
  895. // Schedule timer start operation
  896. timeout_periodic = (p_node->mode == APP_TIMER_MODE_REPEATED) ? timeout_ticks : 0;
  897. return timer_start_op_schedule(user_id_get(),
  898. p_node,
  899. timeout_ticks,
  900. timeout_periodic,
  901. p_context);
  902. }
  903. uint32_t app_timer_stop(app_timer_id_t timer_id)
  904. {
  905. timer_node_t * p_node = (timer_node_t*)timer_id;
  906. // Check state and parameters
  907. VERIFY_MODULE_INITIALIZED();
  908. if ((timer_id == NULL) || (p_node->p_timeout_handler == NULL))
  909. {
  910. return NRF_ERROR_INVALID_STATE;
  911. }
  912. p_node->is_running = false;
  913. // Schedule timer stop operation
  914. return timer_stop_op_schedule(user_id_get(), p_node);
  915. }
  916. uint32_t app_timer_stop_all(void)
  917. {
  918. // Check state
  919. VERIFY_MODULE_INITIALIZED();
  920. return timer_stop_all_op_schedule(user_id_get());
  921. }
  922. uint32_t app_timer_cnt_get(uint32_t * p_ticks)
  923. {
  924. *p_ticks = rtc1_counter_get();
  925. return NRF_SUCCESS;
  926. }
  927. uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to,
  928. uint32_t ticks_from,
  929. uint32_t * p_ticks_diff)
  930. {
  931. *p_ticks_diff = ticks_diff_get(ticks_to, ticks_from);
  932. return NRF_SUCCESS;
  933. }
  934. #ifdef APP_TIMER_WITH_PROFILER
  935. uint8_t app_timer_op_queue_utilization_get(void)
  936. {
  937. return m_max_user_op_queue_utilization;
  938. }
  939. #endif