设置PWM对应引脚PA2
![[QQ_1721613625998.png]]
定时器2受APB1控制
![[QQ_1721613709674.png]]
配置时钟为72MHZ
![[QQ_1721613757231.png]]
HAL库定义PWM
/* TIM2 init function */
void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 1440-1;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 1000-1;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 75;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef* tim_pwmHandle)
{
if(tim_pwmHandle->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspInit 0 */
/* USER CODE END TIM2_MspInit 0 */
/* TIM2 clock enable */
__HAL_RCC_TIM2_CLK_ENABLE();
/* USER CODE BEGIN TIM2_MspInit 1 */
/* USER CODE END TIM2_MspInit 1 */
}
}
主函数中启动TIM2的PWM(CH3)通道
20HZ下的舵机控制(180的舵机)
0 度 -----------------> 占空比为 2.5% -------------> CCR=25
45 度 -----------------> 占空比为 5% -------------> CCR=50
90 度 -----------------> 占空比为 7.5% -------------> CCR=75
135 度 -----------------> 占空比为 10% -------------> CCR=100
180 度 -----------------> 占空比为 12.5% -------------> CCR=125
/* USER CODE BEGIN 2 */
HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_3);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3,25);
HAL_Delay(1000);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3,50);
HAL_Delay(1000);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3,75);
HAL_Delay(1000);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3,100);
HAL_Delay(1000);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3,125);
HAL_Delay(1000);
/* USER CODE BEGIN 3 */
}
标签:TIM2,CODE,HAL,htim2,STM32F429IGT6,TIM,180,STMCubeMX,USER
From: https://blog.csdn.net/sumu0519/article/details/140602697