- ✨高级定时器的输入捕获功能在脉宽信号测量方面是非常方便的。尤其时在使用HC-SR04超声波测距方面。高级定时器的结构相对而言比较复杂,配置一个完善的案例可以方便后续使用该功能时可以直接套用和借鉴。
输入捕获针对的是外部输入信号:上升沿或下降沿信号产生的中断
更新中断是内部定时器计数值超出了重装载值产生溢出的更新事件。当然也有可能是同时是被测量信号电平太长。
72MHz主频下,微秒延时函数测量
void delay_us(uint32_t udelay)
{
uint32_t startval, tickn, delays, wait;
startval = SysTick->VAL;
tickn = HAL_GetTick();
//sysc = 72000; //SystemCoreClock / (1000U / uwTickFreq);
delays = (udelay-3) * 72; //-3测量后修正,sysc / 1000 * udelay;
if(delays > startval)
{
while(HAL_GetTick() == tickn)
{
}
wait = 72000 + startval - delays;
while(wait < SysTick->VAL)
{
}
}
else
{
wait = startval - delays;
while(wait < SysTick->VAL && HAL_GetTick() == tickn)
{
}
}
}
✨实际测量中发现,被测量的脉冲宽度大于1us脉冲信号才能读取正确。测量小于1us脉宽信号读取的计数值就不对了,可能代码上还是存在缺陷。
//TIM5输入通道1:PA0
/* TIM5CH1_CAP_STA 各数据位说明
** bit7 捕获完成标志
** bit6 捕获到高电平标志
** bit5~0 捕获高电平后定时器溢出的次数*/
uint8_t TIM5CH1_CAP_STA = 0;
uint16_t TIM5CH1_CAP_VAL;
//定时器更新中断处理回调函数
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim)
{
if((TIM5CH1_CAP_STA & 0X80) == 0) //还未成功捕获
{
if(TIM5CH1_CAP_STA & 0X40) //已经捕获到高电平
{
if((TIM5CH1_CAP_STA & 0X3F) == 0X3F) //高电平时间太长了
{
TIM5CH1_CAP_STA |= 0X80; //标记为完成一次捕获
TIM5CH1_CAP_VAL = 0XFFFF; //计数器值
}
else
TIM5CH1_CAP_STA++; //溢出次数加1
}
}
}
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef* htim)
{
if((TIM5CH1_CAP_STA & 0X80) == 0) //还未成功捕获
{
if(TIM5CH1_CAP_STA & 0X40) //捕获到上升沿后条件为真
{
TIM5CH1_CAP_STA |= 0X80; //标记为完成一次高电平捕获
TIM5CH1_CAP_VAL = HAL_TIM_ReadCapturedValue(&htim5, TIM_CHANNEL_1); //获取当前的计数器值
TIM_RESET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1); //清除原来的设置
TIM_SET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1, TIM_ICPOLARITY_RISING); //设置上升沿捕获
}
else
{
TIM5CH1_CAP_STA = 0;
TIM5CH1_CAP_VAL = 0;
TIM5CH1_CAP_STA |= 0X40; //标记捕获到上升沿
__HAL_TIM_DISABLE(&htim5); //关闭定时器
__HAL_TIM_SET_COUNTER(&htim5, 0); //计数器值清零
TIM_RESET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1); //清除原来的设置
TIM_SET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1, TIM_ICPOLARITY_FALLING); //设置下降沿捕获
__HAL_TIM_ENABLE(&htim5); //使能定时器
}
}
}
- 在
HAL_TIM_PeriodElapsedCallback()
回调函数中用以处理计数次数和时间;在HAL_TIM_IC_CaptureCallback()
回调函数负责处理捕获到的上升沿和下降沿,并随着捕获到上升沿而更改为下降沿捕获, 随着捕获到下降沿而更改定时器为上升沿捕获.
void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
中被调用。void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
{
/* Capture compare 1 event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) != RESET)
{
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
/* Input capture event */
if ((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U)
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->IC_CaptureCallback(htim);
#else
HAL_TIM_IC_CaptureCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
/* Output compare event */
else
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->OC_DelayElapsedCallback(htim);
htim->PWM_PulseFinishedCallback(htim);
#else
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
}
/* Capture compare 2 event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
/* Input capture event */
if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U)
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->IC_CaptureCallback(htim);
#else
HAL_TIM_IC_CaptureCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
/* Output compare event */
else
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->OC_DelayElapsedCallback(htim);
htim->PWM_PulseFinishedCallback(htim);
#else
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* Capture compare 3 event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
/* Input capture event */
if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U)
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->IC_CaptureCallback(htim);
#else
HAL_TIM_IC_CaptureCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
/* Output compare event */
else
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->OC_DelayElapsedCallback(htim);
htim->PWM_PulseFinishedCallback(htim);
#else
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* Capture compare 4 event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
/* Input capture event */
if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U)
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->IC_CaptureCallback(htim);
#else
HAL_TIM_IC_CaptureCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
/* Output compare event */
else
{
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->OC_DelayElapsedCallback(htim);
htim->PWM_PulseFinishedCallback(htim);
#else
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
}
/* TIM Update event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->PeriodElapsedCallback(htim);
#else
HAL_TIM_PeriodElapsedCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
}
/* TIM Break input event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK);
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->BreakCallback(htim);
#else
HAL_TIMEx_BreakCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
}
/* TIM Trigger detection event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER);
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->TriggerCallback(htim);
#else
HAL_TIM_TriggerCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
}
/* TIM commutation event */
if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET)
{
if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) != RESET)
{
__HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM);
#if (USE_HAL_TIM_REGISTER_CALLBACKS == 1)
htim->CommutationCallback(htim);
#else
HAL_TIMEx_CommutCallback(htim);
#endif /* USE_HAL_TIM_REGISTER_CALLBACKS */
}
}
}
内含一些无关的测试函数和代码。
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 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.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* 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 */
//TIM5输入通道1:PA0
/* TIM5CH1_CAP_STA 各数据位说明
** bit7 捕获完成标志
** bit6 捕获到高电平标志
** bit5~0 捕获高电平后定时器溢出的次数*/
uint8_t TIM5CH1_CAP_STA = 0;
uint16_t TIM5CH1_CAP_VAL;
/* 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 */
/*
for循环实现延时us
*/
static void for_delay_us(uint32_t nus)
{
uint32_t Delay = nus * 72 / 4;//72MHz
do
{
__NOP();
}
while(Delay --);
}
void delay_us(uint32_t udelay)
{
uint32_t startval, tickn, delays, wait;
startval = SysTick->VAL;
tickn = HAL_GetTick();
//sysc = 72000; //SystemCoreClock / (1000U / uwTickFreq);
delays = (udelay-3) * 72; //-3修正,sysc / 1000 * udelay;
if(delays > startval)
{
while(HAL_GetTick() == tickn)
{
}
wait = 72000 + startval - delays;
while(wait < SysTick->VAL)
{
}
}
else
{
wait = startval - delays;
while(wait < SysTick->VAL && HAL_GetTick() == tickn)
{
}
}
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
long long temp = 0;
/* 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();
MX_TIM5_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_IC_Start_IT(&htim5, TIM_CHANNEL_1); //一定要开启TIM5通道1的捕获中断,TIM5通道1:PA0
__HAL_TIM_ENABLE_IT(&htim5, TIM_IT_UPDATE); //一定要开启TIM5的更新中断
printf("This is TIM_CAP test...\n");
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while(1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7,GPIO_PIN_SET);//用于产生超声波Trig触发信号
GPIOA->BSRR = GPIO_PIN_7;
// for_delay_us(10);//超声波触发时间大于等于10us,不要超过1ms,否则不正常
delay_us(500);
// HAL_Delay(1);
// __NOP(); __NOP(); __NOP(); __NOP();
// __NOP(); __NOP(); __NOP(); __NOP();
// __NOP(); __NOP(); __NOP(); __NOP();
// __NOP(); __NOP(); __NOP(); __NOP();
// __NOP(); __NOP();__NOP();__NOP();
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7,GPIO_PIN_RESET);
GPIOA->BSRR = (uint32_t)GPIO_PIN_7 << 16u;
if(TIM5CH1_CAP_STA & 0X80) //完成一次高电平捕获
{
temp = TIM5CH1_CAP_STA & 0X3F;
temp *= 65536; //溢出总时间
temp += TIM5CH1_CAP_VAL; //总的高电平时间
temp /= 4; //TIM5:4MHz
printf("High level duration:%lld us\r\n", temp);
TIM5CH1_CAP_STA = 0; //准备下一次捕获
}
HAL_Delay(1000);
HAL_GPIO_TogglePin(GPIOE, GPIO_PIN_5);
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_5);
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses 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_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
//定时器更新中断处理回调函数
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim)
{
if((TIM5CH1_CAP_STA & 0X80) == 0) //还未成功捕获
{
if(TIM5CH1_CAP_STA & 0X40) //已经捕获到高电平
{
if((TIM5CH1_CAP_STA & 0X3F) == 0X3F) //高电平时间太长了
{
TIM5CH1_CAP_STA |= 0X80; //标记为完成一次捕获
TIM5CH1_CAP_VAL = 0XFFFF; //计数器值
}
else
TIM5CH1_CAP_STA++; //溢出次数加1
}
}
}
//输入捕获中断处理回调函数
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef* htim)
{
if((TIM5CH1_CAP_STA & 0X80) == 0) //还未成功捕获
{
if(TIM5CH1_CAP_STA & 0X40) //捕获到上升沿后条件为真
{
TIM5CH1_CAP_STA |= 0X80; //标记为完成一次高电平捕获
TIM5CH1_CAP_VAL = HAL_TIM_ReadCapturedValue(&htim5, TIM_CHANNEL_1); //获取当前的计数器值
TIM_RESET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1); //清除原来的设置
TIM_SET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1, TIM_ICPOLARITY_RISING); //设置上升沿捕获
}
else
{
TIM5CH1_CAP_STA = 0;
TIM5CH1_CAP_VAL = 0;
TIM5CH1_CAP_STA |= 0X40; //标记捕获到上升沿
__HAL_TIM_DISABLE(&htim5); //关闭定时器
__HAL_TIM_SET_COUNTER(&htim5, 0); //计数器值清零
TIM_RESET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1); //清除原来的设置
TIM_SET_CAPTUREPOLARITY(&htim5, TIM_CHANNEL_1, TIM_ICPOLARITY_FALLING); //设置下降沿捕获
__HAL_TIM_ENABLE(&htim5); //使能定时器
}
}
}
/* 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 */
__disable_irq();
while(1)
{
}
/* 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,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7,GPIO_PIN_SET);//用于产生超声波Trig触发信号
GPIOA->BSRR = GPIO_PIN_7;//Echo
for_delay_us(15);//超声波触发时间大于等于10us,不要超过1ms,否则不正常
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7,GPIO_PIN_RESET);
GPIOA->BSRR = (uint32_t)GPIO_PIN_7 << 16u;
if(TIM5CH1_CAP_STA & 0X80) //完成一次高电平捕获
{
temp = TIM5CH1_CAP_STA & 0X3F;
temp *= 65536; //溢出总时间
temp += TIM5CH1_CAP_VAL; //总的高电平时间
temp /= 4; //TIM5:4MHz
float dist = high_time / 1000.0 * 340 / 2;//cm
printf("High level duration:%lld us, %.2f \r\n", temp,dist);
TIM5CH1_CAP_STA = 0; //准备下一次捕获
}
链接:https://pan.baidu.com/s/17dt-7ESvB01K304rGhrG8w
提取码:dgkj