Hi everyone
Reading several guides and code examples, I've found that people using analog sensors refer to analog pins with the numbers 0 1 2 3 4 5
for example
Using A0 and so on makes it independent of a board (Uno, Mega, ...). So that is the correct approach.
Imagine one board uses pins 0, 1, 2 and 3 (A0 .. A3) for analog inputs and another one uses pins 4, 5, 6 and 7 (the numbers are just fictive numbers).
If one uses the numbers and wants to develop for both boards, one has a problem as one needs to modify the code (every single variable relating to pins) when compiling for another board. The below solves the issue
Change the first line to #define BOARD2 if you compile for BOARD2. This is basically what the IDE does if you select a different board; it changes that first line.
To see what A0 stands for, you can use a line like below in your normal code.
Serial.print("Pin A0: "); Serial.println(A0);
This will print the pin number for A0. It will (hopefully) answer the question 'why it works'.
Morke:
it makes NO difference where I define tempPin as A1, 1 or 15.
I understand using A1 or 15 should be the same
but if I choose to use 1
How does Arduino know i'm referring to Analong 1 or Digital 1?
That is the horror. It doesn't really know, but makes an educated assumption that since you are calling it with an analog function, you must mean it as an analog pin. The code in the analog function explicitly makes this conversion.
In my opinion, the confusion caused by this outweighs the slight convenience of being able to specify either A0 or 0, for example. If I had written it, A0 would be the convention, the 0 designation would be an error. A0,A1, and so on are what is clearly marked on the board. So it makes no sense to call A0, 0.
Hutkikz:
It's coded into the AnalogRead/Write and digitalRead/Write functions.
if analogRead encounters 1 it's coded to recognize that you must mean pin A1.
to use digitalRead on pin A1 you must use A1 or 15 because digitalRead recognizes 1 to mean only pin 1
analogRead() is the only function that does anything special, it maps 0..5 to A0..A5 -
remember you can read the source code to all this machinery, its in every copy of the Arduino you
download there waiting to be read.
Just to avoid any confusion, analogWrite is nothing to do with analog inputs, and except for the DAC
pins on the Due, nothing to do with analog anything.
Just to avoid any confusion, analogWrite is nothing to do with analog inputs, and except for the DAC
pins on the Due, nothing to do with analog anything