geekcowboy.net

Arduino and microcontrollers

AVR assembly on an Arduino Uno in 2026: registers, cycle counts and a blink you can time

When assembly is worth it on an ATmega328P and when the compiler already does the job, the registers and the first instructions with their cycle counts, and one sketch that blinks the onboard LED from GCC inline assembly with a delay loop counted to the cycle, then times itself with micros().

You can write a whole Arduino project without seeing a single AVR instruction, and most of the time you should. But the Uno R3’s ATmega328P is small enough to understand completely, and a few lines of assembly show exactly what it does with each of its 16 million cycles a second. This is the tour for someone who already writes C.

Why, and mostly why not

Assembly on an Uno earns its place in three situations:

  • Timing to the cycle. At 16 MHz one cycle is 62.5 ns. When a signal needs its edges at exact cycle positions, as a WS2812 LED’s data line does, the only way to be sure is to pick every instruction yourself and count.
  • Seeing what the compiler did. A disassembly tells you whether that “fast” line really became one instruction, and reading it takes no assembly writing at all.
  • Tiny interrupt handlers. For a normal ISR() the compiler adds code that saves and restores the machine state, SREG included. avr-libc’s ISR_NAKED leaves that out and makes it your job; in avr-libc’s words, “the only safe part to use inside naked functions is inline assembly”.

And why you usually would not:

  • The compiler is good at this. avr-libc’s FAQ points out that PORTB |= (1 << 7) already becomes a single sbi instruction.
  • It ties you to one chip. The Uno R4 has a Renesas RA4M1, an Arm Cortex-M4, and none of this assembles for it. Even among AVRs the cycle counts change: on the newer cores the instruction manual calls AVRxm and AVRxt, sbi and cbi take one cycle instead of two.
  • The compiler can’t check it. As the avr-libc cookbook puts it, “the C compiler doesn’t check any line of your assembler code”. Wrong constraints can silently produce wrong code.

The advice: write C, read the disassembly, and keep assembly for the dozen instructions where the cycles matter.

Inside the ATmega328P

Your code touches three kinds of storage:

  • 32 general-purpose registers, r0 to r31, 8 bits each. Instructions that take an 8-bit constant (ldi, andi, ori, cpi) only work on r16 to r31. The top six pair up as the 16-bit pointers X (r27:r26), Y (r29:r28) and Z (r31:r30). avr-gcc uses r0 as scratch and expects r1 to hold zero, so if you change r1, clear it again.
  • The I/O space: 64 peripheral registers at I/O addresses 0x00 to 0x3F. in and out reach all 64; sbi, cbi, sbis and sbic only the first 32. The rest sit in extended I/O (0x60 to 0xFF), reachable only with load and store instructions such as lds and sts.
  • SREG, the status register, at I/O address 0x3F: I (global interrupt enable), T, H, S, V, N, Z and C. Arithmetic sets the flags, branches read them, and the chip does not save SREG when an interrupt starts: that is the handler’s job.

Every I/O register has two addresses, because the registers and the I/O space also appear at the start of data memory. The datasheet writes PORTB as “0x05 (0x25)”: C uses the data address in brackets, in, out, sbi and cbi the I/O address, and _SFR_IO_ADDR() converts one into the other.

The Uno’s onboard LED is on pin 13, which the Arduino core maps to port B, bit 5 (PB5). Three registers control it; SREG is listed too:

Register I/O address Data address Bit 5
PINB 0x03 0x23 reads pin 13; writing a 1 toggles PORTB bit 5
DDRB 0x04 0x24 1 makes pin 13 an output
PORTB 0x05 0x25 1 drives pin 13 high: LED on
SREG 0x3F 0x5F (bit 7 is I, the global interrupt enable)

The first instructions, and what they cost

The cycle counts below are from Microchip’s AVR Instruction Set Manual (DS40002198C). The manual lists the ATmega328P as an “AVRe+” core, which uses the AVRe column.

