Skip to content
systemcoding.dev
Embedded

Toggle AVR Pins With the DDRx, PORTx and PINx Registers

Learn the three AVR port registers on an ATmega328P: DDRx sets direction, PORTx drives output or the pull-up, PINx reads and toggles, with avr-gcc examples.

6 min read
Summarize in AI
Flat illustration of a hardware register drawn as bit fields with one field highlighted, with the Arduino, Arm and C logos.

Every digital pin on an ATmega328P is controlled by three bits in three registers, and the same three registers exist for every port on the chip: DDRx, PORTx and PINx, where x is B, C or D. The Arduino functions pinMode, digitalWrite and digitalRead are thin layers over them, and writing the registers directly is faster, smaller and the only way to change several pins in one instruction. This post explains what each register does, including the part that confuses beginners (what writing PORTx means on an input pin), and builds a blink program and a button read that use no Arduino code. It targets the ATmega328P (the chip on the Arduino Uno) with avr-gcc 14.1 and avr-libc 2.2, and the register definitions come from <avr/io.h>.

The three registers

Microchip's ATmega328P datasheet (section "I/O-Ports") describes the registers for each port. Each of the eight bits in a register belongs to the pin of the same number: bit 5 of PORTB is pin PB5.

RegisterNameReadWrite
DDRxData Direction RegisterThe direction1 = output, 0 = input
PORTxPort Data RegisterThe latch valueIf output: the level driven. If input: 1 enables the pull-up
PINxPort Input PinsThe actual pin voltage1 toggles the PORTx bit

The two special behaviours are the ones to remember.

**PORTx has two meanings depending on DDRx.** On an output pin, writing 1 drives the pin high and 0 drives it low. On an input pin, writing 1 connects an internal pull-up resistor (about 20 to 50 kilohms, per the datasheet's electrical characteristics) and 0 leaves the pin floating. The register is the same; the direction bit changes what it means.

**Writing 1 to PINx toggles the pin.** This is a feature of the ATmega48 and later, including the 328P: a write of 1 to a bit in PINx flips the corresponding bit in PORTx, in a single instruction and without a read-modify-write on PORTx. Older AVRs such as the ATmega8 do not have it, and writes to PINx are ignored there.

Arduino Uno's L LED is on PB5 (digital pin 13). Direction first, then a loop:

blink.cc
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
	DDRB |= (1 << DDB5);              /* PB5 as output */

	for (;;) {
		PORTB |= (1 << PORTB5);       /* high: LED on */
		_delay_ms(500);
		PORTB &= ~(1 << PORTB5);      /* low: LED off */
		_delay_ms(500);
	}
}

The expression (1 << DDB5) builds a mask with only bit 5 set. DDB5 is a symbolic constant from <avr/io.h> equal to 5, so the line is DDRB = DDRB | 0b00100000, which sets bit 5 and leaves the other seven bits alone. |= sets bits, &= ~mask clears them, and these two idioms plus ^= for toggling are the whole vocabulary of AVR port code.

Compile and link for the 328P at 16 MHz:

Text
avr-gcc -mmcu=atmega328p -DF_CPU=16000000UL -Os blink.c -o blink.elf
avr-objcopy -O ihex blink.elf blink.hex
avr-size blink.elf
Text
   text	   data	    bss	    dec	    hex	filename
     94	      0	      0	     94	     5e	blink.elf

The program is small enough to fit in under a hundred bytes of flash. The exact count depends on the compiler version and libc.

Toggle with PINx

The single-instruction toggle replaces the two writes and two delays:

c
DDRB |= (1 << DDB5);

for (;;) {
	PINB = (1 << PINB5);              /* flips PORTB bit 5 */
	_delay_ms(500);
}

Note the assignment with =, not |=. Only the bit that is 1 in the written value is toggled; writing zero to the other bits does nothing. Using |= would read PINB (the pin levels), set bit 5 and write all of that back, toggling every pin that currently reads high. That is a classic bug: it toggles pins the code never meant to touch. avr-gcc turns PINB = (1 << PINB5) into one sbi instruction, which completes in two cycles.

