系统滴答

SysTick(系统滴答)

1、 简介

  • SysTick 是 ARM Cortex-M 内核处理器内置的24位向下计数定时器,主要用于生成系统级定时中断(如操作系统的心跳信号),支持查询方式延时和中断功能延时

2、使用方法(HAL)

(1)配置初始化

  • 按照如下方式使能TIM4
    图片
  • 使能USART
    图片
  • 使能RCC
    图片
  • 使能这两个外设的中断
    图片
  • 按照如下方式配置时钟树
    图片
  • 完成计数器设置
    图片

TIM4位于APB1总线上,此时该总线频率为54MHz,因此预分频为5400 - 1,这样计时器周期为$$\frac{54MHz}{5400} = 1000Hz$$
图片
自动重装载寄存器设置为10000 - 1,这样计数器的一个周期为$$\frac{10000Hz}{10000}=1s$$

(2)编写读取代码

  • 在主循环外部写入以下内容
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim4);//使TIM4计时器开始工作,完成一次计时后会发生中断
  int counter = 0;//定义读取计时器当前数值的变量
  char message[20];//定义串口输出的字符串
  /* USER CODE END 2 */
  • 在主循环内部写入以下内容
  while (1)
  {
	  counter = __HAL_TIM_GET_COUNTER(&htim4);//从TIM4计数器中读取数值
      //将数值传出串口
	  sprintf(message, "counter:%d", counter);
	  HAL_UART_Transmit_IT(&huart2, (uint8_t*)message, strlen(message));
	  HAL_Delay(299);//每延时0.3秒,执行一次操作
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  • 这样编写的程序就能在串口看到计时器的数值了
    图片

(3)处理中断

  • 在主函数外部定义计时器中断回调函数
/* USER CODE BEGIN 0 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
	if(htim == &htim4){
		HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
	}
}
/* USER CODE END 0 */

这样每触发一次中断(即计时1秒),LED处的信号会翻转一次
效果如下:
图片

3、代码清单

/**
  * @brief  Sends an amount of data in non blocking mode.
  * @note   When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01),
  *         the sent data is handled as a set of u16. In this case, Size must indicate the number
  *         of u16 provided through pData.
  * @param  huart Pointer to a UART_HandleTypeDef structure that contains
  *               the configuration information for the specified UART module.
  * @param  pData Pointer to data buffer (u8 or u16 data elements).
  * @param  Size  Amount of data elements (u8 or u16) to be sent
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size);
/*----------中断回调函数---------------*/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
	if(htim == &htim4){
		HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
	}
}
/*----------打印结果的函数---------------------*/
int	sprintf (char *__restrict, const char *__restrict, ...)
   _ATTRIBUTE ((__format__ (__printf__, 2, 3)));
/**
  * @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)
posted @ 2025-08-27 13:24  奶龙大王  阅读(16)  评论(0)    收藏  举报