How to do PWM with least ripple in software?
The following algorithm will do what you want:

period = 256;
on_time = 34; // Or whatever you want
off_time = period-on_time;
count = 0;
while (1);
{
    if (count &gt;= 0) {
        count -= off_time;
        output_high();
    } else {
        count += on_time;
        output_low();
    }
    wait_for_next_cycle();
}


I did something like this to generate a 44100 Hz sample clock with a non-simple ratio from the master clock, but your question motivated me to generalize it, thanks.