5 years, 8 months ago.

Can I initialise an analogue pin inside a function?

I need to read a value off an analogue pin only once - at the very beginning. I got a Initialisation() function to do this. Can I do as is written below, as long as I don't need to read the analogue in anywhere else?

initialisation

void Initialisation() {
AnalogIn pinIn(p15);

//read pin value here
}

1 Answer

5 years, 8 months ago.

Hello W K,

Yes you can do it (in main() or any other function). Scoping rules tells you where a variable is valid, where it is created, and where it gets destroyed (i.e., goes out of scope). The scope of a variable extends from the point where it is defined to the first closing brace that matches the closest opening brace before the variable was defined. Remember that since the desctructor defined for AnalogIn in the mbed library doesn't do anything hence the configuration of underlying hardware associated with the pin passed to the constructor remains unchanged even when the AnalogIn goes out of scope. In addition if you make it static like

void Initialisation() {
static AnalogIn pinIn(p15);
 
//read pin value here
}

then it's going to be initialized only once when the Initialisation() function is called for the first time. Basically its' going to global but hidden (unreachable) outside the Initialisation() function.

Accepted Answer