32u4 timer 4 pwm frequency help I have extracted the following code from the multiwii project. It generates a ~490-500hz pwm signal on pin 6 which is used to drive an esc.

I want to change this frequency down to 50Hz to drive a servo instead. But ive had next to no experience at this level of avr programming, and dont want to loose anymore days to it, if its a dead end. (ie not possible) (i have tried reading various websites on the topic)

void setup() { 
    pinMode(6, OUTPUT);
    TCCR4E |= (1&lt;&lt;ENHC4); // enhanced pwm mode
    TCCR4B &amp;= ~(1&lt;&lt;CS41); TCCR4B |= (1&lt;&lt;CS42)|(1&lt;&lt;CS40); // prescaler to 16
    TCCR4D |= (1&lt;&lt;WGM40); TC4H = 0x3; OCR4C = 0xFF; // phase and frequency correct mode &amp; top to 1023 but with enhanced pwm mode we have 2047

    TCCR4C |= (1&lt;&lt;COM4D1)|(1&lt;&lt;PWM4D); // connect pin 6 to timer 4 channel D   


}

void loop() {
    //write out
    int value = 1500;
    TC4H = value&gt;&gt;8; 
    OCR4D = (value&amp;0xFF);
}


here is the new code so far working off the solution provided below:

void setup() {   
    pinMode(6, OUTPUT);
    TCCR4B &amp;= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
    TCCR4B |= _BV(CS43) | _BV(CS41);
    TCCR4D &amp;= ~(_BV(WGM41) | _BV(WGM40));
    TC4H = 624 &gt;&gt; 8; // B10 0x2
    OCR4C = 624 &amp; 0xff;//B1110000 0x70
    TCCR4C |= (1&lt;&lt;COM4D1)|(1&lt;&lt;PWM4D);
}
void loop() {
    //write out
    //30 - 60 gives 1000 to 2000 us, but that only allows 30 increments between ??
    int value = 30;
    TC4H = value &gt;&gt; 8;
    OCR4D = value &amp; 0xff;
}


the wave form i want:
Yeah... sometimes it's easier to scrap what's already there and start fresh.

We need to:


Pick a suitable prescaler to get close to the desired cycle length
Fine-tune the value in TOP in order to get an exact value


Assuming this is a 16MHz Leonardo, and we have Fast 10-bit PWM (PWM4x = 1, WGM4x = 0b00) available:

16MHz / 50Hz / (1 &lt;&lt; 10) = 312.5

Therefore we need a prescaler of 512 (CS4x = 0b1010).

16MHz / 50Hz / 512 = 625

Therefore we need a TOP of 624 (OCR4C = 624).

TCCR4B &amp;= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
TCCR4B |= _BV(CS43) | _BV(CS41);
TCCR4D &amp;= ~(_BV(WGM41) | _BV(WGM40));
TC4H = 624 &gt;&gt; 8;
OCR4C = 624 &amp; 0xff;


And then you set COM4xn and PWM4x to appropriate values for whichever pin(s) you want to output PWM on, and set OCR4x to a value between 0 and 624 (using TC4H appropriately; see the datasheet for details) to control the duty cycle.