AnalogRead () and constants

Hello all,

In this example it uses an Int to declare the analog pin.

int analogPin = 3;     // potentiometer wiper (middle terminal) connected to analog pin 3

                       // outside leads to ground and +5V

int val = 0;           // variable to store the value read



void setup()

{

  Serial.begin(9600);          //  setup serial

}



void loop()

{

  val = analogRead(analogPin);    // read the input pin

  Serial.println(val);             // debug value

}

So if I have a couple different variables:

const int digitaInput1 = 1;
const int digitalInput2 = 2;
const int analogInput = 1;

If I use analogInput is an analogRead statment like this:

int i;
i = analogRead(analogInput);

That will read from pin A1 not pin 1, correct?

Yes. analogRead expects analog pin numbers, which number from 0.

digitalRead/Write expect digital pin numbers.

However analog pins can also be used as digital pins, so they have digital pin
numbers too, which are #define’d as A0, A1, A2, … (On the Uno these happen
to be 14, 15, 16…)

analogRead also accepts A0, A1, … as synonyms for the analog pins (look at the
code for analogRead - that’s how I found that out!)

I would recomend always using the digital numbers (ie use A0 instead of 0 to analogRead)
since then each pin has a unique number which means the same thing to pinMode / digitalRead / digitalWrite / analogRead / analogWrite.

How would I define a constant for that pin then? Use a string?

const int digitaInput1 = 1;
const int digitalInput2 = 2;
const char analogInput[2] = "A1";

int i;
i = analogRead(analogInput);
i = analogRead(analogInput);

Unless you have a particular reason for pre-defining it, I would usually just write

val = analogRead(A1) ;

Well I reference it multiple times in the code and having it predefined at the top of the script makes it easy to change which physical pin is AnalogInput.

I changed it to just call it when I need it an now I’m getting a weird error:

Code example, variable name has been replaced with i to shorten it.

int i; 
i = analogRead(A8);

sketch_may06a.ino:658:32: error: ‘A8’ was not declared in this scope

Edit: I think its because I am doing a quick test on the Uno but was using the mega which DID have an A8 pin.

Edit 2: Yep that was it, sorry for my silly mistake!

const char analogInput[2] = "A1";

Wrong

const byte analogInput = A1;

Right