Basics · 8 min read

Arduino Port Manipulation: Fast Pins with DDRx, PORTx and PINx

Arduino port manipulation: drive pins at once and over 20x faster with DDRx, PORTx and PINx. Uno pin-port-bit table, digitalWrite speed test, ESP32 and Pico.

Arduino port manipulation means controlling pins by writing straight to the microcontroller's DDRx, PORTx and PINx registers instead of calling digitalWrite() and digitalRead(). On the Arduino Uno's ATmega328P the pins are grouped into ports of eight, and each port is one byte; when you change one bit of that byte, the matching pin goes HIGH or LOW immediately. That way you can drive a pin with a single machine instruction, or even change six pins on the same port at exactly the same moment.

In this article you'll see what each of the three registers does, which port and bit every Uno pin belongs to, how to switch a single pin on and off with bit masks and how to drive several pins together. You'll measure the difference from digitalWrite yourself with a timing sketch, spin a stepper motor by changing all four coils at once, learn about a hidden trap involving interrupts, and meet the equivalent idea on the ESP32 and Raspberry Pi Pico. If bit operations are new to you, I recommend reading the binary numbers and bit operations article first.

Arduino Uno with the ATmega328P microcontroller
Arduino Uno: the B, C and D ports of its ATmega328P are spread across the digital and analog pins.

What is port manipulation and why is it fast?

When you write digitalWrite(13, HIGH), the Arduino core first looks up in flash tables which port and bit pin 13 belongs to, turns off PWM if the pin is tied to a PWM timer, briefly disables interrupts, changes the bit and re-enables interrupts. That's a safe and portable approach, but when we count the compiled code it takes about 50 clock cycles on the Uno, a little over 3 µs at 16 MHz. When you do the same with PORTB |= (1 << 5), the compiler turns it into a single sbi instruction: 2 clock cycles, or 125 nanoseconds. That's more than 20 times faster.

RegisterJobBit = 1Bit = 0
DDRxDirection (pinMode)OutputInput
PORTx (on an output)Output level (digitalWrite)HIGHLOW
PORTx (on an input)Internal pull-upPull-up on (INPUT_PULLUP)Pull-up off (INPUT)
PINx (read)Actual pin level (digitalRead)Pin HIGHPin LOW
PINx (write)TogglePin flipsNo change

Arduino Uno pin-to-port-and-bit table

Uno pinPort and bitMaskSpecial function
D0PD00x01RX (USB serial)
D1PD10x02TX (USB serial)
D2PD20x04INT0 interrupt
D3PD30x08INT1, PWM (Timer2)
D4PD40x10-
D5PD50x20PWM (Timer0)
D6PD60x40PWM (Timer0)
D7PD70x80-
D8PB00x01-
D9PB10x02PWM (Timer1)
D10PB20x04PWM (Timer1), SPI SS
D11PB30x08PWM (Timer2), SPI MOSI
D12PB40x10SPI MISO
D13PB50x20SPI SCK, onboard LED
A0PC00x01ADC0
A1PC10x02ADC1
A2PC20x04ADC2
A3PC30x08ADC3
A4PC40x10ADC4, I2C SDA
A5PC50x20ADC5, I2C SCL
Watch out for the bits that aren't in the table: on the Uno PB6 and PB7 are wired to the 16 MHz crystal, and PC6 is the RESET pin. When you write a whole byte to PORTB or DDRB, use a mask so you don't disturb those bits. The most common mistake is writing DDRD = 0xFF: D0 (RX) becomes an output, fights the USB-serial chip, and your next upload fails.

Setting, clearing and reading a single pin with bit operations

What do you want to do?Code (D13 = PB5)digitalWrite equivalent
Make the pin an outputDDRB |= (1 << 5);pinMode(13, OUTPUT);
Set HIGHPORTB |= (1 << 5);digitalWrite(13, HIGH);
Set LOWPORTB &= ~(1 << 5);digitalWrite(13, LOW);
TogglePINB = (1 << 5);digitalWrite(13, !digitalRead(13));
Make D2 an input with pull-upDDRD &= ~(1 << 2); PORTD |= (1 << 2);pinMode(2, INPUT_PULLUP);
Read D2bool b = PIND & (1 << 2);digitalRead(2)

The logic is always the same: |= turns on only the bits that are 1 in the mask, &= ~ turns off only the bits that are 1 in the mask, and the other bits stay as they are. The expression (1 << 5) produces 0b00100000, which is bit 5 (counting from zero); avr/io.h also provides ready-made names like PORTB5, DDB5 and PINB5 that make the code easier to read. Toggling a pin by writing 1 to PINx is a handy feature of the ATmega328P and gives you a blink in a single instruction. If you're wondering why pull-up resistors are needed, see the pull-up and pull-down resistors article.

