Sunday, 22 November 2026

AVR C vs Assembler, a Real World Example

This from the Patreon archive, part of a project I was working on (and still haven't finished).

I am working on a project for an ATmega microcontroller, which is currently written in C using avr-gcc to compile it.

Building C with AVR_GCC

For reference, this is my three line build script. It allows me to have a clean and simple build environment with just a batch file to build the file, rather that the behemoth of whatever the current flavour of the month Atmel development platform is.:

The first line is the C compiler, this generates a binary output.

avr-gcc -Wall -g -Os -mmcu=atmega1284p -DF_CPU=8000000
 -o Test.bin Test.c Utils.c

The second line generate a hex file, suitable for programming the microcontroller with avrdude

avr-objcopy -j .text -j .data -O ihex Test.bin Test.hex

The final line is optional, and generates a listing file which will show the combined C and AVR assembler source.

avr-objdump -h -S Test.bin > Test.lss

C is great for the general structure of the code, the user interface and anything not speed-critical. I am looking to add some new functionality which requires precise timing.

I thought it would be interesting to see if it was possible to write some suitable C that would be complied down to reasonable assembler.

The Task

The task in hand is to generate a 1MHz clock whilst also incrementing at address bus during the low part of the clock cycle.

The microcontroller is running at 8MHz, that means I have 8 cycles to complete each address.

The AVR is a RISC processor, much like the 6502, with a small number of fast, simple instructions, in contrast to things like the PIC and the Z80, with large numbers of slower but more capable instructions.

In the AVR many of the instructions are single cycle, so I could have up to 8 instructions in the loop.

The pseudo-code would look something like this:

loop:
    set clock low (address bus not valid)
    update address bus
    set clock high (address bus should contain valid data)
    goto loop

The target read and write cycles use the period when the clock is low to change the address bus. The time when the clock is high, the bus should remain unchanged. Once the clock goes low again, it can be modified.

First Attempt

The shortest way to write this in C turned out to be the worst way to write it in assembler.

This is using direct modifications to the ports, which should be faster, right?

It seemed like using PORTC++ to increment the value of the output port would be the fastest option.

Nope.

That turned into three cycles of "read the port into a temporary register, increment that register, write it back out to the port". Then some poor optimisation, reading it straight back in again to check if it was zero.

The clock high and low instructions are using SBI (Set Bit on Io register) and CBI (Clear Bit on Io register), single instructions, which is neat, but these are two cycles, so it will be better if I use the single cycle OUT instruction to write a pre-calculated value.

Second Attempt

OK, it should never need to read from the port, so lets setup two local 8-bit registers to hold the address bus value. I have used "address" for the lower byte and "page" for the upper byte.

This time it is better. As before, it has chosen to implement address++ as "subtract 255 from address" rather than "add 1 to address", both give the same results and take the same time but I guess there are reasons.

I worked that out as 9 cycles, the OUT (OUTput) and SUBI (SUBtract Immediate) instructions are single cycle, RJMP (Relative JuMP) is two cycles and BRNE (BRanch if Not Equal) is two cycles if true, one if false (making that if statement two cycles whichever path is taken).

Testing that out on the real hardware and it is working, but it is indeed 9 cycles, the clock output (top) being 894kHz rather than 1MHz as it should be (middle trace).

Switching the middle trace to address line A0, you can see the it is changing whilst the clock is low, as it should.

It is important to note that the compiler output is not guaranteed to stay the same, I have seen code changes elsewhere in the project affect routines that were unrelated and previously working. Sometimes another routine requires some resource which means the unrelated code now has to do something in a different way.

I wouldn't want to rely on this code remaining that way, so I think I will write this in assembler.

Assembler Version

I was able to get it down to 8 cycles in assembler, by using the ADIW instruction (ADd Immediate to Word). Contrary to what it says in the datasheet (!), this is a two cycle instruction which adds a value to a 16-bit number stored in two adjacent registers, in this case r26 and r27.

That is 8 cycles, as you can see, clocking in at 1.004MHz, but it works out asymmetric unfortunately.

The clock set instructions are single cycle, so I have clock set (one cycle), three available cycles, clock set (one cycle), three more available cycles. 

That gives two three cycle gaps. In those gaps, I have three two-cycle tasks to perform, incrementing the address, updating the IO ports and jumping back to the start of the loop.

I could split the port update, but I think it is better to have it slightly asymmetric rather that splitting the port writes and changing part of the address whilst the clock is high.

Worse Case

I thought I would have a go at a very unlikely to succeed approach, just to see how bad it could be.

Here I will use a 16 bit word to store the address, and to split it into high and low bytes to write it out.

Under the hood, there are lots of ways that could be implemented. In a natively 8-bit system, the 16-bit value would be stored as two bytes, but that is difficult to write in C. 

(this is sort of what C UNIONs were designed for a, a word and an array of two bytes sharing the same space, but that seemed like it would over-complicate things)

One way to so this would be to use something like

port_address_high = (address >> 8);
port_address_low = (address & $00FF);

A clever compiler might spot this and be able to optimise that into direct byte accesses, but it might actually have to implement the shift and mask operations, depending on how it is written. The 16-bit addition could also end up very complicated, depending on implementation.

Well, it turns out it is a clever compiler.

I was going to use this as a demonstration of a worst case, but it is actually pretty decent.

Here it is using two one-cycle operations to increment the address. Both subtract!

As hoped, it has bypassed the shift and mask operations to use the underlying two bytes.

That is actually 8 cycles, pretty good for some code that was intended to be awful.

The Final Version

One interesting thing about that version is the address++ is implemented as two instructions, SUBI (SUBtract Immediate from register) and SBCI (SuBtract with Carry Immediate ).

That is using the carry flag from the first operation to nullify the second operation. Most of the time, carry will be set as $FF is larger than the value in the register. The second instruction is then:

register = register - $FF - 1

which is the same as

register = register - 0

When there is no carry from the first operation, the second becomes

register = register - $FF - 0

or rather

register = register + 1

Neat.

It is also interesting to note that the carry flag is not affected by the OUT instruction.

Can you see where I am going here?

You could put an OUT instruction in between those without affecting their operation.

This is my final version, the SUBI and SBCI have been placed either side of the OUT instruction, creating a balanced four cycles each side symmetric clock waveform.

Let's see how it does, with the host 1MHz clock on the middle trace for reference.

Before, it was asymmetric, with 375ns high and 625ns low.

And now it is symmetric, 500ns high, 500ns low. Perfect.

That will do nicely.


(yes, I am still using that caption from the previous post)

I still have most of the things I make in stock, and can ship worldwide.

The easiest way these days is to contact me using the link at the top of the page. Tell me what you want to order and your address so I can get a quote for shipping and duties etc.

The new Minstrel 3 with keyboard are £150 kit, £190 built (£250 kit with Minstrel ZXpand II, £300 built).

Also a short run of Mini PET 40/80s with keyboard, with a few updates. Order now, and you will get one of the new ones in a couple of weeks. £450 kit / £500 built.

The Mini PET 40/80 internal PET replacement boards are also available now, £350 kit / £375 built.


Patreon

If you enjoy posts like this, you can support me via Patreon, and get access to advance previews of blog posts, and exclusive posts.

You also get progress updates on new projects and other behind the scenes updates, as well as access to my Patreon only Discord server for even more regular updates, and to discuss your own projects.