Why is pinMode not required prior to analogRead

I’m not sure if this is the right place to post this, but it’s kinda related to the IDE

I’ve noticed that analogRead doesn’t require that pinMode( x, INPUT) be called prior to use.

Looking at the core code for analogRead it appears that the IDE may be effectively calling pinMode to setup the analog input each time analogRead is called.

This would slow down analogRead

Or an I miss-reading the core source code.

i.e are the “analog” pins always set for Analog input. I know its possible to call digitalRead and also to set them as output using pinMode(A0,OUTPUT) and digitalWrite(A0,HIGH) is also supposed to work.

so either A0 etc is set to Analog mode by default, and setting pinMode(A0,OUTPUT) followed by analogRead would result in it not reading, or analogRead is setting pinMode

I guess i need to test this last hypothesis ??

so either A0 etc is set to Analog mode by default,

A0 is an alias that allows the first analog pin on any Arduino to be used as a digital pin. It is not necessary to use A0 to refer to analog pin 0. Use 0.

Since the analog portion, of the pins that are analog and digital, is input only, there is no need to tell the pin to be an input pin.

If you want to use the digital portion of a pin that is both analog and digital, you need to define whether it is input or output, just like the digital only pins.

The Arduino API, as much as is possible, is intended to be modeless. This makes learning the API much easier for the intended audience (people who have never programmed). Even though sequences like this...

analogWrite( A0, 63 );
digitalWrite( A0, HIGH );
digitalRead( A0 );

...may not make sense, the outcome is exactly what one would expect.

If the Arduino originators had opted for a more traditional modal API this forum would be swamped with people who forgot to ... using your example ... call pinMode before calling analogRead.

And, you are correct. The price of that convenience is performance.

[quote author=Coding Badly link=msg=1977510 date=1417057510]... And, you are correct. The price of that convenience is performance.[/quote] but the duration of pinMode is 1-2 microsecond level where analogRead mostly waits until the conversion is done, on an Uno it takes about 120 micros. In short the pinMode overhead is roughly 1%

I've noticed that analogRead doesn't require that pinMode( x, INPUT) be called prior to use.

The default for all pins is input. After all they can either be input or output. Input is safer.

You can do a digitalRead without using pinMode either.