I'm looking at embedding the calculation for the timer into my ARM C application, can anyone share a calculation (or maybe the code snippet) to generate the most appropriate pre-scaler and timer period values.
Playing with the below code at the moment and the results are close to the timer calculator however I think the calculator may be a touch more refined.
Code: Select all
int cal_pwm(float freq_hz, int duty) {
uint32_t period_cycles = MCU_CLOCK / freq_hz;
uint16_t PrescalerValue = (uint16_t)(period_cycles / MAX_RELOAD + 1);
uint16_t overflow = (uint16_t)((period_cycles + (PrescalerValue / 2)) / PrescalerValue);
uint16_t CCR2_Val = (uint16_t)(overflow * ((float)duty / 100.));
printf("\r\nPrescaler: %u", PrescalerValue);
printf("\r\nOverflow: %u", overflow);
printf("\r\nCCR2 Value: %u", CCR2_Val);
return 1;
}
As an update, I ran the values between the timer calculator and the above function to work out the values to select for a 0.5Hz pulse
The above function returns Period: 65514 and PSC: 2198 which works out to 2000.94 ms and the timer calculator to exactly 2000ms, so would prefer to see the formula for the timer calculator.
Cheers,
Paul