Skip to content

Systick定时器

是一个内核的外设, 内嵌在NVIC里面, 有一个24位的向下递减的自动重装载寄存器, 计数的周期为CLKSource, 可以配置这个时钟最高频率为72MHz

一般来说Cortex-M的内核都有这样一个定时器

一般用于操作系统, 用于任务的调度, 或者进行微妙毫秒级别的延时

RCC通过AHB时钟(HCLK)8分频后作为Cortex系统定时器(SysTick)的外部时钟。通过对SysTick 控制与状态寄存器的设置,可选择上述时钟或Cortex(HCLK)时钟作为SysTick时钟。

使用的HAL_Delay()函数就是依靠这一个时钟生成的, CubeMX提供的配置只有这两个

默认的时候这个时钟会在HAL库初始化的时候进行使能, 设置优先级为最小的优先级, 之后设置时钟的频率以后会再次设置Systick的频率

c
  /* Update the SystemCoreClock global variable计算时钟的频率 */
  SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos];

  /* Configure the source of time base considering new system clocks settings设置Systick时钟*/
  HAL_InitTick(uwTickPrio);
c
/**
  * @brief This function provides minimum delay (in milliseconds) based
  *        on variable incremented.
  * @note In the default implementation , SysTick timer is the source of time base.
  *       It is used to generate interrupts at regular time intervals where uwTick
  *       is incremented.
  * @note This function is declared as __weak to be overwritten in case of other
  *       implementations in user file.
  * @param Delay specifies the delay time length, in milliseconds.
  * @retval None
  */
__weak void HAL_Delay(uint32_t Delay)
{
  uint32_t tickstart = HAL_GetTick();
  uint32_t wait = Delay;

  /* Add a freq to guarantee minimum wait */
  if (wait < HAL_MAX_DELAY)
  {
    wait += (uint32_t)(uwTickFreq);
  }

  while ((HAL_GetTick() - tickstart) < wait)
  {
  }
}

使用一个全局变量进行记录时间