ATmega328PPINB 0x23765432100x000101010101010101DDRB 0x24765432100x000101010101010101PORTB 0x25765432100x00010101010101010116 MHzLPB5 · pin 13011DDRB |= 1 << 5;2while (1) {3 PORTB |= 1 << 5;4 _delay_ms(500);5 PORTB &= ~(1 << 5);6 _delay_ms(500);7}pin 13 -> port B, bit 5130x200xDF
Back: the board, the chip with port B's three registers as rows of bits, the clock and the L LEDFront: the bare-metal blink card and the Arduino core's pin tablesTokens: bit masks, the pin number and clock ticksAn Arduino Uno-style board: the ATmega328P carries port B's three registers, PINB (0x23), DDRB (0x24) and PORTB (0x25), drawn as rows of eight bits; pin PB5 drives the L LED. digitalWrite(13, HIGH) looks up port B, bit 5 and sets that bit. The card does it by hand: DDRB |= 1 << 5 makes PB5 an output, PORTB |= 1 << 5 lights the LED, _delay_ms(500) waits 8,000,000 cycles, PORTB &= ~(1 << 5) turns it off. Writing 0x20 to PINB toggles the pin in one write.

Behind digitalWrite

  1. digitalWrite(13, HIGH) first looks up pin 13 in tables stored in flash: port B, bit 5. It checks whether a timer drives the pin, pauses interrupts, sets that one bit in a register, then restores the interrupt setting it saved.

Blink by hand

Shortcuts and trade-offs

What happens

;; step 1/10 · library
digitalWrite(13, HIGH)   Arduino core, wiring_digital.c
  timer = table[13]   ->  none on pin 13
  bit   = table[13]   ->  _BV(5) = 0x20
  port  = table[13]   ->  port B
  save SREG, cli()        pause interrupts
  *out |= bit             PORTB |= 0x20
  restore SREG            interrupts back on
all that work, for one bit

The card shows the body of main(). The whole program defines F_CPU as 16000000UL, includes <avr/io.h> and <util/delay.h>, and is built with avr-gcc and avr-libc for the ATmega328P, with no Arduino core. _delay_ms needs optimisation turned on and a constant argument to be exact. Port B has 8 bits, but on the Uno PB6 and PB7 are the XTAL pins of the 16 MHz clock, so only PB0 to PB5 reach the headers, as pins 8 to 13. The figure shows the unused PINB bits as 0; a real input pin with nothing connected can read either value.