# Update count values on the fly, PWM , STM8S003F3

#### Vindhyachal Takniki

Joined Nov 3, 2014
584
1. I have made a PWM duty cycle generation code for STM8S00F3. I have interface dc motor using L293D. TO control the speed, I am giving PWM via a pin as in code.
2. Is it ok, to change the count value of timer on the fly as in while(1) loop? TIM2_SetCompare1(cnt);
3. I have checked on CRO with L293d attached, PWM works fine.

Code:
void all_tasks_manager(void)
{
/* Time base configuration */
TIM2_TimeBaseInit(TIM2_PRESCALER_1, 999);

/* PWM1 Mode configuration: Channel1 */
TIM2_OC1Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE,CCR1_Val, TIM2_OCPOLARITY_HIGH);

/* PWM1 Mode configuration: Channel2 */
TIM2_OC2Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE,CCR2_Val, TIM2_OCPOLARITY_HIGH);

/* PWM1 Mode configuration: Channel3 */
TIM2_OC3Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE,CCR3_Val, TIM2_OCPOLARITY_HIGH);

/* TIM2 enable counter */
TIM2_Cmd(ENABLE);

while(1)
{
uint16_t cnt;
for(cnt = 998U; cnt > 0U ; cnt--)
{
TIM2_SetCompare1(cnt);
}
}

} /* function ends here */

void TIM2_SetCompare1(uint16_t Compare1)
{
/* Set the Capture Compare1 Register value */
TIM2->CCR1H = (uint8_t)(Compare1 >> 8);
TIM2->CCR1L = (uint8_t)(Compare1);

}

#### dannyf

Joined Sep 13, 2015
2,197
1 you can, but typically with bad results on anything other than count up count down pwm generators.

2 the code you have makes no sense. What's the practical result you look to generate with it?

#### Vindhyachal Takniki

Joined Nov 3, 2014
584
CCR1H & CCR1L, are two register. In code, first high resgister is updated & then lower. Won't it create conflict or error results?

Nothing practical to obtain. Just proing by CRO to see the PWN duty generation.

#### dannyf

Joined Sep 13, 2015
2,197
Generally, multi byte access on an 8 bit machine requires caution and you should check the data sheet for that.

Having said that, those are compare registers and they don't change much.

If the compares are active, transient values due to multi byte access can trigger abnormal behaviors. Thus you want to put the timer in up/down mode.

#### Vindhyachal Takniki

Joined Nov 3, 2014
584
User manual of STM8S control says as in attached image.
I think we can update the CCR register on the fly according to this.
Only problem is it says this about Timer1 & I am using timer2 which is different. In timer2 there is no mention of this.

Is it ok to assume that CCR of Timer2 can also be updated on the fly?