Instruction What it does Cycles
ldi Rd, K load a constant 0-255 into r16-r31 1
out A, Rr write a register to I/O address 0-63 1
in Rd, A read I/O address 0-63 into a register 1
sbi A, b set bit b of I/O address 0-31 2
cbi A, b clear bit b of I/O address 0-31 2
sbis A, b skip the next instruction if the bit is set 1; 2 if it skips (3 over a two-word instruction)
rjmp k jump up to 2K words either way 2
rcall k / ret call a subroutine / return 3 / 4
dec Rd subtract 1; sets Z, N, V, S but not C 1
brne k branch if Z is clear (the last result wasn’t zero), within about 64 words 2 if taken, 1 if not

One more cost, from the datasheet: an interrupt takes 4 cycles to respond, 3 for the jmp in the vector table and 4 for the final reti, on top of whatever the handler does.

Inline assembly without surprises

GCC’s form is asm volatile ("code" : outputs : inputs : clobbers);. The parts that bite:

  • volatile. GCC may delete an asm statement whose outputs nobody seems to use; volatile forbids that. An asm with no outputs is volatile anyway, but writing it says what you mean.
  • Constants go in as operands. "sbi PORTB, 5" fails: the preprocessor doesn’t look inside strings, so the assembler sees the word PORTB and stops with “constant value required”. Pass it in: "I" (_SFR_IO_ADDR(PORTB)). "I" means a constant 0 to 63, the I/O range (sbi and cbi also need it below 32, and PORTB’s 0x05 is). "M" is a constant 0 to 255, what ldi takes.
  • Keep those constants int. Declared as const uint8_t, a count above 127 fails with “impossible constraint in ‘asm’”: GCC holds an 8-bit constant sign-extended, so 200 reaches the constraint as -56, outside 0 to 255. The same 200 as an int passes. That is why the sketch’s loop counts are int.
  • Registers. Let the compiler pick ("d" gives one of r16 to r31, as ldi needs), or name them and list them as clobbers so the compiler keeps nothing there across your block. The sketch names r18, r19 and r20.
  • Flags and memory. "cc" says the flags change (dec changes Z, N, V and S). "memory" says the block touches memory, so other memory accesses must not move across it; avr-libc’s own I/O examples use it.
  • Labels. Use numeric local labels such as 1:, jumped to as 1b (back) or 1f (forward). They may repeat, and the compiler can copy an asm statement, for example when it inlines a function twice.

The whole blink is one asm block: jump over a delay subroutine (three nested dec/brne loops), LED on with sbi, call the delay, LED off with cbi, call it again. micros() times the block, and the sketch prints that next to what the cycle count predicts.

asm_blink.ino

// asm_blink.ino: blinks the Uno's onboard LED (pin 13, PB5) from AVR inline assembly, with a delay loop counted
// to the cycle, and prints how long each blink took according to micros().
// Arduino Uno R3 only (ATmega328P at 16 MHz; the Uno R4 is an Arm chip). Serial Monitor at 115200 baud.
// geekcowboy.net, 2026. MIT licence.

const int OUTER = 200, MIDDLE = 132, INNER = 100;  // loop counts, 1-255 each (ldi loads 8 bits); int on purpose

// ATmega328P cycles, from Microchip's AVR Instruction Set Manual (DS40002198): ldi, dec, nop 1; brne 2 when it
// jumps back, 1 when it falls through; sbi, cbi, rjmp 2; rcall 3; ret 4.
const uint32_t INNER_LOOP = 3UL * INNER - 1;                          // dec + brne; the last brne falls through
const uint32_t MIDDLE_LOOP = MIDDLE * (1 + INNER_LOOP + 3) - 1;       // ldi, inner loop, dec + brne
const uint32_t OUTER_LOOP = OUTER * (1 + MIDDLE_LOOP + 1 + 3) - 1;    // ldi, middle loop, nop, dec + brne
const uint32_t HALF = 2 + 3 + 1 + OUTER_LOOP + 4;  // sbi (or cbi), rcall, ldi, the loops, ret: LED edge to edge
const uint32_t BLOCK = 2 + 2 * HALF;               // rjmp, then the on half and the off half
static_assert(BLOCK == 16000020UL, "the cycle count worked out in the article");