Step by step: a 6-LED binary counter on D8–D13

  1. Connect six LEDs to D8, D9, D10, D11, D12 and D13, each with a 220 Ω resistor in series (you can check the value with the LED resistor calculator).
  2. D8 is the lowest bit (PB0) and D13 the highest (PB5), so line the LEDs up on the breadboard in that order.
  3. Connect one side of a push button to D2 and the other to GND; no external resistor is needed because the internal pull-up will be used.
  4. Upload the code below and watch the LEDs count from 0 to 63 in binary each time you press the button.
C++ (Arduino IDE)
1// Arduino Uno (ATmega328P): D8-D13 ikilik sayaç, D2 buton
2// Arduino Uno (ATmega328P): binary counter on D8-D13, button on D2
3
4uint8_t counter = 0;
5
6void setup() {
7  DDRB |= 0b00111111;        // PB0-PB5 (D8-D13) çıkış / outputs
8  DDRD &= ~(1 << DDD2);      // PD2 (D2) giriş / input
9  PORTD |= (1 << PORTD2);    // D2 dahili pull-up açık / internal pull-up on
10}
11
12void loop() {
13  bool pressed = !(PIND & (1 << PIND2));       // basınca LOW okunur / reads LOW when pressed
14  if (pressed) {
15    counter = (counter + 1) & 0x3F;            // 0-63 arası dolaş / wrap around 0-63
16    PORTB = (PORTB & 0b11000000) | counter;    // 6 LED tek komutta / all 6 LEDs in one write
17    delay(250);                                // basit bekleme / simple delay
18  }
19}

The heart of the code is this line: PORTB = (PORTB & 0b11000000) | counter. First the top two bits of PORTB (the crystal pins PB6 and PB7) are kept and the lower six bits are cleared; then the counter value is dropped into that gap. All six LEDs change in the same clock cycle, so there's none of the "smear" you get when driving them one by one with digitalWrite, which can show up in high-speed footage. In the line that reads the button, bit 2 of PIND is masked; because the pull-up is on, a released button reads 1 and a pressed one reads 0. In real projects I'd suggest doing the timing with millis() instead of delay().

Speed comparison with digitalWrite

To see the speed difference on your own board, the code below switches D13 on and off 10,000 times, first with digitalWrite and then with PORTB, and prints the average time of one on/off pair in nanoseconds. The loop's own cost (incrementing the counter and branching) is included, so the result is a little longer than the bare instruction time.

C++ (Arduino IDE)
1// digitalWrite ile port yazmacını karşılaştır (Uno, D13)
2// Compare digitalWrite with the port register (Uno, D13)
3
4const uint16_t N = 10000;
5
6void setup() {
7  Serial.begin(115200);
8  pinMode(13, OUTPUT);
9
10  unsigned long t0 = micros();
11  for (uint16_t i = 0; i < N; i++) {
12    digitalWrite(13, HIGH);
13    digitalWrite(13, LOW);
14  }
15  unsigned long t1 = micros();
16  for (uint16_t i = 0; i < N; i++) {
17    PORTB |= (1 << PORTB5);             // D13 HIGH (tek sbi komutu / single sbi instruction)
18    PORTB &= ~(1 << PORTB5);            // D13 LOW  (tek cbi komutu / single cbi instruction)
19  }
20  unsigned long t2 = micros();
21
22  Serial.print(F("digitalWrite cifti / pair: "));
23  Serial.print((t1 - t0) * 1000.0 / N);
24  Serial.println(F(" ns"));
25  Serial.print(F("PORTB cifti / pair:        "));
26  Serial.print((t2 - t1) * 1000.0 / N);
27  Serial.println(F(" ns"));
28}
29
30void loop() {
31}
OperationClock cyclesTime (16 MHz)
digitalWrite(13, ...) single call~50~3.2 µs
PORTB |= (1 << 5) (sbi)2125 ns
PORTB = value (8 bits at once, out)162.5 ns
One digitalWrite pair in the sketch (with loop)108~6.8 µs
One PORTB pair in the sketch (with loop)8~0.5 µs

The cycle counts in the table come from counting the machine code compiled with AVR core 1.8.6; in the Serial Monitor you should see values very close to these, a few percent higher because of the Timer0 interrupt. With a different core version or a PWM pin (e.g. D9), digitalWrite takes a few cycles longer. In the timing sketch the gap is about 13 times, because the loop adds the same overhead to both; for a single pin change the gap goes up to 25 times. That speed matters when you bit-bang a serial protocol in software, clock bits into chips like the 74HC595 or produce pulses with microsecond precision; for blinking an LED once a second it makes no difference at all.

