PB0PB5ATmega328PPORTB@ 0x25mask mCPU regb70b60b50b40b30b20b10b01b7·b6·b5·b4·b3·b2·b1·b0·1uint8_t m = 1 << 5;2PORTB |= m; // set3PORTB &= ~m; // clear4PORTB ^= m; // flip5bool on = PORTB & m;6PORTB = m; // oops7digitalWrite(13, LOW);PIN 8PIN 1311011m0
Back: the ATmega328P with PORTB (0x25) and the mask, bit for bitBoard: LEDs on pin 8 (bit 0) and pin 13 (bit 5); front: the sketchTokens: bits moving from the mask into PORTB; moving dashes: current flowingPORTB, the ATmega328P's port B register, is one byte at data address 0x25; bit 0 drives pin 8 and bit 5 drives pin 13. With the mask m = 1 << 5 = 0x20, OR sets bit 5, AND with ~m clears it, XOR flips it and AND tests it, and the other seven bits keep their values. A plain write PORTB = m rewrites all eight bits and turns pin 8 off; digitalWrite(13, LOW) does the same AND NOT as line 3.

Registers

  1. Inside the Uno's ATmega328P, PORTB is a register: one byte at data address 0x25. Unlike RAM, each bit is wired to a pin: bit 0 drives pin 8, bit 5 drives pin 13. Now PORTB holds 0x01, so only pin 8's LED glows.

Masks

Pitfalls and the library

What happens

;; step 1/9 · addr
PORTB   I/O 0x05 + 0x20 = data address 0x25
bits    b7 b6 b5 b4 b3 b2 b1 b0
now     0  0  0  0  0  0  0  1   = 0x01
b0      pin 8   (PB0)  LED on
b5      pin 13  (PB5)  LED off

Before line 1 the sketch has already made pins 8 and 13 outputs (DDRB = 0x21, with pinMode) and set pin 8 HIGH. Each LED in the figure stands for an LED and its series resistor; the lesson "Digital output: driving an LED" sizes that resistor. A read-modify-write takes several steps. If an interrupt changed PORTB between the read and the write, its change would be lost. That is why digitalWrite saves the status register SREG, turns interrupts off with cli(), and restores SREG afterwards.