Summary of AVRStudio4 and Atmega128: An AVR Assembly Beginner Tutorial Guide
This article describes an AVR Assembly beginner tutorial for ECE students using AVR Studio 4 and the ATmega128. It covers installation, project creation, simulation, debugging techniques, PonyProg2000 for hardware programming, ATmega128 architecture (registers, memory, I/O, interrupts), assembler directives, instruction sets, coding style, and example starter code like an LED blink program.
Parts used in the AVR Assembly Beginner Tutorial:
- PC running Windows
- AVR Studio 4 (software)
- ATmega128 microcontroller (target device)
- AVR Simulator (debug platform in AVR Studio 4)
- ISP dongle (parallel port programmer interface)
- ISP cable (ribbon cable)
- AVR microcontroller board with ISP header (J22)
- PonyProg2000 (software programmer)
- Parallel port LPT1 (PC interface)
- ponyprogV205a.zip / setup.exe (PonyProg installer files)
- m128def.inc (ATmega128 definition include file)
Introduction to AVR Assembly in ECE Education
This paragraph emphasizes a team approach to continue to improve how students learn in Electrical and Computer Engineering (ECE) programs. This goal is to provide greater consistency across the learning experience and process in varying courses. For example, the ECE 375 laboratory, where students learn about computer structure and assembly language programming. These labs are being updated to use Atmel tools and AVR RISC microcontrollers, forming the basis of an AVR Assembly Beginner Tutorial experience. This helps students by giving them a more uniform setup, making it easier to understand complicated topics like computer architecture and assembly code.
Purpose
The primary purpose of this document is to assist the reader in developing a fundamental understanding of writing assembly programs for the ATmega128 microcontroller and using AVR Studio 4 to compile the programs. Use this document as a supplementary resource alongside the lectures in ECE 375: Computer Structure and Assembly Language Programming. This resource supports students by providing extra hands-on experience that reinforces the learning that is happening within the classroom. This assists students in connecting the theoretical ideas discussed within lectures to a real, working programming environment.
AVR Studio 4 Overview
This software assists in the development and testing of AVR microcontroller programs. Its full environment includes writing source code, compiling, and debugging. THE software implements a whole range of programming and hardware tools, including: ICE50, JTAGICE, ICE200, STK500, and AVRISP. Developed by Atmel and offered free of charge, it allows students and developers a supported and direct way to develop and enhance their AVR-based projects. For those not familiar, Atmel made the software, and it is free to use. The program provides an easily accessible and consolidated avenue for students and developers to build and provide advancement of AVR projects.
ATmega128 Overview
The ATmega128 is a low-power 8-bit CMOS microcontroller based on the AVR enhanced RISC architecture. It is intended for embedded systems and delivers a combination of high performance and energy efficiency. It processes instructions in just one clock cycle, achieving a throughput of 1 MIPS per MHz. Its architecture makes it well-suited for applications where power consumption is a critical concern. Due to its simplicity and reliability, the ATmega128 is often part of an AVR Assembly Beginner Tutorial to teach students the basics of embedded systems programming.
Nomenclature
The different formatting styles in the document give a separation to different kinds of content. These conventions help improve clarity by showing the difference between regular text and code, or commands and menu items. This instructional approach can help readers traverse and understand the material better by giving clear definitions for each element.
Disclaimer
This portion acts as a legal disclaimer, properly attributing any trademarks and copyrights associated with the project. This section notes that “TekBots” and “Oregon State University” are trademarks of OSU, “AVR Studio 4′ and “ATmega128” are owned by Atmel, and “Windows” is owned by Microsoft. Noting these rights serves to inform readers and respects the ownership of intellectual property of the respective owners.
AVR Studio 4
| Bit | 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
|---|---|---|---|---|---|---|---|---|
| Label | SP15 | SP14 | SP13 | SP12 | SP11 | SP10 | SP9 | SP8 |
| Register | → → → → → → → → → → → → → → → → SPH |
| Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Label | SP7 | SP6 | SP5 | SP4 | SP3 | SP2 | SP1 | SP0 |
| Register | → → → → → → → → → → → → → → → → SPL |
This paragraph explains how to initialize the Stack Pointer in the ATmega128. Setting the Stack’s starting address ensures PUSH and POP operations do within a safe memory region, precluding corruption or crashes. Including the ATmega128 description train allows the use of meaningful register names like SPH and SPL, perfecting the law’s clarity. This setup is essential for any program that uses the stack for temporary storage or function calls.
| Instruction | Description |
|---|---|
.include "m128def.inc" |
Includes ATmega128 register and constant definitions. |
LDI R16, LOW(RAMEND) |
Load the low byte of the SRAM end address into register R16. |
OUT SPL, R16 |
Set the Stack Pointer Low (SPL) register. |
LDI R16, HIGH(RAMEND) |
Load the high byte of the SRAM end address into register R16. |
OUT SPH, R16 |
Set the Stack Pointer High (SPH) register. |
I/O Ports
This paragraph explains the I/ O Anchorages A to G on the ATmega128, used for communication between the microcontroller and external bias. These anchorages arebi-directional with voluntary internal pull-up resistors, allowing flexible input/output configurations. Each leg follows the Pxn naming format. The three main control registers are DDxn for setting direction, PORTxn for affair or enabling pull-ups, and PINxn for reading inputs. While some anchorages support advanced features, the focus is on their introductory I/ O use, which is essential in bedded systems.
| Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | Register | Access | Initial Value |
|---|---|---|---|---|---|---|---|---|---|---|---|
| PORTA | PORTA7 | PORTA6 | PORTA5 | PORTA4 | PORTA3 | PORTA2 | PORTA1 | PORTA0 | Output | R/W | 0 |
| DDRA | DDA7 | DDA6 | DDA5 | DDA4 | DDA3 | DDA2 | DDA1 | DDA0 | Direction | R/W | — |
| PINA | PINA7 | PINA6 | PINA5 | PINA4 | PINA3 | PINA2 | PINA1 | PINA0 | Input | Read Only | Undefined (N/A) |
-
PORTA: Used to write output values or enable pull-up resistors (if the pin is input).
-
DDRA: Configures direction: 1 = Output, 0 = Input.
-
PINA: Reads the actual logic level at the pin.
This paragraph explains the roles of the DDxn and PORTxn bits in configuring I/O pin behavior on the ATmega128.
-
DDxn (Data Direction Register): Controls whether a pin is input (
0) or output (1). This allows dynamic control of data flow direction. -
PORTxn (Output Mode): When configured as an output (
DDxn = 1), writing1toPORTxnsets the pin high; writing0sets it low, enabling control over external devices. -
PORTxn (Input Mode): When configured as input (
DDxn = 0), writing1enables the internal pull-up resistor to prevent floating states. Writing0disables the pull-up.
This paragraph explains the use of I/ O registers and provides a law illustration for harborage setup. The PINx register reads input countries from external bias, while PORTx sets affair situations. The illustration configures Port B as affair( transferring data) and Port D as input( entering data), icing correct leg geste
from the launch. This prevents crimes and improves law clarity. Including the ATmega128 description train allows for readable, emblematic register names like PORTB and DDRD.
| Instruction | Meaning |
|---|---|
LDI R16, $FF |
Load 0xFF into register R16 (all bits set) |
OUT DDRB, R16 |
Set all pins of Port B as outputs |
LDI R16, $FF |
Set initial value high (0xFF) |
OUT PORTB, R16 |
Set all Port B output pins to high (5V) |
LDI R16, $00 |
Load 0x00 into R16 (all bits cleared) |
OUT DDRD, R16 |
Set all pins of Port D as inputs |
LDI R16, $00 |
No internal pull-up resistors |
OUT PORTD, R16 |
Ensure Port D inputs are in tri-state (Hi-Z) mode |
Additional Special Function Registers
This final paragraph attendants compendiums to the ATmega128 datasheet for detailed information on Special Function Registers( SFRs) not covered then. It highlights that unborn performances may expand to include other registers applicable to ECE 375, supporting deeper literacy. This ensures inventors know where to find accurate specs and reinforces the document’s evolving, educational purpose.
Interrupt Vectors
This paragraph introduces interrupts in the ATmega128 as tackle-touched off functions that allow the microcontroller to respond to events like button presses or data appearance without constant polling. Interrupts ameliorate effectiveness and responsiveness by executing special routines when specific events occur. The Global Interrupt Enable bit( bit 7 of SREG), along with AVR instructions like SEI and CLI, controls whether interrupts are allowed. Each intrusion also requires individual enabling. When touched off, the microcontroller saves the current address to the stack and jumps to a predefined Interrupt Vector, icing smooth and timely running before returning to the main program.
| Vector No. | Address | Source | Interrupt Name |
|---|---|---|---|
| 1 | $0000 | Reset | RESET |
| 2 | $0002 | External INT0 | INT0 |
| 3 | $0004 | External INT1 | INT1 |
| 4 | $0006 | External INT2 | INT2 |
| 5 | $0008 | External INT3 | INT3 |
| 6 | $000A | External INT4 | INT4 |
| 7 | $000C | External INT5 | INT5 |
| 8 | $000E | External INT6 | INT6 |
| 9 | $0010 | External INT7 | INT7 |
| 10 | $0012 | Timer2 Compare Match | TIMER2 COMP |
| 11 | $0014 | Timer2 Overflow | TIMER2 OVF |
| 12 | $0016 | Timer1 Capture Event | TIMER1 CAPT |
| 13 | $0018 | Timer1 Compare Match A | TIMER1 COMPA |
| 14 | $001A | Timer1 Compare Match B | TIMER1 COMPB |
| 15 | $001C | Timer1 Overflow | TIMER1 OVF |
| 16 | $001E | Timer0 Compare Match | TIMER0 COMP |
| 17 | $0020 | Timer0 Overflow | TIMER0 OVF |
| 18 | $0022 | SPI Transfer Complete | SPI, STC |
| 19 | $0024 | USART0 Receive Complete | USART0 RX |
| 20 | $0026 | USART0 Data Register Empty | USART0 UDRE |
| 21 | $0028 | USART0 Transmit Complete | USART0 TX |
| 22 | $002A | ADC Conversion Complete | ADC |
| 23 | $002C | EEPROM Ready | EE READY |
| 24 | $002E | Analog Comparator | ANALOG COMP |
| 25 | $0030 | Timer1 Compare Match C | TIMER1 COMPC |
| 26 | $0032 | Timer3 Capture Event | TIMER3 CAPT |
| 27 | $0034 | Timer3 Compare Match A | TIMER3 COMPA |
| 28 | $0036 | Timer3 Compare Match B | TIMER3 COMPB |
| 29 | $0038 | Timer3 Compare Match C | TIMER3 COMPC |
| 30 | $003A | Timer3 Overflow | TIMER3 OVF |
| 31 | $003C | USART1 Receive Complete | USART1 RX |
| 32 | $003E | USART1 Data Register Empty | USART1 UDRE |
| 33 | $0040 | USART1 Transmit Complete | USART1 TX |
| 34 | $0042 | Two-Wire Interface (I²C) | TWI |
| 35 | $0044 | Store Program Memory Ready | SPM READY |
Memory Specifications
The ATmega128 has three main memory types: Program Memory for code, Data Memory for variables, and EEPROM for non-volatile storage. EEPROM retains data indeed when power is lost, making it useful for saving settings. All memory spaces use a direct addressing scheme, which simplifies access and memory operation for inventors.
Program Memory
The Flash memory in the ATmega128 stores the main program and supports in-system reprogramming, allowing updates without removing the chip. It has 128K bytes organized as 64K x 16 to match the AVR’s 16- or 32-bit instructions. For added security, it’s resolved into a charge section and an operation section, guarding the critical bootloader law from being overwritten. This design supports a secure, flexible, and effective program storehouse and updates.