Changing pins at the same time: a stepper motor example

Just as important as speed is simultaneity. When you drive a 28BYJ-48 stepper with a ULN2003 board, the state of all four coils changes together at every step. If you change the coils one by one with digitalWrite, an in-between pattern exists for a brief moment; writing the lower four bits of PORTB in a single instruction removes that intermediate state from the half-step sequence. In the code below IN1–IN4 go to D8–D11 (PB0–PB3) in order, and PB4–PB5 are protected by the mask. For details on the motor, see the 28BYJ-48 stepper motor article.

C++ (Arduino IDE)
1// 28BYJ-48 + ULN2003: IN1-IN4 -> D8-D11 (PB0-PB3), yarım adım / half-step
2const uint8_t HALF_STEP[8] = {
3  0b0001, 0b0011, 0b0010, 0b0110,
4  0b0100, 0b1100, 0b1000, 0b1001
5};
6
7void setup() {
8  DDRB |= 0x0F;                         // PB0-PB3 çıkış, PB4-PB5 dokunulmaz / outputs, PB4-PB5 untouched
9}
10
11void stepMotor(int steps, unsigned int us) {
12  static uint8_t idx = 0;
13  for (int s = 0; s < abs(steps); s++) {
14    idx = (steps > 0) ? (idx + 1) & 7 : (idx + 7) & 7;    // ileri ya da geri / forward or back
15    uint8_t sreg = SREG;
16    cli();                                               // oku-değiştir-yaz koruması / protect read-modify-write
17    PORTB = (PORTB & 0xF0) | HALF_STEP[idx];             // 4 bobin aynı anda / all 4 coils at once
18    SREG = sreg;
19    delayMicroseconds(us);
20  }
21}
22
23void loop() {
24  stepMotor(4096, 1200);                // yaklaşık bir tur ileri / about one turn forward
25  PORTB &= 0xF0;                        // bobinleri boşalt / de-energise coils
26  delay(500);
27  stepMotor(-4096, 1200);               // bir tur geri / one turn back
28  PORTB &= 0xF0;
29  delay(500);
30}

Atomicity and interrupts: the read-modify-write trap

PORTB |= (1 << 5), written with a single-bit constant mask, is one sbi instruction and no interrupt can get in the middle of it. But when the mask has more than one bit, or when you write something like PORTB = (PORTB & 0xF0) | x, the compiler produces three steps: read the register, modify it, write it back. If an interrupt arrives between the read and the write and changes another pin on the same port, the old value you write back wipes out that change. The bug looks rare and random, which makes it hard to find. The fix is to protect these lines by disabling interrupts for a moment; saving SREG and calling cli() in the stepper code does exactly that. digitalWrite already does this protection internally. You can read how interrupts work in the Arduino interrupt article.

For a more readable version of the same protection, include util/atomic.h and wrap the code in ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ... }. When the block ends, the interrupt state is restored automatically. Keep the block short, and don't put delay() or Serial output inside it.

Other boards: Nano, Mega, Leonardo and Uno R4

BoardChipWhere is D13?Note
Uno R3, Nano, Pro MiniATmega328PPB5Same mapping; A6 and A7 on the Nano are analog-only with no port bit
Mega 2560ATmega2560PB7Completely different mapping; e.g. D2 = PE4
Leonardo, MicroATmega32U4PC7Different mapping; USB is built into the chip
Uno R4 Minima / WiFiRenesas RA4M1-No AVR registers; code using PORTB won't compile

Port manipulation on the ESP32: GPIO.out_w1ts and REG_WRITE

Instead of ports, the ESP32 has 32-bit GPIO registers, with one important difference from AVR: separate set and clear registers. Every 1 bit you write to GPIO_OUT_W1TS_REG (write 1 to set) drives that pin HIGH, every 1 bit you write to GPIO_OUT_W1TC_REG (write 1 to clear) drives it LOW, and 0 bits don't touch any pin. So no read-modify-write is needed, and it's safe across both cores and interrupts. The GPIO.out_w1ts = mask form you see in many examples reaches the same register through a struct; however, on some chips and core versions you have to write the field via .val, while REG_WRITE works the same everywhere. These registers cover GPIO 0–31; for GPIO 32 and up you use GPIO_OUT1_W1TS_REG and GPIO_OUT1_W1TC_REG. The easiest way to set a pin's direction and function is to keep using pinMode().

