[STM32WL] 有没有特定的应用案例可以分享?

[复制链接]
 楼主| 呈兴 发表于 2024-10-31 23:29 | 显示全部楼层 |阅读模式
在使用STM32的定时器时,您是如何配置周期和中断的?


 楼主| 呈兴 发表于 2024-10-31 23:29 | 显示全部楼层
如何配置周期和中断的?
gaoyang9992006 发表于 2024-11-20 14:37 | 显示全部楼层
  1. void TIM2_IRQHandler(void) {
  2.     if (TIM2->SR & TIM_SR_UIF) {  // 检查更新中断标志
  3.         TIM2->SR &= ~TIM_SR_UIF;  // 清除中断标志
  4.         // 执行定时器周期事件(如LED切换等)
  5.     }
  6. }

  7. void Timer_Init(void) {
  8.     // 1. 启动定时器时钟(这里假设已经开启了 TIM2 的时钟)
  9.    
  10.     // 2. 配置预分频器和自动重载寄存器以产生 1s 周期(假设系统时钟为 72 MHz)
  11.     uint32_t prescaler = 7199;  // PSC = 7199 => 72 MHz / (7199+1) = 10 kHz
  12.     uint32_t arr = 9999;         // ARR = 9999 => (10 kHz / (9999+1)) = 1 Hz
  13.    
  14.     TIM2->PSC = prescaler;  // 设置预分频器
  15.     TIM2->ARR = arr;        // 设置自动重载值
  16.    
  17.     // 3. 启用定时器更新中断
  18.     TIM2->DIER |= TIM_DIER_UIE;  // 启用更新中断
  19.    
  20.     // 4. 启动定时器
  21.     TIM2->CR1 |= TIM_CR1_CEN;  // 启动定时器
  22.    
  23.     // 5. 配置 NVIC 中断优先级和使能
  24.     NVIC_SetPriority(TIM2_IRQn, 1);  // 设置定时器中断优先级
  25.     NVIC_EnableIRQ(TIM2_IRQn);       // 启用定时器中断请求
  26. }
