I need to produce 0-500 kHz square wave on my STM32F103. How can we simply do this?
The integer dividers make this a little less than ideal but basically you need to factor
FreqOut = TIMCLK / (P * Q); // TIMCLK is nominally 72 MHz for either APB on F1
Prescaler = Q-1; // And 0-65535, 16-bit
Period = P-1; // Again 0-65535 all F1 timers 16-bit
Pulse = P / 2; // 50/50 Duty
Simple? Maths a teenager old should be able to do.
you could use a timer for 50% duty cycle,
any other duty cycle you would definitely want to use the PWM function.( which is the same but slightly different)
you would run the timer at the highest possible rate to give you the most steps upto 500KHz
set the Output Compare to toggle pin on overflow
no interrupts are needed,
this is a classic function of the timers.
The Period div 2 does however allow for odd periods where you are one cycle shy of 50/50, slewed in favour of a shorter mark vs space
I thought that when you use the timer overflow function with toggle, it would be inherently exactly 50/50 duty cycle...
Well yes, toggle would infer 50/50, and you'd run at twice the rate.
Problem is that a period of 11 cycles isn't going to toggle at 5.5, but would work with a 5 and 6 for mark/space, for example.
The integers tend to limit the available choices, you're likely to need to make some compromises and pick the best fit for the desired frequency, and this may include one that is marginally off the 50/50 duty.
Thank you for the all reply, I will try this.
Retrieving data ...