I'm interested in generating a PWM signal in software on a micro (it is not possible to use hardware PWM in this case). It is simple to use (for example) a loop with a counter that counts to 255 and wraps around, and transitions high-low when the counter hits N and low-high when it wraps around, for an N out of 255 pulse.
However, because this PWM is rather slow, I would like to smooth it out, as follows: if the output is (for example) high for 2 out of 255 counts, I would like the output to be high during the the 0th and 127th count, not the 0th and 1st. If it is 127 out of 255, I would like to transition low-high and high-low every count, instead of staying high for the first 127 and low for the last 128.
In other words, the lows and highs should be as evenly spread out as possible. I realize when the PWM is near either extreme of the range it would still have a large ripple, but this will reduce ripple a lot near the middle of the range. How to do this in an efficient way?
EDIT: It seems like I have rediscovered Pulse Density Modulation. I'm still not sure how to do this in practice, especially in a fast loop.