STM32 CubeMX如何生成微秒(us)级延时
会自动在tim.c里面生成代码,如下:
/* Includes ------------------------------------------------------------------*/
#include "tim.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
TIM_HandleTypeDef htim17;
/* TIM17 init function */
void MX_TIM17_Init(void)
{
htim17.Instance = TIM17;
htim17.Init.Prescaler = 0;
htim17.Init.CounterMode = TIM_COUNTERMODE_UP;
htim17.Init.Period = 65535;
htim17.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim17.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&htim17) != HAL_OK)
{
Error_Handler();
}
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM17)
{
/* USER CODE BEGIN TIM17_MspInit 0 */
/* USER CODE END TIM17_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_TIM17_CLK_ENABLE();
/* USER CODE BEGIN TIM17_MspInit 1 */
/* USER CODE END TIM17_MspInit 1 */
}
}
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM17)
{
/* USER CODE BEGIN TIM17_MspDeInit 0 */
/* USER CODE END TIM17_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM17_CLK_DISABLE();
}
/* USER CODE BEGIN TIM17_MspDeInit 1 */
/* USER CODE END TIM17_MspDeInit 1 */
}
然后自己再写一个函数;
/* USER CODE BEGIN 4 */
void Delay_us(uint16_t nus)
{
__HAL_TIM_SetCounter(&htim17, 0);//htim17
__HAL_TIM_ENABLE(&htim17);
while(__HAL_TIM_GetCounter(&htim17) < (36 * nus));//36是系统时钟,更改这里就行了。
/* Disable the Peripheral */
__HAL_TIM_DISABLE(&htim17);
}
/* USER CODE END 4 */
因为36 * 1/36M 对应的就是1us,用定时器来做延时是很准的。