Hi,
I am using the STM32F411 MCU and i am trying to generate PWM signal with fixed dutycycle and frequency.
clock configuration and timer settings is attached below.


When I set the PWM frequency to 10KHz and the duty cycle to 50%, I get the output as 10 KHz frequency and the dutycycle toggles between 50.00% and 49.97%. When setting PWM frequency to 40KHz and duty cycle to 50%, I get output as 40 KHz frequency and dutycycle toggles between 48.00% and 47.97%.
Program code:
void PWM_Frequency_Init(uint8_t PWM_Frequency)
{
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
Auto_Reload_Value= 1000000/(PWM_Frequency*1000); //Calculate the ARR value
TIM4->CCR1 = 0;
htim4.Instance = TIM4;
htim4.Init.Prescaler = 72-1;
htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
htim4.Init.Period = Auto_Reload_Value -1;
htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim4) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
HAL_TIM_MspPostInit(&htim4);
}
/**
* @brief Generating PWM with respect to the duty cycle and frequency
*
@PAram PWM_Dutycycle, Duty cycle with respect to the voltage/current/half-cell voltage
*
@PAram PWM_Frequency, Frequency with respect to the voltage/current/half-cell voltage
* @retval None
*/
void PWM_Genertion(float PWM_Dutycycle)
{
CCR1_Value = ((PWM_Dutycycle*Auto_Reload_Value)/100); //calculate the ccr1 value
TIM4->CCR1= CCR1_Value;
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
}
Could you please explain why getting like this?
Thank you