cancel
Showing results for 
Search instead for 
Did you mean: 

How to enable PWM using interrupt

RSy.1
Associate III

Hi I'm new to STM32 and I am exploring this MCU. I have the STM32F103C8T6 MCU. I just want to ask some help how to enable PWM using interrupts. I am using TIM2 CH1 and set them on the CubeMX. Now I use PA6 as input switch to enable and disable the PWM. However after flashing the MCU the PWM is always activated and cannot be disabled by the PA6 pin. Appreciate if you could tell me what is wrong with the code. Here's my code:

 /* Initialize all configured peripherals */

 MX_GPIO_Init();

 MX_TIM2_Init();

 /* USER CODE BEGIN 2 */

HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1);

 /* USER CODE END 2 */

/* Here is the callback*/

void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)

{

/*Toggle PA6 to enable/ disable the PWM*/

if(!(HAL_GPIO_ReadPin(BUTTON_PWM1_GPIO_Port, BUTTON_PWM1_Pin)))

{

if(htim -> Instance == TIM2)

{

HAL_GPIO_TogglePin(LED_PWM1_GPIO_Port, LED_PWM1_Pin);

}

}

else

{

HAL_GPIO_WritePin(LED_PWM1_GPIO_Port, LED_PWM1_Pin, GPIO_PIN_RESET);

}

}

3 REPLIES 3

I don't follow your code. Can you please explain what exactly do you intend with that snippet?

If LED_PWM1_Pin pin is set as PWM output, you won't be able to influence it using the HAL_GPIO_*** functions, as it's controlled directly by the timer.

JW

Thank you for the input. I will also check the One Pulse that you mentioned I have not studied this yet.

Do you see a way to improve the code above without using the One Pulse that you mentioned?

Probably no. I misinterpreted your code, then rewrote my answer hoping you won't notice...

Try changing the output pin on GPIO_MODER from AF to Out (read the GPIO chapter in RM).

JW