The Arduino Mega 2560 has 15 pins which can be used for PWM output. Normally you do this with the analogWrite() command, however, you can access the Atmel registers directly for finer control over the PWM on an Arduino including changing the type, range and frequency of the pulse width modulation PWM.
The following table gives the Arduino pin number and the corresponding register for controlling the duty cycle
Very simply we can use the register to set the duty cycle instead of the analogWrite command. Using the register is slightly faster.
One of the most annoying aspects of the native arduino PWM commands is that the PWM frequency is set to a value which is audible. This is extremely annoying as it produces a nasty noise when operating DC or stepper motors by PWM.
We need to look at the timer counter control registers. These control the type, range and frequency of the PWM generated by the Arduino. Please see section 17.9 in the datasheet. This is demonstrated by the code below. Please note that the control registers 4, sections A & B will effect the PWM on all the OCR4n pins, see table above.
The 4 statements relating to the WGM bits control the mode of operation of the PWM. We have set it to mode 14, which is fast PWM with ICRn used as the maximum for the counter. The CS bits relate to the clock selection, see table 17-6 in the datasheet. We have selected no prescaling, which corresponds to the native 16Mhz frequency of the Arduino clock.
The actual frequency of the PWM is a function of these settings and the final entry, the input capture register. Setting this to 400 results in a PWM frequency on the Arduino Mega pin of 16Mhz / 400 = 47304Hz, or possibly half that! The duty cycle is then changed by setting OCR4A or B to some value between 0 and 400
Further reading of the datasheet will explain all the registers, but hopefully this will point you in the right direction
Please note, not all PWM mode are available on all clocks.