pin assignments in code

I’m confused on pin assignments on the Nano.

There’s the pins on the board itself and pins on the chip.
The schematic shows board pin #'s that are the same, because there are two jacks.

There are examples of code that call out a pin by # and others that call it out by name.

myservo.attach(9) - is this pin 9 on the board (D6) or pin 9 on the chip (D5)?
If I call out pin 9, how do I determine if it’s the D6 pin or the A3 pin on the other header?

val=analogRead(A0) - does this indicate that the compiler knows that A0 is attached to the chip pin 23, and the board pin 12,

Would it be better to call out pins by name per the analog command, and let the compiler figure out what the pin# is or should I go by pin #'s on the chip, since there are duplicated pin #'s on the nano board itself?

This helped me.

Yes, it's almost always better to use the predefined constants, for portability between boards, as well as convenience. If you do that, all the mental machinations above will mostly disappear.

All references to the pin number in code are refer to the logical/arduino pin numbers. So 9 means the pin marked D9, physical pin 15 on the DIP version of the ATMega328p, physical pin 13 on the TQFP version.

The digital pin number, or the D# constant can be used interchangibly (they're just #defines - D9 is #defined to be 9, so the preprocessor searches for D9 and replaces them all with 9).

With analog pins, you use either the A# define, or you keep counting up from the last digital pin* (eg, on nano, last digital pin is 13; A0 is 14). For analogRead(), you can also use the number of the channel (eg, analogRead(0), analogRead(A0), and analogRead(14) do the same thing (though the last one will confuse a lot of the people who read it, so it's not good practice).

Physical pin numbers are never used when writing code, and frankly, almost never used when talking about the pins on microcontrollers period. As I noted above, for example, the physical pin numbers between the same chip in different packages are often different.

Sometimes pins are refered to like Pxn (where X is a letter and N is a number from 0~7, ex, arduino pin 9 is PB1) - these refer to the "port" and pin number within that port - this is relevant if doing direct port manipulation, or talking to people who don't use the Arduino IDE.

  • This is how it's done on all the official AVR-based cores (haven't looked at the SAM/ARM boards), and every third party AVR core I've seen, but an idiot could create a core where that convention wasn't followed.