AnsweredAssumed Answered

Efficient way to fade a LED

Question asked by Fede Rico on Oct 12, 2017
Latest reply on Oct 23, 2017 by waclawek.jan

Hi there,


I'm trying to Fade (In and Out) a LED with TIM5.


This is my configuration (Just a recap of the configuration):


1) Configure TIM5 in order to generate a signal with 100 Hz as period with no pulse.

htim5.Instance = TIM5;
htim5.Init.Prescaler = 9;
htim5.Init.CounterMode = TIM_COUNTERMODE_UP;
htim5.Init.Period = 63999;
htim5.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;


sConfigOC.Pulse = 0;


2) I write this function to vary the duty cycle:

StatusCode_e PWM_Configure( PWM_TimerId_e timerId, PWM_ChannelId_e channelId, uint8_t dutyCyclePercent )

TIM_OC_InitTypeDef outputConfiguration;



outputConfiguration.OCMode = TIM_OCMODE_PWM1;
outputConfiguration.Pulse = (((PWM_TimerHandler[PWM_TIMER_ID_1].timPeriod + 1) * dutyCyclePercent) / 100) + 1;
outputConfiguration.OCPolarity = TIM_OCPOLARITY_HIGH;
outputConfiguration.OCFastMode = TIM_OCFAST_DISABLE;

HAL_TIM_PWM_ConfigChannel( PWM_TimerHandler[timerId].handler, &outputConfiguration, PWM_ChannelHandler[channelId] );


return StatusCode_OK;


3) I realise the fade effects with this function:

StatusCode_e LED_FADE_FadeIn( LED_FADE_Id_e ledFadeId, uint16_t fadeMs )

uint8_t dutyCycleCnt;


for( dutyCycleCnt = 1; dutyCycleCnt <= 100; dutyCycleCnt++ )
PWM_Off( LED_FADE_Handler[ledFadeId].timerId, LED_FADE_Handler[ledFadeId].channelId );
PWM_Configure( LED_FADE_Handler[ledFadeId].timerId, LED_FADE_Handler[ledFadeId].channelId, dutyCycleCnt );
PWM_On( LED_FADE_Handler[ledFadeId].timerId, LED_FADE_Handler[ledFadeId].channelId );


return StatusCode_OK;



This method works well but I think that is not efficient. In fact every time I want to increase the Duty Cycle, the timer must be stopped, reconfigure the output channel and start the timer.


These action are repeated for 100 times to fade the led.



Is there a best way to change the CCR without stop the timer?


Thanks for the help.