打印
[STM32WL]

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

[复制链接]
868|18
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
呈兴|  楼主 | 2024-10-31 23:29 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
在使用STM32的定时器时,您是如何配置周期和中断的?


使用特权

评论回复
沙发
呈兴|  楼主 | 2024-10-31 23:29 | 只看该作者
如何配置周期和中断的?

使用特权

评论回复
板凳
gaoyang9992006| | 2024-11-20 14:37 | 只看该作者
void TIM2_IRQHandler(void) {
    if (TIM2->SR & TIM_SR_UIF) {  // 检查更新中断标志
        TIM2->SR &= ~TIM_SR_UIF;  // 清除中断标志
        // 执行定时器周期事件(如LED切换等)
    }
}

void Timer_Init(void) {
    // 1. 启动定时器时钟(这里假设已经开启了 TIM2 的时钟)
   
    // 2. 配置预分频器和自动重载寄存器以产生 1s 周期(假设系统时钟为 72 MHz)
    uint32_t prescaler = 7199;  // PSC = 7199 => 72 MHz / (7199+1) = 10 kHz
    uint32_t arr = 9999;         // ARR = 9999 => (10 kHz / (9999+1)) = 1 Hz
   
    TIM2->PSC = prescaler;  // 设置预分频器
    TIM2->ARR = arr;        // 设置自动重载值
   
    // 3. 启用定时器更新中断
    TIM2->DIER |= TIM_DIER_UIE;  // 启用更新中断
   
    // 4. 启动定时器
    TIM2->CR1 |= TIM_CR1_CEN;  // 启动定时器
   
    // 5. 配置 NVIC 中断优先级和使能
    NVIC_SetPriority(TIM2_IRQn, 1);  // 设置定时器中断优先级
    NVIC_EnableIRQ(TIM2_IRQn);       // 启用定时器中断请求
}

使用特权

评论回复
地板
gaoyang9992006| | 2024-11-20 14:38 | 只看该作者
定时器预分频器:设置为 7199,表示将定时器的时钟频率从 72 MHz 降到 10 kHz。
自动重载寄存器:设置为 9999,定时器每计数 10000 次(10 kHz 下 1 秒)溢出一次。
中断服务程序:当定时器溢出时,触发 TIM2 中断,进入 TIM2_IRQHandler 进行相应操作,并清除中断标志。

使用特权

评论回复
5
gaoyang9992006| | 2024-11-20 14:40 | 只看该作者
如果使用F1可以看下面路径的实例:
G:\MCU\STM32Cube_FW_F1_V1.8.0\Projects\STM32F103RB-Nucleo\Examples\TIM\TIM_TimeBase\Src

使用特权

评论回复
6
gaoyang9992006| | 2024-11-20 14:40 | 只看该作者
/**
  ******************************************************************************
  * [url=home.php?mod=space&uid=288409]@file[/url]    TIM/TIM_TimeBase/Src/main.c
  * [url=home.php?mod=space&uid=187600]@author[/url]  MCD Application Team
  * [url=home.php?mod=space&uid=247401]@brief[/url]   This sample code shows how to use STM32F1xx TIM HAL API to generate
  *          a time base of one second with the corresponding Interrupt request.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */

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

/** @addtogroup STM32F1xx_HAL_Examples
  * @{
  */

/** @addtogroup TIM_TimeBase
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* TIM handle declaration */
TIM_HandleTypeDef    TimHandle;

/* Prescaler declaration */
uint32_t uwPrescalerValue = 0;

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void Error_Handler(void);

/* Private functions ---------------------------------------------------------*/

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

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

  /* Configure LED2 */
  BSP_LED_Init(LED2);

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

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

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

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

  /* Initialize TIMx peripheral as follows:
       + Period = 10000 - 1
       + Prescaler = (SystemCoreClock/10000) - 1
       + ClockDivision = 0
       + Counter direction = Up
  */
  TimHandle.Init.Period            = 10000 - 1;
  TimHandle.Init.Prescaler         = uwPrescalerValue;
  TimHandle.Init.ClockDivision     = 0;
  TimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;
  TimHandle.Init.RepetitionCounter = 0;
  TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;

  if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /*##-2- Start the TIM Base generation in interrupt mode ####################*/
  /* Start Channel1 */
  if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)
  {
    /* Starting Error */
    Error_Handler();
  }

  while (1)
  {
  }
}