void setup() {
  Serial.begin(115200);
  // DDRB bit 5 = 1: pin 13 is an output. "I" is a constant 0-63; _SFR_IO_ADDR turns DDRB into I/O address 0x04.
  asm volatile("sbi %[ddr], %[bit]" : : [ddr] "I" (_SFR_IO_ADDR(DDRB)), [bit] "I" (DDB5) : "memory");
}

void loop() {
  uint32_t start = micros();
  asm volatile(
    "    rjmp 9f              \n\t"  // jump over the delay subroutine to label 9
    "8:  ldi  r20, %[outer]   \n\t"  // the delay subroutine starts here
    "1:  ldi  r19, %[middle]  \n\t"
    "2:  ldi  r18, %[inner]   \n\t"
    "3:  dec  r18             \n\t"  // inner loop: 3 cycles a pass, 2 for the last one
    "    brne 3b              \n\t"
    "    dec  r19             \n\t"
    "    brne 2b              \n\t"
    "    nop                  \n\t"  // one spare cycle: makes each outer pass exactly 40,000 cycles
    "    dec  r20             \n\t"
    "    brne 1b              \n\t"
    "    ret                  \n\t"
    "9:  sbi  %[port], %[bit] \n\t"  // LED on: PORTB bit 5 = 1
    "    rcall 8b             \n\t"
    "    cbi  %[port], %[bit] \n\t"  // LED off
    "    rcall 8b             \n\t"
    :                                                                  // no outputs
    : [port] "I" (_SFR_IO_ADDR(PORTB)), [bit] "I" (PORTB5),            // I/O address 0x05, bit 5
      [outer] "M" (OUTER), [middle] "M" (MIDDLE), [inner] "M" (INNER)  // 8-bit constants for ldi
    : "r18", "r19", "r20", "cc", "memory");  // the counters, the flags dec changes, and a port write
  uint32_t took = micros() - start;

  Serial.print(F("asm block: "));
  Serial.print(BLOCK / (F_CPU / 1000000UL));
  Serial.print(F(" us by the cycle count, "));
  Serial.print(took);
  Serial.println(F(" us by micros()"));
  Serial.flush();  // send it all now, so the serial interrupt stays out of the next measurement
}

Upload it and open the Serial Monitor at 115200 baud. Each blink prints asm block: 1000001 us by the cycle count, N us by micros(). The LED stays off a few milliseconds longer than it is on, because the printing happens while it is off, outside the asm block.

The arithmetic

Counting from the inside out, with the cycle counts from the table:

Piece How it adds up Cycles
Inner loop, r18 = 100 99 × (dec 1 + brne 2) + (dec 1 + brne 1) 299
One middle pass ldi 1 + inner loop 299 + dec 1 + brne 2 303
Middle loop, r19 = 132 132 × 303, minus 1 for the last brne 39,995
One outer pass ldi 1 + middle loop 39,995 + nop 1 + dec 1 + brne 2 40,000 (2.5 ms)
Outer loop, r20 = 200 200 × 40,000, minus 1 7,999,999
One half, LED edge to edge sbi or cbi 2 + rcall 3 + ldi 1 + outer loop + ret 4 8,000,009
The whole asm block rjmp 2 + two halves 16,000,020

At 16 MHz that is 500,000.5625 µs per half (half a second plus nine cycles) and 1,000,001.25 µs for the block. An outer pass is 3 × MIDDLE × (INNER + 1) + 4 cycles, so 40,000 needs MIDDLE × (INNER + 1) = 13,332 = 132 × 101; without the nop, no whole numbers fit. The sketch repeats the sum in C, and static_assert stops the build if it doesn’t come to 16,000,020.

What micros() will say

micros() runs from the same clock as the loop: Timer0 ticks once every 64 CPU cycles. So the comparison is cycles against cycles, and the accuracy of the board’s oscillator drops out. What you are checking is the arithmetic, to within the 4 µs steps micros() counts in on a 16 MHz board.

