3

https://www.arduino.cc/en/Tutorial/AnalogInput

https://www.arduino.cc/en/Tutorial/Knob

For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?

4

The answer is in the source code. Keep in mind that for this answer, I'm assuming you have a standard Arduino Uno. For other Arduino platforms the values are different but the situation is the same.

If you look at the analog pin definitions in hardware/arduino/avr/variants/standard/pins_arduino.h, you'll find these lines:

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
...

Which tells you that if you call analogRead(A0), it is equivalent to calling analogRead(14). So, really, the question is "How can calling analogRead(0) work?"

The answer to that is in hardware/arduino/avr/cores/arduino/wiring_analog.c. If you wade through the defines, you'll see that at the top of analogRead, there is the following code:

if (pin >= 14) pin -= 14; // allow for channel or pin numbers

The result is that passing either 0 or A0 results in 0 being used in the analogRead code.

1

You can use 0 to 5 for analogRead of pins A0 to A5. However if you want to do digitalRead or digitalWrite on those pins then you have to use A0 through to A5 in order to avoid confusing them with the digital pins 0 to 5 (on the other side of the board).

can use A1, A2, etc. to define other analog pins?

Yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.