cancel
Showing results for 
Search instead for 
Did you mean: 

PWM not working on STM32l431

rickard2
Associate III

When I trying to run PWM on PA8 I get no PWM at all. The pin just goes high and I can't understand why. I used HAL example code. The cpu is running at 16 MHz and here is the code

HW_TIM_PWM_Set(4000, 70);
HW_TIM_PWM_Enable();
HW_TIM_Delay(1000);
HW_TIM_PWM_Disable();
 
 
void HW_TIM_PWM_Set(uint16_t freq, uint16_t duty)
{
	uint32_t period;
 
	period = 140 -(freq /100);
	period = period *20;	// Lite osäker...
	uint16_t PULSE_VALUE = (period * duty)/100;
	uint16_t PrescalerValue = 0;
 
	/* Compute the prescaler value */
	PrescalerValue = (uint16_t) ((SystemCoreClock /2) / 4000000) - 1;	// 4 MHz PWM
 
	printf("PWM: period %d prescaler %d puls %d \n\r", (int)period, PrescalerValue, PULSE_VALUE);
	PWMTimHandle.Instance = TIM1;
 
	PWMTimHandle.Init.Prescaler         = PrescalerValue;
	PWMTimHandle.Init.Period            = period;
	PWMTimHandle.Init.ClockDivision     = 0;
	PWMTimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;
	PWMTimHandle.Init.RepetitionCounter = 0;
	if (HAL_TIM_PWM_Init(&PWMTimHandle) != HAL_OK)
	{
		printf("Error TIM!\r\n");
		return;
	}
 
	sConfig.OCMode       = TIM_OCMODE_PWM1;
	sConfig.OCPolarity   = TIM_OCPOLARITY_HIGH;
	sConfig.OCFastMode   = TIM_OCFAST_DISABLE;
	sConfig.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
	sConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET;
	sConfig.OCIdleState  = TIM_OCIDLESTATE_RESET;
 
	sConfig.Pulse = PULSE_VALUE;
	if (HAL_TIM_PWM_ConfigChannel(&PWMTimHandle, &sConfig, TIM_CHANNEL_1) != HAL_OK)
	{
		printf("Error PWM!\r\n");
	}
}
 
void HW_TIM_PWM_Enable()
{
	GPIO_InitTypeDef   GPIO_InitStruct;
	__HAL_RCC_GPIOA_CLK_ENABLE();
	GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull = GPIO_PULLUP;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
	GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
	GPIO_InitStruct.Pin = GPIO_PIN_8;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
 
	if (HAL_TIM_PWM_Start(&PWMTimHandle, TIM_CHANNEL_1) != HAL_OK)
	{
		printf("PWM start error\r\n");
	}
}
 
void HW_TIM_PWM_Disable()
{
	GPIO_InitTypeDef   GPIO_InitStruct;
	HAL_TIM_PWM_Stop(&PWMTimHandle, TIM_CHANNEL_1);
 
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Pull = GPIO_PULLUP;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
	GPIO_InitStruct.Pin = GPIO_PIN_8;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	HAL_GPIO_WritePin(GPIOA,  GPIO_PIN_8, GPIO_PIN_RESET);
}

Any suggestions?

4 REPLIES 4

Read out and post content of relevant GPIO and TIM registers.

TIM1 is Advanced timer, did you set TIMx_BDTR.MOE?

I don't Cube.

JW

You enable the peripheral clock somewhere?

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
rickard2
Associate III

Port A peripheral clock is enabled in other code yes.

Can you clarify TIMx_BDTR.MOE?

0690X00000Arc6cQAB.png

I was lazy to locate the RM for your particular chip, but the timers are much the same.

JW