STM32定时器输出PWM
使用步骤
1.初始对应的化定时器 2.选择定时器的时钟源 3.配置PWM相关参数 4.初始化对应的PWM输出通道和使能PWM输出
一、初始对应的化定时器
TIM_HandleTypeDef htim4;
htim4.Instance = TIM4;
htim4.Init.Prescaler = 0X10;
htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
htim4.Init.Period = 65535;
htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV4;
htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
HAL_TIM_Base_Init(&htim4);
二、选择定时器的时钟源
TIM_ClockConfigTypeDef Htim4_Clock;
Htim4_Clock.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
HAL_TIM_ConfigClockSource(&htim4, &Htim4_Clock);
三、配置PWM相关参数
sConfig.OCMode = TIM_OCMODE_PWM1;
sConfig.OCPolarity = TIM_OCNPOLARITY_HIGH;
sConfig.Pulse = 0x2FFF;
sConfig.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(&htim4,&sConfig,TIM_CHANNEL_1);
四、初始化对应的PWM输出通道和使能PWM输出
GPIO_InitTypeDef GPIO_Init_B;
__HAL_RCC_GPIOB_CLK_ENABLE() ;
GPIO_Init_B.Mode = GPIO_MODE_AF_PP;
GPIO_Init_B.Pin = GPIO_PIN_6;
GPIO_Init_B.Speed=GPIO_SPEED_HIGH;
HAL_GPIO_Init(GPIOB,&GPIO_Init_B);
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_1);
|