gaoyang9992006 发表于 2024-11-20 14:38 | 显示全部楼层
定时器预分频器:设置为 7199,表示将定时器的时钟频率从 72 MHz 降到 10 kHz。
自动重载寄存器:设置为 9999,定时器每计数 10000 次(10 kHz 下 1 秒)溢出一次。
中断服务程序:当定时器溢出时,触发 TIM2 中断,进入 TIM2_IRQHandler 进行相应操作,并清除中断标志。
gaoyang9992006 发表于 2024-11-20 14:40 | 显示全部楼层
如果使用F1可以看下面路径的实例:
G:\MCU\STM32Cube_FW_F1_V1.8.0\Projects\STM32F103RB-Nucleo\Examples\TIM\TIM_TimeBase\Src
gaoyang9992006 发表于 2024-11-20 14:40 | 显示全部楼层
  1. /**
  2.   ******************************************************************************
  3.   * [url=home.php?mod=space&uid=288409]@file[/url]    TIM/TIM_TimeBase/Src/main.c
  4.   * [url=home.php?mod=space&uid=187600]@author[/url]  MCD Application Team
  5.   * [url=home.php?mod=space&uid=247401]@brief[/url]   This sample code shows how to use STM32F1xx TIM HAL API to generate
  6.   *          a time base of one second with the corresponding Interrupt request.
  7.   ******************************************************************************
  8.   * @attention
  9.   *
  10.   * Copyright (c) 2016 STMicroelectronics.
  11.   * All rights reserved.
  12.   *
  13.   * This software is licensed under terms that can be found in the LICENSE file
  14.   * in the root directory of this software component.
  15.   * If no LICENSE file comes with this software, it is provided AS-IS.
  16.   *
  17.   ******************************************************************************
  18.   */

  19. /* Includes ------------------------------------------------------------------*/
  20. #include "main.h"

  21. /** @addtogroup STM32F1xx_HAL_Examples
  22.   * @{
  23.   */

  24. /** @addtogroup TIM_TimeBase
  25.   * @{
  26.   */

  27. /* Private typedef -----------------------------------------------------------*/
  28. /* Private define ------------------------------------------------------------*/
  29. /* Private macro -------------------------------------------------------------*/
  30. /* Private variables ---------------------------------------------------------*/
  31. /* TIM handle declaration */
  32. TIM_HandleTypeDef    TimHandle;

  33. /* Prescaler declaration */
  34. uint32_t uwPrescalerValue = 0;

  35. /* Private function prototypes -----------------------------------------------*/
  36. void SystemClock_Config(void);
  37. static void Error_Handler(void);

  38. /* Private functions ---------------------------------------------------------*/

  39. /**
  40.   * @brief  Main program
  41.   * @param  None
  42.   * @retval None
  43.   */
  44. int main(void)
  45. {
  46.   /* STM32F103xB HAL library initialization:
  47.        - Configure the Flash prefetch
  48.        - Systick timer is configured by default as source of time base, but user
  49.          can eventually implement his proper time base source (a general purpose
  50.          timer for example or other time source), keeping in mind that Time base
  51.          duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
  52.          handled in milliseconds basis.
  53.        - Set NVIC Group Priority to 4
  54.        - Low Level Initialization
  55.      */
  56.   HAL_Init();

  57.   /* Configure the system clock to 64 MHz */
  58.   SystemClock_Config();

  59.   /* Configure LED2 */
  60.   BSP_LED_Init(LED2);

  61.   /*##-1- Configure the TIM peripheral #######################################*/
  62.   /* -----------------------------------------------------------------------
  63.     In this example TIM3 input clock (TIM3CLK)  is set to APB1 clock (PCLK1) x2,
  64.     since APB1 prescaler is set to 4 (0x100).
  65.        TIM3CLK = PCLK1*2
  66.        PCLK1   = HCLK/2
  67.     => TIM3CLK = PCLK1*2 = (HCLK/2)*2 = HCLK = SystemCoreClock
  68.     To get TIM3 counter clock at 10 KHz, the Prescaler is computed as following:
  69.     Prescaler = (TIM3CLK / TIM3 counter clock) - 1
  70.     Prescaler = (SystemCoreClock /10 KHz) - 1

  71.     Note:
  72.      SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f1xx.c file.
  73.      Each time the core clock (HCLK) changes, user had to update SystemCoreClock
  74.      variable value. Otherwise, any configuration based on this variable will be incorrect.
  75.      This variable is updated in three ways:
  76.       1) by calling CMSIS function SystemCoreClockUpdate()
  77.       2) by calling HAL API function HAL_RCC_GetSysClockFreq()
  78.       3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
  79.   ----------------------------------------------------------------------- */

  80.   /* Compute the prescaler value to have TIMx counter clock equal to 10000 Hz */
  81.   uwPrescalerValue = (uint32_t)(SystemCoreClock / 10000) - 1;

  82.   /* Set TIMx instance */
  83.   TimHandle.Instance = TIMx;

  84.   /* Initialize TIMx peripheral as follows:
  85.        + Period = 10000 - 1
  86.        + Prescaler = (SystemCoreClock/10000) - 1
  87.        + ClockDivision = 0
  88.        + Counter direction = Up
  89.   */
  90.   TimHandle.Init.Period            = 10000 - 1;
  91.   TimHandle.Init.Prescaler         = uwPrescalerValue;
  92.   TimHandle.Init.ClockDivision     = 0;
  93.   TimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;
  94.   TimHandle.Init.RepetitionCounter = 0;
  95.   TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;

  96.   if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
  97.   {
  98.     /* Initialization Error */
  99.     Error_Handler();
  100.   }

  101.   /*##-2- Start the TIM Base generation in interrupt mode ####################*/
  102.   /* Start Channel1 */
  103.   if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)
  104.   {
  105.     /* Starting Error */
  106.     Error_Handler();
  107.   }

  108.   while (1)
  109.   {
  110.   }
  111. }

  112. /**
  113.   * @brief  Period elapsed callback in non blocking mode
  114.   * @param  htim : TIM handle
  115.   * @retval None
  116.   */
  117. void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
  118. {
  119.   BSP_LED_Toggle(LED2);
  120. }

  121. /**
  122.   * @brief  System Clock Configuration
  123.   *         The system Clock is configured as follow :
  124.   *            System Clock source            = PLL (HSI)
  125.   *            SYSCLK(Hz)                     = 64000000
  126.   *            HCLK(Hz)                       = 64000000
  127.   *            AHB Prescaler                  = 1
  128.   *            APB1 Prescaler                 = 2
  129.   *            APB2 Prescaler                 = 1
  130.   *            PLLMUL                         = 16
  131.   *            Flash Latency(WS)              = 2
  132.   * @param  None
  133.   * @retval None
  134.   */
  135. void SystemClock_Config(void)
  136. {
  137.   RCC_ClkInitTypeDef clkinitstruct = {0};
  138.   RCC_OscInitTypeDef oscinitstruct = {0};
  139.   
  140.   /* Configure PLL ------------------------------------------------------*/
  141.   /* PLL configuration: PLLCLK = (HSI / 2) * PLLMUL = (8 / 2) * 16 = 64 MHz */
  142.   /* PREDIV1 configuration: PREDIV1CLK = PLLCLK / HSEPredivValue = 64 / 1 = 64 MHz */
  143.   /* Enable HSI and activate PLL with HSi_DIV2 as source */
  144.   oscinitstruct.OscillatorType  = RCC_OSCILLATORTYPE_HSI;
  145.   oscinitstruct.HSEState        = RCC_HSE_OFF;
  146.   oscinitstruct.LSEState        = RCC_LSE_OFF;
  147.   oscinitstruct.HSIState        = RCC_HSI_ON;
  148.   oscinitstruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  149.   oscinitstruct.HSEPredivValue    = RCC_HSE_PREDIV_DIV1;
  150.   oscinitstruct.PLL.PLLState    = RCC_PLL_ON;
  151.   oscinitstruct.PLL.PLLSource   = RCC_PLLSOURCE_HSI_DIV2;
  152.   oscinitstruct.PLL.PLLMUL      = RCC_PLL_MUL16;
  153.   if (HAL_RCC_OscConfig(&oscinitstruct)!= HAL_OK)
  154.   {
  155.     /* Initialization Error */
  156.     while(1);
  157.   }

  158.   /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
  159.      clocks dividers */
  160.   clkinitstruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  161.   clkinitstruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  162.   clkinitstruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  163.   clkinitstruct.APB2CLKDivider = RCC_HCLK_DIV1;
  164.   clkinitstruct.APB1CLKDivider = RCC_HCLK_DIV2;  
  165.   if (HAL_RCC_ClockConfig(&clkinitstruct, FLASH_LATENCY_2)!= HAL_OK)
  166.   {
  167.     /* Initialization Error */
  168.     while(1);
  169.   }
  170. }

  171. /**
  172.   * @brief  This function is executed in case of error occurrence.
  173.   * @param  None
  174.   * @retval None
  175.   */
  176. static void Error_Handler(void)
  177. {
  178.   while (1)
  179.   {
  180.   }
  181. }
  182. #ifdef  USE_FULL_ASSERT

  183. /**
  184.   * @brief  Reports the name of the source file and the source line number
  185.   *         where the assert_param error has occurred.
  186.   * @param  file: pointer to the source file name
  187.   * @param  line: assert_param error line source number
  188.   * @retval None
  189.   */
  190. void assert_failed(uint8_t *file, uint32_t line)
  191. {
  192.   /* User can add his own implementation to report the file name and line number,
  193.      ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  194.   /* Infinite loop */
  195.   while (1)
  196.   {
  197.   }
  198. }

  199. #endif

  200. /**
  201.   * @}
  202.   */

  203. /**
  204.   * @}
  205.   */
