
Lesson 1: Digital output
Pin 13 on the UNO R3 is bit 5 of the PORTB register1. This lesson blinks it twice: once with Arduino calls, then again by writing the register yourself.
What you need
- Arduino UNO R3
- USB cable
- Nothing else: the board has an LED on pin 13
Wire it, then check it
The UNO R3 has a built-in LED on pin 135, so this lesson needs no wiring.
Not working on a real board? Start with the wiring checklist.
Arduino version
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);
}Register version
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);
}| 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 |
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 |
Run it in the lab
Switch between the two programs. The register panel shows the same PORTB5 bit turning on and off in both.
Drill
Which register bit is pin 13 on an UNO R3?
Show the answer
PORTB bit 5 (PB5). The UNO’s pin map puts digital pin 13 on PB5. 1
What does
DDRB |= (1 << DDB5);do?Show the answer
It makes pin 13 an output, like
pinMode(13, OUTPUT). A 1 in a pin’s DDxn bit makes that pin an output. 2Why does
PORTB &= ~(1 << PORTB5);leave pins 8 to 12 alone?Show the answer
The AND with an inverted mask clears bit 5 only. Every other bit of the mask is 1, so ANDing keeps those bits as they were.
Sources
- 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 reference: digitalWrite
- Arduino reference: delay
- Arduino UNO R3 technical specifications: Built-in LED Pin: 13
- Arduino: Port Manipulation (retired page, written for the ATmega8/168): DDRx, PORTx and PINx