A Real analogWrite command?

On the way home today, I was thinking that it would be useful sometimes to have an actual analogWrite command- one that can output any voltage from 0 to 5. Eventually I came up with something along the lines of the code below with a digital out and an analog in connected to a cap.

if(analogRead(analogPin)  < voltage) 
// after mapping from 1023 scale to 0-5, of course
{
digitalWrite(digitalPin, HIGH);
}

if(analogRead(analogPin) > voltage)
// after mapping from 1023 scale to 0-5, of course
{
digitalWrite(digitalPin, LOW);
}

So that once the cap got up to, say, 3.1 V, the load would drain it a bit, the chip would see that, and set the charging pin high. Once it got above 3.1, it would see that and turn it off. Assume all appropriate resistors are in place. Has anyone done this or similar, and if not then why not?

You just re-implemented PWM with an output filtering cap.

right, but for a specific voltage. the eventual plan is to pass the voltage as a parameter. I couldn't just use PWM because the cap value is unknown and not all loads are equal.

..you intend to run in a loop which maintains the desired voltage at the cap?

yeah, that was kind of a problem. Maybe something with interrupts could be worked out? I've never used them before, so I'm not sure.

Put an RC filter on a PWM output and you will get a more or less smooth voltage output. How smooth depends on the time constant. You should actually be buffering this output if you plan to drive a load...it's not usually a concern with this scenario because you're not typically driving a load when generating a smooth control voltage. But just in case you are pulling some current, the PWM solution will start to get choppy and resemble PWM more than analog again, but the average will still be correct. Your plan will do the same thing, but when ripple starts to appear, the average will actually droop below the target voltage because you're only charging up to the target voltage and not offsetting the ripple above the target voltage.

Basically you're trying to create a switching regulator, but it's not ideal for trying to create an actual smooth/accurate control voltage.