Analog read question

22 Oct 2010

Hi, I've looked at the AnalogIn class documentation and header file, but it is not clear to me when the analog read is actually done.  In the example code it looks like simply checking the value reads it (i.e. if(temperature > 0.5)...), but what is the read() function for then?

Is the code for the library available or just the header files?

Thanks,

Moses

22 Oct 2010

Moses, can you provide a link to the sample code you're talking about?

When you declare an AnalogIn object, you can use the object itself in an expression without referring to any of the member functions.  In this context that use is equivalent to calling the read() function.

22 Oct 2010

I think he's speaking about this example.

#include "mbed.h"

AnalogIn temperature(p20);

int main() {
    while(1) {
        if(temperature > 0.5) {
            printf("Too hot! (%f)", temperature.read());
        }
    }
}

//////////////
And I'll give it a try. Using temperature by itself is the same as using 
 temperature.read()   So, it seems to me like it's actually reading the analog
value twice. In general bad code. It could read at the 'if' statement and get
an answer of .51 (causing the printf to execute. Then during the printf it reads
again and gets .49, thereby displaying "Too hot! .49"   

23 Oct 2010

That's the sample code I was refering to, and I agree that it is bad code.  That was part of what was confusing me.  Looks like you're right - I see now the "operator float()" in the header file.  I had missed that before.

Thanks!