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.
| PIND bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Port pin | PD7 | PD6 | PD5 | PD4 | PD3 | PD2 | PD1 | PD0 |
| Arduino pin | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| PIND bit | Port pin | Arduino pin |
|---|---|---|
| 7 | PD7 | 7 |
| 6 | PD6 | 6 |
| 5 | PD5 | 5 |
| 4 | PD4 | 4 |
| 3 | PD3 | 3 |
| 2 | PD2 | 2 |
| 1 | PD1 | 1 |
| 0 | PD0 | 0 |
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
| Register | Address | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|---|---|
| DDRD | 0x2A | DDD7 | DDD6 | DDD5 | DDD4 | DDD3 | DDD2 | DDD1 | DDD0 |
| PIND | 0x29 | PIND7 | PIND6 | PIND5 | PIND4 | PIND3 | PIND2 | PIND1 | PIND0 |
| PORTB | 0x25 | PORTB7 | PORTB6 | PORTB5 | PORTB4 | PORTB3 | PORTB2 | PORTB1 | PORTB0 |
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
- ArduinoCore-avr, variants/standard/pins_arduino.h: pins 0 to 7 are port D; pin 2 is PD2; pin 13 is PB5
- ArduinoCore-avr, cores/arduino/wiring_digital.c: pinMode and digitalRead
- avr-libc, include/avr/iom328p.h: PIND, DDRD and PORTD, and their bit names