cancel
Showing results for 
Search instead for 
Did you mean: 

How to generate PWM and use timer interrupt at the same time?

M7890.1
Associate III

I am using the Bluepill board. I want to generate PWM signal on Timer2 and set up a timer interrupt at 20ms interval on Timer3. I realized that the PWM signal cannot be generated if I set up the timer interrupt on Timer3. How do I solve this problem?

11 REPLIES 11
TDK
Guru

> left_pwm / 1000000

> right_pwm / 1000000

These always evaluate to 0. If you want to use float, cast them to float first instead.

	TIM2->CCR1 = (int) ((((float) left_pwm / 1000000) / 0.02) * 65535);
	TIM2->CCR2 = (int) ((((float) right_pwm / 1000000) / 0.02) * 65535);

If you feel a post has answered your question, please click "Accept as Solution".

The constant 0.02 is of a double type and because of the brackets there will be double operations, including the division, at runtime. One can write 0.02f to use a float type, but in this case the whole expression can be reordered into much more efficient.

TIM2->CCR1 = (float)left_pwm * (float)(65535 / 0.02 / 1000000);

No double operations at runtime, no divisions at all - just a single multiplication at runtime.