cancel
Showing results for 
Search instead for 
Did you mean: 

Nucleo-L476RG TIM2 PWM output not work

I want to use Nucleo-L476RG to generate pwm output. but the problem is i can't use TIM2. TIM5 is ok. i use PA1 to generate pwm, when set PA1 as TIM2 CH2, it doesn't work. but when i use it as TIM5 CH2. it works. How can this be happened? is there any difference between TIM2 and TIM5? can someone help me? thanks in advance.

Initialize code is below:
 
TIM_HandleTypeDef led_pwm_tim_handle;
TIM_OC_InitTypeDef led_pwm_oc_init;
   
    led_pwm_tim_handle.Instance = TIM5; // tim2 not work
    led_pwm_tim_handle.Init.Prescaler = 80-1;
    led_pwm_tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
    led_pwm_tim_handle.Init.Period = 666-1;
    led_pwm_tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV2;
    led_pwm_tim_handle.Init.RepetitionCounter = 0;
    led_pwm_tim_handle.Init.AutoReloadPreload = ENABLE;
    HAL_TIM_PWM_Init(&led_pwm_tim_handle);
 
    led_pwm_oc_init.Pulse = 332;
    led_pwm_oc_init.OCMode = TIM_OCMODE_PWM1;
    led_pwm_oc_init.OCPolarity = TIM_OCPOLARITY_HIGH;
    led_pwm_oc_init.OCNPolarity = TIM_OCNPOLARITY_HIGH;
    led_pwm_oc_init.OCFastMode = TIM_OCFAST_DISABLE;
    led_pwm_oc_init.OCIdleState = TIM_OCNIDLESTATE_RESET;
    led_pwm_oc_init.OCNIdleState = TIM_OCNIDLESTATE_RESET;
    HAL_TIM_PWM_ConfigChannel(&led_pwm_tim_handle,&led_pwm_oc_init,TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&led_pwm_tim_handle,TIM_CHANNEL_2);

initialize pin is here:
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
 
    __HAL_RCC_TIM5_CLK_ENABLE();//TIM2 not work
    __HAL_RCC_GPIOA_CLK_ENABLE();
 
    GPIO_InitStruct.Pin = GPIO_PIN_1;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF2_TIM2;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}

1 ACCEPTED SOLUTION

Accepted Solutions
Peter Mather
Associate III

Have you changed the setup of the pin - it has a different AF setting

TIM2 is AF1, TIM5 is AF2

View solution in original post

4 REPLIES 4
Peter Mather
Associate III

Have you changed the setup of the pin - it has a different AF setting

TIM2 is AF1, TIM5 is AF2

In debugger, read out and check/compare the relevant timer registers content. Also read out and check the relevant GPIO registers content - as Peter Mather pointed out above, the two settings differ in the content of GPIOx_AFR.

JW

That's right. it works. Thank you. but i also found GPIO_AF2_TIM2 is exist in *.h file. what 's different between them? i can't find the answer in Description of STM32L4/L4+ HAL and low-layer drivers document.

Peter is right, it works after i change it to GPIO_AF1_TIM2. but what's different between GPIO_AF2_TIM2 and GPIO_AF1_TIM2, is there any document to show the difference?