johnwasser:
There are three ways to set the PWM frequency: Fast PWM, 'prescale' and 'TOP'.
Fast PWM just counts in one direction. The other PWM modes count up and down so they run at half the frequency.
There are very few choices of prescale (already mentioned above). You would start by picking the one that gives you the highest frequency below your desired frequency.
'TOP' is the maximum value to which the timer counts. You can increase the PWM frequency by decreasing TOP but that will also decrease the PWM range.
If you want 8-bit PWM you are stuck with:
16 MHz (clock) / 1024 (prescale) / 256 (TOP+1) = 61.03+ Hz Fast PWM
or
16 MHz (clock) / 256 (prescale) / 2 (PWM) / 256 (TOP+1) = 122.07+ Hz PWM
I think the closest you can get to 108.7 is:
16 MHz (clock) / 1024 (prescale) / 144 (TOP+1) = 108.50+ Hz Fast PWM.
In that case your PWM outputs will be limited to the range 0 to 143 instead of 0 to 255.
Thanks you for the detail. I looked up some of the keywords and came to this link:
The following code snip:
pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22);
OCR2A = 180;
OCR2B = 50;
Above that code, the following was posted:
"Fast PWM Mode
The following code fragment sets up fast PWM on pins 3 and 11 (Timer 2). To summarize the register settings, setting the waveform generation mode bits WGM to 011 selects fast PWM. Setting the COM2A bits and COM2B bits to 10 provides non-inverted PWM for outputs A and B. Setting the CS bits to 100 sets the prescaler to divide the clock by 64. (Since the bits are different for the different timers, consult the datasheet for the right values.) The output compare registers are arbitrarily set to 180 and 50 to control the PWM duty cycle of outputs A and B. (Of course, you can modify the registers directly instead of using pinMode, but you do need to set the pins to output.)"
I'm missing some very basic stuff somewhere. When i see "summarize the register settings, setting the waveform generation mode bits WGM to 011 selects fast PWM", I expected to see that somewhere in the code example, but I don't.
Looking back at your post, this section "16 MHz (clock) / 1024 (prescale) / 144 (TOP+1) = 108.50+ Hz Fast PWM.", the math is clear but the "why" isn't. I'm guessing you choose 1024 because it's the largest prescale dividor and we need to divide by a prescale value...only guessing. The 144, i'm not sure where it came from. I looked for 143 and could not find it or that TOP was 143.
I see the bitwise or operator in the example code, but i'm not sure how to convert that if I want to achieve a result. Is there a way to figure out what to put where in that code to achieve 108.5 Hz for example?