✨对于单脉冲输出模式,高级定时器和通用定时器的实现是由差异的,为了在通用定时器上实现此功能,也是卡了很久。
现有的SDK资源,所能提供的公开资料里面,对于单脉冲模式具体使用很少。
工程的配置方法可以参考《Air001 TIM16通用定时器作PWM输出和延时使用》
TIM_OCMODE_PWM1
和TIM_OCMODE_PWM2
TIM_OCPOLARITY_LOW
或TIM_OCPOLARITY_HIGH
HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel);//开启
//给一定的延时时间
HAL_Delay(500);//给一定的延时
HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel);//关闭
__HAL_TIM_ENABLE(&htim16);
HAL_TIM_PWM_Start(&htim16, TIM_CHANNEL_1);
HAL_Delay(500);//给一定的延时
__HAL_TIM_DISABLE(&htim16);//关闭定时器
TIM_HandleTypeDef htim16;
/* TIM16 init function */
void MX_TIM16_Init(void)
{
/* USER CODE BEGIN TIM16_Init 0 */
/* USER CODE END TIM16_Init 0 */
TIM_OC_InitTypeDef sConfigOC = {0};
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};
/* USER CODE BEGIN TIM16_Init 1 */
/* USER CODE END TIM16_Init 1 */
htim16.Instance = TIM16;
htim16.Init.Prescaler = 8-1;
htim16.Init.CounterMode = TIM_COUNTERMODE_UP;
htim16.Init.Period = 5000;
htim16.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim16.Init.RepetitionCounter = 0;
htim16.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim16) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim16) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_OnePulse_Init(&htim16, TIM_OPMODE_SINGLE) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 2000;
sConfigOC.OCPolarity = TIM_OCPOLARITY_LOW;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_OC_ConfigChannel(&htim16, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&htim16, &sBreakDeadTimeConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM16_Init 2 */
/* USER CODE END TIM16_Init 2 */
HAL_TIM_MspPostInit(&htim16);
}
int main(void)
{
uint16_t plusewidth = 5000;//脉冲宽度;f=1000 000/5000=200Hz
uint16_t plusedelay = 1000;//脉宽1MS
/* 初始化所有外设,Flash接口,SysTick */
HAL_Init();
/* 系统时钟配置 */
APP_SystemClockConfig();
MX_GPIO_Init();
MX_TIM16_Init();
__HAL_TIM_SET_AUTORELOAD(&htim16, plusewidth - 1); //调整分频系数,可以改变arr以改变频率
__HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, plusedelay); //PWM脉冲宽度,修改占空比比较值
// if(HAL_TIM_PWM_Start(&htim16, TIM_CHANNEL_1) != HAL_OK)
// {
// Error_Handler();
// }
while(1)
{
__HAL_TIM_ENABLE(&htim16);
HAL_TIM_PWM_Start(&htim16, TIM_CHANNEL_1);
HAL_Delay(500);
__HAL_TIM_DISABLE(&htim16);
}
}
链接:https://pan.baidu.com/s/1dLwa-6uBFhZKxEnYTBIeCg
提取码:myw9