Directly read analog voltage using PWM duty cycle timer registers I'm outputting an analog voltage by setting an 8-bit duty cycle using analogWrite. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the OCR4D register, which matches the value set, e.g.:

pinMode(6, OUTPUT);
analogWrite(6, 123);
Serial.print(OCR4D);   // 123


However, when setting the duty cycle to 0 or 255, OCR4D is not actually set at all; instead analogWrite calls digitalWrite behind the scenes and the pin is digitally set to LOW or HIGH. This is seen in the source for analogWrite:

if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}
else
{
// set PWM duty cycle as normal...


The problem with this is that OCR4D is simply left at its previous value, so it's not always possible to tell the actual output by reading OCR4D alone. In other words there is no way to tell the difference between:
- PWM is active and OCR4D reflects the duty cycle
- PWM is disabled and OCR4D reflects a previous duty cycle (which is not useful)

Which register(s) can I read to crosscheck the PWM is active? 

I'm also aware of the pulseIn function, but would rather read the PWM register directly.
In the end I managed to do this by reading the timer/counter control register relevant to pin 6:

// read the voltage on an analog output pin
int analogReadOutput(int pin) {
    switch(digitalPinToTimer(pin)) {
        case TIMER4D:
            if (TCCR4C &amp; (1 &lt;&lt; COM4D1)) {   // PWM active
                return OCR4D;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        case TIMER4A:
            if (TCCR4A &amp; (1 &lt;&lt; COM4A1)) {   // PWM active
                return OCR4A;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        default:
            return -1;
    }
}


Note that this assumes two things that possibly aren't always true (outside of my simple program):


COM4D1 bit is a reliable way of telling if PWM is enabled,
duty cycle value is 8 bit with a max of 255.