C++ (Arduino IDE)
1// ESP32: 4 LED'i (GPIO 16-19) aynı anda sürmek, GPIO 4'ü okumak
2// ESP32: drive 4 LEDs (GPIO 16-19) at once, read GPIO 4
3#include "soc/gpio_reg.h"
4
5const uint32_t LED_MASK = (1UL << 16) | (1UL << 17) | (1UL << 18) | (1UL << 19);
6const int BUTTON_PIN = 4;
7
8void setup() {
9  Serial.begin(115200);
10  for (int p = 16; p <= 19; p++) pinMode(p, OUTPUT);   // pin işlevi ve yön / pin function and direction
11  pinMode(BUTTON_PIN, INPUT_PULLUP);
12}
13
14void loop() {
15  REG_WRITE(GPIO_OUT_W1TS_REG, LED_MASK);              // 4 pin HIGH, diğerleri değişmez / 4 pins HIGH, others unchanged
16  delay(200);
17  REG_WRITE(GPIO_OUT_W1TC_REG, LED_MASK);              // 4 pin LOW / 4 pins LOW
18  delay(200);
19
20  uint32_t in = REG_READ(GPIO_IN_REG);                 // GPIO 0-31 tek okumada / GPIO 0-31 in one read
21  bool pressed = !(in & (1UL << BUTTON_PIN));
22  if (pressed) Serial.println("Buton basili / Button pressed");
23}

SIO registers on the Raspberry Pi Pico

On the Pico's RP2040 the pins are handled by the SIO (single-cycle I/O) block, which, like the ESP32, has separate registers: GPIO_OUT_SET (0xD0000014) drives pins HIGH, GPIO_OUT_CLR (0xD0000018) drives them LOW, GPIO_OUT_XOR (0xD000001C) toggles them, and GPIO_IN (0xD0000004) returns all 30 pins in one read. In MicroPython you can write to these addresses with machine.mem32. You need to create the pins with Pin(n, Pin.OUT) first, because that call switches the pin to the SIO function and enables the output. Since MicroPython is interpreted, the real gain isn't speed but having four pins change at the same time. These addresses are for the RP2040 (Pico, Pico W); the offsets are different on the Pico 2's RP2350, so check the datasheet for that board.

MicroPython
1# Raspberry Pi Pico (RP2040): SIO yazmaçlarıyla GP10-GP13'ü aynı anda sürmek
2# Raspberry Pi Pico (RP2040): drive GP10-GP13 at once through the SIO registers
3from machine import Pin, mem32
4import time
5
6SIO_BASE = 0xD0000000
7GPIO_IN      = SIO_BASE + 0x004
8GPIO_OUT_SET = SIO_BASE + 0x014
9GPIO_OUT_CLR = SIO_BASE + 0x018
10GPIO_OUT_XOR = SIO_BASE + 0x01C
11
12leds = [Pin(n, Pin.OUT) for n in (10, 11, 12, 13)]   # pinleri SIO işlevine al / put pins in SIO mode
13button = Pin(2, Pin.IN, Pin.PULL_UP)
14MASK = 0b1111 << 10
15
16while True:
17    mem32[GPIO_OUT_SET] = MASK          # 4 pin HIGH / 4 pins HIGH
18    time.sleep_ms(200)
19    mem32[GPIO_OUT_CLR] = MASK          # 4 pin LOW / 4 pins LOW
20    time.sleep_ms(200)
21    if not (mem32[GPIO_IN] >> 2) & 1:   # GP2 GND'ye çekildi mi / is GP2 pulled low?
22        mem32[GPIO_OUT_XOR] = 1 << 10   # GP10'u tersle / toggle GP10
23        time.sleep_ms(300)

When should you use port manipulation?

  • Use it where timing at the microsecond level matters (software serial protocols, ultrasonic triggers, fast pulse generation).
  • Use it when several pins have to change at the same moment (stepper coils, a parallel data bus, a simple DAC with an R-2R resistor ladder).
  • Use it inside interrupt routines to keep the ISR as short as possible.
  • Use it when you're sending lots of bits to chips like the 74HC595 or an LED matrix.
  • Don't use it if your code also has to run on other boards; digitalWrite behaves the same on every board.
  • Don't use it for jobs where speed doesn't matter, such as reading a button, switching a relay or blinking an LED a few times a second; readability is worth more there.

Common mistakes and how to fix them

