1 /**
2   ******************************************************************************
3   * @file    tick.c
4   * @author  MCD Application Team
5   * @brief   Tick implementation without tick interrupt
6    ******************************************************************************
7   * @attention
8   *
9   * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
10   * All rights reserved.</center></h2>
11   *
12   * This software component is licensed by ST under BSD 3-Clause license,
13   * the "License"; You may not use this file except in compliance with the
14   * License. You may obtain a copy of the License at:
15   *                        opensource.org/licenses/BSD-3-Clause
16   *
17   ******************************************************************************
18   */
19 #include "stm32hal.h"
20 #include "tick_device.h"
21 /**
22   * @brief This function configures the source of the time base:
23   *        The time source is configured to have 1ms time base with a dedicated
24   *        Tick interrupt priority.
25   * @note This function overwrites the one declared as __weak in HAL.
26   *       In this implementation, nothing is done.
27   * @retval HAL status
28   */
29 
HAL_InitTick(uint32_t TickPriority)30 HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
31 {
32   /* load 1Hz for timeout 1 second */
33   uint32_t ticks = SystemCoreClock ;
34   SysTick->LOAD  = (uint32_t)(ticks - 1UL);                         /* set reload register */
35   SysTick->VAL   = 0UL;                                             /* Load the SysTick Counter Value */
36   SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
37                    SysTick_CTRL_ENABLE_Msk;
38   return HAL_OK;
39 }
40 
41 /**
42   * @brief Provide a tick value in millisecond.
43   * @note This function overwrites the one declared as __weak in HAL.
44   *       In this implementation, time is counted without using SysTick timer interrupts.
45   * @retval tick value
46   */
HAL_GetTick(void)47 uint32_t HAL_GetTick(void)
48 {
49   static uint32_t m_uTick = 0U;
50   static uint32_t t1 = 0U, tdelta = 0U;
51   uint32_t t2;
52 
53   /* device specific behaviour for HAL_GetTick */
54   DEVICE_GET_TICK;
55   t2 =  SysTick->VAL;
56 
57   if (t2 <= t1)
58   {
59     tdelta += t1 - t2;
60   }
61   else
62   {
63     tdelta += t1 + SysTick->LOAD - t2;
64   }
65 
66   if (tdelta > (SystemCoreClock / (1000U)))
67   {
68     tdelta = 0U;
69     m_uTick ++;
70   }
71 
72   t1 = t2;
73   return m_uTick;
74 }