AVR Assembly to HEX Tutorial for ATmega328

Welcome! This tutorial is designed for students and enthusiasts who want to deeply understand how AVR assembly code is compiled into HEX for the ATmega328 microcontroller. We'll go step by step, explaining little-endian encoding, HEX modification, and checksums. You can compile the code online using AVR Compiler JS.

1. Assembly Source

.org 0
    rjmp init
.org 0x60
init:
    sbi 4,5
    inc r16
    brne init
    inc r17
    brne init
    dec r18
    brne init
    ldi r18,0x10
    sbi 3,5
    rjmp init

2. Full HEX File Generated

:020000020000FC
:100000005FC00000000000000000000000000000D1
:1000100000000000000000000000000000000000E0
:1000200000000000000000000000000000000000D0
:1000300000000000000000000000000000000000C0
:1000400000000000000000000000000000000000B0
:1000500000000000000000000000000000000000A0
:100060000000000000000000000000000000000090
:100070000000000000000000000000000000000080
:100080000000000000000000000000000000000070
:100090000000000000000000000000000000000060
:1000A0000000000000000000000000000000000050
:1000B0000000000000000000000000000000000040
:1000C000259A0395E9F71395D9F72A95C9F720E101
:0400D0001D9AF6CFB0
:00000001FF

3. Example Instruction Encoding

Focus on this instruction:

ldi r18, 0x10
ASM Opcode Format Binary HEX Stored in Flash (Little Endian)
ldi r18,0x10 1110 KKKK dddd KKKK 1110 0001 0010 0000 E1 20 20 E1

4. Where to Find It in HEX

In the Intel HEX file, the instruction appears here:

:1000C000259A0395E9F71395D9F72A95C9F720E101

The bytes 20 E1 correspond to ldi r18,0x10 in little-endian format.

5. Modifying the Value

To change ldi r18,0x10 into ldi r18,0xf0:

ASM Opcode Little Endian HEX Line
ldi r18,0xf0 EF 20 20 EF :1000C000259A0395E9F71395D9F72A95C9F720EFF3

6. Importance of Checksum

Every line in an Intel HEX file ends with a checksum byte, ensuring data integrity. The microcontroller uses it to detect corrupted data. Checksum calculation:

Checksum = (sum of all bytes in the record, excluding ':' and checksum) & 0xFF
Then take 2's complement (invert bits + 1)

Online tools like AVR Compiler JS compute checksums automatically when generating HEX.

7. Why This Matters

Understanding ASM → HEX → little-endian → checksum gives students a strong foundation in embedded systems. It shows how a microcontroller executes instructions and teaches universal principles of data integrity applicable in modern software and hardware.


Prepared as an educational example for ATmega328 programming. Compile this code online with AVR Compiler JS.