一路向北lm 发表于 2024-11-20 16:43 | 显示全部楼层
在STM32中,你可以使用HAL库或标准外设库来配置定时器以产生周期性的中断。以下是一个基本的例子,展示如何使用HAL库来配置STM32的定时器并设置周期中断。假设我们使用TIM2定时器(一个通用定时器)。
首先,确保你的项目中已经包含了相关的HAL库文件,并且已经正确配置了时钟系统。接下来,按照以下步骤操作:
  • 配置定时器的基本参数(如预分频器、自动重装载值等)。
  • 启动定时器并配置相应的中断优先级和使能中断。
以下是具体的代码示例:
  1. #include "stm32f4xx_hal.h" // 根据你的STM32系列修改头文件

  2. // 假设的定时器句柄
  3. TIM_HandleTypeDef htimX; // X代表定时器的实例,如TIM2、TIM3等

  4. // 初始化定时器配置函数
  5. void MX_TIMX_Init(uint32_t period) {
  6.     TIM_OC_InitTypeDef sConfigOC = {0};
  7.    
  8.     // 配置定时器时钟源和预分频器(这通常在CubeMX中完成或通过代码手动配置)
  9.     // 例如:使用内部时钟源和预分频器为0(不分频)
  10.    
  11.     // 配置自动重装载值以设置定时周期(假设使用的是自动重载模式)
  12.     htimX.Instance = TIMX; // X代表定时器实例,如TIM2等
  13.     htimX.Init.Period = period - 1; // 自动重装载值(周期-1)因为是从0开始计数到Period的值产生更新事件(中断)
  14.     htimX.Init.CounterMode = TIM_COUNTERMODE_UP; // 向上计数模式
  15.     htimX.Init.Prescaler = 0; // 预分频器值(根据你的时钟配置设置)
  16.     HAL_TIM_Base_Init(&htimX); // 初始化定时器基本功能
  17.     HAL_TIM_Base_Start_IT(&htimX); // 启动定时器并启用中断版本,这样当定时器更新时会触发中断
  18.     HAL_NVIC_SetPriority(TIMX_IRQn, 0, 0); // 设置中断优先级(根据你的需求调整优先级)并启用中断
  19. }

  20. // TIMX中断服务函数(中断处理程序)
  21. void TIMX_IRQHandler(void)


