Abstract
The digitalPinToPort() is a macro that returns the port of a specified pin.
Source Code
The digitalPinToPort() is defined in hardware/arduino/avr/cores/arduino/Arduino.h as below.
|
|
The input is P. The macro calls pgm_read_byte() with an argument digital_pin_to_port_PGM + (P).
The digital_pin_to_port_PGM is defined in hardware/arduino/variants/standard/pins_arduino.h(in case of Arduino Uno). It is an array shown below. As this array is declared as PROGMEM, it is placed on flash memory rather than SRAM.
|
|
As the digital_pin_to_port_PGM is an array, adding (P) to the digital_pin_to_port_PGM means the (P+1)th element of the array. In C++ language, the element of array x[i] can be accessed by *(x + i). For example, if the P is 13, the forteenth element(note that the elements begins with 0) of the array, that is PB, is returned.
The pgm_read_byte() is a macro to read a valiable maked as PROGMEM and is defined in hardware/tools/avr/avr/include/avr/pgmspace.h.
As a result digitalPinToPort() returns the (P+1)th element of digital_pin_to_port_PGM which is placed on the flash memory.
The relation of pin, port and bit is shown below. For example, D0(digital pin number 0) is mapped to the 0th bit of the PORTD. Reading digitalPinToBitMask() would help to understand.
PORTB(PB) | PORTC(PC) | PORTD(PD) | |
D0 | 0 | ||
D1 | 1 | ||
D2 | 2 | ||
D3 | 3 | ||
D4 | 4 | ||
D5 | 5 | ||
D6 | 6 | ||
D7 | 7 | ||
D8 | 0 | ||
D9 | 1 | ||
D10 | 2 | ||
D11 | 3 | ||
D12 | 4 | ||
D13 | 5 | ||
A0 | 0 | ||
A1 | 1 | ||
A2 | 2 | ||
A3 | 3 | ||
A4 | 4 | ||
A5 | 5 |
Version
Arduino AVR Boards 1.8.6
Last Update
March 21, 2023