MistakeWhat happens?Do this instead
Turning on D13 with PORTB = 0x20The other B pins go LOW tooUse PORTB |= 0x20 to set only that bit
DDRD = 0xFFD0/D1 become outputs, Serial and uploads breakUse DDRD |= 0xFC to make only D2–D7 outputs
Treating the pin number as the bit (PORTB |= 1 << 13)There's no bit 13, nothing happensCheck the table: D13 = PB5, so 1 << 5
Reading with PORTDYou get the output register, not the pinUse PIND to read inputs
Multi-bit writes on a port shared with an ISRRare, random pin glitchesProtect with cli()/SREG or ATOMIC_BLOCK
Moving Uno code to a MegaA different pin changes instead of the LEDRewrite it using the Mega's mapping table

LED projects are the best playground for trying port manipulation: the Running LED, Knight Rider LED and Traffic Light projects in the BlueGrays app come with step-by-step circuit diagrams and ready-to-use code. Run the project as it is first, then replace the digitalWrite lines with the PORTB and PORTD forms from this article and see the difference for yourself.

Frequently asked questions

What is Arduino port manipulation?

It's controlling pins by writing to and reading the microcontroller's DDRx, PORTx and PINx registers directly instead of using digitalWrite and digitalRead. Because the eight pins of a port are represented by one byte, several pins can be changed with a single instruction. On the Uno this is more than 20 times faster than digitalWrite.

How slow is digitalWrite?

On the Arduino Uno a single digitalWrite call takes about 50 clock cycles, a little over 3 µs; PWM pins add a few more cycles. PORTB |= (1 << 5), which does the same job, takes 2 cycles, or 125 ns. For most projects the difference doesn't matter; it only becomes decisive when you need microsecond precision.

What's the difference between PORTB, DDRB and PINB?

DDRB sets the direction of the pins on port B (1 output, 0 input). PORTB sets the level of output pins and, on input pins, switches the internal pull-up on or off. PINB is for reading the actual level of the pins; on the ATmega328P, writing 1 to PINB toggles the matching pin.

Does port manipulation work on the Arduino Mega?

Yes, the Mega is AVR-based too and has DDRx, PORTx and PINx registers, but its pin-to-port mapping is completely different from the Uno's. For example, on the Mega D13 is PB7 and D2 is PE4. Before using port code written for the Uno on a Mega, update it according to the mapping table.

Does the ESP32 have PORTB?

No, the ESP32 isn't an AVR and has no registers like PORTB. Instead it has 32-bit GPIO registers: GPIO_OUT_W1TS_REG drives pins HIGH, GPIO_OUT_W1TC_REG drives them LOW and GPIO_IN_REG reads the inputs. Writing REG_WRITE(GPIO_OUT_W1TS_REG, mask) is the most portable way.

Can port manipulation damage an Arduino?

Used with the right mask it does no harm at all; digitalWrite changes the very same registers. The risk is touching the wrong bits: making D0 and D1 outputs blocks uploads, and turning an input into an output that's shorted to another output can damage the pin. Before each write, check in the table which bits you're changing.

See all projects
LED Chaser
AR-5Intermediate

LED Chaser

Lights that switch on one after another, as if they were running. The Arduino lights six LEDs one at a time; each glows for a brief moment and goes out, so the light walks from start to end and then…

4.5(89)
238
Knight Rider LED Effect
AR-6Intermediate

Knight Rider LED Effect

The classic scanner light: a dot of light slides from one end of six LEDs to the other and then comes back.

4.8(107)
236
Traffic Light
AR-3Beginner

Traffic Light

A tiny copy of the traffic light you see on the road every day. Red stays on for two seconds, yellow flashes for a moment, green stays on for two seconds, then it goes back to red through yellow…

4.8(139)
490
LED Control with a Push Button (Push)
AR-9Beginner

LED Control with a Push Button (Push)

Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

4.8(118)
283
LED Blink
AR-1Beginner

LED Blink

The very first hello of electronics: switching a single LED on and off. The Arduino keeps the LED on for one second and off for one second, so you can easily follow every blink.

4.6(203)
1383
Displaying Numbers 0-9 on a 7-Segment Display
AR-41Intermediate
Premium

Displaying Numbers 0-9 on a 7-Segment Display

Write those familiar numbers you see in elevators and digital clocks yourself. On a display made of seven little light bars, the Arduino shows a digit from 0 to 9, one each second, and then starts…

4.5(30)
43
Displaying 0-9999 on a 4-Digit 7-Segment Display
AR-47Intermediate
Premium

Displaying 0-9999 on a 4-Digit 7-Segment Display

On a four-digit number display, numbers race from 0 to 9999 and then start again from zero.

4.4(19)
25
Using a Stepper Motor
AR-67Intermediate
Premium

Using a Stepper Motor

A motor that turns step by step, exactly as far as you want, like the hand of a clock.

4.5(31)
42