一秒落纱 发表于 2024-12-4 21:50 | 显示全部楼层
在使用STM32的定时器时,配置周期和中断是非常重要的步骤
远山寻你 发表于 2024-12-5 03:00 | 显示全部楼层
使能定时器中断,并配置NVICNested Vectored Interrupt Controller

光辉梦境 发表于 2024-12-5 04:00 | 显示全部楼层
设置预分频器,将定时器的时钟频率降低到10kHz

三生万物 发表于 2024-12-5 05:00 | 显示全部楼层

一般是需要设置自动重装载寄存器(ARR),使得定时器的周期为*
淡漠安然 发表于 2024-12-5 06:00 | 显示全部楼层
定时器中断服务程序,调用HAL_TIM_IRQHandler处理中断

暖了夏天蓝了海 发表于 2024-12-5 07:00 | 显示全部楼层
定时器周期中断回调函数,处理具体的定时器中断任务

江河千里 发表于 2024-12-5 08:00 | 显示全部楼层
直接使用cubemx来搞就好了

别乱了阵脚 发表于 2024-12-5 09:00 | 显示全部楼层
我觉得这种周期应该是有例程的吧,参考一下例程呢

冰春彩落下 发表于 2024-12-5 10:00 | 显示全部楼层
正常配置就可以啊,感觉比较简单吧,定时器来说

而服务器人 发表于 2024-12-31 23:28 | 显示全部楼层
STM32 的定时器时钟通常与 APB 总线时钟相关
您需要登录后才可以回帖 登录 | 注册

本版积分规则

26

主题

149

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部

26

主题

149

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部