Read value on an AnalogWrite channel

Is it possible to read back the value that was written to an analogwrite channel?

For example
Analogwrite(1,127) //Sets PWM of channel 1 to 50%
analogread(1) //reads back PWM setting of channel 1

Just do something like this:

analogWriteValue = 127;
analogWrite(1, analogWriteValue);

Then you have the value you wrote stored in a variable that you can access whenever you want.

i do understand that and that is the way I am currently doing it but the question was if I could read back the value I wrote to the analog channel directly.

A PWM output (which is what analogWrite on the AVRs is) is a digital signal, switching on and off rapidly, with a variable duty-cycle.
As such, it isn't read correctly with a slow analogRead.

I am away from my data sheet at the moment. Isn't the PWM value in a register somewhere? Does this vary between Arduinos?

I am using a mobile device and cannot currently look at the Arduino IDE, but I would think that reviewing the code for the analogWrite(...) function would answer this question.

vaj4088:
I am away from my data sheet at the moment. Isn't the PWM value in a register somewhere? Does this vary between Arduinos?

I am using a mobile device and cannot currently look at the Arduino IDE, but I would think that reviewing the code for the analogWrite(...) function would answer this question.

Yes, you could just read off the OCRxY register for whichever timer that pin was on. If you look carefully at analogWrite() and how it handles the pin number - register correlation, you could even set it up as a simple function taking a pin number and returning what it is set to currently.

Such a function would be redundant though for most good code which is why I guess no one ever bothered to include it. Why would it ever be worth the code space to have such a function when you could simply keep the value in a variable?

I agree.

Why would it ever be worth the code space to have such a function when you could simply keep the value in a variable?

Because in systems such a Blynk, the analogWrite() was performed somewhere deep in a library in response to a widget on a phone. The code in the sketch cant get at it. Yes, one could instead design the Blynk app to change one of their virtual pins, then get that event, store the value and do the analogWrite oneself...

I think it is a fair case for needing to retrieve the value of an analog output pin.

DaleSchultz:
Because in systems such a Blynk, the analogWrite() was performed somewhere deep in a library in response to a widget on a phone.

I never let Blynk directly manipulate my hardware. I always filter it through a virtual pin and my own code. That way, I have precise control over what's happening and when.

+1. This sounds like a design fail from the person who wrote the code.