Look below the sketch

You can skip this page. It shows what pinMode and digitalRead do inside the chip.

The chip keeps small memory slots called registers. Each one holds 8 bits, and a bit is 0 or 1.

Pin 2 is bit 2 of port D, called PD21.

digitalRead(2) looks at bit 2 of the PIND register. A 1 there means HIGH2.

pinMode(2, INPUT) clears bit 2 of DDRD, and bit 2 of PORTD too2.

PORTD bits 7 to 0, with the port pin and Arduino pin each one belongs to
PIND bit76543210
Port pinPD7PD6PD5PD4PD3PD2PD1PD0
Arduino pin76543210
PORTD bits 7 to 0, with the port pin and Arduino pin each one belongs to
PIND bitPort pinArduino pin
7PD77
6PD66
5PD55
4PD44
3PD33
2PD22
1PD11
0PD00
Arduino pins 0 to 7 are port D, and each pin’s number is its bit1.
Pin 2 is bit 2, called PD2. PIND bit 2 shows what pin 2 reads2.

The same button, two ways

l4-button-arduino.ino
// Lesson 4, Arduino version.
// Lights the UNO R3's LED on pin 13 while the button on pin 2 is held.
void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  if (digitalRead(2) == HIGH) {
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW);
  }
}
l4-button-registers.ino
// Lesson 4, register version: the same button, read
// straight from the PIND register.
// Pin 2 is PORTD bit 2 (PD2); pin 13 is PORTB bit 5 (PB5).
void setup() {
  DDRD &= ~(1 << DDD2);       // pin 2 is an input
  PORTD &= ~(1 << PORTD2);    // with no pull-up
  DDRB |= (1 << DDB5);        // pin 13 is an output
}

void loop() {
  if (PIND & (1 << PIND2)) {  // pin 2 reads HIGH
    PORTB |= (1 << PORTB5);   // pin 13 HIGH
  } else {
    PORTB &= ~(1 << PORTB5);  // pin 13 LOW
  }
}

PIND & (1 << PIND2) keeps bit 2 and clears the others. The answer is not 0 while the button is down.

Registers in this lesson (ATmega328P data-⁠space addresses)13

RegisterAddressBit 7Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
DDRD0x2ADDD7DDD6DDD5DDD4DDD3DDD2DDD1DDD0
PIND0x29PIND7PIND6PIND5PIND4PIND3PIND2PIND1PIND0
PORTB0x25PORTB7PORTB6PORTB5PORTB4PORTB3PORTB2PORTB1PORTB0

Watch the bit

Run either program and hold the button. PIND bit 2 turns to 1, and PORTB bit 5 follows it.

Sources for this page

  1. ArduinoCore-⁠avr, variants/standard/pins_arduino.h: pins 0 to 7 are port D; pin 2 is PD2; pin 13 is PB5
  2. ArduinoCore-⁠avr, cores/arduino/wiring_digital.c: pinMode and digitalRead
  3. avr-⁠libc, include/avr/iom328p.h: PIND, DDRD and PORTD, and their bit names