I was looking to find out how to set the frequency of a PWM output. I have already found a lot about it but it seems that the PWM frequency can only be set to some specific values such as in the table below:
Setting Divisor Frequency
0x01 1 31372.55
0x02 8 3921.16
0x03 64 490.20 <–DEFAULT
0x04 256 122.55
0x05 1024 30.64
I was wondering if I could just pick a random frequency like 20 or 30 kHz for the PWM output. In fact I would need an output of 50 kHz to 80 kHz so I hope that this is possible for Arduino boards? Is there an upper limit to the output frequency? And how do I do it?
You need to go deeper than the cheatsheet to get near-arbitrary frequencies.
The way you do it is to configure the timer to run in PWM mode (fast or phase correct) where you set the TOP value ( - set this value, and the prescaler, such that you get the right frequency. (ie, F_CPU/(prescaler)/(TOP), divided by 2 if using phase correct mode gives you the right frequency).
Then set the timer output compare register to a value between 0 and TOP to set the duty cycle.
Use timer1 if possible - it's a 16-bit timer, so can you get better resolution, and you can use ICR1 as the TOP, instead of having to use OCRxA to set it, which takes up one of your PWM channels.
You'll need to study the datasheet, but it's all there. Starts on page 94 (with timer0)