Amplify PWM from ATmega using OpAmp
It's not clear exactly what you're doing, but it seems the problem is that there is still too much PWM ripple left on a filtered PWM signal.

If so, then the answer is simple: Filter it more aggressively.

Before you design any filter, you have to decide how fast you want the result to settle, and how much noise you can tolerate, neither of which you specified.  It is therefore impossible to recommend a specific filter since we don't know what specs it's supposed to meet.

However, here is a example.  You don't say what voltage this PWM is, so I'll assume 3.3 V.  You say the PWM frequency is 4 kHz, so that's what we have to attenuate to oblivion.  Let's say that "oblivion" is 10 &micro;V or less in this context.  So, you have 3.3 V in and want 10 &micro;V out at 4 kHz.  That's attenuation by 330 k.

Let's see how a simple passive RC filter could accomplish this.  A factor of 330 k is way too much for a single pole, so lets look into 3 poles.  The cube root of 330 k is 69.  Therefore placing 3 poles at (4 kHz)/69 = 58 Hz would do it.  Whether you can live with the settling time, only you can say.

A single RC low pass filter with 58 Hz rolloff can be achieved by a 10 k&Omega; resistor in series followed by 274 nF to ground, so 300 nF it is.  So here is a filter that will achieve what we specified:



There will be minimal interaction between the individual filter poles at the frequency of interest of 4 kHz since the capacitors will have much less impedance than the resistors.  Each stage is essentially fed by a low impedance source.

The overall output of this filter may be too high impedance to be useful directly.  If so, you can follow it with a unity gain buffer.

Again, you have to look at the step response and decide whether it's fast enough for your purposes.  If not, you have to use more poles, a higher PWM frequency, or a different filter topology altogether.  The advantage of simple RC filters in series like this is that they have no corner cases you have to worry about, are inherently stable, and quite tolerant of part value variations.