Button: input with pull-up

The button read uses DDRx as input, PORTx as the pull-up enable and PINx as the reading. A pushbutton between PD2 (digital pin 2) and ground:

button.cc
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
	DDRB |= (1 << DDB5);                  /* LED output */
	DDRD &= ~(1 << DDD2);                 /* PD2 input (the reset default) */
	PORTD |= (1 << PORTD2);               /* enable the pull-up on PD2 */

	for (;;) {
		if (!(PIND & (1 << PIND2)))       /* button pressed: pin pulled low */
			PORTB |= (1 << PORTB5);
		else
			PORTB &= ~(1 << PORTB5);
	}
}

With the pull-up on, an unpressed button reads 1 (the resistor pulls the pin to VCC) and a pressed button connects the pin to ground and reads 0. So the test is for 0, and the LED follows the button. PIND & (1 << PIND2) masks out all pins except PD2; the result is nonzero when the pin is high. No external resistor is needed.

The DDRD &= ~(1 << DDD2) line is redundant, since all pins reset to input, but writing it states the intent and survives someone changing the startup code.

Setting several pins at once

Because a register write touches all eight bits, you can set or clear groups in one instruction:

c
DDRD = 0xF0;               /* PD7..PD4 outputs, PD3..PD0 inputs */
PORTD = 0x0F;              /* outputs low, pull-ups on the four inputs */
PORTD = (PORTD & 0x0F) | (value << 4);    /* put a 4-bit value on PD7..PD4 */

The last line is a read-modify-write of the whole port. It keeps the input pins' pull-up bits (the low nibble) and replaces the output nibble. If an interrupt service routine also writes PORTD, the pair of read and write is not atomic; wrap it in an ATOMIC_BLOCK from <util/atomic.h>:

c
#include <util/atomic.h>

ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
	PORTD = (PORTD & 0x0F) | (value << 4);
}

ATOMIC_RESTORESTATE disables interrupts for the block and restores the previous state afterwards, even if interrupts were already off.

Reading the pin versus the latch

Reading PORTx returns what the program last wrote, and reading PINx returns the voltage actually on the pin. They differ when the pin is overloaded or something else drives it. After setting PORTB |= (1 << PORTB5) with a short to ground on the pin, PORTB bit 5 reads 1 and PINB bit 5 reads 0. That makes PINx the diagnostic: a pin that does not follow what you wrote is shorted, overloaded or connected to another driver.

A related detail after enabling a pull-up on an input: the pin's synchroniser delays the PINx reading by one to two clock cycles, so an instruction that sets PORTx and immediately reads PINx can still see the old level. The datasheet recommends a nop between them:

c
PORTD |= (1 << PORTD2);
__asm__ __volatile__("nop");
if (PIND & (1 << PIND2)) { /* now reflects the pull-up */ }

The unwritten rule about unused pins

Leave unused pins as inputs with the pull-up on, or as outputs driven low, never floating inputs with no pull-up: a floating CMOS input can oscillate and draw extra current. In a low-power design, this is where the first microamps go missing.

Checking the generated code

Direct register code is only worth it if the compiler turns it into single instructions, and it is easy to confirm. Disassemble the blink program:

Text
avr-objdump -d blink.elf | grep -A6 '<main>:'
Text
00000080 <main>:
  80:	25 9a       	sbi	0x04, 5	; 4
  82:	1d 9a       	sbi	0x03, 5	; 3

sbi 0x04, 5 sets bit 5 of I/O register DDRB (I/O address 0x04) in one 16-bit instruction, and sbi 0x03, 5 does the same for PORTB. The compiler used the single-bit instructions because DDRB and PORTB are in the low I/O range that sbi and cbi can reach (addresses 0x00 to 0x1F), and the operations were constant bit masks. The exact addresses and code depend on the compiler version; the point is that no read-modify-write sequence appears, and that sbi is atomic with respect to interrupts, which a longer sequence is not.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.