Constant data, such as lookup tables or fixed messages, stays in the ATmega128’s program (Flash) memory to save SRAM. Since this data doesn’t change, Flash offers a persistent and efficient storage option. The AVR instructions LPM and ELPM load this data into registers during execution, allowing efficient memory usage and reliable access to fixed values.
SRAM Data Memory
The two available SRAM configurations in the ATmega128 are Normal mode and ATmega103 Compatibility mode. These options allow developers to adapt memory behavior for current or legacy applications. You select the mode using fuse bits, which are non-volatile and retain their settings after power loss. Although this context uses only Normal mode, having multiple options adds flexibility for memory management and system design.

The ATmega128 microcontroller features a structured data memory organization that supports various addressing modes for flexible and efficient data handling. The data memory divides into distinct regions: the first 32 locations store the register file, followed by 64 locations for standard I/O memory, then 160 bytes for extended I/O memory, and finally 4096 bytes for internal data SRAM. Some applications may also utilize optional external SRAM for increased storage capacity. The extended I/O space (from address $60 to $FF) is especially important for accessing certain peripheral registers and can only be reached using specific instructions like ST/STS/STD and LD/LDS/LDD.
To access these memory regions, the ATmega128 supports five addressing modes: Direct, Indirect, Indirect with Displacement, Indirect with Pre-decrement, and Indirect with Post-increment. These modes allow developers to use general-purpose registers X, Y, and Z (composed of register pairs R26–R31) as pointers for indirect addressing. This flexibility enhances the ability to manipulate data structures efficiently, whether accessing simple variables or navigating arrays and stacks. The automatic pre-decrement and post-increment features, in particular, make stack operations and loop-based array traversals more streamlined and efficient.
>>data-end=”1456″>EEPROM Data Memory
The ATmega128 microcontroller includes 4KB of EEPROM (Electrically Erasable Programmable Read-Only Memory), a non-volatile memory type that retains data even after removing power. This makes it ideal for operations taking patient storehouse, similar to saving configuration settings, estimation data, or storage preferences that may change during the device’s operation. For illustration, a smart device can store and modernize network credentials without demanding a full reprogram. Although not bandied in depth then, the EEPROM’s addition highlights the ATmega128’s inflexibility and flexibility for field-justifiable bedded systems.
Starter Code
This section presents an AVR program template that offers a ready-to-use foundation for developing operations on the ATmega128 microcontroller. By allowing inventors to copy the template into new systems, it eliminates the need to write boilerplate law from scratch, speeding up the setup process. The template promotes good coding practices and includes essential features such as reserved sections for intrusion vectors and introductory initialization routines. These rudiments help ensure proper supplemental setup and effective intruder handling. Overall, the template provides a structured and dependable starting point that reduces development time and supports clean, justifiable law.
;***************************************************************
;*
;* Project Name: LED Blink
;* Description: Blink LED connected to PB0 with delay
;*
;***************************************************************
;* Author: Your Name
;* Lab: Lab 1
;* Date: 31 July 2025
;***************************************************************
.include "m128def.inc" ; Definition file for ATmega128
;***************************************************************
;* Program Constants
;***************************************************************
.equ const = $00 ; Generic constant
.equ DELAY = 200 ; Delay constant (approximate)
;***************************************************************
;* Program Variable Definitions
;***************************************************************
.def mpr = r16 ; Multipurpose Register
.def loop1 = r17 ; Inner loop counter
.def loop2 = r18 ; Outer loop counter
;***************************************************************
;* Interrupt Vectors
;***************************************************************
.cseg
.org $0000
rjmp RESET ; Reset Handler
reti ; External IRQ0
nop
reti ; External IRQ1
nop
reti ; Timer2 Compare
nop
reti ; Timer2 Overflow
nop
reti ; Timer1 Capture
nop
reti ; Timer1 Compare A
nop
reti ; Timer1 Compare B
nop
reti ; Timer1 Overflow
nop
reti ; Timer0 Overflow
nop
reti ; SPI Transfer Complete
nop
reti ; USART RX Complete
nop
reti ; USART UDR Empty
nop
reti ; USART TX Complete
nop
reti ; ADC Conversion Complete
nop
reti ; EEPROM Ready
nop
reti ; Analog Comparator
nop
reti ; Two-wire Interface
nop
reti ; SPM Ready
nop
;***************************************************************
;* Func: RESET
;* Desc: Reset Handler Routine
;***************************************************************
RESET:
; Initialize Stack Pointer
ldi mpr, LOW(RAMEND)
out SPL, mpr
ldi mpr, HIGH(RAMEND)
out SPH, mpr
rjmp MAIN
;***************************************************************
;* Func: MAIN
;* Desc: Main Entry into program
;***************************************************************
MAIN:
; Set PB0 as output
ldi mpr, (1 << PB0)
out DDRB, mpr
LOOP:
; Toggle PB0
in mpr, PORTB
eor mpr, (1 << PB0)
out PORTB, mpr
; Delay loop
rcall Delay
rjmp LOOP
;***************************************************************
;* Func: Delay
;* Desc: Simple delay routine using nested loops
;***************************************************************
Delay:
ldi loop2, DELAY
Outer:
ldi loop1, 255
Inner:
dec loop1
brne Inner
dec loop2
brne Outer
ret
To apply an intrude tutor in the ATmega128, inventors produce a custom routine analogous to the RESET tutor that responds to specific interrupt events like timekeeper overflows or just changes. Replace the default NOP at the interrupt vector with an RJMP to the new handler. This setup lets the microcontroller efficiently manage real-time, asynchronous events, ensuring responsive behavior in embedded systems.
AVR Assembly Programming
The companion focuses on practical, commonly used AVR instructions and assembler directives, rather than serving as a complete reference. This approach benefits newcomers by emphasizing the most applicable commands and teaching effective usage techniques that lead to faster, smaller, and more resource-efficient programs.
Pre-compiler Directives
AVR pre-compiler directives, marked by a fleck( e.g.,. EQU), companion how law is assembled without generating executable instructions. They help manage memory, define macros, and organize law, perfecting readability and effectiveness. These tools give inventors less control over program structure. The forthcoming sections will cover the generally used directives and give a summary table.
| Directive | Description |
|---|---|
.BYTE |
Reserve byte(s) for a variable |
.CSEG |
Start code segment |
.DB |
Define constant byte(s) |
.DEF |
Define a symbolic name for a register |
.DEVICE |
Specify the target device for assembly |
.DSEG |
Start data segment |
.DW |
Define constant word(s) |
.ENDMACRO |
End a macro definition |
.EQU |
Assign a constant value to a symbol |
.ESEG |
Start EEPROM segment |
.EXIT |
Exit the current file |
.INCLUDE |
Include another source file |
.LIST |
Enable list file generation |
.LISTMAC |
Enable macro expansion in the list file |
.MACRO |
Begin macro definition |
.NOLIST |
Disable list file generation |
.ORG |
Set code or data origin address |
.SET |
Assign a value to a symbol (can be changed) |
CSEG – Code Segment
The A .CSEG directive in AVR assembly marks the start of a code segment and helps organize executable instructions. While developers can separate code into logical blocks, the assembler combines them into one continuous segment. Since the directive takes no parameters, it’s simple to use and supports clear, modular code, especially helpful in larger embedded projects.
| Syntax | .CSEG |
|---|---|
| Purpose | Defines the Code Segment, where program instructions are stored. |
| Example | Below is an example showing how .CSEG and They .DSEG are used together. |
| Line of Code | Explanation |
|---|---|
.DSEG |
Begin Data Segment (SRAM). |
vartab: .BYTE 4 |
Reserve 4 bytes in SRAM for the variable vartab. |
.CSEG |
Switch to Code Segment (Flash memory). |
const: .DW 2 |
Define a constant word 0x0002 in program memory at const. |
mov r1, r0 |
Move the contents of the register r0 into register r1. |
DB – Define constant byte(s)
In the AVR Assembly Beginner Tutorial, the .DB (Define Byte) A directive is introduced as a tool to reserve memory for byte-sized data, either in program memory or EEPROM. This directive is especially useful for storing constants, character strings, or arrays directly within the program code. Developers typically label .DB lines to symbolically reference the stored values, making the code easier to read and manage.
The The .DB directive accepts one or more expressions, with each representing a value between -128 and 255. When used in a code segment, the assembler efficiently packs these byte values, placing two bytes into each program memory word. If there’s an odd number of expressions, the final byte still uses a full word to maintain alignment. This efficient storage method, explained in the AVR Assembly Beginner Tutorial, helps conserve memory and improve data access in embedded applications.
| Field | Details |
|---|---|
| Directive | .DB (Define Byte) |
| Category | AVR Assembly Beginner Tutorial |
| Purpose | Store byte-sized constants in program memory or EEPROM |
| Syntax | LABEL: .DB expressionlist |
| Expression | Values must be between -128 and 255 |
| Label Usage | A label is used to symbolically reference the stored data |
| Packing Rule | Two bytes are packed per program memory word; the odd last byte takes the full word |
| Use Case | Useful for storing arrays, strings, and constants |
| Example | “`asm |
| .CSEG | |
| consts: .DB 0, 255, 0b01010101, -128, $AA | |
| text: .DB “Hello World” | |
| “` |
DEF – Set a symbolic name on a register
The. DEF directive in AVR assembly lets inventors assign emblematic names to registers( e.g., naming R16 as loop_counter). This improves law readability and makes programs easier to understand and maintain. Developers can assign multiple symbolic names to a register and reassign those symbols later, allowing flexibility in complex or modular code. This makes. DEF is essential for writing clear, tone- tone-establishing assembly programs.
| Field | Value |
|---|---|
| Directive | .DEF |
| Syntax | .DEF Symbol = Register |
| Example 1 | .DEF temp = R16 |
| Example 2 | .DEF ior = R0 |
| Instruction 1 | ldi temp, $F0 – Load 0xF0 into temp |
| Instruction 2 | in ior, $3f – Read SREG into ior |
| Instruction 3 | eor temp, ior – Exclusive OR |
EQU – Set a symbol equal to an expression
The. EQU directive in AVR assembly assigns a constant value to an emblematic marker, perfecting law clarity. Formerly defined, the marker can not be changed or readdressed. This helps inventors avoid hardcoding values and simplifies updates. It also allows the use of markers in expressions for better readability and error reduction.
| Directive | Syntax | Example | Description |
|---|---|---|---|
.EQU |
.EQU label = expression |
.EQU io_offset = $23.EQU porta = io_offset + 2 |
Defines a constant value for a symbolic label. |
clr r2out porta, r2 |
Uses the defined constant in later instructions. |
INCLUDE – Include another file
The INCLUDE directive in AVR assembly lets the assembler insert one file’s contents into another during assembly. It helps modularize law by letting inventors exercise delineations, macros, or routines across multiple lines. When encountered, the assembler reads the specified train until EOF or an. EXIT directive. This improves thickness, reduces duplication, and supports hierarchical association. Include lines that can themselves contain further. INCLUDE directives.
| Directive | Syntax | Description |
|---|---|---|
.INCLUDE |
.INCLUDE "filename" |
Inserts the contents of another file into the assembly file during assembly. |
| Example File | Code |
|---|---|
iodefs.asm |
.EQU sreg = $3F .EQU sphigh = $3E .EQU splow = $3D |
incdemo.asm |
.INCLUDE "iodefs.asm" in r0, sreg ; Read status register |
ORG – Set program origin
A .ORG directive in AVR assembly sets the memory address for the following code or data, controlling the location counter. It’s mainly used to position routines, bootloaders, or interrupt vectors at fixed addresses. Within a Code Segment, it sets the program memory counter, which counts in words (2 bytes each). Labels on the same line as .ORG take on the specified address, allowing symbolic referencing. The counter defaults to zero if not set. This precise memory control is essential for systems with fixed memory layouts or hardware-specific constraints.
| Directive | Syntax | Description |
|---|---|---|
.ORG |
.ORG expression |
Sets the memory address (location counter) where the next code or data appears. |
| Example Code | Explanation |
|---|---|
.CSEG |
Start code segment (Program Memory) |
rjmp main |
Jump to the label main |
.ORG $0042 |
Set the location counter to the address $0042, often to skip interrupt vectors |
main: |
Label where the main program starts |
mov r0, r1 |
Operate (move content from R1 to R0) |
Expressions
The AVR assembler supports expressions made of operands, operators, and functions for dynamic value and address calculations. The assembler evaluates all expressions as 32-bit values, enabling precise and flexible computations in assembly code.
Operands, Functions, and Operators in AVR Expressions
The AVR assembler builds expressions using operands, functions, and operators to perform complex compile-time calculations and assignments.
Operands include:
-
User-defined labels that act as symbolic references to memory locations and take on the value of the location counter at their point of definition.
-
Constants are defined using the EQU directive, offering fixed symbolic values for clarity and reuse.
-
Integer constants in Decimal, Hexadecimal, or Binary format, offering flexibility for value representation.
-
PC, the current value of the Program memory location counter, is useful for relative addressing.
Functions available in the assembler include:
-
LOW(),HIGH(),BYTE2(),BYTE3(), andBYTE4()for extracting individual bytes from a 32-bit expression. -
LWRD()andHWRD()to get the low and high 16-bit words. -
PAGE()to extract bits 16–21, useful in paged memory systems. -
EXP2()for computing 2 raised to a power, andLOG2()for the integer part of a base-2 logarithm.
Drivers supported are analogous to those in C/ C and are used for collect-time computations only — they don’t induce executable AVR instructions. These include computation and logical drivers similar as-, *,/, &,|, etc.
This structure allows for largely flexible and effective configuration of registers, address computations, and emblematic programming in AVR assembly.
Basic Instructions
MAIN:
ldi r16, 4
LOOP:
rcall WAIT ; Delay loop
dec r16
brne LOOP
rcall WAIT ; Reuse subroutine again
DONE:
rjmp DONE
MUL Function – Multiply Two 8-Bit Numbers
This function multiplies two 8-bit numbers (in mplr and mplc) using repeated addition. The result is stored in two registers (resh, resl) as a 16-bit value.
.def mplr = r18 ; Multiplier
.def mplc = r19 ; Multiplicand
.def resh = r1 ; High byte result
.def resl = r2 ; Low byte result
.def zero = r0
MUL:
push resh
push resl
push zero
clr zero
clr resh
clr resl
cpi mplr, 0
breq EXIT
ADD:
add resl, mplc
adc resh, zero
dec mplr
brne ADD
EXIT:
mov mplr, resh ; Store result back
mov mplc, resl
pop zero
pop resl
pop resh
ret
Calling the MUL Function:
This example calls the function twice with different inputs and stores the results.
.def mplr = r18
.def mplc = r19
INIT:
ldi r16, high(RAMEND)
out SPH, r16
ldi r16, low(RAMEND)
out SPL, r16
MAIN:
ldi mplr, 25 ; First input
ldi mplc, 93 ; Second input
rcall MUL ; Call function
st X+, mplr ; Store high byte
st X, mplc ; Store low byte
mov mplr, r5 ; Second input set
mov mplc, r8
rcall MUL
mov r0, mplr ; Result into r0:r1
mov r1, mplc
DONE:
rjmp DONE
Let me know if you want:
-
These examples are in commented PDF form
-
A flowchart for a subroutine/function structure
-
Quiz or practice exercises for each concept
Read more: AVRStudio4 and Atmega128: An AVR Assembly Beginner Tutorial Guide
- How do I install AVR Studio 4?
Download astudio4.zip, unzip to a folder, run setup.exe, follow onscreen instructions, and click Finish. - How do I create a new project for ATmega128 in AVR Studio 4?
Start AVR Studio 4, choose New Project, select Atmel AVR Assembler, name the project, set location, uncheck create initial file if needed, then add existing source files. - Can I simulate ATmega128 code without hardware?
Yes; select AVR Simulator as the Debug Platform and choose ATmega128 as the device to compile and run simulations within AVR Studio 4. - How do I start line-by-line debugging?
Start debugging (F5) or pause a running simulation, or set a breakpoint to enter line-by-line mode, then use Step Into (F11), Step Over (F10), or Step Out (Shift+F11). - How do I upload a compiled program to the ATmega128?
Compile in AVR Studio 4 to generate a .hex file, open it in PonyProg2000, then use Write All (Ctrl+W) to upload to the chip. - What hardware connections are required for PonyProg2000 programming?
Connect the ISP dongle to the PC parallel port (LPT1), connect the ISP cable from dongle to the AVR board ISP header (J22), then power the microcontroller board. - How do I set up PonyProg2000 for ATmega128?
Launch PonyProg2000, disable sound if desired, select AVR micro and ATmega128 in device menus, run Setup→Estimation and interface setup, then Probe to test connection. - What registers serve as X, Y, and Z pointers on ATmega128?
X is R27:R26, Y is R29:R28, and Z is R31:R30 for 16-bit pointer addressing. - How is the Stack Pointer initialized on ATmega128?
Load LOW(RAMEND) into a register and OUT to SPL, then load HIGH(RAMEND) and OUT to SPH as shown in the RESET routine. - What file provides ATmega128 register definitions?
The m128def.inc include file supplies register and constant definitions for the ATmega128.







