【蓝桥杯】【嵌入式组别】第四节:Systick系统滴答定时器

news/2024/12/2 21:51:48/

Systick编程

  • Systick简介
  • Systick程序设计

Systick简介

  1. Systick是CM4内核的系统定时器,是一个24位向下递减计数器,理论上可以计数2242^{24}224个值,当重装载寄存器的值减为0时就产生一次中断。
  2. STM32CUBEMX生成的工程,会自动把Systick配置成1ms中断的定时器,并在中断函数里,在中断处理函数中将变量uwTick每1ms增加1。这样我们就可以知道芯片的走时情况,知道芯片到目前为止上电多长时间。

Systick是向下递减的,而51单片机是向上计数,每来一个时间脉冲就计数加一,而Systick是每来一个就向下计数加一。理论上可以计2^24个值,减为0的时候产生中断,恢复成某个设定的的数,然后重新向下递减。

Systick的作用:

  • 精确延时:HAL_Delay函数,用于延时x毫秒
  • 给系统提供一个单独的时钟节拍(时间基准)(相当于是芯片的一个心跳,上电之后就会一直工作)

下面结合程序看一下Systick初始化的流程:
看一下HAL_Init();函数的实现:

HAL_StatusTypeDef HAL_Init(void)
{HAL_StatusTypeDef  status = HAL_OK;/* Configure Flash prefetch, Instruction cache, Data cache *//* Default configuration at reset is:                      *//* - Prefetch disabled                                     *//* - Instruction cache enabled                             *//* - Data cache enabled                                    */
#if (INSTRUCTION_CACHE_ENABLE == 0U)__HAL_FLASH_INSTRUCTION_CACHE_DISABLE();
#endif /* INSTRUCTION_CACHE_ENABLE */#if (DATA_CACHE_ENABLE == 0U)__HAL_FLASH_DATA_CACHE_DISABLE();
#endif /* DATA_CACHE_ENABLE */#if (PREFETCH_ENABLE != 0U)__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
#endif /* PREFETCH_ENABLE */
//上面这些宏定义和if,endif都是一些初始化的东西,不用管/* Set Interrupt Group Priority */HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
//上面这句是配置中断优先级的组/* Use SysTick as time base source and configure 1ms tick (default clock after Reset is HSI) */if (HAL_InitTick(TICK_INT_PRIORITY) != HAL_OK){status = HAL_ERROR;}else{/* Init the low level hardware */HAL_MspInit();}/* Return function status */return status;
//上面这段就是将Systick配置成一个1ms的时间基准,并且将上电默认的时钟设置为HSI。
}

点开HAL_InitTick()这个函数可以看到:

__weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
{HAL_StatusTypeDef  status = HAL_OK;if (uwTickFreq != 0U){/* Configure the SysTick to have interrupt in 1ms time basis*///这个函数最主要的部分就是下面这句,设置了一个溢出的标志位if (HAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq)) == 0U){/* Configure the SysTick IRQ priority */if (TickPriority < (1UL << __NVIC_PRIO_BITS)){HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority, 0U);uwTickPrio = TickPriority;}else{status = HAL_ERROR;}}else{status = HAL_ERROR;}}else{status = HAL_ERROR;}/* Return function status */return status;
}

再打开HAL_SYSTICK_Config()这个函数中的SysTick_Config()函数:

__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{//可以看到就是很重要的一步:配置了重装载值if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk){return (1UL);                                                   /* Reload value impossible */}SysTick->LOAD  = (uint32_t)(ticks - 1UL);                         /* set reload register */NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */SysTick->VAL   = 0UL;                                             /* Load the SysTick Counter Value */SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |SysTick_CTRL_TICKINT_Msk   |SysTick_CTRL_ENABLE_Msk;                         /* Enable SysTick IRQ and SysTick Timer */return (0UL);                                                     /* Function successful */
}

最后就是要明白一点:对于Systick来说,一定要知道的就是uwTick这个变量的意义:就是每过1ms他就会自加1。
uwTick这个变量在程序中是定义为__IO uint32_t uwTick;,是一个32位的无符号数,所以他一共可以计2322^{32}232这么多毫秒,差不多是49天左右,所以不用担心会有溢出的问题,即使溢出了,他也会自动归零。

Systick程序设计

HAL_Delay延时会阻塞程序,使其他程序实时性下降。
除了HAl_Delay延时函数之外,可以将Systick用于程序调度。
我们以LED灯的程序为例写出如下调度代码:

//由于uwTick的类型是32位无符号整型,所以我们自定义的ledTick也定义为这样的类型:
__IO uint32_t ledTick =0;
//下面这个变量的定义是上一篇文章中提到的对led灯哪个亮哪个不亮的控制,初始化为0xff就是使所有灯都亮
u8 led_ctrl=0xff;
void LED_Process(void)
{
//由于uwTick在上电之后就会每1ms加一,而ledTick一开始初始化为0,所以uwTick-ledTick的值就是uwTick本身,当uwTick大于500,即程序上电500毫秒之后,执行后面的代码,否则就return,也就是退出这个函数if(uwTick-ledTick<500)return;
//	把uwTick的值赋给ledTick,为了下次进入这个函数还是500毫秒之后执行该程序(因为uwTick的值是一直递增的,所以想要控制uwTick与ledTick的差值始终为500就需要每进一次这个函数更新一次ledTick)ledTick=uwTick;//控制led灯的亮灭LED_Control(led_ctrl);//每进一次这个函数就把led_ctrl取反,相当于每500毫秒,灯整体亮或者灭led_ctrl=~led_ctrl;
}

最终的主函数如下:

/* USER CODE BEGIN Header */
/********************************************************************************* @file           : main.c* @brief          : Main program body******************************************************************************* @attention** <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.* All rights reserved.</center></h2>** This software component is licensed by ST under BSD 3-Clause license,* the "License"; You may not use this file except in compliance with the* License. You may obtain a copy of the License at:*                        opensource.org/licenses/BSD-3-Clause********************************************************************************/
/* USER CODE END Header *//* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "gpio.h"
#include "led.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes *//* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD *//* USER CODE END PTD *//* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD *//* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM *//* USER CODE END PM *//* Private variables ---------------------------------------------------------*//* USER CODE BEGIN PV *//* USER CODE END PV *//* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
//Led执行程序
__IO uint32_t ledTick =0;
u8 led_ctrl=0xff;
void LED_Process(void)
{if(uwTick-ledTick<500)return;ledTick=uwTick;LED_Control(led_ctrl);led_ctrl=~led_ctrl;
}
/* USER CODE END 0 *//*** @brief  The application entry point.* @retval int*/
int main(void)
{/* USER CODE BEGIN 1 *//* USER CODE END 1 *//* MCU Configuration--------------------------------------------------------*//* Reset of all peripherals, Initializes the Flash interface and the Systick. */HAL_Init();/* USER CODE BEGIN Init *//* USER CODE END Init *//* Configure the system clock */SystemClock_Config();/* USER CODE BEGIN SysInit *//* USER CODE END SysInit *//* Initialize all configured peripherals */MX_GPIO_Init();/* USER CODE BEGIN 2 */LCD_Init();/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */LCD_Clear(Blue);LCD_SetBackColor(Blue);LCD_SetTextColor(White);LCD_DisplayStringLine(Line0, (uint8_t *)"                    ");LCD_DisplayStringLine(Line1, (uint8_t *)"                    ");LCD_DisplayStringLine(Line2, (uint8_t *)"      LCD Test      ");LCD_DisplayStringLine(Line3, (uint8_t *)"                    ");LCD_DisplayStringLine(Line4, (uint8_t *)"                    ");LCD_SetBackColor(White);LCD_SetTextColor(Blue);LCD_DisplayStringLine(Line5, (uint8_t *)"                    ");LCD_DisplayStringLine(Line6, (uint8_t *)"       HAL LIB      ");LCD_DisplayStringLine(Line7, (uint8_t *)"                    ");LCD_DisplayStringLine(Line8, (uint8_t *)"         @80        ");LCD_DisplayStringLine(Line9, (uint8_t *)"                    ");while (1){/* USER CODE END WHILE *//* USER CODE BEGIN 3 */LED_Process();}/* USER CODE END 3 */
}/*** @brief System Clock Configuration* @retval None*/
void SystemClock_Config(void)
{RCC_OscInitTypeDef RCC_OscInitStruct = {0};RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};/** Configure the main internal regulator output voltage*/HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);/** Initializes the CPU, AHB and APB busses clocks*/RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;RCC_OscInitStruct.HSIState = RCC_HSI_ON;RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;RCC_OscInitStruct.PLL.PLLN = 20;RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK){Error_Handler();}/** Initializes the CPU, AHB and APB busses clocks*/RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK){Error_Handler();}
}/* USER CODE BEGIN 4 *//* USER CODE END 4 *//*** @brief  This function is executed in case of error occurrence.* @retval None*/
void Error_Handler(void)
{/* USER CODE BEGIN Error_Handler_Debug *//* User can add his own implementation to report the HAL error return state *//* USER CODE END Error_Handler_Debug */
}#ifdef  USE_FULL_ASSERT
/*** @brief  Reports the name of the source file and the source line number*         where the assert_param error has occurred.* @param  file: pointer to the source file name* @param  line: assert_param error line source number* @retval None*/
void assert_failed(uint8_t *file, uint32_t line)
{/* USER CODE BEGIN 6 *//* User can add his own implementation to report the file name and line number,tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) *//* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT *//************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

就可以实现500毫秒的间隔闪烁。这样做的好处就是不堵塞程序,而不是在while里面用delay。


http://www.ppmy.cn/news/38895.html

相关文章

【JavaWeb】8—过滤器

⭐⭐⭐⭐⭐⭐ Github主页&#x1f449;https://github.com/A-BigTree 笔记链接&#x1f449;https://github.com/A-BigTree/Code_Learning ⭐⭐⭐⭐⭐⭐ 如果可以&#xff0c;麻烦各位看官顺手点个star~&#x1f60a; 如果文章对你有所帮助&#xff0c;可以点赞&#x1f44d;…

ChatGPT 的平替 Claude 使用指南

Claude的独立体验版本姗姗来迟&#xff0c;经过近半个月的等待后&#xff0c;收到了体验邮件&#xff0c;不过之前早已体验过poe和slack的集成版&#xff0c;响应速度上要比ChatGPT快很多。目前提供的Model有&#xff1a;"claude-v1"&#xff1a;我们最大的型号&…

Dubbo负载均衡策略

文章目录Dubbo负载均衡策略Dubbo负载均衡策略操作步骤1. 环境准备2. 配置提供者3. 编写服务提供者接口与实现类4. 配置消费者5. 编写服务消费者代码6. 运行项目7. 扩展Dubbo负载均衡策略8. 配置扩展负载均衡策略9. 运行项目Dubbo负载均衡策略 在Dubbo中&#xff0c;负载均衡是…

STM-32:TIM输出比较—PWM驱动LED呼吸灯/PWM驱动舵机/PWM驱动直流电机

目录一、输出比较二、PWM三、定时器结构3.1输出比较通道&#xff08;通用&#xff09;3.2输出比较通道&#xff08;高级&#xff09;3.3输出模式控制器模式3.4PWM基本结构3.5PWM参数值计算四、外设4.1舵机4.2直流电机五、程序代码5.1PWM驱动LED呼吸灯5.2PWM驱动舵机5.3PWM驱动直…

学会吊打面试官之underedmap

小白&#xff1a;大牛你好&#xff01;我最近学习了STL容器&#xff0c;看到有个叫做unordered_map的容器&#xff0c;这是什么&#xff1f; 大牛&#xff1a;unordered_map是一个无序的关联式容器&#xff0c;也就是一种键值对的存储结构&#xff0c;其中的元素没有固定的顺序…

[linux kernel]slub内存管理分析(0) 导读

文章目录简介整体目录SLUB中的结构体关系图kmalloc 申请逻辑逻辑图逻辑简述kfree 释放逻辑逻辑图逻辑简述slab page状态转换关系图简介 linux 内核内存管理算法有管理页面分配的伙伴算法&#xff0c;和对于小块内存的slab、slob、slub算法。其中slab是slob和slub的基础&#x…

开心档之开发入门网-C++ 有用的资源

C 有用的资源 目录 C 有用的资源 C 有用的网站 C 有用的书籍 以下资源包含了 C 有关的网站、书籍和文章。请使用它们来进一步学习 C 的知识。 C 有用的网站 C Standard Library headers − C 标准库。C Programming − 这本书涵盖了 C 语言编程、软件交互设计、C 语言的现…

CMake入门教程【基础篇】4.target_include_directories包含指定文件夹头文件

target_include_directories包含指定文件夹头文件 文章目录 知识点实例代码目录代码实现编译知识点 target_include_directories() 指定目标包含的头文件路径 实例 代码目录 |-📁prj3   |-- 🎴CMakeLists.txt   |-📁include    |-- 📄Hello.h   |-📁src…