/**
  * @brief  Period elapsed callback in non blocking mode
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  BSP_LED_Toggle(LED2);
}

/**
  * @brief  System Clock Configuration
  *         The system Clock is configured as follow :
  *            System Clock source            = PLL (HSI)
  *            SYSCLK(Hz)                     = 64000000
  *            HCLK(Hz)                       = 64000000
  *            AHB Prescaler                  = 1
  *            APB1 Prescaler                 = 2
  *            APB2 Prescaler                 = 1
  *            PLLMUL                         = 16
  *            Flash Latency(WS)              = 2
  * @param  None
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_ClkInitTypeDef clkinitstruct = {0};
  RCC_OscInitTypeDef oscinitstruct = {0};
  
  /* Configure PLL ------------------------------------------------------*/
  /* PLL configuration: PLLCLK = (HSI / 2) * PLLMUL = (8 / 2) * 16 = 64 MHz */
  /* PREDIV1 configuration: PREDIV1CLK = PLLCLK / HSEPredivValue = 64 / 1 = 64 MHz */
  /* Enable HSI and activate PLL with HSi_DIV2 as source */
  oscinitstruct.OscillatorType  = RCC_OSCILLATORTYPE_HSI;
  oscinitstruct.HSEState        = RCC_HSE_OFF;
  oscinitstruct.LSEState        = RCC_LSE_OFF;
  oscinitstruct.HSIState        = RCC_HSI_ON;
  oscinitstruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  oscinitstruct.HSEPredivValue    = RCC_HSE_PREDIV_DIV1;
  oscinitstruct.PLL.PLLState    = RCC_PLL_ON;
  oscinitstruct.PLL.PLLSource   = RCC_PLLSOURCE_HSI_DIV2;
  oscinitstruct.PLL.PLLMUL      = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&oscinitstruct)!= HAL_OK)
  {
    /* Initialization Error */
    while(1);
  }

  /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
     clocks dividers */
  clkinitstruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  clkinitstruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  clkinitstruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  clkinitstruct.APB2CLKDivider = RCC_HCLK_DIV1;
  clkinitstruct.APB1CLKDivider = RCC_HCLK_DIV2;  
  if (HAL_RCC_ClockConfig(&clkinitstruct, FLASH_LATENCY_2)!= HAL_OK)
  {
    /* Initialization Error */
    while(1);
  }
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
static void Error_Handler(void)
{
  while (1)
  {
  }
}
#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 can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}

#endif

/**
  * @}
  */

/**
  * @}
  */

使用特权

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

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

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

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


使用特权

评论回复
8
一秒落纱| | 2024-12-4 21:50 | 只看该作者
在使用STM32的定时器时,配置周期和中断是非常重要的步骤

使用特权

评论回复
9
远山寻你| | 2024-12-5 03:00 | 只看该作者
使能定时器中断,并配置NVICNested Vectored Interrupt Controller

使用特权

评论回复
10
光辉梦境| | 2024-12-5 04:00 | 只看该作者
设置预分频器,将定时器的时钟频率降低到10kHz

使用特权

评论回复
11
三生万物| | 2024-12-5 05:00 | 只看该作者

一般是需要设置自动重装载寄存器(ARR),使得定时器的周期为*

使用特权

评论回复
12
淡漠安然| | 2024-12-5 06:00 | 只看该作者
定时器中断服务程序,调用HAL_TIM_IRQHandler处理中断

使用特权

评论回复
13
暖了夏天蓝了海| | 2024-12-5 07:00 | 只看该作者
定时器周期中断回调函数,处理具体的定时器中断任务

使用特权

评论回复
14
江河千里| | 2024-12-5 08:00 | 只看该作者
直接使用cubemx来搞就好了

使用特权

评论回复
15
别乱了阵脚| | 2024-12-5 09:00 | 只看该作者
我觉得这种周期应该是有例程的吧,参考一下例程呢

使用特权

评论回复
16
冰春彩落下| | 2024-12-5 10:00 | 只看该作者
正常配置就可以啊,感觉比较简单吧,定时器来说

使用特权

评论回复
17
而服务器人| | 2024-12-31 23:28 | 只看该作者
STM32 的定时器时钟通常与 APB 总线时钟相关

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

23

主题

146

帖子

0

粉丝