Expect N to come out higher than 1,000,001, and that is the lesson. Timer0 overflows every 64 × 256 = 16,384 cycles (1,024 µs), about 977 times per block, and each time the chip leaves your loop to run the handler that keeps millis() and micros() going. Your instructions take exactly the cycles you counted; the chip just isn’t yours alone. Turn the reading around to get C, the cost of one Timer0 interrupt:

C = 16,384 × (N − 1,000,001) ÷ N cycles

Each extra microsecond in N moves C by only 0.016 cycles, so the micros() calls themselves hardly matter. Serial.flush() keeps the serial transmit interrupt out of the next measurement; typing into the Serial Monitor would bring the receive interrupt in.

Truly cycle-exact means interrupts off, but noInterrupts() around the whole second won’t work: the overflow counter only moves inside that interrupt, and micros() makes up for at most one missed overflow. Timing code that turns interrupts off keeps it short, as the LED libraries below do.

Reading the compiler’s own output

To look at the machine code, keep the build in a folder you choose and disassemble the ELF file with the avr-objdump that comes with the core’s compiler:

arduino-cli compile --fqbn arduino:avr:uno --build-path build asm_blink
gcc_dir=$(arduino-cli compile --fqbn arduino:avr:uno --show-properties asm_blink | sed -n 's/^runtime\.tools\.avr-gcc\.path=//p')
"$gcc_dir/bin/avr-objdump" -d build/asm_blink.ino.elf > asm_blink.lst

Without --build-path, arduino-cli builds in a temporary folder. The ELF is named after the sketch’s main file, asm_blink.ino.elf. --show-properties prints the build properties instead of compiling; runtime.tools.avr-gcc.path is the core’s avr-gcc (7.3.0-atmel3.6.1-arduino7 for arduino:avr 1.8.8), with avr-objdump in its bin folder.

In asm_blink.lst, look for:

  • 0x05, 5: your sbi and cbi on PORTB bit 5, with the loops exactly as you wrote them.
  • <__vector_16>: the Timer0 overflow handler from the core’s wiring.c (vector 17 in the datasheet, which counts reset as 1). Add up its instructions with the manual (push, pop, lds and sts take 2 cycles, most arithmetic 1), add 7 for the response and the vector jmp, and compare with your board’s C. One branch in it runs about once every 42 interrupts, so the average sits slightly above the usual path.

While you are there, compile PORTB |= _BV(5); and find the single sbi that avr-libc’s FAQ promises.

Where assembly still matters in 2026

WS2812 and NeoPixel LEDs on AVR. Adafruit’s NeoPixel library (1.15.5) sends the bits from hand-written inline assembly: on a 16 MHz AVR, 20 cycles per bit, the 1.25 µs an 800 kHz bit needs. It turns interrupts off while sending, and its documentation warns that millis() and micros() lose about 30 µs per RGB pixel. FastLED (3.10.10) does the same with its own cycle-counting delays and interrupts off by default; with FASTLED_ALLOW_INTERRUPTS it blocks them only a few cycles at a time, and every handler must then finish within 5 µs (80 cycles) or the strip may latch halfway.

PIO on the RP2040 and RP2350. Raspberry Pi’s answer is hardware. Each PIO block has four small state machines sharing a 32-instruction program memory; the RP2040 (Pico) has two blocks, the RP2350 (Pico 2) three. Nine instructions (JMP, WAIT, IN, OUT, PUSH, PULL, MOV, IRQ, SET), each exactly one cycle unless it waits, each able to add up to 31 cycles of delay. The RP2350 datasheet’s WS2812 driver is four instructions. Still assembly, but it runs beside the CPU, so your code and its interrupts can’t upset the timing.

The Parallax Propeller 2. From parallax.com, read on 27 November 2026: eight independent 32-bit cores (cogs), each with 512 32-bit registers, 512 KB of shared hub RAM, 64 “smart pins”, programmed in Spin2 and its own assembly language, PASM2. It also comes on a module, the P2 Edge. Parallax stresses its “deterministic operation”: rather than share one core with interrupts, each timing-critical job gets a core of its own.

Sources