Calculating adequate PWM Resolution can be a hit or miss process. We know RTM_TimerCalc generates code for a Timer's specific Frequency or Interval. But what if we need code to realize a specific PWM resolution? How do we get that answer?
Well, you could iterate through different frequencies and check the resulting divider-N for a desired PWM Resolution. But there's a much easier method.
Choose PWM resolution the fast way
For starters, N-Divide is the key value to know. As an Arduino Timer's N-Divide goes up, so does PWM Resolution. Your Duty-Cycle step-size equals 1-part in the N-Divide number. So if N-Divide equals 5000, you can make Duty-Cycle changes as small as 1/5000th. If N-Divide is only 10, your changes are huge -- 10% steps.
To avoid empirically iterating (guess-and-test) frequencies to realize a suitable PWM Resolution, try the following tactic.
I want a PWM Resolution of 1 in 2000 using the standard 16 MHz clock. I enter 2000 Hz for my frequency using a 16-bit Timer in mode 14 (Fast PWM). Here's an image of what that looks like.
TimerCalc indicates ICR1 needs an N-Divide of 8000-1. Here's a shortened version of the resulting code;
// RTM_TimerCalc 1.20, RuntimeMicro.com // Timer-1 Mode_14_16Bit_Fast_TOP_is_ICR TCCR1B = 0x18; // 0001 1000, Disable Timer Clock TCCR1A = 0xA2; // 1010 0010= ICR1 = 8000-1; // <--- N-Divide is your next Frequency to try for PWM resolution of 2000 TCCR1B |= 1; // Prescale=1, Enable Timer Clock
So, I take 8000 and enter -that- as my wanted frequency and click Calculate. RTM_TimerCalc indicates my needed divider is 2000. Bingo! I know at 8000 Hz, I get a PWM Resolution of 1 part in 2000! That equates to about 0.05% step size! Here's what the code looked like with the wanted frequency edited for 8000-Hz;
// RTM_TimerCalc 1.20, RuntimeMicro.com // Timer-1 Mode_14_16Bit_Fast_TOP_is_ICR TCCR1B = 0x18; // 0001 1000, Disable Timer Clock TCCR1A = 0xA2; // 1010 0010 ICR1 = 2000-1; // New N-Divide: Resolution of 1/2000th realized at 8kHz TCCR1B |= 1; // Prescale=1, Enable Timer Clock
I need a PWM Resolution of 5000 using an 8 MHz internal Clock. I enter 5000 Hz and get told ICR1 needs an N-Divide of 1600.
So I enter 1600 Hz for my wanted frequency and click Calculate. RTM_TimerCalc spits out 5000 as the needed divider! That equates to a Duty-Cycle step size of 0.02%. Nice...
WARNING: Keep your eye on the Precale value. It must not change when you substitute your numbers. If it does, you'll get misleading and nonsensical results. What you can do is on the second-step, enter slightly smaller frequencies such that Prescale stays the same for both calculations. Then you'll get useful data.
See this link for more info about PWM Resolution.