Look below the sketch
You can skip this page. It shows what pinMode and digitalWrite do inside the chip.
The chip keeps small memory slots called registers. Each one holds 8 bits, and a bit is 0 or 1.
In the pin registers, each bit belongs to one pin6. Pin 13 is bit 5 of the register called PORTB1. PORTB sets each pin HIGH or LOW, and DDRB sets which pins are outputs6. A 1 in DDRB bit 5 makes pin 13 an output2.
| PORTB bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Port pin | PB7 | PB6 | PB5 | PB4 | PB3 | PB2 | PB1 | PB0 |
| Arduino pin | none | none | 13 | 12 | 11 | 10 | 9 | 8 |
| Chip pin | 10 | 9 | 19 | 18 | 17 | 16 | 15 | 14 |
| PORTB bit | Port pin | Arduino pin | Chip pin |
|---|---|---|---|
| 7 | PB7 | none | 10 |
| 6 | PB6 | none | 9 |
| 5 | PB5 | 13 | 19 |
| 4 | PB4 | 12 | 18 |
| 3 | PB3 | 11 | 17 |
| 2 | PB2 | 10 | 16 |
| 1 | PB1 | 9 | 15 |
| 0 | PB0 | 8 | 14 |
The same blink, two ways
l1-blink-arduino.ino// Lesson 1, Arduino version.
// Blinks the UNO R3's LED on pin 13: 1 s on, 1 s off.
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}l1-blink-registers.ino// Lesson 1, register version: the same blink, written
// directly to the port registers.
// Pin 13 is PORTB bit 5 (PB5) on the UNO R3.
void setup() {
DDRB |= (1 << DDB5); // pin 13 is an output
}
void loop() {
PORTB |= (1 << PORTB5); // pin 13 HIGH
delay(1000);
PORTB &= ~(1 << PORTB5); // pin 13 LOW
delay(1000);
}|= with (1 << PORTB5) sets bit 5 and leaves the other bits alone. &= ~ with the same mask clears bit 5 only.
Registers in this lesson (ATmega328P data-space addresses)2
| Register | Address | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|---|---|
| DDRB | 0x24 | DDB7 | DDB6 | DDB5 | DDB4 | DDB3 | DDB2 | DDB1 | DDB0 |
| PORTB | 0x25 | PORTB7 | PORTB6 | PORTB5 | PORTB4 | PORTB3 | PORTB2 | PORTB1 | PORTB0 |
| PINB | 0x23 | PINB7 | PINB6 | PINB5 | PINB4 | PINB3 | PINB2 | PINB1 | PINB0 |
Watch the bit
Switch between the two programs. The register panel shows the same PORTB5 bit turning on and off in both.
Sources for this page
- ArduinoCore-avr, variants/standard/pins_arduino.h: LED_BUILTIN is 13; pin 13 is PB5
- Microchip ATmega328P datasheet DS40002061A: Pin configurations (p12); I/O ports; PORTB and DDRB at p100
- Arduino: Port Manipulation (retired page, written for the ATmega8/168): DDRx, PORTx and PINx