Atmel AVR Assembler

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

Beginners Introduction to the

Assembly Language of
ATMEL-AVR-Microprocessors
by
Gerhard Schmidt
http://www.avr-asm-tutorial.net
April 2009
History:
Added chapter on code structures in April 2009
Additional corrections and updates as of January 2008
Corrected version as of July 2006
Original version of December 200
Avr!Asm!"utorial # http$%%&&&'avr!asm!tutorial'net
Content
Why learning Assembler?..........................................................................................................................1
Short and easy.......................................................................................................................................1
Fast and quick........................................................................................................................................1
Assembler is easy to learn.....................................................................................................................1
AVRs are ideal for learning assembler..................................................................................................1
Test it!....................................................................................................................................................2
Hardware for AVR-Assembler-Programming...........................................................................................3
The ISP-Interface of the AVR-processor family...................................................................................3
Programmer for the PC-Parallel-Port....................................................................................................3
Experimental boards..............................................................................................................................4
Experimental board with an ATtiny13.............................................................................................4
Experimental board with an AT90S2313/ATmega2313..................................................................5
Ready-to-use commercial programming boards for the AVR-family...................................................7
STK200.............................................................................................................................................7
STK500.............................................................................................................................................7
AVR Dragon.....................................................................................................................................8
Tools for AVR assembly programing........................................................................................................9
From a text file to instruction words in the flash memory....................................................................9
The editor..........................................................................................................................................9
Structuring assembler code.............................................................................................................10
Comments.......................................................................................................................................10
Things to be written on top.............................................................................................................10
Things that should be done at program start...................................................................................11
Structuring of program code...........................................................................................................11
The assembler.................................................................................................................................14
Programming the chips........................................................................................................................15
Simulation in the studio.......................................................................................................................15
What is a register?...............................................................................................................................20
Different registers................................................................................................................................21
Pointer-registers...................................................................................................................................21
Accessing memory locations with pointers....................................................................................21
Reading program flash memory with the Z pointer........................................................................22
Tables in the program flash memory..............................................................................................22
Accessing registers with pointers...................................................................................................22
Recommendation for the use of registers............................................................................................23
Ports.........................................................................................................................................................24
What is a Port?....................................................................................................................................24
Write access to ports.......................................................................................................................24
Read access to ports........................................................................................................................25
Read-Modify-Write access to ports................................................................................................25
Memory mapped port access..........................................................................................................25
Details of relevant ports in the AVR..............................................................................................26
The status register as the most used port.............................................................................................26
Port details...........................................................................................................................................27
SRAM......................................................................................................................................................28
Using SRAM in AVR assembler language.........................................................................................28
What is SRAM?...................................................................................................................................28
For what purposes can I use SRAM?..................................................................................................28
How to use SRAM?.............................................................................................................................28
Direct addressing............................................................................................................................28
Pointer addressing...........................................................................................................................29
Pointer with offset...........................................................................................................................29
Use of SRAM as stack.........................................................................................................................29
Defining SRAM as stack................................................................................................................30
Use of the stack...............................................................................................................................30
Bugs with the stack operation.........................................................................................................31
Jumping and Branching............................................................................................................................32
Avr!Asm!"utorial 2 http$%%&&&'avr!asm!tutorial'net
Controlling sequential execution of the program................................................................................32
What happens during a reset?.........................................................................................................32
Linear program execution and branches..............................................................................................33
Branching........................................................................................................................................33
Timing during program execution.......................................................................................................34
Macros and program execution...........................................................................................................34
Subroutines..........................................................................................................................................35
Interrupts and program execution........................................................................................................36
Calculations..............................................................................................................................................39
Number systems in assembler.............................................................................................................39
Positive whole numbers (bytes, words, etc.)..................................................................................39
Signed numbers (integers)..............................................................................................................39
Binary Coded Digits, BCD.............................................................................................................39
Packed BCDs..................................................................................................................................40
Numbers in ASCII-format..............................................................................................................40
Bit manipulations................................................................................................................................40
Shift and rotate....................................................................................................................................41
Adding, subtracting and comparing....................................................................................................42
Adding and subtracting 16-bit numbers.........................................................................................42
Comparing 16-bit numbers.............................................................................................................42
Comparing with constants..............................................................................................................42
Packed BCD math...........................................................................................................................43
Format conversion for numbers...........................................................................................................44
Conversion of packed BCDs to BCDs, ASCII or Binaries............................................................44
Conversion of Binaries to BCD......................................................................................................44
Multiplication......................................................................................................................................44
Decimal multiplication...................................................................................................................44
Binary multiplication......................................................................................................................45
AVR-Assembler program...............................................................................................................45
Binary rotation................................................................................................................................46
Multiplication in the studio.............................................................................................................46
Hardware multiplication......................................................................................................................48
Hardware multiplication of 8-by-8-bit binaries..............................................................................48
Hardware multiplication of a 16- by an 8-bit-binary......................................................................49
Hardware multiplication of a 16- by a 16-bit-binary......................................................................51
Hardware multiplication of a 16- by a 24-bit-binary......................................................................53
Division...............................................................................................................................................54
Decimal division.............................................................................................................................54
Binary division...............................................................................................................................54
Program steps during division........................................................................................................55
Division in the simulator................................................................................................................55
Number conversion.............................................................................................................................57
Decimal Fractions................................................................................................................................57
Linear conversions..........................................................................................................................57
Example 1: 8-bit-AD-converter with fixed decimal output............................................................58
Example 2: 10-bit-AD-converter with fixed decimal output..........................................................59
Annex.......................................................................................................................................................60
Instructions sorted by function............................................................................................................60
Directives and Instruction lists in alphabetic order.............................................................................62
Assembler directives in alphabetic order........................................................................................62
Instructions in alphabetic order......................................................................................................63
Port details...........................................................................................................................................65
Status-Register, Accumulator flags................................................................................................65
Stackpointer....................................................................................................................................65
SRAM and External Interrupt control............................................................................................65
External Interrupt Control...............................................................................................................66
Timer Interrupt Control..................................................................................................................66
Timer/Counter 0..............................................................................................................................67
Timer/Counter 1..............................................................................................................................68
Avr!Asm!"utorial http$%%&&&'avr!asm!tutorial'net
Watchdog-Timer.............................................................................................................................69
EEPROM........................................................................................................................................69
Serial Peripheral Interface SPI........................................................................................................70
UART.............................................................................................................................................71
Analog Comparator........................................................................................................................71
I/O Ports..........................................................................................................................................72
Ports, alphabetic order.........................................................................................................................72
List of abbreviations............................................................................................................................73
Avr!Asm!"utorial # http$%%&&&'avr!asm!tutorial'net
Why learning Assembler?
Assembler or other languages( that is the )uestion' *hy should + learn another language( if + already
learned other programming languages, "he best argument$ &hile you live in -rance you are able to get
through by spea.ing /nglish( but you &ill never feel at home then( and life remains complicated' 0ou can
get through &ith this( but it is rather inappropriate' +f things need a hurry( you should use the country1s
language'
2any people that are deeper into programming A34s and use higher!level languages in their daily &or.
recommend that beginners start &ith learning assembly language' "he reason is that sometimes( namely
in the follo&ing cases$
if bugs have to be analy5ed(
if the program e6ecutes different than designed and e6pected(
if the higher!level language doesn1t support the use of certain hard&are features(
if time!critical in line routines re)uire assembly language portions(
it is necessary to understand assembly language( e'g' to understand &hat the higher!level language
compiler produced' *ithout understanding assembly language you do not have a chance to proceed
further in these cases'
Short and easy
Assembler instructions translate one by one to e6ecuted machine instructions' "he processor needs only
to e6ecute &hat you &ant it to do and &hat is necessary to perform the tas.' 7o e6tra loops and
unnecessary features blo& up the generated code' +f your program storage is short and limited and you
have to optimi5e your program to fit into memory( assembler is choice #' 8horter programs are easier to
debug( every step ma.es sense'
Fast and quick
9ecause only necessary code steps are e6ecuted( assembly programs are as fast as possible' "he
duration of every step is .no&n' "ime critical applications( li.e time measurements &ithout a hard&are
timer( that should perform e6cellent( must be &ritten in assembler' +f you have more time and don1t mind if
your chip remains 99: in a &ait state type of operation( you can choose any language you &ant'
Assembler is easy to learn
+t is not true that assembly language is more complicated or not as easy to understand than other
languages' ;earning assembly language for &hatever hard&are type brings you to understand the basic
concepts of any other assembly language dialects' Adding other dialects later is easy' As some features
are hard&are!dependent optimal code re)uires some familiarity &ith the hard&are concept and the dialect'
*hat ma.es assembler sometimes loo. complicated is that it re)uires an understanding of the controller1s
hard&are functions' Consider this an advantage$ by learning assembly language you simultaneously learn
more about the hard&are' <igher level languages often do not allo& you to use special hard&are features
and so hide these functions'
"he first assembly code does not loo. very attractive( &ith every #00 additional lines programmed it loo.s
better' =erfect programs re)uire some thousand lines of code of e6ercise( and optimi5ation re)uires lots of
&or.' "he first steps are hard in any language' After some &ee.s of programming you &ill laugh if you go
through your first code' 8ome assembler instructions need some months of e6perience'
AVRs are ideal for learning assembler
Assembler programs are a little bit silly$ the chip e6ecutes anything you tell it to do( and does not as. you if
you are sure over&riting this and that' All protection features must be programmed by you( the chip does
e6actly anything li.e it is told( even if it doesn1t ma.e any sense' 7o &indo& &arns you( unless you
programmed it before'
"o correct typing errors is as easy or complicated as in any other language' 9asic design errors( the more
tric.y type of errors( are also as complicated to debug li.e in any other computer language' 9ut$ testing
programs on A"2/; chips is very easy' +f it does not do &hat you e6pect it to do( you can easily add some
diagnostic lines to the code( reprogram the chip and test it' 9ye( bye to you /=4O2 programmers( to the
>3 lamps used to erase your test program( to you pins that don1t fit into the soc.et after having them
removed some do5en times'
Changes are no& programmed fast( compiled in no time( and either simulated in the studio or chec.ed in!
circuit' 7o pin is removed( and no >3 lamp gives up ?ust in the moment &hen you had your e6cellent idea
about that bug'
Avr!Asm!"utorial 2 http$%%&&&'avr!asm!tutorial'net
Test it!
9e patient doing your first steps@ +f you are familiar &ith another Ahigh!levelB language$ forget it for the first
time' 9ehind every assembler language there is a certain hard&are concept' 2ost of the special features
of other computer languages don1t ma.e any sense in assembler'
"he first five instructions are not easy to learn( after that your learning speed rises fast' After you had your
first lines$ grab the instruction set list and lay bac. in the bathtub( &ondering &hat all the other instructions
are li.e'
8erious &arning$ Don1t try to program a mega!machine to start &ith' "his does not ma.e sense in any
computer language( and ?ust produces frustration' 8tart &ith the small C<ello &orldD!li.e e6amples( e'g'
turning some ;/Ds on and off for a certain time( then e6plore the hard&are features a bit deeper'
4ecommendation$ Comment your subroutines and store them in a special directory( if debugged$ you &ill
need them again in a short time'
<ave success@
Avr!Asm!"utorial http$%%&&&'avr!asm!tutorial'net
Hardware for AVR-Assembler-Programming
;earning assembler re)uires some simple hard&are e)uipment to test your programs( and see if it &or.s
in practice'
"his section sho&s t&o easy schematics that enable you to home bre& the re)uired hard&are and gives
you the necessary hints on the re)uired bac.ground' "his hard&are really is easy to build' + .no& nothing
easier than that to test your first soft&are steps' +f you li.e to ma.e more e6periments( leave some more
space for future e6tensions on your e6perimental board'
+f you don1t li.e the smell of soldering( you can buy a ready!to!use board( too' "he available boards are
characteri5ed in this section belo&'
The ISP-Interface of the AVR-processor family
9efore going into practice( &e have to learn a fe& essentials on the serial programming mode of the A34
family' 7o( you don1t need three different voltages to program and read an A34 flash memory' 7o( you
don1t need another pre!programmed microprocessor to program the A34s' 7o( you don1t need #0 +%O lines
to tell the chip &hat you li.e it to do' And you don1t even have to remove the A34 from the soc.et on your
your e6perimental board( before programming it' +t1s even easier than that'
All this is done by a build!in interface in the A34 chips( that enable you to &rite and read the content of the
program flash and the built!in!//=4O2' "his interface &or.s serially and needs only three signal lines$
8CE$ A cloc. signal that shifts the bits to be &ritten to the memory into an internal shift register( and
that shifts out the bits to be read from another internal shift register(
2O8+$ "he data signal that sends the bits to be &ritten to the A34(
2+8O$ "he data signal that receives the bits read from the A34'
"hese three signal pins are internally connected to the programming machine only if you change the
4/8/" Asometimes also called 48" or restartB pin to 5ero' Other&ise( during normal operation of the A34(
these pins are programmable +%O lines li.e all the others'
+f you li.e to use these pins for other purposes during normal operation( and for in!
system!programming( you1ll have to ta.e care( that these t&o purposes do not
conflict' >sually you then decouple these by resistors or by use of a multiple6er'
*hat is necessary in your case( depends from your use of the pins in the normal
operation mode' 0ou1re luc.y( if you can use them for in!system!programming
e6clusively'
7ot necessary( but recommendable for in!system!programming is( that you supply
the programming hard&are out of the supply voltage of your system' "hat ma.es it
easy( and re)uires t&o additional lines bet&een the programmer and the A34
board' F7D is the common ground or negative pole of the supply voltage( 3"F
Atarget voltageB the supply voltage Ausually GH'0 voltsB' "his adds up to 6 lines
bet&een the programmer hard&are and the A34 board' "he resulting +8=6
connection( as defined by A2/;( is sho&n on the left'
8tandards al&ays have alternative standards( that &ere used earlier' "his is the
technical basis that constitutes the adapter industry' +n our case the alternative
standard &as designed as +8=#0 and &as used on the 8"E200 board( sometimes
also called CA7DA interface' +t1s still a very &idespread standard( and even the
more recent 8"EH00 board is e)uipped &ith it' +8=#0 has an additional signal to
drive a red ;/D' "his ;/D signals that the programmer is doing his ?ob' A good
idea' Just connect the ;/D to a resistor and clamp it the positive supply voltage'
Programmer for the PC-Parallel-Port
7o&( heat up your soldering iron and build up your programmer' +t is a )uite easy schematic and &or.s
&ith standard parts from your &ell!sorted e6periments bo6'
0es( that1s all you need to program an A34' "he 2H!pin plug goes into the parallel port of your =C( the #0!
pin!+8= goes to your A34 e6perimental board' +f your bo6 doesn1t have a IJ;82JH( you can also use a
IJ<C2JH A&ith no hard&are changesB or a IJ;82JJ%IJ<C2JJ Aby changing some pins and signalsB' +f you
use <C( don1t forget to tie unused inputs either to F7D or the supply voltage( other&ise the buffers might
produce e6tra noise by capacitive s&itching'
Avr!Asm!"utorial J http$%%&&&'avr!asm!tutorial'net
"he necessary program algorithm is done by the +8= soft&are' 9e a&are that this parallel port interface is
not supported by A"2/;1s studio soft&are any more' 8o( if you &ant to program your A34 directly from
&ithin the studio( use different programmers' "he +nternet provides several solutions'
+f you already have a programming board( you &ill not need to build this programmer( because you1ll find
the +8= interface on some pins' Consult your handboo. to locate these'
Experimental boards
0ou probably &ant to do your first programming steps &ith a self!made A34 board' <ere are t&o versions
offered$
A very small one &ith an A"tiny#( or
a more complicated one &ith an A"9082# or A"mega2#( including a serial 4822 interface'
Experimental board with an ATtiny13
"his is a very small board that allo&s e6periments &ith the A"tiny#1s internal hard&are' "he picture
sho&s
the +8=#0 programming interface on the left( &ith a programming ;/D attached via a resistor of
90 Ohms(
the A"tiny# &ith a pull!up of #0. on its 4/8/" pin Apin #B(
the supply part &ith a bridge rectifier( to be supplied &ith 9''#H3 from an AC or DC source( and a
small H3 regulator'
"he A"tiny# re)uires no e6ternal K"A; or cloc. generator( because it &or.s &ith its internal 9'6 2cs%s
Avr!Asm!"utorial H http$%%&&&'avr!asm!tutorial'net
4C generator and( by default( &ith a cloc. divider of 8 Acloc. fre)uency #'2 2cs%sB'
"he hard&are can be build on a
small board li.e the one sho&n in
the picture' All pins of the tiny# are
accessible( and e6ternal hard&are
components( li.e the ;/D sho&n(
can be easily plugged in'
"his board allo&s the use of the
A"tn#1s hard&are components li.e
+%O!ports( timers( AD converters(
etc'
Experimental board with an AT90S2313/ATmega2313
-or test purposes( &ere more +%O!pins or a serial communication interface is necessary( &e can use a
A"9082# or A"mega2# on an e6perimental board' "he schematic sho&s
a small voltage supply for connection to an AC transformer and a voltage regulator H3%#A(
a K"A; cloc. generator Ahere &ith a #0 2cs%s K"A;( all other fre)uencies belo& the ma6imum for
the 2# &ill also &or.B(
Avr!Asm!"utorial 6 http$%%&&&'avr!asm!tutorial'net
the necessary parts for a safe reset during supply voltage s&itching(
the +8=!=rogramming!+nterface Ahere &ith a +8=#0=+7!connectorB'
8o that1s &hat you need to start &ith' Connect other peripheral add!ons to the numerous free +%O pins of
the 2#'
"he easiest output device can be a ;/D( connected via a resistor to the positive supply voltage' *ith that(
you can start &riting your first assembler program s&itching the ;/D on and off'
Avr!Asm!"utorial I http$%%&&&'avr!asm!tutorial'net
+f you
do not need the serial communication interface( ?ust s.ip the hard&are connected to pins 2% and
#J%#6(
if you do not need hard&are handsha.e signals( s.ip the hard&are on the pins #J%#6 and connect
4"8 on the 9!pin!connector over a 2'2. resistor to G93'
+f you use an A"mega2# instead of an A"9082#( the follo&ing changes are resulting$
the e6ternal K"A; is not necessary( as the A"mega has an internal 4C cloc. generator( so ?ust
s.ip all connections to pins J and H(
if you &ant to use the e6ternal K"A; instead of the build!in 4C as cloc. source( you &ill have to
program the fuses of the A"mega accordingly'
Ready-to-use commercial programming boards for the
AVR-family
+f you do not li.e homebre&ed hard&are( and if have some e6tra money left that you don1t .no& &hat to do
&ith( you can buy a commercial programming board' Depending from the amount of e6tra money you1d li.e
to spend( you can select bet&een more or less costly versions' -or the amateur the follo&ing selection
criteria should be loo.ed at$
price(
=C interface Apreferably >89( less convenient or durable$ 9!pin 4822( re)uiring additional
soft&are$ interfaces for the parallel port of the =CB(
support reliability for ne&er devices Aupdates are re)uired from time to time( other&ise you sit on a
nearly dead horseB(
hard&are features Adepends on your foreseeable re)uirements in the ne6t five yearsB'
"he follo&ing section describes the three standard boards of A"2/;( the 8"E200( the 8"EH00 and the
Dragon' "he selection is based on my o&n e6periences and is not a recommendation'
STK200
"he 8"E200 from A"2/; is a historic board' +f you grab a used one you1ll get
a board &ith some soc.ets Afor 8( 20( 28 and J0 pin devicesB(
eight .eys and ;/Ds( hard connected to port D and 9(
an ;CD standard #J!pin interface(
an option for attaching a 28!pin 84A2(
a 4822 interface for communication(
a cable interface for a =C parallel port on one side and a #0!pin!+8= on the other side'
<3 programming is not supported'
"he board cannot be programmed from &ithin the 8tudio( the programming soft&are is no longer
maintained( and you must use e6ternal programs capable of driving the =C parallel port'
+f someone offers you such a board( ta.e it only for free and if you1re used to operate soft&are of the
necessary .ind'
STK500
/asy to get is the 8"EH00 Ae'g' from A"2/;B' +t has the follo&ing hard&are$
8oc.ets for programming most of the A34 types Ae'g' #J!pin devices or "L-= pac.ages re)uire
additional hard&areB(
serial and parallel programming in normal mode or &ith high voltage A<3 programming brings
devices bac. to life even if their 4/8/" pin has been fuse!programmed to be normal port inputB(
+8=6=+7! and +8=#0=+7!connection for e6ternal +n!8ystem!=rogramming(
programmable oscillator fre)uency and supply voltages(
plug!in s&itches and ;/Ds(
a plugged 4822C!connector A>A4"B(
a serial -lash!//=4O2 Aonly older boards have thisB(
Avr!Asm!"utorial 8 http$%%&&&'avr!asm!tutorial'net
access to all port pins via #0!pin connectors'
A ma?or disadvantage of the board is that( before programming a device( several connections have to be
made manually &ith the delivered cables'
"he board is connected to the =C using a serial port ACO26B' +f your laptop doesn1t have a serial interface(
you can use one of the common >89!to!8erial!+nterface cables &ith a soft&are driver' +n that case the
driver must be ad?usted to use bet&een CO2# and CO28 and a baud rate of ##H. to be automatically
detected by the 8tudio soft&are'
=rogramming is performed and controlled by recent versions of A34 studio( &hich is available for free from
A"2/;1s &eb page after registration' >pdates of the device list and programming algorithm are provided
&ith the 8tudio versions( so the support for ne&er devices is more li.ely than &ith other boards and
programming soft&are'
/6periments can start &ith the also supplied A34 Aolder versions$ A"9088H#H( ne&er boards versions
include different typesB' "his covers all hard&are re)uirements that the beginner might have'
AVR Dragon
"he A34 dragon is a very small board' +t has an >89 interface( &hich also supplies the board and the 6!
pin!+8= interface' "he 6!pin!+8=!+nterface is accompanied by a 20!pin <3 programming interface' "he
board is prepared for adding some soc.ets on board( but doesn1t have soc.ets for target devices and other
hard&are on board'
"he dragon is supported by the 8tudio soft&are and is a updated automatically'
+ts price and design ma.es it a nice gift for an A34 amateur' "he bo6 fits nicely in a ro& &ith other
precious and carefully designed bo6es'
Avr!Asm!"utorial 9 http$%%&&&'avr!asm!tutorial'net
Tools for AVR assembly programing
-our basic programs are necessary for assembly programming' "hese tools are$
the editor(
the assembler program(
the chip programing interface( and
the simulator'
"&o different basic routes are possible$
#' anything necessary in one pac.age(
2' each tas. is performed &ith a specific program( the results are stored as specific files'
>sually route M# is chosen' 9ut because this is a tutorial( and you are to understand the underlying
mechanism first( &e start &ith the description of route M2 first'
From a text file to instruction words in the flash memory
The editor
Assembler programs are &ritten &ith an editor' "he editor ?ust has to be able to create and edit A8C++ te6t
files' 8o( basically( any simple editor does it'
8ome features of the editor can have positive effects$
/rrors( that the assembler later detects( are reported along &ith the line number in the te6t file' ;ine
numbers are also a po&erful invention of the computer!age &hen it comes to discussions on your
code &ith someone else' 8o your editor should be able to display the line number' >nfortunately
nearly all editors( that a mighty soft&are company provides as part of its operating systems( are
missing that feature' =robably *ido&s 20#9 re!invents that feature( and sells better among
assembler frea.s'
"yping errors are largely reduced( if those errors are mar.ed &ith colors' +t is a nice feature of an
editor to highlight the components of a line in different colors' 2ore or less intelligent recognition of
errors ease typing' 9ut this is a feature that + don1t really miss'
+f your editor allo&s the selection of fonts( chose a font &ith fi6ed spacing( li.e Courier' <eaders
loo. nicer &ith that'
0our editor should be capable of recogni5ing line ends &ith any combination of characters
Acarriage returns( line feeds( bothB &ithout producing unacceptable screens' Another item on the
&ishlist for *ido&s 20#'
+f you prefer shooting &ith cannons to .ill sparro&s( you can use a mighty &ord processing soft&are to
&rite assembler programs' +t might loo. nicer( &ith large bold headings( gray comments( red &arnings(
changes mar.ed( and reminders on "o!Do1s in e6tra bubble fields' 8ome disadvantages here$ you have to
convert your te6t to plain te6t at the end( losing all your nice design &or.( and your resulting te6tfile should
not have a single control byte left' Other&ise this single byte &ill cause an error message( &hen you
assemble the te6t' And remember$ ;ine numbers here are only correct on page one of your source code'
8o( &hatever te6t program you chose(
it1s up to you' "he follo&ing e6amples
are &ritten in &avrasm( an editor
provided by A"2/; in earlier days'
+n the plain editor field &e type in our
directives and assembly instructions' +t
is highly recommended that lines come
together &ith some comments Astarting
&ith NB' ;ater understanding of &hat
&e1ve planned here &ill be helpful in
later debugging'
7o& store the program te6t( named to
something'asm into a dedicated
directory( using the file menu' "he
assembly program is complete no&'
+f you1d li.e to see &hat synta6!highlighting means( + have a snapshot of such an A34 editor here'
Avr!Asm!"utorial #0 http$%%&&&'avr!asm!tutorial'net
"he editor recogni5es
instructions automatically and
uses different colors Asynta6
highlightingB to signal user
constants and typing errors in
those instructions Ain blac.B'
8toring the code in an 'asm file
provides nearly the same te6t
file( colors are not stored in the
file'
Don1t try to find this editor or its
authorN the editor is history and
no longer maintained'

Structuring assembler code
This page shows the basic structure of an assembler program. These structures are typical for AVR
assembler. This text discusses
comments (
header informations (
code at program start and
the general structure of programs'
Comments
"he most helpful things in assembler programs are comments' +f you need to understand older code that
you &rote( sometimes years after( you &ill be happy about having some or more hints &hat is going on in
that line' +f you li.e to .eep your ideas secret( and to hide them against yourself and others$ don1t use
comments' A comment starts &ith a semicolon' All that follo&s behind on the same line &ill be ignored by
the compiler' +f you need to &rite a comment over multiple lines( start each line &ith a semicolon' 8o each
assembler program should start li.e that$
;
; Click.asm, Program to switch a relais on and off each two seconds
; Written by G.Schmidt, last change: 7.1.!1
;
=ut comments around all parts of the program( be it a complete subroutine or a table' *ithin the comment
mention the special nature of the routine( pre!conditions necessary to call or run the routine' Also mention
the results of the subroutine in case you later &ill have to find errors or to e6tend the routine later' 8ingle
line comments are defined by adding a semicolon behind the command on the line' ;i.e this$
"#$ %1&,'( ; )ere something is loaded
*+, %17,%1& ; and co-ied somewhere else
Things to be written on top
=urpose and function of the program( the author( version information and other comments on top of the
program should be follo&ed by the processor type that the program is &ritten for( and by relevant
constants and by a list &ith the register names' "he processor type is especially important' =rograms do
not run on other chip types &ithout changes' "he instructions are not completely understood by all types(
each type has typical amounts of //=4O2 and internal 84A2' All these special features are included in a
header file that is named 6666def'inc( &ith 6666 being the chip type( e'g' 2#( tn22( or m8H#H' "hese
files are available by A"2/;' +t is good style to include this file at the beginning of each program' "his is
done li.e that$
..+"$S/ ; #on0t list the following in the list file
.$.C"1#2 3m4515def.inc3 ; $m-ort of the file
."$S/ ; Switch list on again
"he path( &here this file can be found( is only necessary if you don1t &or. &ith A"2/;1s 8tudio' Of course
you have to include the correct path to fit to your place &here these files are located' During assembling(
the outpu of a list file listing the results is s&itched on by default' <aving listing ob might result in very long
list file AO'lstB if you include the header file' "he directive '7O;+8" turns off this listing for a &hile( ;+8" turns
it on again' ;et1s have a short loo. at the header file' -irst these files define the processor type$
.#2,$C2 (/*2G(4515 ; /he target de6ice ty-e
"he directive 'D/3+C/ advices the assembler to chec. all instructions if these are available for that A34
Avr!Asm!"utorial ## http$%%&&&'avr!asm!tutorial'net
type' +t results in an error message( if you use code se)uences that are not defined for this type of
processor' 0ou don1t need to define this &ithin your program as this is already defined &ithin the header
file' "he header file also defines the registers K<( K;( 0<( 0;( P< and P;' "hese are needed if you use the
#6!bit!pointers K( 0 or P to access the higher or lo&er byte of the pointer separately' All port locations are
also defined in the header file( so =O4"9 translates to a he6 number &here this port is located on the
defined device' "he port1s names are defined &ith the same names that are used in the data sheets for the
respective processor type' "his also applies to single bits in the ports' 4ead access to port 9( 9it ( can be
done using its bit name =+79( as defined in the data sheet' +n other &ords$ if you forget to include the
header file you &ill run into a lot of error messages during assembly' "he resulting error messages are in
some cases not necessarily related to the missing header file' Others things that should be on top of your
programs are the register definitions you &or. &ith(e'g'$
.#27 m-r 8 %1& ; #efine a new name for register %1&
"his has the advantage of having a complete list of registers( and to see &hich registers are still available
and unused' 4enaming registers avoids conflicts in the use of these registers and the names are easier to
remember' -urtheron &e define the constants on top of the source file( especially those that have a
relevant role in different parts of the program' 8uch a constant &ould( e'g'( be the Ktal fre)uency that the
program is ad?usted for( if you use the serial interface on board' *ith
.291 f: 8 ; ; </al fre:=ency definition
at the beginning of the source code you immediately see for &hich cloc. you &rote the program' 3ery
much easier than searching for this information &ithin #J82 lines of source code' "o the top of that page
Things that should be done at program start
After you have done the header( the program code should start' At the beginning of the code the reset! and
interrupt!vectors Atheir function see in the J>2= sectionB are placed' As these re)uire relative ?umps( &e
should place the respective interrupt service routines right behind' +n case of A"mega types &ith larger
flash memory J>2= instructions can be used here( so be careful here' "here is some space left then for
other subroutines( before &e place the main program' "he main program al&ays starts &ith initiali5ation of
the stac. pointer( setting registers to default values( and the init of the hard&are components used' "he
follo&ing code is specific for the program'
Structuring of program code
"he described standardi5ed structure is included in a program &ritten for *indo&s Operating 8ystems(
&hich can be do&nloaded at http$%%&&&'avr!asm!do&nload'de%avrQhead'5ip'
>n5ip the e6ecutable file( and simply run
it' +t sho&s this$ <ere you can choose
ATtiny by clic.ing on it( and then select
ATtiny13 in the dropdo&n field AVR-
Type'
0ou are no& as.ed to navigate to its respective include!file tn#def'inc' 8ho& the program the &ay &here
the header file is located'
Avr!Asm!"utorial #2 http$%%&&&'avr!asm!tutorial'net
<ere you can enter
your desired multi
purpose register(
the output configu!
ration on ports A
and 9( if available(
and if you &ant to
use interrupts'
Clic. Update to fill
the &indo& &ith
your code frame'
Clic.
CopyToClipboard
( if you &ant to
paste this code into
your code editor( or
WriteToFile to
&rite this to an
assembler code file
instead'
+f you don1t .no&
&hat it is for and
&hat to do( press
the Help button'
"his produces the follo&ing code$
;
; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
; > ?(dd Pro@ect title hereA >
; > ?(dd more info on software 6ersion hereA >
; > BCC!'' by ?(dd Co-yright $nfo hereA >
; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
;
; $ncl=ded header file for target (,% ty-e
..+"$S/
.$.C"1#2 3tn1Ddef.inc3 ; )eader for (//$.E1D
."$S/
;
; 88888888888888888888888888888888888888888888
; ) ( % # W ( % 2 $ . 7 + % * ( / $ + .
; 88888888888888888888888888888888888888888888
;
; ?(dd all hardware information hereA
;
; 88888888888888888888888888888888888888888888
; P + % / S ( . # P $ . S
; 88888888888888888888888888888888888888888888
;
; ?(dd names for hardware -orts and -ins hereA
; 7ormat: .291 Control-orto=t 8 P+%/(
; .291 Control-ortin 8 P$.(
; .291 "ed+=t-=tPin 8 P+%/(!
;
; 88888888888888888888888888888888888888888888
; C + . S / ( . / S / + C ) ( . G 2
; 88888888888888888888888888888888888888888888
;
Avr!Asm!"utorial # http$%%&&&'avr!asm!tutorial'net
; ?(dd all constants here that can be s=b@ect
; to change by the =serA
; 7ormat: .291 const 8 F(GC#
;
; 88888888888888888888888888888888888888888888
; 7 $ < H # 2 % $ , 2 # C + . S / ( . / S
; 88888888888888888888888888888888888888888888
;
; ?(dd all constants here that are not s=b@ect
; to change or calc=lated from constantsA
; 7ormat: .291 const 8 F(GC#
;
; 88888888888888888888888888888888888888888888
; % 2 G $ S / 2 % # 2 7 $ . $ / $ + . S
; 88888888888888888888888888888888888888888888
;
; ?(dd all register names here, incl=de info on
; all =sed registers witho=t s-ecific namesA
; 7ormat: .#27 rm- 8 %1&
.#27 rm- 8 %1& ; *=lti-=r-ose register
;
; 88888888888888888888888888888888888888888888
; S % ( * # 2 7 $ . $ / $ + . S
; 88888888888888888888888888888888888888888888
;
.#S2G
.+%G <&
; 7ormat: "abel: .GE/2 . ; reser6e . Gytes from "abel:
;
; 88888888888888888888888888888888888888888888
; % 2 S 2 / ( . # $ . / , 2 C / + % S
; 88888888888888888888888888888888888888888888
;
.CS2G
.+%G F
r@m- *ain ; %eset 6ector
reti ; $nt 6ector 1
reti ; $nt 6ector !
reti ; $nt 6ector D
reti ; $nt 6ector ;
reti ; $nt 6ector 5
reti ; $nt 6ector &
reti ; $nt 6ector 7
reti ; $nt 6ector 4
reti ; $nt 6ector I
;
; 88888888888888888888888888888888888888888888
; $ . / 2 % % 1 P / S 2 % , $ C 2 S
; 88888888888888888888888888888888888888888888
;
; ?(dd all interr=-t ser6ice ro=tines hereA
;
; 88888888888888888888888888888888888888888888
; * ( $ . P % + G % ( * $ . $ /
; 88888888888888888888888888888888888888888888
;
*ain:
; $nit stack
ldi rm-, "+WB%(*2.#C ; $nit "SG stack
o=t SP",rm-
; $nit Port G
ldi rm-,B1JJ##G!CKB1JJ##G1CKB1JJ##GC ; #irection of Port G
o=t ##%G,rm-
; ?(dd all other init ro=tines hereA
ldi rm-,1JJS2 ; enable slee-
o=t *C1C%,rm-
sei
;
; 88888888888888888888888888888888888888888888
; P % + G % ( * " + + P
; 88888888888888888888888888888888888888888888
;
"oo-:
slee- ; go to slee-
no- ; d=mmy for wake =-
r@m- loo- ; go back to loo-
;
Avr!Asm!"utorial #J http$%%&&&'avr!asm!tutorial'net
; 2nd of so=rce code
;
The assembler
7o& &e have a te6t file( &ith blan. A8C++ characters' "he ne6t step is to translate this code to a machine!
oriented form &ell understood by the A34 chip' Doing this is called assembling( &hich means Cput together
the right instruction &ordsD' "he program that reads the te6t file and produces some .ind of output files is
called Assembler' +n the easiest form this is a instruction!line program that( &hen called( e6pects the
address of the te6t file and some optional s&itches( and then starts assembling the instructions found in
the te6t file'
+f your editor allo&s calling e6ternal programs( this is an easy tas.' +f not Aanother item on the &ish list for
the editor in *ido&s 20#0B( it is more convenient to &rite a short batch file Aagain using an editorB' "hat
batch file should have a line li.e this$
=ath"oAssemblerRAssembler'e6e !options =ath"o"e6tfileR"e6tfile'asm
Elic.ing on the editor1s e6ternal program
caller or on the batch file starts the
command line assembler' "hat piece of
soft&are reports the complete translation
process Ain the smaller &indo&B( here
&ith no errors' +f errors occur these are
notified( along &ith their type and line
number' Assembling resulted in one &ord
of code &hich resulted from the 4J2=
instruction that &e used' Assembling our
single asm!te6t file no& has produced
four other files Anot all apply hereB'
"he first of these four ne& files(
"/8"'//=( holds the content that should
be &ritten to the //=4O2 of the A34'
"his is not very interesting in our case(
because &e didn1t program any content
for the //=4O2' "he assembler has
therefore deleted this file &hen he
completed the assembly run( because it is empty'
"he second file( "/8"'</K( is more relevant
because this file holds the instructions later
programmed into the A34 chip' "his file loo.s
li.e this'
"he he6 numbers are &ritten in a special
A8C++ form( together &ith address
informations and a chec.sum for each line'
"his form is called +ntel!he6!format( and is
very old and stems from the early &orld of
computing' "he form is &ell understood by
the programing soft&are'
"he third file( "/8"'O9J( &ill be
introduced later( this file is needed to
simulate an A34' +ts format is
he6adecimal and defined by A"2/;'
>sing a he6!editor its content loo.s
li.e this' Attention$ "his file format is
not compatible &ith the programmer
soft&are( don1t use this file to program the A34 Aa very common error &hen startingB' O9J files are only
produced by certain A"2/; assemblers( don1t e6pect these files &ith other assemblers'
"he fourth file( "/8"';8"( is a te6t file' Display its content &ith a simple editor' "he follo&ing results'
Avr!Asm!"utorial #H http$%%&&&'avr!asm!tutorial'net
"he program &ith all its addresses( instructions and
error messages are displayed in a readable form' 0ou
&ill need that file in some cases to debug errors'
;istfiles are generated only if the appropriate option is
selected on the command line options and if the
'7O;+8" directive doesn1t suppress listing'
Programming the chips
"o program our he6 code( as coded in te6t form in the '</K!file( to the A34 a programmer soft&are is
necessary' "his soft&are reads the '</K!file and transfers its content( either bit!by!bit Aserial
programmingB or byte!by!byte Aparallel programmingB to the A341s flash memory' *e start the programmer
soft&are and load the he6 file that &e ?ust generated'
+n an e6ample that loo.s
li.e this' =lease note$ the
displayed &indo& stems
from +8='e6e( a historic
program no longer distribu!
ted by A"2/;' Other pro!
grammer soft&are loo.s
similar'
"he soft&are &ill burn our
code in the chip1s program
store' "here are a number
of preconditions necessary
for this step and several
reasons possible( if this
step fails' Consult your
programmer soft&are help(
if problems occur'
=rogramming hard&are and appropriate soft&are alternatives for different =C operating systems are
available on the +nternet' As an e6ample for programming over the =C1s parallel or serial communication
port( =ony=rog2000 should be mentioned here'
Simulation in the studio
+n some cases self!&ritten assembly code( even assembled &ithout errors( does not e6actly do &hat it
should do &hen burned into the chip' "esting the soft&are on the chip could be complicated( esp' if you
have a minimum hard&are and no opportunity to display interim results or debugging signals' +n these
cases the 8tudio soft&are pac.age from A"2/; provides ideal opportunities for debugging' "esting the
soft&are or parts of it is possible( the program code could be tested step!by!step displaying results'
"he pictures sho&n here are ta.en from 3ersion J of the 8tudio( that is available for free on A"2/;1s
&ebsite' Older versions loo.s different( but do nearly the same' "he 8tudio is a soft&are that has all you
need to develop( debug( simulate and burn your assembler programs into the A34 type of your choice'
"he studio is started and loo.s li.e this'
Avr!Asm!"utorial #6 http$%%&&&'avr!asm!tutorial'net
"he first dialog as.s &hether an e6isting pro?ect should be opened or a ne& pro?ect is to be started' +n
case of a ne&ly installed 8tudio D7e& =ro?ectS is the correct ans&er' "he 9utton D7e6tTTS brings you to the
settings dialog of your ne& pro?ect'
<ere you select DAtmel A34 AssemblerS as your pro?ect type( give that pro?ect a name Ahere Dtest#SB and
let the 8tudio crate an initial AemptyB file for your source code( let it create a folder and select a location for
that pro?ect( &here you have &rite access to'
"he button D7e6tTTS opens the platform and device selection dialog$
Avr!Asm!"utorial #I http$%%&&&'avr!asm!tutorial'net
As debug platform select either DA34 simulatorS or DA34 simulator 2S' As Device select your A34 type(
here an A"mega8 &as selected' +f your desired type is grayed out( select another simulator platform'
Close this &indo& &ith the D-inishS button' 7o& a large &indo& pops up( &hich has lots of different sub!
&indo&s'
On the left( the pro?ect &indo& allo&s you to manipulate and vie& all your pro?ect files' +n the middle( the
editor &indo&( allo&s you to &rite your source code Atry typing its content to your editor &indo&( don1t care
about the colors U these are added by the editor U remember synta6!highlighting,B' On the left bottom is a
D9uildS section( &here all your error messages go to' On the right side is a strange +%O vie& and belo& a
rather &hite field( &e1ll come to that later on'
All &indo& portions can be made larger and smaller and even can be shifted around on the screen' "ry
mi6ing these &indo&s@ "he ne6t pictures sho& some differently loo.ing &indo&s( but they are all the same
as here'
After typing the source code sho&n above to your source file in the editor completely( push the menu
D9uildS and its sub!menu D9uildS' +f you typed correctly( the follo&ing sho&s up in your D9uildS &indo&$
Avr!Asm!"utorial #8 http$%%&&&'avr!asm!tutorial'net
2a.e sure( you read all &indo& content once for the first time( because it gives you a lot more info besides
the small green circle' All that should be fine( other&ise you typed errors into the code and the circle is red'
0ou can no& push the menu item DDebugS and some &indo&s change their content( si5e and position' +f
you also push the menu item D3ie&S( D"oolbarsS and D=rocessorS and shift around &indo&s( it should loo.
li.e this$
"he former editor &indo& has
a yello& arro& no&' "his
arro& points to the ne6t
instruction that &ill be
e6ecuted Anot really e6ecuted(
but rather DsimulatedSB'
"he processor &indo& sho&s
the current program counter
value Ayes( the program starts
at address 0B( the stac.
pointer Ano matter &hat that
might be U &ait for that later
in the courseB( a cycle counter
and a stop &atch' +f you push
on the small DGS left to the
&ord D4egistersS( the content
of the 2 registers is
displayed Ayes( they are all
empty &hen you start the
processor simulationB'
7o& let us proceed &ith the
first instruction' 2enu item
DDebugS and D8tep intoS or
simply -## e6ecutes the first
instruction'
"he instruction Dldi rmp(0b########S
loads the binary value ####'#### to
register 4#6' An instruction &e &ill learn
more about later on in the course'
"he yello& arro& no& has advanced
one instruction do&n( is no& at the O>"
instruction'
+n the processor &indo&( the program
counter and the cycle counter are both
at # no&'
And register #6( do&n the list of
registers( is red no& and sho&s 06--(
&hich is he6adecimal for binary
####'####'
"o learn about another simulator
&indo& ?ust advance simulation one
step further to e6ecute the O>"
instruction Ae' g' by pushing the .ey -##'
Avr!Asm!"utorial #9 http$%%&&&'avr!asm!tutorial'net
"he instruction DOut DD49(rmpS &rites 06-- to a port named DD49' 7o& the action is on the +%O vie&
&indo&' +f you push on =O4"9 and the small DGS left of it( this &indo& displays the value 06-- in the port
DD49 in t&o different forms$ as 06-- in the upper &indo& portion and as 8 blac. s)uares in the lo&er
&indo& section'
"o ma.e it even more blac.( &e push -## t&o times and &rite 06HH to the port =O4"9'
As e6pected( the
port =O4"9
changes its
content and has
four blac. and
four &hite
s)uares no&'
Another t&o -##(
&riting 06AA to
=O4"9( changes
the blac. and
&hite s)uares to
the opposite
color'
All &hat has been
e6pected( but &hat
happened to port
=+79, *e didn1t
&rite something to
=+79( but it has
the opposite colors
than =O4"9( ?ust
li.e the colors
before in =O4"9'
=+79 is an input
port for e6ternal
pins' 9ecause the
direction ports in
DD49 are set to
be outputs( =+79
follo&s the pin
status of =O4"9(
?ust one cycle later' 7othing &rong here' +f you li.e to chec. this( ?ust press -## several times and you see
that this is correct'
"hat is our short trip through the simulator soft&are &orld' "he simulator is capable to much more( so it
should be applied e6tensively in cases of design errors' 3isit the different menu items( there is much more
than can be sho&n here' +n the mean time( instead of playing &ith the simulator( some basic things have to
learned about assembler language( so put the 8tudio aside for a &hile'
Avr!Asm!"utorial 20 http$%%&&&'avr!asm!tutorial'net
What is a register?
4egisters are special storages &ith 8 bits capacity and they loo. li.e this$
9it I 9it 6 9it H 9it J 9it 9it 2 9it # 9it 0
7ote the numeration of these bits$ the least significant bit starts &ith 5ero Amathematically$ 2
0
V #B'
A register can either store numbers from 0 to 2HH Apositive number( no negative valuesB( or numbers from !
#28 to G#2I A&hole number &ith a sign bit( located in bit IB( or a value representing an A8C++!coded
character Ae' g' 1A1B( or ?ust eight single bits that do not have something to do &ith each other Ae' g' for eight
single flags( used to signal eight different yes%no decisionsB'
"he special character of registers( compared to other storage sites( is that
they are connected directly to the central processing unit called the accumulator(
they can be used directly in assembler instructions( either as target register for the result or as read
register for a calculation or transfer(
operations &ith their content re)uire only a single instruction &ord'
"here are 2 registers in an A34' "hey are originally named 40 to 4#( but you can choose to name them
to more meaningful ones using a so!called assembler directive' An e6ample$
.DEF MyPreferredRegister = R16
Assembler directives al&ays start &ith a dot' +nstructions or labels do 7/3/4 start &ith a dot' 7ote that
assembler directives li.e this are only meaningful for the assembler but do not produce any code that is
e6ecutable in the A34 target chip' "he name D2y=referred4egisterS &ill not sho& up in the assembled he6
code( and therefore this name cannot be derived from that he6 code'
+nstead of using the register name 4#6 &e can no& use our o&n name D2y=referred4egisterS( if &e &ant
to use 4#6 &ithin an instruction' 8o &e &rite a little bit more te6t each time &e use this register( but &e
have an association &hat might be the content of this register'
>sing the instruction line
LDI MyPreferredRegister, 150
&hich means$ load the number #H0 immediately to the register 4#6( ;oaD +mmediate' "his loads a fi6ed
value or a constant to that register' -ollo&ing the assembly( or translation of this code into binary or he6(
the program storage &ritten to the A34 chip loo.s li.e this$
000000 E906
"his &ill sho& up in the listing( a file called O'lst produced by the assembler soft&are( &hich is a simple te6t
file' All numbers are in he6 format$ "he first he6 number is the address A000000B( &here the instruction is
&ritten to in the program flash memory of the A34( the second is the instruction code A/906B' /906 tells
the processor three different things in one &ord( even if you don1t see this directly$
a basic load instruction code( that stands for ;D+(
the target register A4#6B &here the value #H0 is to be &ritten to(
the value of the constant A#H0B'
Don1t be afraid$ you don1t have to remember this coding because the assembler .no&s ho& to translate all
this to finally yield /906 and the A34 e6ecutes it'
*ithin one instruction t&o different registers can play a role' "he easiest instruction of this type is the copy
instruction( 2O3' "he naming of this instruction 2O3 deserves a price for the most confusing definition(
because the content of a register cannot be moved A&hat &ould be left in a register( if you 2O3/ its
content to some&here else,B' +t should better be named CO=0( because it copies the content of one
register to another register' ;i.e this$
.DEF MyPreferredRegister = R16
.DEF AnotherRegister = R15
LDI MyPreferredRegister, 150
MO AnotherRegister, MyPreferredRegister
"he first t&o lines of this monster program are directives that define the ne& names of the registers 4#6
and 4#H for the assembler' Again( these lines do not produce any code for the A34' "he instruction lines
&ith ;D+ and 2O3 produce code$
000000 E906
000001 !F01
"he instruction &rite the value #H0 into register 4#6 and copy its content to the target register 4#H' 3ery
Avr!Asm!"utorial 2# http$%%&&&'avr!asm!tutorial'net
+2=O4"A7" 7O"+C/$
The first register is always the target register where the reslt is written to!
A"his is unfortunately different from &hat one e6pects or from ho& &e spea.( thin. and &rite U left to right'
+t is a simple convention( probably inspired by some Asian languages &here &riting is from right to left'
"hat &as once defined that &ay to confuse the beginners learning assembler' "hat is &hy assembly
language is that complicated'B
Different registers
"he beginner might &ant to &rite the above instructions li.e this$
.DEF AnotherRegister = R15
LDI AnotherRegister, 150
And$ you lost' Only the registers from 4#6 to 4# load a constant immediately &ith the ;D+ instruction( 40
to 4#H don1t do that' "his restriction is not very fine( but could not be avoided during construction of the
instruction set for the A34s'
"here is one e6ception from that rule$ setting a register to Pero' "his instruction
"LR MyPreferredRegister
is valid for all registers'
9esides the ;D+ instruction you &ill find this register class restriction &ith the follo&ing additional
instructions$
A7D+ 46(E N 9it!And of register 46 &ith a constant value E(
C94 46(2 N Clear all bits in register 46 that are set to one &ithin the constant mas. value 2(
C=+ 46(E N Compare the content of the register 46 &ith a constant value E(
89C+ 46(E N 8ubtract the constant E and the current value of the carry flag from the content of
register 46 and store the result in register 46(
894 46(2 N 8et all bits in register 46 to one( that are one in the constant mas. 2(
8/4 46 N 8et all bits in register 46 to one Ae)ual to ;D+ 46(2HHB(
8>9+ 46(E N 8ubtract the constant E from the content of register 46 and store the result in register
46'
+n all these instructions the register must be bet&een 4#6 and 4#@ +f you plan to use these instructions
you should select one of these registers for that operation' +t is shorter and easier to program' "his is an
additional reason &hy you should use the directive to define a register1s name( because you can easier
change the registers location later on( if re)uired'
Pointer-registers
A very special e6tra role is defined for the register pairs 42I$426( 429$428 and 4#$42' "he role is so
important that these pairs have e6tra short names in A34 assembler$ K( 0 and P' "hese short names are
understood by the assembler' "hese pairs are #6!bit pointer registers( able to point to addresses &ith ma6'
#6 bit length( e' g' into 84A2 locations AK( 0 or PB or into locations in program memory APB'
Accessing memory locations with pointers
"he lo&er byte of the #6!bit!address is located in the lo&er register( the higher byte in the upper register'
9oth parts have their o&n names( e'g' the higher byte of P is named P< AV4#B( the lo&er 9yte is P;
AV40B' "hese names are defined &ithin the assembler' Dividing a #6!bit!&ord constant into its t&o
different bytes and &riting these bytes to a pointer register is done li.e follo&s$
.E#$ %ddress = RAME&D ' RAME&D is the highest 16()it %ddress in *RAM, defined in the +def.in, he%der fi-e,
LDI ./,/I0/1%ddress2 ' Lo%d the M*3 of %ddress
LDI .L,LO41%ddress2 ' Lo%d the L*3 of %ddress
Accesses via pointer registers are programmed &ith specially designed instructions' 4ead access is
named ;D A;oaDB( &rite access named 8" A8"oreB( e' g' &ith the K!pointer$
8imilarly you can use 0 and P for that purpose'
Avr!Asm!"utorial 22 http$%%&&&'avr!asm!tutorial'net
Pointer Sequence Examples
K 4ead%*rite from address K( don1t change the pointer ;D 4#(K or 8" K(4#
KG 4ead%*rite from%to address K( and increment the pointer after&ards by
one
;D 4#(KG or 8" KG(4#
!K -irst decrement the pointer by one and read%&rite from%to the ne&
address after&ards
;D 4#(!K or 8" !K(4#
Reading program flash memory with the Z pointer
"here is only one instruction for the read access to the program storage space' +t is defined for the pointer
pair P and it is named ;=2 A;oad from =rogram 2emoryB' "he instruction copies the byte at program flash
address P to the register 40' As the program memory is organi5ed &ord!&ise Aone instruction on one
address consists of #6 bits or t&o bytes or one &ordB the least significant bit selects the lo&er or upper
byte A0Vlo&er byte( #V upper byteB' 9ecause of this the original address must be multiplied by 2 and
access is limited to #H!bit or 2 .9 program memory' ;i.e this$
LDI 5/,/I0/1!+%ddress2
LDI 5L,LO41!+%ddress2
LPM
-ollo&ing this instruction the address must be incremented to point to the ne6t byte in program memory'
As this is used very often a special pointer incrementation instruction has been defined to do this$
ADI4 5L,1
LPM
AD+* means ADd +mmediate *ord and a ma6imum of 6 can be added this &ay' 7ote that the assembler
e6pects the lo&er of the pointer register pair P; as first parameter' "his is some&hat confusing as addition
is done as #6!bit! operation'
"he complement instruction( subtracting a constant value of bet&een 0 and 6 from a #6!bit pointer
register is named 89+*( 8ubtract +mmediate *ord' A8u9tract +mmediate *ordB' AD+* and 89+* are
possible for the pointer register pairs K( 0 and P and for the register pair 42H$42J( that does not have an
e6tra name and does not allo& access to 84A2 or program memory locations' 42H$42J is ideal for
handling #6!bit values'
+n some later types of A34 the automatic incrementation of P follo&ing the ;=2 instruction has an e6tra
instruction( ;=2 PG' =lease consult the instruction list in the data sheet of your A34 type to see if this
applies to the type you are &or.ing &ith'
Tables in the program flash memory
7o& that you .no& ho& to read from flash memory you might &ish to place a list of constants or a string of
te6t to the flash and read these' <o& to insert that table of values in the program memory, "his is done
&ith the assembler directives 'D9 and 'D*' *ith that you can insert byte &ise or &ord &ise lists of values'
9yte &ise organi5ed lists loo. li.e this$
.D3 1!6,75,68,99 ' % -ist of fo:r )ytes, ;ritten in de,i<%- for<
.D3 =>his is % te?t. = ' % -ist of )yte ,h%r%,ters, ;ritten %s te?t
0ou should al&ays place an even number of bytes on each single line' Other&ise the assembler &ill add a
5ero byte at the end( &hich might be un&anted'
"he similar list of &ords loo.s li.e this$
.D4 1!675,6899 ' % -ist of t;o ;ord ,onst%nts
+nstead of constants you can also place labels Ae' g' ?ump targetsB on that list( li.e that$
L%)e-1@
A ... here %re so<e instr:,tions ... B
L%)e-!@
A ... here %re so<e <ore instr:,tions ... B
>%)-e@
.D4 L%)e-1,L%)e-! ' % ;ord ;ise -ist of -%)e-s
;abels should start in column #( but have to be ending &ith a D$S' 7ote that reading the labels from that
table &ith ;=2 Aand subse)uent incrementation of the pointerB first yields the lo&er byte of the &ord( then
the upper byte'
Accessing registers with pointers
A very special application for the pointer registers is the access to the registers themselves' "he registers
are located in the first 2 bytes of the chip1s address space Aat address 060000 to 0600#-B' "his access is
Avr!Asm!"utorial 2 http$%%&&&'avr!asm!tutorial'net
only meaningful if you have to copy the register1s content to 84A2 or //=4O2 or read these values from
there bac. into the registers' 2ore common for the use of pointers is the access to tables &ith fi6ed values
in the program memory space' <ere is( as an e6ample( a table &ith #0 different #6!bit values( &here the
fifth table value is read to 42H$42J$
My>%)-e@
.D4 0?1!67,0?!675,0?6756,0?7569,0?5689 ' >he t%)-e C%-:es, ;ord ;ise
.D4 0?6899,0?899A,0?99A3,0?9A3",0?A3"D ' org%niDed
Re%d5@ LDI 5/,/I0/1My>%)-e+!2 ' %ddress of t%)-e to Eointer 5
LDI 5L,LO41My>%)-e+!2 ' <:-tiE-ied )y ! for )yte;ise %,,ess
ADI4 5L,10 ' Point to fifth C%-:e in t%)-e
LPM ' Re%d -e%st signifi,%nt )yte fro< Erogr%< <e<ory
MO R!7,R0 ' "oEy L*3 to 16()it register
ADI4 5L,1 ' Point to M*3 in Erogr%< <e<ory
LPM ' Re%d M*3 of t%)-e C%-:e
MO R!5,R0 ' "oEy M*3 to 16()it register
"his is only an e6ample' 0ou can calculate the table address in P from some input value( leading to the
respective table values' "ables can be organi5ed byte! or character!&ise( too'
Recommendation for the use of registers
"he follo&ing recommendations( if follo&ed( decide if you are an effective assembler programmer$
Define names for registers &ith the 'D/- directive( never use them &ith their direct name 46'
+f you need pointer access reserve 426 to 4# for that purpose'
A #6!bit!counter is best located in 42H$42J'
+f you need to read from the program memory( e' g' fi6ed tables( reserve P A4#$40B and 40 for that
purpose'
+f you plan to have access to single bits &ithin certain registers Ae' g' for testing flagsB( use 4#6 to
42 for that purpose'
4egisters necessary for math are best placed to 4# to 4#H'
+f you have more than enough registers available( place all your variables in registers'
+f you get short in registers( place as many variables as necessary to 84A2'
Avr!Asm!"utorial 2J http$%%&&&'avr!asm!tutorial'net
Ports
What is a Port?
=orts in the A34 are gates from the central processing unit to internal and e6ternal hard! and soft&are
components' "he C=> communicates &ith these components( reads from them or &rites to them( e' g' to
the timers or the parallel ports' "he most used port is the flag register( &here flags from previous
operations are &ritten to and branching conditions are read from'
"here are 6J different ports( &hich are not physically available in all different A34 types' Depending on the
storage space and other internal hard&are the different ports are either available and accessible or not'
*hich of the ports can be used in a certain A34 type is listed in the data sheets for the processor type'
;arger A"mega and A"Kmega have more than 6J ports( access to the ports beyond M6 is different then
Asee belo&B'
=orts have a fi6ed address( over &hich the C=> communicates' "he address is independent from the type
of A34' 8o e'g' the port address of port 9 is al&ays 06#8 A06 stands for he6adecimal notation( 06#8 is
decimal 2JB' 0ou don1t have to remember these port addresses( they have convenient aliases' "hese
names are defined in the include files Aheader filesB for the different A34 types( that are provided from the
producer' "he include files have a line defining port 91s address as follo&s$
.E#$ POR>3, 0?19
8o &e ?ust have to remember the name of port 9( not its location in the +%O space of the chip' "he include
file 8H#Hdef'inc is involved by the assembler directive
.I&"L$DE ="@F*o<e;hereF9515def.in,=
and the registers of the 8H#H are all defined there and easily accessible'
=orts usually are organi5ed as 8!bit numbers( but can also hold up to 8 single bits that don1t have much to
do &ith each other' +f these single bits have a meaning they have their o&n name associated in the include
file( e' g' to enable the manipulation of a single bit' Due to that name convention you don1t have to
remember these bit positions' "hese names are defined in the data sheets and are given in the include file(
too' "hey are provided here in the port tables'
Write access to ports
As an e6ample the 2C> Feneral Control 4egister( called 2C>C4( consists of a number of single control
bits that control the general property of the chip' <ere are the details of port 2C>C4 in the A"9088H#H(
ta.en from the device data boo.' Other ports loo. similar'
+t is a port( fully pac.ed &ith 8 control bits &ith their o&n names A+8C00( +8C0#( '''B' "hose &ho &ant to
send their A34 to a deep sleep need to .no& from the data sheet ho& to set the respective bits' ;i.e this$
.DEF MyPreferredRegister = R16
LDI MyPreferredRegister, 0)00100000
O$> M"$"R, MyPreferredRegister
*LEEP
"he Out instruction brings the content of my preferred register( a 8leep!/nable!9it called 8/( to the port
2C>C4' 8/ enables the A34 to go to sleep( &henever the 8;//= instruction sho&s up in the code' As
all the other bits of 2C>C4 are also set by the above instructions and the 8leep 2ode bit 82 &as set to
5ero( a mode called half!sleep &ill result$ no further instruction e6ecution &ill be performed but the chip still
reacts to timer and other hard&are interrupts' "hese e6ternal events interrupt the big sleep of the C=> if
they feel they should notify the C=>'
"he above formulation is not very transparent( because D0b00#00000S is not easy to remember( and no
one sees easily &hat bit e6actly has been set to one by this instruction' 8o it is a good idea to formulate
the ;D+ instruction as follo&s$
LDI MyPreferredRegister, 1GG*E
"his formulation tells the assembler to
ta.e a one AD#SB(
to read the bit position of the 8leep /nable bit AD8/SB from the symbol list( as defined in the header
Avr!Asm!"utorial 2H http$%%&&&'avr!asm!tutorial'net
file 8H#Hdef'inc( &hich yields a value of DHS in that case(
to shift ADWWSB the D#S five times left AD#WWHSB( in steps$
#' initial$ 0000'000#(
2' first shift left$ 0000'00#0(
' second shift left$ 0000'0#00( and so on until
J' fifth shift left$ 00#0'0000'
to associate this value to MyPreferredRegister and to insert this ;D+ instruction into the code'
"o ma.e it clear again$ "his shifting is done by the assembler soft&are only( not &ithin the code in the
A34' +t is pure convention to increase the readability of the assembler source te6t'
<o& does this change( if you &ant to set the 8leep 2ode bit AD82SB and the 8leep /nable bit AD8/SB &ithin
the same ;D+ instruction, 82V# and 8/V# enables your A34 to react to a 8;//= instruction by going to a
big sleep( so only do this if you understand &hat the conse)uences are' "he formulation is li.e this$
LDI MyPreferredRegister, 11GG*M2 X 11GG*E2
7o&( the assembler first calculates the value of the first brac.et( A#WW82B( a D#S shifted four times left
Abecause 82 is JB and that yields 000#'0000( then calculates the second brac.et( A#WW8/B( a D#S shifted
five times left Abecause 8/ is HB' "he DXS bet&een the t&o brac.ets means 9+"!O4 the first and the second
value( each bit one by one' "he result of doing this &ith 000#'0000 and 00#0'0000 in that case is
00##'0000( and that is our desired value for the ;D+ instruction' /ven though the formulation
A#WW82B X A#WW8/B
might( on the first loo.( not be more transparent than the resulting value
00##'0000
for a beginner( it is easier to understand &hich bits of 2C>C4 are intended to be manipulated in this ;D+
instruction' /specially if you have to read and understand your code some months later( 82 and 8/ are a
better hint that the 8leep 2ode and /nable bits are targeted here' Other&ise you &ould have to consult the
device1s data boo. much more often'
Read access to ports
4eading a port1s content is in most cases possible using the +7 instruction' "he follo&ing se)uence
.DEF MyPreferredRegister = R16
I& MyPreferredRegister, M"$"R
reads the bits in port 2C>C4 to the register named MyPreferredRegister' As many ports have undefined
and unused bits in certain ports( these bits al&ays read bac. as 5eros'
2ore often than reading all 8 bits of a port one must react to a certain status bit &ithin a port' +n that case
&e don1t need to read the &hole port and isolate the relevant bit' Certain instructions provide an
opportunity to e6ecute instructions depending on the level of a certain bit of a port Asee the J>2= sectionB'
Read-Modify-Write access to ports
8etting or clearing certain bits of a port( &ithout changing the other port bits( is also possible &ithout
reading and &riting the other bits in the port' "he t&o instructions are 89+ A8et 9it +%OB and C9+ AClear 9it +%
OB' /6ecution is li.e this$
.E#$ A,tiCe3it=0 ' >he )it th%t is to )e ,h%nged
*3I Port3, A,tiCe3it ' >he )it HA,tiCe3itI ;i-- )e set to one
"3I Port3, A,tiCe)it ' >he )it HA,tiCe3itI ;i-- )e ,-e%red to Dero
"hese t&o instructions have a limitation$ only ports &ith an address smaller than 0620 can be handled(
ports above cannot be accessed that &ay' 9ecause 2C>C4 in the above e6amples is at he6 address Y8(
the sleep mode and enable bits can1t be set or cleared that &ay' 9ut all the port bits controlling e6ternal
pins A=O4"6( DD46( =+76B are accessible that &ay'
Memory mapped port access
-or the more e6otic programmer and the Delephant!li.eS A"mega and A"Kmega A&here A"2/; ran out of
accessible port addressesB$ the ports can also be accessed using 84A2 access instructions( e'g' 8" and
;D' Just add 0620 to the port1s address Aremember$ the first 2 addresses are associated to the registers@B
and access the port that &ay' ;i.e demonstrated here$
.DEF MyPreferredRegister = R16
LDI 5/,/I0/1POR>3J6!2
LDI 5L,LO41POR>3J6!2
LD MyPreferredRegister,5
Avr!Asm!"utorial 26 http$%%&&&'avr!asm!tutorial'net
"hat only ma.es sense in certain cases( because it re)uires more instructions( e6ecution time and
assembler lines( but it is possible' +t is also the reason &hy the first address location of the 84A2 is 0660
or 06#00 in some larger A34 types'
Details of relevant ports in the AVR
"he follo&ing table holds the most used ports in a DsmallS A"9088H#H' 7ot all ports are listed here( some
of the 2/FA and A"908JJJ%8HH types are s.ipped' +f in doubt see the original reference'
Component Port name Port-Register
Accumulator 84/F 8tatus 4egister
8tac. 8=;%8=< 8tac.pointer
/6ternal 84A2%/6ternal +nterrupt 2C>C4 2C> Feneral Control 4egister
/6ternal +nterrupts F+28E +nterrupt 2as. 4egister
F+-4 +nterrupt -lag 4egister
"imer +nterrupts "+28E "imer +nterrupt 2as. 4egister
"+-4 "imer +nterrupt -lag 4egister
8!bit "imer 0 "CC40 "imer%Counter 0 Control 4egister
"C7"0 "imer%Counter 0
#6!bit "imer # "CC4#A "imer%Counter Control 4egister # A
"CC4#9 "imer%Counter Control 4egister # 9
"C7"# "imer%Counter #
OC4#A Output Compare 4egister # A
OC4#9 Output Compare 4egister # 9
+C4#;%< +nput Capture 4egister
*atchdog "imer *D"C4 *atchdog "imer Control 4egister
//=4O2 Access //A4 //=4O2 address 4egister
//D4 //=4O2 Data 4egister
//C4 //=4O2 Control 4egister
8erial =eripheral +nterface 8=+ 8=C4 8erial =eripheral Control 4egister
8=84 8erial =eripheral 8tatus 4egister
8=D4 8erial =eripheral Data 4egister
8erial Communication >A4" >D4 >A4" Data 4egister
>84 >A4" 8tatus 4egister
>C4 >A4" Control 4egister
>944 >A4" 9aud 4ate 4egister
Analog Comparator AC84 Analog Comparator Control and 8tatus 4egister
+%O!=orts =O4"6 =ort Output 4egister
DD46 =ort Direction 4egister
=+76 =ort +nput 4egister
The status register as the most used port
9y far the most often used port is the status register &ith its 8 bits' >sually access to this port is only by
automatic setting and clearing bits by the C=> or accumulator( some access is by reading or branching on
certain bits in that port( in a fe& cases it is possible to manipulate these bits directly Ausing the assembler
instructions 8/6 or C;6( &here 6 is the bit abbreviationB' 2ost of these bits are set or cleared by the
accumulator through bit!test( compare! or calculation!operations'
"he most used bits are$
P$ +f set to one( the previous instruction yielded a 5ero result'
C$ +f set to one( the previous instruction caused a carry of the most significant bit'
"he follo&ing list has all assembler instructions that set or clear status bits depending on the result of the
previous instruction e6ecution'
Avr!Asm!"utorial 2I http$%%&&&'avr!asm!tutorial'net
Bit Calculation Logic Compare Bits Shift Other
P ADD( ADC( AD+*( D/C(
+7C( 8>9( 8>9+( 89C(
89C+( 89+*
A7D( A7D+( O4(
O4+( /O4( CO2(
7/F( 894( C94
C=( C=C(
C=+
9C;4 P(
98/" P( C;P(
8/P( "8"
A84( ;8;(
;84( 4O;(
4O4
C;4
C ADD( ADC( AD+*( 8>9(
8>9+( 89C( 89C+( 89+*
CO2( 7/F C=( C=C(
C=+
9C;4 C(
98/" C(
C;C( 8/C
A84( ;8;(
;84( 4O;(
4O4
!
7 ADD( ADC( AD+*( D/C(
+7C( 8>9( 8>9+( 89C(
89C+( 89+*
A7D( A7D+( O4(
O4+( /O4( CO2(
7/F( 894( C94
C=( C=C(
C=+
9C;4 7(
98/" 7(
C;7( 8/7(
"8"
A84( ;8;(
;84( 4O;(
4O4
C;4
3 ADD( ADC( AD+*( D/C(
+7C( 8>9( 8>9+( 89C(
89C+( 89+*
A7D( A7D+( O4(
O4+( /O4( CO2(
7/F( 894( C94
C=( C=C(
C=+
9C;4 3(
98/" 3( C;3(
8/3( "8"
A84( ;8;(
;84( 4O;(
4O4
C;4
8 89+* ! ! 9C;4 8(
98/" 8( C;8(
8/8
! !
< ADD( ADC( 8>9( 8>9+(
89C( 89C+
7/F C=( C=C(
C=+
9C;4 <(
98/" <(
C;<( 8/<
! !
" ! ! ! 9C;4 "(
98/" "( 98"(
C;"( 8/"
! !
+ ! ! ! 9C;4 +( 98/"
+( C;+( 8/+
! 4/"+
Port details
=ort details of the most common ports are sho&n in an e6tra table Asee anne6B'
Avr!Asm!"utorial 28 http$%%&&&'avr!asm!tutorial'net
SRAM
Using SRAM in AVR assembler language
7early all A34!types have static 4A2 A84A2B on board Aonly very fe& old devices don1tB' Only very
simple assembler programs can avoid using this memory space by putting all necessary information into
registers' +f you run out of registers you should be able to program the 84A2 to utili5e more space'
What is SRAM?
84A2 are memories that are not directly accessible by the central processing unit AArithmetic and ;ogical
>nit A;>( sometimes called
accumulatorB li.e the registers
are' +f you access these
memory locations you usually
use a register as interim
storage' +n the e6ample
displayed here a value in
84A2 &ill be copied to the
register 42 A#st instructionB( a
calculation &ith the value in 4
is made and the result is
&ritten to 4 Asecond
instructionB' After that this value
is &ritten bac. to the same
84A2 location Ainstruction (
not sho&n hereB'
8o it is clear that operations &ith values stored in the 84A2 are slo&er to perform than those using
registers alone' On the other hand$ even the smallest A34 types have #28 bytes of 84A2 available( much
more than the 2 registers can hold'
"he types from the old A"9088H#H up&ards offer the additional opportunity to connect additional e6ternal
4A2( e6panding the internal H#2 bytes' -rom the assembler point!of!vie&( e6ternal 84A2 is accessed li.e
internal 84A2' 7o e6tra instructions must be learned for accessing that e6ternal 84A2'
For what purposes can I use SRAM?
9esides simple storage of values( 84A2 offers additional opportunities for its use' 7ot only access &ith
fi6ed addresses is possible( but also the use of pointers( so that floating access to subse)uent locations in
84A2 can be programmed' "his &ay you can build up ring buffers for interim storage of values or
calculated AvariableB tables' "his is not very often used &ith registers( because they are too fe& and prefer
fi6ed access'
/ven more relative is the access using an offset to a fi6ed starting address in one of the pointer registers'
+n that case a fi6ed address is stored in a pointer register( a constant value is added to this address and
read%&rite access is made to that address &ith an offset' *ith that .ind of access( tables are very more
effective'
9ut the most relevant use for 84A2 is the so!called stac.' 0ou can push values AvariablesB to that stac.'
9e it the content of a register( that is temporarily needed for another purpose' 9e it a return address prior to
calling a subroutine( or the return address prior to a hard&are!triggered interrupt'
How to use SRAM?
Direct addressing
"o copy a value to a memory location in 84A2 you have to define the address' "he 84A2 addresses you
can use reach from the start address Avery often 060060 in smaller A34s( 060#00 in larger A"megaB to the
end of the physical 84A2 on the chip Ain the A"9088H#H the highest accessible internal 84A2 location is
0602H-( see the device data sheet of your A34 type for more details on thisB'
*ith the instruction
*>* 0?0060, R1
the content of register 4# is copied to the first 84A2 location in address 060060' *ith
LD* R1, 0?0060
the 84A2 content at address 060060 is copied to the register' "his is the direct access &ith an address
Avr!Asm!"utorial 29 http$%%&&&'avr!asm!tutorial'net
that has to be defined by the programmer'
"he symbols defined in the Odef'inc include file( 84A2Q8"A4" and 4A2/7D( allo& to place your
variables &ithin the 84A2 space' 8o it is better to use these definitions to access the #H
th
memory byte(
li.e this$
LD* R1,*RAMK*>AR>J15
8ymbolic names can be used to avoid handling fi6ed addresses( that re)uire a lot of &or.( if you later &ant
to change the structure of your data in the 84A2' "hese names are easier to handle than he6 numbers( so
give that address a name li.e$
.E#$ MyPreferred*tor%ge"e-- = *RAMK*>AR>
*>* MyPreferred*tor%ge"e--, R1
0es( it isn1t shorter( but easier to remember' >se &hatever name that you find to be convenient'
Pointer addressing
Another .ind of access to 84A2 is the use of pointers' 0ou need t&o registers for that purpose( that hold
the #6!bit address of the location' As &e learned in the =ointer!4egister!Division( pointer registers are the
register pairs K AK<$K;( 42I$426B( 0 A0<$0;( 429$428B and P AP<$P;( 4#$40B' "hey allo& access to the
location they point to directly Ae' g' &ith 8" K( 4#B( after prior decrementing the address by one Ae' g' 8"
!K( 4#B or &ith subse)uent auto!incrementation of the address Ae' g' 8" KG( 4#B' A complete access to
three cells in a ro& loo.s li.e this$
.E#$ MyPreferred*tor%ge"e-- = *RAMK*>AR>
.DEF MyPreferredRegister = R1
.DEF AnotherRegister = R!
.DEF And.etAnotherRegister = R6
LDI L/, /I0/1MyPreferred*tor%ge"e--2
LDI LL, LO41MyPreferred*tor%ge"e--2
LD MyPreferredRegister, LJ
LD AnotherRegister, LJ
LD And.etAnotherRegister, L
/asy to operate( those pointers' And as easy as in other languages than assembler( that claim to be easier
to learn'
Pointer with offset
"he third construction is a little bit more e6otic and only e6perienced programmers use this in certain
cases' ;et1s assume &e very often in our program need to access three consecutive 84A2 locations' ;et1s
further assume that &e have a spare pointer register pair( so &e can afford to use it e6clusively for our
purpose' +f &e &ould use the 8"%;D instructions &e al&ays have to change the pointer if &e access
another location of the three' 7ot very convenient'
"o avoid this( and to confuse the beginner( the access &ith offset &as invented' During that access the
register value isn1t changed' "he address is calculated by temporarily adding the fi6ed offset' +n the above
e6ample the access to location 060062 &ould loo. li.e this' -irst( the pointer register is set to our central
location 84A2Q8"A4"$
.E#$ MyPreferred*tor%ge"e-- = *RAMK*>AR>
.DEF MyPreferredRegister = R1
LDI ./, /I0/1MyPreferred*tor%ge"e--2
LDI .L, LO41MyPreferred*tor%ge"e--2
8ome&here later in the program +1d li.e to &rite to cell 2 above 84A2Q8"A4"$
*>D .J!, MyPreferredRegister
"he corresponding instruction for reading from 84A2 &ith an offset
LDD MyPreferredRegister, .J!
is also possible'
7ote that the 2 is not really added to 0( ?ust temporarily during the e6ecution of this instruction' "o confuse
you further( this can only be done &ith the 0! and P!register!pair( not &ith the K!pointer@
Of about #00 cases( the use of this opportunity is more effective in one single case' 8o don1t care if you
don1t understand this in detail' +t is only for e6perts( and only necessary in a fe& cases'
"hat1s it &ith the 84A2( but &ait$ the most relevant use as stac. is still to be learned'
Use of SRAM as stack
"he most common use of 84A2 is its use as stac.' "he stac. is a to&er of &ooden bloc.s' /ach
Avr!Asm!"utorial 0 http$%%&&&'avr!asm!tutorial'net
additional bloc. goes onto the top of the to&er( each recall of a value removes the most upper bloc. from
the to&er' 4emoval of bloc.s from the base or from any lo&er portion of the to&er is too complicated and
confuses your &hole to&er( so never try this' "his structure is called ;ast!+n!-irst!Out A;+-OB or easier$ the
last to go on top &ill be the first coming do&n from the top'
Defining SRAM as stack
"o use 84A2 as stac. re)uires the setting of the stac. pointer first' "he stac. pointer is a #6!bit!pointer(
accessible li.e a port' "he double register is named 8=<$8=;' 8=< holds the most significant address
byte( 8=; the least significant' "his is only true( if the A34 type has more than 2H6 byte 84A2' +f not( 8=<
is not necessary( is undefined( and must not and cannot be used' *e assume &e have more than 2H6
bytes 84A2 in the follo&ing e6amples'
"o construct the stac.( the stac. pointer is loaded &ith the highest available 84A2 address' A+n our case
the to&er gro&s do&n&ards( to&ards lo&er addresses( ?ust for historic reasons and to confuse the
beginner@B'
.DEF MyPreferredRegister = R16
LDI MyPreferredRegister, /I0/1RAME&D2 ' $EEer )yte
O$> *P/,MyPreferredRegister ' to st%,M Eointer
LDI MyPreferredRegister, LO41RAME&D2 ' Lo;er )yte
O$> *PL,MyPreferredRegister ' to st%,M Eointer
"he value 4A2/7D is( of course( specific for the processor type' +t is defined in the +7C;>D/ file for the
processor type' "he file 8H#Hdef'inc has the line$
.eN: RAME&D =O!5F ' L%st On("hiE *RAM Lo,%tion
"he file 8H#Hdef'inc is included &ith the assembler directive
.I&"L$DE ="@Fso<e;hereF9515def.in,=
at the beginning of our assembler source code'
8o &e defined the stac. no&( and &e don1t have to care about the stac. pointer any more( because
manipulations of that pointer are mostly automatic'
Use of the stack
>sing the stac. is easy' "he content of registers are pushed onto the stac. li.e this$
P$*/ MyPreferredRegister ' >hro; th%t C%-:e on toE of the st%,M
*here that value goes to is totally uninteresting' "hat the stac. pointer &as decremented after that push(
&e don1t have to care' +f &e need the content again( &e ?ust add the follo&ing instruction$
POP MyPreferredRegister ' Re%d )%,M the C%-:e fro< the toE of the st%,M
*ith =O= &e ?ust get the value that &as last pushed on top of the stac.' =ushing and popping registers
ma.es sense( if
the content is again needed some lines of the code later(
all registers are in use( and if
no other opportunity e6ists to store that value some&here else'
+f these conditions are not given( the use of the stac. for saving registers is useless and ?ust &astes
processor time'
2ore sense ma.es the use of the stac. in subroutines( &here you have to return to the program location
that called the routine' +n that case the calling program code pushes the return address Athe current
program counter valueB onto the stac. and temporarily ?umps to the subroutine' After its e6ecution the
subroutine pops the return address from the stac. and loads it bac. into the program counter' =rogram
e6ecution is continued e6actly one instruction behind the instruction( &here the call happened$
R"ALL *o<e;h%t ' P:<E to the -%)e- Hso<e;h%t@I
A...B here ;e ;i-- -%ter ,ontin:e ;ith the Erogr%<.
<ere the ?ump to the label Dsome&hat$S some&here in the program code(
*o<e;h%t@ ' this is the Q:<E %ddress
A...B /ere ;e do so<ething
A...B %nd ;e %re finished %nd ;%nt to Q:<E )%,M to the ,%--ing -o,%tion@
RE>
During e6ecution of the 4CA;; instruction the already incremented program counter( a #6!bit!address( is
pushed onto the stac.( using t&o pushes Athe ;89 and the 289B' 9y reaching the 4/" instruction( the
content of the previous program counter is reloaded &ith t&o pops and e6ecution continues there'
0ou don1t need to care about the address of the stac.( &here the counter is loaded to' "his address is
Avr!Asm!"utorial # http$%%&&&'avr!asm!tutorial'net
automatically generated' /ven if you call a subroutine &ithin that subroutine the stac. function is fine' "his
?ust pac.s t&o return addresses on top of the stac.( the nested subroutine removes the first one( the
calling subroutine the remaining one' As long as there is enough 84A2( everything is fine'
8ervicing hard&are interrupts isn1t possible &ithout the stac.' +nterrupts stop the normal e6ecution of the
program( &herever the program currently is' After e6ecution of a specific service routine as a reaction to
that interrupt program e6ecution must return to the previous location( to before the interrupt occurred' "his
&ould not be possible if the stac. is not able to store the return address'
"he enormous advances of having a stac. for interrupts are the reason( &hy even the smallest A34s
&ithout having 84A2 have at least a very small hard&are stac.'
Bugs with the stack operation
-or the beginner there are a lot of possible bugs( if you first learn to use stac.'
3ery clever is the use of the stac. &ithout first setting the stac. pointer' 9ecause this pointer is set to 5ero
at program start( the pointer points to the location 060000( &here register 40 is located' =ushing a byte
results in a &rite to that register( over&riting its previous content' An additional push to the stac. &rites to
06----( an undefined position Aif you don1t have e6ternal 84A2 thereB' A 4CA;; and 4/" &ill return to a
strange address in program memory' 9e sure$ there is no &arning( li.e a &indo& popping up saying
something li.e C+llegal access to memory location 6666D'
Another opportunity to construct bugs is to forget to pop a previously pushed value( or popping a value
&ithout pushing one first'
+n a very fe& cases the stac. overflo&s to belo& the first 84A2 location' "his happens in case of a never!
ending recursive call' After reaching the lo&est 84A2 location the ne6t pushes &rite to the ports A0600H-
do&n to 060020B( then to the registers A0600#- to 060000B' -unny and unpredictable things happen &ith
the chip hard&are( if this goes on' Avoid this bug( it can even destroy your e6ternal hard&are@
Avr!Asm!"utorial 2 http$%%&&&'avr!asm!tutorial'net
Jumping and Branching
<ere &e discuss all instructions that control the se)uential e6ecution of a program' +t starts &ith the starting
se)uence on po&er!up of the processor( continues &ith ?umps( interrupts( etc'
Controlling sequential execution of the program
What happens during a reset?
*hen the po&er supply voltage of an A34 rises and the processor starts its &or.( the hard&are triggers a
reset se)uence' "he ports are set to their initial values( as defined in the device data sheet' "he counter
for the program steps &ill be set to 5ero' At this address the e6ecution al&ays starts' <ere &e have to have
our first &ord of code' 9ut not only during po&er!up this address is activated$
During an e6ternal reset on the reset pin of the device a restart is e6ecuted'
+f the *atchdog counter reaches its ma6imum count( a reset is initiated' A &atchdog timer is an
internal cloc. that must be reseted from time to time by the program( other&ise it restarts the
processor'
0ou can call reset by a direct ?ump to that address Asee the ?ump section belo&B'
"he third case is not a real reset( because the automatic resetting of register! and port!values to a &ell!
defined default value is not e6ecuted' 8o( forget that for no&'
"he second option( the &atchdog reset( must first be enabled by the program' +t is disabled by default'
/nabling re)uires &rite instructions to the &atchdog1s port' 8etting the &atchdog counter bac. to 5ero
re)uires the e6ecution of the instruction
4DR
to avoid a reset'
After e6ecution of a reset( &ith setting registers and ports to default values( the code at address 0000 is
&ord &ise read to the e6ecution part of the processor and is e6ecuted' During that e6ecution the program
counter is already incremented by one and the ne6t &ord of code is already read to the code fetch buffer
A-etch during /6ecutionB' +f the e6ecuted instruction does not re)uire a ?ump to another location in the
program the ne6t instruction is e6ecuted immediately' "hat is &hy the A34s e6ecute e6tremely fast( each
cloc. cycle e6ecutes one instruction Aif no ?umps occurB'
"he first instruction of an e6ecutable is al&ays located at address 0000' "o tell the compiler Aassembler
programB that our source code starts no& and here( a special directive can be placed at the beginning(
before the first code in the source is &ritten$
."*E0
.OR0 0000
"he first directive( 'C8/F( lets the compiler s&itch his output to the code section' All follo&ing is translated
as code and is later &ritten to the program flash memory section of the processor' Another target segment
&ould be the //=4O2 section of the chip( &here you also can &rite bytes or &ords to'
.E*E0
"he third segment is the 84A2 section of the chip'
.D*E0
Other than &ith //=4O2 content( &here content is really going to the //=4O2 during programming of
the chip( the D8/F segment content is not programmed to the chip' "here is no opportunity to burn any
84A2 content' 8o the 'D8/F is only used for correct label calculation during the assembly process' An
e6ample$
.D*E0 ' >he fo--o;ing %re -%)e- definitions ;ithin the *RAM seg<ent
MyFirst%ri%)-eIsA3yte@
.3.>E 1 ' the D*E0(Pointer <oCes one )yte :E;%rds
My*e,ond%ri%)-eIsA4ord@
.3.>E ! ' the D*E0(Pointer <oCes t;o )ytes :E;%rds
My>hird%ri%)-eIsAFie-dForA3:ffer@
.3.>E 6!' the D*E0(Pointer <oCes 6! )ytes :E;%rds
8o( only three labels are defined &ithin the assembler( no content is produced'
"he O4F directive &ithin the code segment( 'O4F( above stands for the &ord DoriginS and manipulates the
address &ithin the code segment( &here assembled &ords go to' As our program al&ays starts at 060000
the C8/F%O4F directives are trivial( you can s.ip these &ithout getting into an error' *e could start at
060#00( but that ma.es no real sense as the processor starts e6ecution at 0000' +f you &ant to place a
table e6actly to a certain location of the code segment( you can use O4F' 9ut be careful &ith that$ Only
?ump for&ard &ith 'O4F( never bac.&ards' And be a&are that the flash memory space that you s.ipped in
Avr!Asm!"utorial http$%%&&&'avr!asm!tutorial'net
bet&een your current code location and the one you forced &ith 'O4F is al&ays filled &ith the instruction
&ord 06----' "his instruction does nothing( ?ust goes to the ne6t instruction' 8o be sure your e6ecution
never ?umps into such undefined space in bet&een'
+f on the beginning of your code section you &ant to set a clear sign &ithin your code( after first defining a
lot of other things &ith 'D/-! and '/L>!directives( use the C8/F%O4F se)uence as a signal for yourself(
even though it might not be necessary to do that'
As the first code &ord is al&ays at address 5ero( this location is also called the reset vector' -ollo&ing the
reset vector the ne6t positions in the program space( addresses 06000#( 060002 etc'( are interrupt vectors'
"hese are the positions &here the e6ecution ?umps to if an e6ternal or internal interrupt has been enabled
and occurs' "hese positions called vectors are specific for each processor type and depend on the internal
hard&are available Asee belo&B' "he instructions to react to such an interrupt have to be placed to the
proper vector location' +f you use interrupts( the first code( at the reset vector( must be a ?ump instruction(
to ?ump over the other vectors' /ach interrupt vector( that is planned to be enabled( must hold a ?ump
instruction to the respective interrupt service routine' +f the vector is not used( a dummy instruction li.e
4/"+ A4/"urn from +nterruptB is best placed here' "he typical program se)uence at the beginning is li.e
follo&s$
."*E0
.OR0 0000
RPMP *t%rt ' the reset Ce,tor
RPMP Int*erCRo:t1 ' the interr:Et serCi,e ro:tine for the first interr:Et
RE>I ' % d:<<y for %n :n:sed interr:Et
RPMP Int*erCRo:t6 ' the interr:Et serCi,e ro:tine for the third interr:Et
A...B here ;e E-%,e %-- the other interr:Et Ce,tor instr:,tions
A...B %nd here is % good E-%,e for the interr:Et serCi,e ro:tines the<se-Ces
Int*erCRo:t1@
A...B "ode of the first int serCi,e ro:tine
RE>I ' end of serCi,e ro:tine 1
Int*erCRo:t!@
A...B "ode of the third int serCi,e ro:tine
RE>I ' end of serCi,e ro:tine !
A...B other ,ode
*t%rt@ ' >his here is the Erogr%< st%rt
A...B /ere ;e E-%,e o:r <%in Erogr%<
"he instruction D4J2= 8tartS results in a ?ump to the label 8tart$( located some lines belo&' 4emember(
labels al&ays end &ith a D$S' ;abels( that don1t fulfill these conditions are not ta.en for serious( but
interpreted as instructions' 2issing labels result in an error message AZ>ndefined labelZB( and compilation
is interrupted'
Linear program execution and branches
=rogram e6ecution is al&ays linear( if nothing changes the se)uential e6ecution' "hese changes are the
e6ecution of an interrupt or of branching instructions'
Branching
9ranching is very often depending on some condition( called conditional branching' As an e6ample &e
assume &e &ant to construct a 2!bit!counter using the registers 4# to 4J' "he least significant byte in 4#
is incremented by one' +f the register overflo&s during that operation A2HH G # V 0B( &e have to increment
42 similarly' +f 42 overflo&s( &e have to increment 4( and so on'
+ncrementation by one is done &ith the instruction +7C' +f an overflo& occurs during that e6ecution of
+7C 4#( the 5ero bit in the status register is set to one Athe result of the operation is 5eroB' "he carry bit in
the status register( as usually set &hen something overflo&s( is not changed during an +7C' "his is not to
confuse the beginner( but carry can be used for other purposes instead' "he Pero!9it or Pero!flag in this
case is enough to detect an overflo&' +f no overflo& occurs &e can ?ust leave the counting se)uence'
+f the Pero!bit is set( &e must e6ecute additional incrementation of the ne6t upper register' "o confuse the
beginner the branching instruction( that &e have to use( is not named 947P but 947/ A94anch if 7ot
/)ualB' A matter of taste '''
"he &hole count se)uence of the 2!bit!counter should then loo. li.e this$
I&" R1 ' in,re%se ,ontent of register R1
3R&E 0oOn6! ' if not Dero, )r%n,h to 0oOn6!@
I&" R! ' in,re%se ,ontent of register R!
3R&E 0oOn6!
I&" R6
3R&E 0oOn6!
I&" R7
0oOn6!@
8o that1s about it' An easy thing' "he opposite condition to 947/ is 94/L or 94anch /Lual'
Avr!Asm!"utorial J http$%%&&&'avr!asm!tutorial'net
*hich of the status bits( also called processor flags( are changed during e6ecution of an instruction is
listed in instruction code tables( see the ;ist of +nstructions' 8imilarly to the Pero!bit you can use the other
status bits li.e that$
3R"" -%)e-R3R"* -%)e-' "%rry(f-%g 0 13R""2 or 1 13R"*2
3R*/ -%)e-' EN:%- or gre%ter
3RLO -%)e-' *<%--er
3RMI -%)e-' Min:s
3RPL -%)e-' P-:s
3R0E -%)e-' 0re%ter or eN:%- 1;ith sign )it2
3RL> -%)e-' *<%--er 1;ith sign )it2
3R/" -%)e-R3R/* -%)e-' /%-f oCerf-o; f-%g 0 or 1
3R>" -%)e-R3R>* -%)e-' >(3it 0 or 1
3R" -%)e-R3R* -%)e-' >;oSs ,o<E-e<ent f-%g 0 or 1
3RIE -%)e-R3RID -%)e-' Interr:Et en%)-ed or dis%)-ed
to react to the different conditions' 9ranching al&ays occurs if the condition is met' Don1t be afraid( most of
these instructions are rarely used' -or the beginner only Pero and Carry are relevant'
Timing during program execution
;i.e mentioned above the re)uired time to e6ecute one instruction is e)ual to the processor1s cloc. cycle'
+f the processor runs on a J 2<5 cloc. fre)uency then one instruction re)uires #%J [s or 2H0 ns( at #0 2<5
cloc. only #00 ns' "he re)uired time is as e6act as the internal or e6ternal or 6tal cloc. is' +f you need
e6act timing an A34 is the optimal solution for your problem' 7ote that there are a fe& instructions that
re)uire t&o or more cycles( e' g' the branching instructions Aif branching occursB or the 84A2 read%&rite
se)uence' 8ee the instruction table for details'
"o define e6act timing there must be an opportunity that does nothing else than delay program e6ecution'
0ou might use other instructions that do nothing( but more clever is the use of the no!operation instruction
7O=' "his is the most useless instruction$
&OP
"his instruction does nothing but &asting processor time' At J 2<5 cloc. &e need ?ust four of these
instructions to &aste # [s' 7o other hidden meanings here on the 7O= instruction' -or a signal generator
&ith # .<5 &e don1t need to add J000 such instructions to our source code( but &e use a soft&are counter
and some branching instructions' *ith these &e construct a loop that e6ecutes for a certain number of
times and are e6actly delayed' A counter could be a 8!bit!register that is decremented &ith the D/C
instruction( e' g' li.e this$
"LR R1 ' one ,-o,M ,y,-e
"o:nt@
DE" R1 ' one ,-o,M ,y,-e
3R&E "o:nt ' t;o for )r%n,hing, one for not )r%n,hing
"his se)uence &astes A#B G A2HHO2B G A#OB V H#J cloc. cycles or #28'H [s at J 2<5'
#6!bit counting can also be used to delay e6actly( li.e this
LDI 5/,/I0/1655652 ' one ,-o,M ,y,-e
LDI 5L,LO41655652 ' one ,-o,M ,y,-e
"o:nt@
*3I4 5L,1 ' t;o ,-o,M ,y,-es
3R&E "o:nt ' t;o for )r%n,hing, one for not )r%n,hing
"his se)uence &astes A#G#B G A6HHJOJB G A#OB V 262(#J# cloc. cycles or 6H(HH'2H [s at J 2<5'
+f you use more registers to construct nested counters you can reach any delay' And the delay is as e6act
as your cloc. source is( even &ithout a hard&are timer'
Macros and program execution
3ery often you have to &rite identical or similar code se)uences on different occasions in your source
code' +f you don1t &ant to &rite it once and ?ump to it via a subroutine call you can use a macro to avoid
getting tired &riting the same se)uence several times' 2acros are code se)uences( designed and tested
once( and inserted into the code by its macro name' As an e6ample &e assume &e need to delay program
e6ecution several times by # [s at J 2<5 cloc.' "hen &e define a macro some&here in the source$
.MA"RO De-%y1
&OP
&OP
&OP
&OP
.E&DMA"RO
"his definition of the macro does not yet produce any code( it is silent' Code is produced only if you call
that macro by its name$
Avr!Asm!"utorial H http$%%&&&'avr!asm!tutorial'net
A...B so<e;here in the so:r,e ,ode
De-%y1
A...B ,ode goes on here
"his results in four 7O= instructions inserted to the code at that location' An additional DDelay#S inserts
additional four 7O= instructions'
+f your macro has longer code se)uences( or if you are short in code storage space( you should avoid the
use of macros and use subroutines instead'
9y calling a macro by its name you can add some parameters to manipulate the produced code' 9ut this is
more than a beginner has to .no& about macros'
Subroutines
+n contrary to macros a subroutine does save program storage space' "he respective se)uence is only
once stored in the code and is called from &hatever part of the code' "o ensure continued e6ecution of the
se)uence follo&ing the subroutine call you need to return to the caller' -or a delay of #0 cycles you need
to &rite this subroutine$
De-%y10@ ' the ,%-- of the s:)ro:tine reN:ires so<e ,y,-es
&OP ' de-%y one ,y,-e
&OP ' de-%y one ,y,-e
&OP ' de-%y one ,y,-e
RE> ' ret:rn to the ,%--er
8ubroutines al&ays start &ith a label( other&ise you &ould not be able to ?ump to it( here named
DDelay#0$S' "hree 7O=s follo& and a 4/" instruction' +f you count the necessary cycles you ?ust find I
cycles A for the 7O=s( J for the 4/"B' "he missing are for calling that routine$
A...B so<e;here in the so:r,e ,ode@
R"ALL De-%y10
A...B f:rther on ;ith the so:r,e ,ode
4CA;; is a relative call' "he call is coded as relative ?ump( the relative distance from the calling routine to
the subroutine is calculated by the compiler' "he 4/" instruction ?umps bac. to the calling routine' 7ote
that before you use subroutine calls you must set the stac. pointer Asee 8tac.B( because the return
address must be pac.ed on top of the stac. during the 4CA;; instruction'
+f you &ant to ?ump directly to some&here else in the code you have to use the ?ump instruction$
A...B so<e;here in the so:r,e ,ode
RPMP De-%y10
Ret:rn@
A...B f:rther on ;ith so:r,e ,ode
7ote that 4J2= is also a relative ?ump instruction &ith limited distance' Only A"mega A34s have a J2=
instruction allo&ing ?umps over the complete flash memory space( but these instructions re)uire t&o &ords
and more instruction time than 4J2=( so avoid it if possible'
"he routine that you ?umped to can not use the 4/" instruction in that case( because 4J2= does not
place the current e6ecution address to the stac.' "o return bac. to the calling location in the source
re)uires to add another label and the called routine to ?ump bac. to this label' Jumping li.e this is not li.e
calling a subroutine because you can1t call this routine from different locations in the code'
4CA;; and 4J2= are unconditioned branches' "o ?ump to another location( depending on some
condition( you have to combine these &ith branching instructions' Conditioned calling of a subroutine can
best be done &ith the follo&ing AconfusingB instructions' +f you &ant to call a subroutine depending on a
certain bit in a register use the follo&ing se)uence$
*3R" R1,8 ' *MiE the ne?t instr:,tion if )it 8 in register 1 is 0
R"ALL $EL%)e- ' "%-- th%t s:)ro:tine
894C reads C8.ip ne6t instruction if 9it I in 4egister 4# is Clear AVPeroBD' "he 4CA;; instruction to
D>p;abel$S is only e6ecuted if bit I in register 4# is #( because the ne6t instruction is s.ipped if it &ould be
0' +f you li.e to call the subroutine in case this bit is 0 then you use the corresponding instruction 8948'
"he instruction follo&ing 8948%894C can be a single &ord or double &ord instruction( the processor
.no&s ho& far he has to ?ump over it' 7ote that e6ecution times are different then' "o ?ump over more than
one follo&ing instruction these instructions cannot be used'
+f you have to s.ip an instruction in case t&o registers have the same value you can use the follo&ing
e6otic instruction$
"P*E R1,R! ' "o<E%re R1 %nd R!, sMiE ne?t instr:,tion if eN:%-
R"ALL *o<e*:)ro:tine ' "%-- *o<e*:)ro:tine
A rarely used instruction( forget it for the beginning' +f you li.e to s.ip the follo&ing instruction depending
on a certain bit in a port use the follo&ing instructions 89+C and 89+8' "hat reads D8.ip if the 9it in +%o
space is Clear Aor 8etBS( li.e this$
Avr!Asm!"utorial 6 http$%%&&&'avr!asm!tutorial'net
*3I" PI&3,0 ' *MiE ne?t instr:,tion if 3it 0 on inE:t Eort 3 is 0
RPMP A>%rget ' P:<E to the -%)e- A>%rget
"he 4J2=!instruction is only e6ecuted if bit 0 in port 9 is high' "his is something confusing for the
beginner' "he access to the port bits is limited to the lo&er half of ports( the upper 2 ports are not usable
here'
7o&( another e6otic application for the e6pert' 8.ip this if you are a beginner' Assume &e have a bit s&itch
&ith J s&itches connected to port 9' Depending on the state of these J bits &e &ould li.e to ?ump to #6
different locations in the code' 7o& &e can read the port and use several branching instructions to find out(
&here &e have to ?ump to today' As alternative you can &rite a table holding the #6 addresses( li.e this$
My>%)@
RPMP Ro:tine1
RPMP Ro:tine!
A...B
RPMP Ro:tine16
+n our code &e copy that address of the table to the P pointer register$
LDI 5/,/I0/1My>%)2
LDI 5L,LO41My>%)2
and add the current state of the port 9 Ain 4#6B to this address'
ADD 5L,R16
3R"" &oOCerf-o;
I&" 5/
&oOCerf-o;@
7o& &e can ?ump to this location in the table( either for calling a subroutine$
I"ALL ' ,%-- the s:)ro:tine ;hi,h %ddress is in 5
or as a ?ump &ith no &ay bac.$
IPMP ' Q:<E to %ddress in 5
"he processor loads the content of the P register pair into its program counter and continues operation
there' 2ore clever than branching over and over,
Interrupts and program execution
3ery often &e have to react on hard&are conditions or other events' An e6ample is a change on an input
pin' 0ou can program such a reaction by &riting a loop( as.ing &hether a change on the pin has occurred'
"his method is called polling( its li.e a bee running around in circles searching for ne& flo&ers' +f there are
no other things to do and reaction time does not matter( you can do this &ith the processor' +f you have to
detect short pulses of less than a [s duration this method is useless' +n that case you need to program an
interrupt'
An interrupt is triggered by some hard&are conditions' All hard&are interrupts are disabled at reset time by
default( so the condition has to be enabled first' "he respective port bits enabling the component1s interrupt
ability are set first' "he processor has a bit in its status register enabling him to respond to the interrupt of
all components( the +nterrupt /nable -lag' /nabling the general response to interrupts re)uires the
follo&ing instruction$
*EI ' *et Int En%)-e 3it
/ach single interrupt re)uires additional port manipulation to be enabled'
+f the interrupting condition occurs( e' g' a change on the port bit( the processor pushes the actual program
counter to the stac. A&hich must be enabled first@ 8ee initiation of the stac.pointer in the 8tac. section of
the 84A2 descriptionB' *ithout that( the processor &ouldn1t be able to return bac. to the location( &here
the interrupt occurred A&hich could be any time and any&here &ithin program e6ecutionB' After that(
processing ?umps to the predefined location( the interrupt vector( and e6ecutes the instructions there'
>sually the instruction there is a J>2= instruction to the interrupt service routine( located some&here in
the code' "he interrupt vector is a processor!specific location and depending from the hard&are
component and the condition that leads to the interrupt' "he more hard&are components and the more
conditions( the more vectors' "he different vectors for some older A34 types are listed in the follo&ing
table' A"he first vector isn1t an interrupt but the reset vector( performing no stac. operation@B
Name Interrupt Vector !!ress
"#$# "#"# %&$&
'riggere! ()
4/8/" 0000 0000 0000 <ard&are 4eset( =o&er!On!4eset( *atchdog 4eset
+7"0 000# 000# 000# ;evel change on the e6ternal +7"0 pin
+7"# 0002 ! 0002 ;evel change on the e6ternal +7"# pin
Avr!Asm!"utorial I http$%%&&&'avr!asm!tutorial'net
Name Interrupt Vector !!ress
"#$# "#"# %&$&
'riggere! ()
"+2/4#CA=" 000 ! 000 Capture event on "imer%Counter #
"+2/4#CO2=A ! ! 000J "imer%Counter # V Compare value A
"+2/4# CO2=9 ! ! 000H "imer%Counter # V Compare value 9
"+2/4# CO2=# 000J ! ! "imer%Counter # V Compare value #
"+2/4# O3- 000H ! 0006 "imer%Counter # Overflo&
"+2/40 O3- 0006 0002 000I "imer%Counter 0 Overflo&
8=+ 8"C ! ! 0008 8erial "ransmit Complete
>A4" "K 000I ! 0009 >A4" char in receive buffer available
>A4" >D4/ 0008 ! 000A >A4" transmitter ran empty
>A4" "K 0009 ! 0009 >A4" All 8ent
A7AQCO2= ! ! 000C Analog Comparator
7ote that the capability to react to events is very different for the different types' "he addresses are
se)uential( but not identical for different types' Consult the data sheet for each A34 type'
"he higher a vector in the list the higher is its priority' +f t&o or more components have an interrupt
condition pending at the same time( the up most vector &ith the lo&er vector address &ins' "he lo&er int
has to &ait until the upper int &as served' "o disable lo&er ints from interrupting during the e6ecution of its
service routine the first e6ecuted int disables the processor1s +!flag' "he service routine must re!enable this
flag after it is done &ith its ?ob'
-or re!setting the + status bit there are t&o &ays' "he service routine can end &ith the instruction$
RE>I
"his return from the int routine restores the +!bit after the return address has been loaded to the program
counter'
"he second &ay is to enable the +!bit by the instruction
*EI ' *et Interr:Et En%)-ed
RE> ' Ret:rn
"his is not the same as the 4/"+( because subse)uent interrupts are already enabled before the program
counter is re!loaded &ith the return address' +f another int is pending( its e6ecution is already starting
before the return address is popped from the stac.' "&o or more nested addresses remain on the stac.'
7o bug is to be e6pected( but it is an unnecessary ris. doing that' 8o ?ust use the 4/"+ instruction to avoid
this unnecessary flo& to the stac.'
An +nt!vector can only hold a relative ?ump instruction to the service routine' +f a certain interrupt is not used
or undefined &e can ?ust put a 4/"+ instruction there( in case an erroneously enabled int happens before
&e &rote an interrupt service routine' +n a fe& cases it is absolutely necessary to react to these false ints'
"hat is the case if the e6ecution of the respective service routine does not automatically reset the interrupt
condition flag of the peripheral' +n that case a simple 4/"+ &ould reset the other&ise never!ending
interrupts' "his is the case &ith some of the >A4" interrupts'
As( after an interrupt is under service( further e6ecution of lo&er!priority interrupts are bloc.ed( all int
service routines should be as short as possible' +f you need to have a longer routine to serve the int( use
one of the t&o follo&ing methods' "he first is to allo& ints by 8/+ &ithin the service routine( &henever
you1re done &ith the most urgent tas.s' "his is not very clever' 2ore convenient is to perform the urgent
tas.s( setting a flag some&here in a register for the slo&er reaction portions and return from the int
immediately'
A very serious rule for int service routines is$
The first instr"tion is always to sa#e the pro"essor stats flags in a register or on the sta"$%
Do this before you use instructions that might change flags in the status flag register' "he reason is that
the interrupted main program might ?ust be in a state using the flag for a branch decision( and the int &ould
?ust change that flag to another state' -unny things &ould happen from time to time' "he last instruction
before the 4/"+ therefore is to copy the saved flags from the register bac. to status port or to pop the
status register content from the stac. and restore its original content' "he follo&ing sho&s e6amples ho&
to do that$
8aving in a register$ 8aving on the stac.$
Isr@ Isr@
I& R15,*RE0 ' s%Ce f-%gs P$*/ R15 ' s%Ce register on st%,M
A... <ore instr:,tions...B I& R15, *RE0
Avr!Asm!"utorial 8 http$%%&&&'avr!asm!tutorial'net
A...<ore instr:,tions...B
O$> *RE0,R15 ' restore f-%gs O$> *RE0,R15 ' restore f-%gs
POP R15
RE>I ' ret:rn fro< interr:Et RE>I ' ret:rn fro< interr:Et
"he method on the right is slo&er( the method on the left re)uires a register e6clusively for that purpose'
Fenerally$ All used registers in a service routine should either be e6clusively reserved for that purpose or
saved on stac. and restored at the end of the service routine' 7ever change the content of a register &ithin
an int service routine that is used some&here else in the normal program &ithout restoring it'
9ecause of these basic re)uirements a more sophisticated e6ample for an interrupt service routine here'
."*E0 ' "ode(*eg<ent st%rts here
.OR0 0000 ' Address is Dero
RPMP *t%rt ' >he reset(Ce,tor on Address 0000
RPMP I*erCi,e ' 0001@ first Int(e,tor, I&>0 serCi,e ro:tine
A...B here other Ce,tors

*t%rt@ ' /ere the <%in Erogr%< st%rts
A...B here is eno:gh sE%,e for defining the st%,M %nd other things

I*erCi,e@ ' /ere ;e st%rt ;ith the Interr:Et(*erCi,e(Ro:tine
P$*/ R16 ' s%Ce % register to st%,M
I& R16,*RE0 ' re%d st%t:s register
P$*/ R16 ' %nd E:t on st%,M
A...B /ere the Int(*erCi,e(Ro:tine does so<ething %nd :ses R16
POP R16 ' get EreCio:s f-%g register fro< st%,M
O$> *RE0,R16 ' restore o-d st%t:s
POP R16 ' get EreCio:s ,ontent of R16 fro< the st%,M
RE>I ' %nd ret:rn fro< int
;oo.s a little bit complicated( but is a prere)uisite for using ints &ithout producing serious bugs' 8.ip
=>8< 4#6 and =O= 4#6 if you can afford reserving the register for e6clusive use &ithin the service
routine' As an interrupt service routine cannot be interrupted Aunless you allo& interrupts &ithin the
routineB( all different int service routines can use the same register'
0ou understand no&( &hy allo&ing interrupts &ithin an interrupt service routine( and not at its end &ith
4/"+( is not a good idea,
"hat1s it for the beginner' "here are some other things &ith ints( but this is enough to start &ith( and not to
confuse you'
Avr!Asm!"utorial 9 http$%%&&&'avr!asm!tutorial'net
Calculations
<ere &e discuss all necessary instructions for calculating in A34 assembler language' "his includes
number systems( setting and clearing bits( shift and rotate( and adding%subtracting%comparing and the
format conversion of numbers'
Number systems in assembler
"he follo&ing formats of numbers are common in assembler$
=ositive &hole numbers A9ytes( *ords( ;ong&ords( etc'B(
8igned &hole numbers A8hort+nts( +ntegers( ;ong+nts( etc'B(
9inary Coded Digits A9CDB(
=ac.ed 9CDs(
A8C++!formatted numbers'
+f you come from a high!level language$ forget pre!defined number formats' Assembler doesn1t have that
concept nor its Asometimes frustatingB limitations' *hat you earn is$ you are the master of your o&n format@
Positive whole numbers (bytes, words, etc.)
"he smallest &hole number to be handled in assembler is a byte &ith eight bits' "his codes numbers
bet&een 0 and 2HH' 8uch bytes fit e6actly into one register of the 2C>' All larger numbers must be based
on this basic format( using more than one register' "&o bytes yield a &ord Arange from 0 '' 6H(HHB( three
bytes form a longer &ord Arange from 0 '' #6(III(2#HB and four bytes form a double &ord Arange from 0 ''
J(29J(96I(29HB'
"he single bytes of a &ord or a double &ord can be stored in &hatever register you prefer' Operations &ith
these single bytes are programmed byte by byte( so you don1t have to put them in a ro&' +n order to form a
ro& for a double &ord &e could store it li.e this$
.DEF r16 = d;0
.DEF r18 = d;1
.DEF r19 = d;!
.DEF r19 = d;6
4egisters d&0 to d& are in a ro&( but don1t need to be' +f &e need to initiate this double &ord at the
beginning of an application Ae' g' to J(000(000B( this should loo. li.e this$
.E#$ d;i = 7000000 ' define the ,onst%nt
LDI d;0,LO41d;i2 ' >he -o;est 9 )its to R16
LDI d;1,3.>E!1d;i2 ' )its 9 .. 15 to R18
LDI d;!,3.>E61d;i2 ' )its 16 .. !6 to R19
LDI d;6,3.>E71d;i2 ' )its !7 .. 61 to R19
8o &e have splitted this decimal number( called d&i( to its binary portions 90"/J to 90"/# and pac.ed
them into the four byte pac.ages' 7o& you can calculate &ith this double &ord'
Signed numbers (integers)
8ometimes( but in rare cases( you need negative numbers to calculate &ith' A negative number is defined
by interpreting the most significant bit of a byte as sign bit' +f it is 0 the number is positive' +f it is # the
number is negative' +f the number is negative &e usually do not store the rest of the number as is( but &e
use its inverted value' +nverted means that !# as a byte integer is not &ritten as #000'000# but as
####'#### instead' "hat means$ subtract # from 0 Aand forget the overflo&B' "he first bit is the sign bit(
signaling that this is a negative number' *hy this different format Asubtracting the number from 0B is used
is easy to understand$ adding !# A####'####B and G# A0000'000#B yields e6actly 5ero( if you forget the
overflo& that occurs during that operation Ato the ninth bitB'
+n one byte the largest integer number to be handled is G#2I Abinary 0#######B( the smallest one is !#28
Abinary #(0000000B' +n other computer languages this number format is called short integer' +f you need a
bigger range of values you can add another byte to form a larger integer value( ranging from G2(I6I ''
!2(I68B( four bytes provide a range from G2(#JI(J8(6JI '' !2(#JI(J8(6J8( in other languages called a
;ong+nt or Double+nt'
Binary Coded Digits, BCD
=ositive or signed &hole numbers in the formats discussed above use the available space most effectively'
Another( less dense number format( but easier to handle and understand is to store decimal numbers in a
byte for one digit each' "he decimal digit is stored in its binary form in a byte' /ach digit from 0 '' 9 needs
four bits Abinary values 0000 '' #00#B( the upper four bits of the byte are al&ays 5eros( blo&ing a lot of hot
air into one byte' -or to handle the value 2H0 &e &ould need at least three bytes( e' g'$
Avr!Asm!"utorial J0 http$%%&&&'avr!asm!tutorial'net
Bit *alue $"% +, #" $+ % , " $
4#6( Digit # V2 0 0 0 0 0 0 # 0
4#I( Digit 2 V H 0 0 0 0 0 # 0 #
4#8( Digit V 0 0 0 0 0 0 0 0 0
'Instr:,tions to :se@
LDI R16,!
LDI R18,5
LDI R19,0

0ou can calculate &ith these numbers( but this is a bit more complicated in assembler than calculating &ith
binary values' "he advantage of this format is that you can handle as long numbers as you li.e( as long as
you have enough storage space' "he calculations are as precise as you li.e Aif you program A34s for
ban.ing applicationsB( and you can convert them very easily to character strings'
Packed BCDs
+f you pac. t&o decimal digits into one byte you don1t loose that much storage space' "his method is called
pac.ed binary coded digits' "he t&o parts of a byte are called upper and lo&er nibble' "he upper nibble
usually holds the more significant digit( &hich has advantages in calculations Aspecial instructions in A34
assembler languageB' "he decimal number 2H0 &ould loo. li.e this &hen formatted as a pac.ed 9CD$
B)te -igits Value % , " $ % , " $
2 J \ 02 0 0 0 0 0 0 # 0
# 2 \ # H0 0 # 0 # 0 0 0 0
' Instr:,tions for setting@
LDI R18,0?0! ' $EEer )yte
LDI R16,0?50 ' Lo;er )yte
"o set this correct you can use the binary notation A0b'''B or the he6adecimal notation A06'''B to set the
proper bits to their correct nibble position'
Calculating &ith pac.ed 9CDs is a little more complicated compared to the binary form' -ormat changes to
character strings are nearly as easy as &ith 9CDs' ;ength of numbers and precision of calculations is only
limited by the storage space'
Numbers in ASCII-format
3ery similar to the unpac.ed 9CD format is to store numbers in A8C++ format' "he digits 0 to 9 are stored
using their A8C++ AA8C++ V American 8tandard Code for +nformation +nterchangeB representation' A8C++ is
a very old format( developed and optimi5ed for teletype &riters( unnecessarily very complicated for
computer use Ado you .no& &hat a char named /nd Of "ransmission /O" meant &hen it &as invented,B(
very limited in range for other than >8 languages Aonly I bits per characterB( still used in communications
today due to the limited efforts of some operating system programmers to s&itch to more effective
character systems' "his ancient system is only topped by the /uropean H!bit long teletype character set
called 9audot set or the 2orse code( still used by some finger!nervous people'
*ithin the A8C++ code system the decimal digit 0 is represented by the number J8 Ahe6 060( binary
0b00##'0000B( digit 9 is HI decimal Ahe6 069( binary 0b00##'#00#B' A8C++ &asn1t designed to have these
numbers on the beginning of the code set as there are already instruction chars li.e the above mentioned
/O" for the teletype' 8o &e still have to add J8 to a 9CD Aor set bit J and H to #B to convert a 9CD to
A8C++' A8C++ formatted numbers need the same storage space li.e 9CDs' ;oading 2H0 to a register set
representing that number &ould loo. li.e this$
LDI R19,S!S
LDI R18,S5S
LDI R16,S0S
"he A8C++ representation of these characters are &ritten to the registers'
Bit manipulations
"o convert a 9CD coded digit to its A8C++ representation &e need to set bit J and H to a one' +n other
&ords &e need to O4 the 9CD &ith a constant value of he6 060' +n assembler this is done li.e this$
ORI R16,0?60
+f &e have a register that is already set to he6 060 &e can use the O4 &ith this register to convert the
9CD$
Avr!Asm!"utorial J# http$%%&&&'avr!asm!tutorial'net
OR R1,R!
9ac. from an A8C++ character to a 9CD is as easy' "he instruction
A&DI R16,0?0F
isolates the lo&er four bits AV the lo&er nibbleB' 7ote that O4+ and A7D+ are only possible &ith registers
above 4#H' +f you need to do this( use one of the registers 4#6 to 4#@
+f the he6 value 060- is already in register 42( you can A7D the A8C++ character &ith this register$
A&D R1,R!
"he other instructions for manipulating bits in a register are also limited for registers above 4#H' "hey
&ould be formulated li.e this$
*3R R16,0)00110000 ' *et )its 7 %nd 5 to one
"3R R16,0)00110000 ' "-e%r )its 7 %nd 5 to Dero
+f one or more bits of a byte have to be inverted you can use the follo&ing instruction A&hich is not possible
for use &ith a constantB$
LDI R16,0)10101010 ' InCert %-- :neCen )its
EOR R1,R16 ' in register R1 %nd store res:-t in R1
"o invert all bits of a byte is called the One1s complement$
"OM R1
inverts the content in register 4# and replaces 5eros by one and vice versa' Different from that is the "&o1s
complement( &hich converts a positive signed number to its negative complement Asubtracting from 5eroB'
"his is done &ith the instruction
&E0 R1
8o G# Adecimal$ #B yields !# Abinary #'#######B( G2 yields !2 Abinary #'######0B( and so on'
9esides the manipulation of the bits in a register( copying a single bit is possible using the so!called "!bit
of the status register' *ith
3*> R1,0
the "!bit is loaded &ith a copy of bit 0 in register 4#' "he "!bit can be set or cleared( and its content can be
copied to any bit in any register$
"L> ' ,-e%r >()it, or
*E> ' set >()it, or
3LD R!,! ' ,oEy >()it to register R!, )it !
Shift and rotate
8hifting and rotating of binary numbers means multiplying and dividing them by 2' 8hifting has several sub!
instructions'
2ultiplication &ith 2 is easily done by shifting all bits of a byte one binary digit left and &riting a 5ero to the
least significant bit' "his is called logical shift left or ;8;' "he former bit I of the byte &ill be shifted out to
the carry bit in the status register'
L*L R1
"he inverse division by 2 is the instruction called logical shift right( ;84'
L*R R1
"he former bit I( no& shifted to bit 6( is filled &ith a 0( &hile the former bit 0 is shifted into the carry bit of
the status register' "his carry bit could be used to round up and do&n Aif set( add one to the resultB'
/6ample( division by four &ith rounding$
L*R R1 ' diCision )y !
3R"" DiC! ' P:<E if no ro:nd :E
I&" R1 ' ro:nd :E
DiC!@
L*R R1 ' On,e %g%in diCision )y !
3R"" DiCE ' P:<E if no ro:nd :E
I&" R1 ' Ro:nd $E
DiCE@
8o( dividing is easy &ith binaries as long as you divide by multiples of 2'
+f signed integers are used the logical shift right &ould over&rite the sign!bit in bit I' "he instruction
Carithmetic shift rightD A84 leaves bit I untouched and shifts the I lo&er bits( inserting a 5ero into bit
location 6'
Avr!Asm!"utorial J2 http$%%&&&'avr!asm!tutorial'net
A*R R1
;i.e &ith logical shifting the former bit 0 goes to the carry bit in the status register'
*hat about multiplying a #6!bit &ord by 2, "he most significant bit of the lo&er byte has to be shifted to
yield the lo&est bit of the upper byte' +n that step a shift &ould set the lo&est bit to 5ero( but &e need to
shift the carry bit from the previous shift of the lo&er byte into bit 0 of the upper byte' "his is called a rotate'
During rotation the carry bit in the status register is shifted to bit 0( the former bit I is shifted to the carry
during rotation'
L*L R1 ' Logi,%- *hift Left of the -o;er )yte
ROL R! ' ROt%te Left of the :EEer )yte
"he logical shift left in the first instruction shifts bit I to carry( the 4O; instruction rolls it to bit 0 of the upper
byte' -ollo&ing the second instruction the carry bit has the former bit I of the upper byte' "he carry bit can
be used to either indicate an overflo& Aif #6!bit!calculation is performedB or to roll it into more upper bytes
Aif more than #6 bit calculation is doneB'
4olling to the right is also possible( dividing by 2 and shifting carry to bit I of the result$
L*R R! ' Logi,%- *hift Right, )it 0 to ,%rry
ROR R1 ' ROt%te Right %nd shift ,%rry in )it 8
+t1s easy dividing &ith big numbers' 0ou see that learning assembler is not "<A" complicated'
"he last instruction that shifts four bits in one step is very often used &ith pac.ed 9CDs' "his instruction
shifts a &hole nibble from the upper to the lo&er position and vice versa' +n our e6ample &e need to shift
the upper nibble to the lo&er nibble position' +nstead of using
ROR R1
ROR R1
ROR R1
ROR R1
&e can perform that &ith a single
*4AP R1
"his instruction e6changes the upper and lo&er nibble' 7ote that the content of the upper nibble &ill be
different after applying these t&o methods'
Adding, subtracting and comparing
"he follo&ing calculation operations are too complicated for the beginners and demonstrate that assembler
is only for e6treme e6perts( hi' 4ead on your o&n ris.@
Adding and subtracting 16-bit numbers
"o start complicated &e add t&o #6!bit!numbers in 4#$42 and 4$4J' A+n this notation( &e mean that the
first register is the most significant byte( the second the least significantB'
ADD R!,R7 ' first %dd the t;o -o;()ytes
AD" R1,R6 ' then the t;o high()ytes
+nstead of a second ADD &e use ADC in the second instruction' "hat means add &ith carry( &hich is set or
cleared during the first instruction( depending from the result' Already scared enough by that complicated
math, +f not$ ta.e this@
*e subtract 4$4J from 4#$42'
*$3 R!,R7 ' first the -o;()yte
*3" R1,R6 ' then the high()yte
Again the same tric.$ during the second instruction &e subtract another # from the result if the result of the
first instruction had an overflo&' 8till breathing, +f yes( handle the follo&ing@
Comparing 16-bit numbers
7o& &e compare a #6!bit!&ord in 4#$42 &ith the one in 4$4J to evaluate &hether it is bigger than the
second one' +nstead of 8>9 &e use the compare instruction C=( instead of 89C &e use C=C$
"P R!,R7 ' ,o<E%re -o;er )ytes
"P" R1,R6 ' ,o<E%re :EEer )ytes
+f the carry flag is set no&( 4#$42 is larger than 4$4J'
Comparing with constants
7o& &e add some more complicated stuff' *e compare the content of 4#6 &ith a constant$ 0b#0#0#0#0'
Avr!Asm!"utorial J http$%%&&&'avr!asm!tutorial'net
"PI R16,0?AA
+f the Pero!bit in the status register is set after that( &e .no& that 4#6 is e)ual to 06AA' +f the carry!bit is
set( &e .no&( it is smaller' +f Carry is not set and the Pero!bit is not set either( &e .no& it is larger'
And no& the most complicated test' *e evaluate &hether 4# is 5ero or negative$
>*> R1
+f the P!bit is set( the register 4# is 5ero and &e can follo& &ith the instructions 94/L( 947/( 942+(
94=;( 94;O( 948<( 94F/( 94;"( 943C or 9438 to branch around a little bit'
Packed BCD math
8till &ith us, +f yes( here is some pac.ed 9CD calculations' Adding t&o pac.ed 9CDs can result in t&o
different overflo&s' "he usual carry sho&s an overflo&( if the higher of the t&o nibbles overflo&s to more
than #H decimal' Another overflo&( from the lo&er to the upper nibble occurs( if the t&o lo&er nibbles add
to more than #H decimal'
"o ta.e an e6ample &e add the pac.ed 9CDs J9 AVhe6 J9B and 99 AVhe6 99B to yield #J8 AVhe6 060#J8B'
Adding these in binary math( results in a byte holding he6 06/2( no byte overflo& occurs' "he lo&er of the
t&o nibbles should have an overflo&( because 9G9V#8 Amore than 9B and the lo&er nibble can only handle
numbers up to #H' "he overflo& &as added to bit J( the lo&est significant bit of the upper nibble' *hich is
correct@ 9ut the lo&er nibble should be 8 and is only 2 A#8 V 0b000#'00#0B' *e should add 6 to that nibble
to yield a correct result' *hich is )uite logic( because &henever the lo&er nibble reaches more than 9 &e
have to add 6 to correct that nibble'
"he upper nibble is totally incorrect( because it is 06/ and should be A&ith a # overflo&ing to the ne6t
upper digit of the pac.ed 9CDB' +f &e add 6 to this 06/ &e get to 06J and the carry is set AV06#JB' 8o the
tric. is to first add these t&o numbers and then add 0666 to correct the 2 digits of the pac.ed 9CD' 9ut
halt$ &hat if adding the first and the second number &ould not result in an overflo& to the ne6t nibble, And
not result in a digit above 9 in the lo&er nibble, Adding 0666 &ould then result in a totally incorrect result'
"he lo&er 6 should only be added if the lo&er nibble either overflo&s to the upper nibble or results in a
digit larger than 9' "he same &ith the upper nibble'
<o& do &e .no&( if an overflo& from the lo&er to the upper nibble has occurred, "he 2C> sets the <!bit
in the status register( the half!carry bit' "he follo&ing sho&s the algorithm for the different cases that are
possible after adding t&o nibbles and adding he6 066 after that'
#' Add the nibbles' +f overflo& occurs AC for the upper nibbles( or < for the lo&er nibblesB( add 6 to correct(
if not( do step 2'
2' Add 6 to the nibble' +f overflo& occurs AC resp' <B( you1re done' +f not( subtract 6'
"o program an e6ample &e assume that the t&o pac.ed 9CDs are in 42 and 4( 4# &ill hold the overflo&(
and 4#6 and 4#I are available for calculations' 4#6 is the adding register for adding 0666 Athe register 42
cannot add a constant valueB( 4#I is used to correct the result depending from the different flags' Adding
42 and 4 goes li.e that$
LDI R16,0?66 ' for %dding 0?66 to the res:-t
LDI R18,0?66 ' for -%ter s:)tr%,ting fro< the res:-t
ADD R!,R6 ' %dd the t;o t;o(digit(3"Ds
3R"" &o"y1 ' Q:<E if no )yte oCerf-o; o,,:rs
I&" R1 ' in,re<ent the ne?t higher )yte
A&DI R18,0?0F ' donSt s:)tr%,t 6 fro< the higher ni))-e
&o"y1@
3R/" &o/,1 ' Q:<E if no h%-f(,%rry o,,:rred
A&DI R18,0?F0 ' donSt s:)tr%,t 6 fro< -o;er ni))-e
&o/,1@
ADD R!,R16 ' %dd 0?66 to res:-t
3R"" &o"y! ' Q:<E if no ,%rry o,,:rred
I&" R1 ' in,re<ent the ne?t higher )yte
A&DI R18,0?0F ' donSt s:)tr%,t 6 fro< higher ni))-e
&o"y!@
3R/" &o/,! ' Q:<E if no h%-f(,%rry o,,:rred
A&DI R18,0?F0 ' donSt s:)tr%,t 6 fro< -o;er ni))-e
&o/,!@
*$3 R!,R18 ' s:)tr%,t ,orre,tion
A little bit shorter than that$
LDI R16,0?66
ADD R!,R16
ADD R!,R6
3R"" &o"y
I&" R1
A&DI R16,0?0F
&o"y@
3R/" &o/,
A&DI R16,0?F0
Avr!Asm!"utorial JJ http$%%&&&'avr!asm!tutorial'net
&o/,@
*$3 R!,R16
Luestion to thin. about$ *hy is that e)ually correct( half as long and less complicated and &here is the
tric.,
Format conversion for numbers
All number formats can be converted to any other format' "he conversion from 9CD to A8C++ and vice
versa &as already sho&n above A9it manipulationsB'
Conversion of packed BCDs to BCDs, ASCII or Binaries
Conversion of pac.ed 9CDs is not very complicated either' -irst &e have to copy the number to another
register' *ith the copied value &e change nibbles using the 8*A= instruction to e6change the upper and
the lo&er one' "he upper part is cleared( e' g' by A7Ding &ith 060-' 7o& &e have the 9CD of the upper
nibble and &e can either use as is A9CDB or set bit J and H to convert it to an A8C++ character' After that &e
copy the byte again and treat the lo&er nibble &ithout first 8*A=ping and get the lo&er 9CD'
A little bit more complicated is the conversion of 9CD digits to a binary' Depending on the numbers to be
handled &e first clear the necessary bytes that &ill hold the result of the conversion' *e then start &ith the
highest 9CD digit' 9efore adding this to the result &e multiply the result &ith #0' A7ote that in the first step
this is not necessary( because the result is 5ero eitherB'
+n order to do the multiplication by #0( &e copy the result to some&here else' "hen &e multiply the result
by four At&o left shifts resp' rollsB' Adding the previously copied number to this yields a multiplication &ith H'
7o& a multiplication &ith 2 Aleft shift%rollB yields the #0!fold of the result' -inally &e add the 9CD and repeat
that algorithm until all decimal digits are converted' +f( during one of these operations( there occurs a carry
of the result( the 9CD is too large to be converted' "his algorithm handles numbers of any length( as long
as the result registers are prepared'
Conversion of Binaries to BCD
"he conversion of a binary to 9CDs is more complicated than that' +f &e convert a #6!bit!binary &e can
subtract #0(000 A062I#0B( until an overflo& occurs( yielding the first digit' "hen &e repeat that &ith #(000
A060/8B to yield the second digit' And so on &ith #00 A06006JB and #0 A06000AB( then the remainder is
the last digit' "he constants #0(000( #(000( #00 and #0 can be placed to the program memory storage in a
&ord &ise organi5ed table( li.e this$
DeD>%)@
.D4 10000, 1000, 100, 10
and can be read &ord!&ise &ith the ;=2 instruction from the table'
An alternative is a table that holds the decimal value of each bit in the #6!bit!binary( e' g'
.D3 0,6,!,8,6,9
.D3 0,1,6,6,9,7
.D3 0,0,9,1,9,!
.D3 0,0,7,0,9,6
.D3 0,0,!,0,7,9 ' %nd so on :nti-
.D3 0,0,0,0,0,1
"hen you shift the single bits of the binary left out of the registers to the carry' +f it is a one( you add the
number in the table to the result by reading the numbers from the table using ;=2' "his is more
complicated to program and a little bit slo&er than the above method'
A third method is to calculate the table value( starting &ith 00000#( by adding this 9CD &ith itself( each
time after you have shifted a bit from the binary to the right( and added to the 9CD result'
2any methods( much to optimi5e here'
Multiplication
2ultiplication of binary numbers is e6plained here'
Decimal multiplication
+n order to multiply t&o 8!bit!binaries &e remind ourselves( ho& this is done &ith decimal numbers$
Avr!Asm!"utorial JH http$%%&&&'avr!asm!tutorial'net
1234 * 567 = ?
------------------------
1234 * 7 = 8638
+ 1234 * 60 = 74040
+ 1234 * 500 = 617000
------------------------
1234 * 567 = 699678
========================
+n single steps decimal$
*e multiply the first number &ith the lo&est significant digit of the second number and add this to the
result'
*e multiply the first number &ith #0 and then &ith the ne6t higher digit of the second number and
add this to the result'
*e multiply the first number &ith #00( then &ith the third!highest digit( and add this to the result'
Binary multiplication
7o& in binary' 2ultiplication &ith the single digits is not necessary( because there are only the digits # Aadd
the numberB and 0 Adon1t add the numberB' 2ultiplication by #0 in decimal goes to multiplication by 2 in
binary mode' 2ultiplication by 2 is done easily( either by adding the number &ith itself( or by shifting all bits
one position left and &riting a 0 to the void position on the right' 0ou see that binary math is very much
easier than decimal' *hy didn1t man.ind use this from the beginning,
AVR-Assembler program
"he follo&ing source code demonstrates reali5ation of multiplication in assembler'
' M:-t9.%s< <:-tiE-ies t;o 9()it(n:<)ers to yie-d % 16()it(res:-t
'
.&OLI*>
.I&"L$DE ="@F%Crtoo-sF%EEnotesF9515def.in,=
.LI*>
'
' F-o; of <:-tiE-i,%tion
'
' 1.>he )in%ry to )e <:-tiE-i,%ted ;ith is shifted )it;ise into the ,%rry )it. If it is % one, the )in%ry n:<)er is %dded to the
' res:-t, if it is not % one th%t ;%s shifted o:t, the n:<)er is not %dded.
' !.>he )in%ry n:<)er is <:-tiE-ied )y ! )y rot%ting it one Eosition -eft, shifting % 0 into the Coid Eosition.
' 6.If the )in%ry to )e <:-tiE-ied ;ith is not Dero, the <:-tiE-i,%tion -ooE is reEe%ted. If it is Dero, the <:-tiE-i,%tion is done.
'
' $sed registers
'
.DEF r<1 = R0 ' 3in%ry n:<)er to )e <:-tiE-i,%ted 19 3it2
.DEF r<h = R1 ' Interi< stor%ge
.DEF r<! = R! ' 3in%ry n:<)er to )e <:-tiE-i,%ted ;ith 19 3it2
.DEF re- = R6 ' Res:-t, L*3 116 3it2
.DEF reh = R7 ' Res:-t, M*3
.DEF r<E = R16 ' M:-ti E:rEose register for -o%ding
'
."*E0
.OR0 0000
'
rQ<E *>AR>
'
*>AR>@
-di r<E,0?AA ' e?%<E-e )in%ry 1010.1010
<oC r<1,r<E ' to the first )in%ry register
-di r<E,0?55 ' e?%<E-e )in%ry 0101.0101
<oC r<!,r<E ' to the se,ond )in%ry register
'
' /ere ;e st%rt ;ith the <:-tiE-i,%tion of the t;o )in%ries in r<1 %nd r<!, the res:-t ;i-- go to reh@re- 116 3it2
'
M$L>9@
'
' "-e%r st%rt C%-:es
,-r r<h ' ,-e%r interi< stor%ge
,-r re- ' ,-e%r res:-t registers
,-r reh
'
' /ere ;e st%rt ;ith the <:-tiE-i,%tion -ooE
'
M$L>9%@
Avr!Asm!"utorial J6 http$%%&&&'avr!asm!tutorial'net
'
' *teE 1@ Rot%te -o;est )it of )in%ry n:<)er ! to the ,%rry f-%g 1diCide )y !, rot%te % Dero into )it 82
'
,-, ' ,-e%r ,%rry )it
ror r<! ' )it 0 to ,%rry, )it 1 to 8 one Eosition to the right, ,%rry )it to )it 8
'
' *teE !@ 3r%n,h deEending if % 0 or 1 h%s )een rot%ted to the ,%rry )it
'
)r,, M$L>9) ' Q:<E oCer %dding, if ,%rry h%s % 0
'
' *teE 6@ Add 16 )its in r<h@r<- to the res:-t, ;ith oCerf-o; fro< L*3 to M*3
'
%dd re-,r<1 ' %dd L*3 of r<1 to the res:-t
%d, reh,r<h ' %dd ,%rry %nd M*3 of r<1
'
M$L>9)@
'
' *teE 7@ M:-tiE-y r<h@r<1 )y ! 116 )its, shift -eft2
'
,-, ' ,-e%r ,%rry )it
ro- r<1 ' rot%te L*3 -eft 1<:-tiE-y )y !2
ro- r<h ' rot%te ,%rry into M*3 %nd M*3 one -eft
'
' *teE 5@ "he,M if there %re sti-- oneSs in )in%ry !, if yes, go on <:-tiE-i,%ting
'
tst r<! ' %-- )its DeroT
)rne M$L>9% ' if not, go on in the -ooE
'
' End of the <:-tiE-i,%tion, res:-t in reh@re-
'
' End-ess -ooE
'
LOOP@
rQ<E -ooE
Binary rotation
-or understanding the multiplication operation(
it is necessary to understand the binary
rotation instructions 4O; and 4O4' "hese
instructions shift all bits of a register one
position left A4O;B resp' right A4O4B' "he void
position in the register is filled &ith the content
of the carry bit in the status register( the bit that
rolls out of the register is shifted to this carry
bit' "his operation is demonstrated using 06AA
as an e6ample for 4O; and 06HH as an
e6ample for 4O4'
Multiplication in the studio
"he follo&ing screen shots sho& the multiplication program in the simulator Ato ma.e a difference$ here
8tudio version B'
"he ob?ect!code has been
opened( the cursor is placed
on the first e6ecutable
instruction' -## does single
steps'

Avr!Asm!"utorial JI http$%%&&&'avr!asm!tutorial'net
"he registers 40 and 42 are
set to 06AA and 06HH( our test
binaries( to be multiplied'

42 is rotated to the
right( to roll the least
significant bit into the
carry bit' 06HH
A0#0#'0#0#B yielded
062A A00#0'#0#0B'

9ecause the carry bit
had a one( the
content of the
registers 4#$40 is
added to the AemptyB
register pair 4J$4(
resulting in 0600AA
there'

Avr!Asm!"utorial J8 http$%%&&&'avr!asm!tutorial'net
7o& the register pair
4#$40 is rotated one
position left to
multiply this binary
by 2' -rom 0600AA(
multiplication by 2
yields 060#HJ'
"he &hole multipli!
cation loop is repea!
ted as long there is
at least one binary #
in register 42' "hese
follo&ing loops are
not sho&n here'

>sing .ey -H of the
studio &e multi!
stepped over these
loops to a brea.!
point at the end of
the multiplication
routine' "he result
register pair 4J$4
has the result of
the multiplication of
06AA by 06HH$
068I2'

"his &asn1t that complicated( ?ust remind yourself on the similar decimal operations' 9inary multiplication is
much easier than decimal'
Hardware multiplication
All A"mega( A"Kmega( A"90CA7 and A"90=*2 have an on!board hard&are multiplicator( that performs
8 by 8 bit multiplications in only t&o cloc. cycles' 8o &henever you have to do multiplications and you are
sure that this soft&are never ever needs not to run on an A"908! or A"tiny!chip( you can ma.e use of this
hard&are feature'
"he follo&ing sho&s ho& to multiply
8!by!8!binaries(
#6!by!8!binaries(
#6!by!#6!binaries(
#6!by!2J!binaries'
Hardware multiplication of 8-by-8-bit binaries
"he use is simple and straight!for&ard$ if the t&o binaries to be multiplied are in the registers 4#6 and
4#I( ?ust type
Avr!Asm!"utorial J9 http$%%&&&'avr!asm!tutorial'net
<:- R16,R18
As the result of these t&o 8!bit
binaries might be up t&o #6 bits
long( the result &ill be in the
registers 4# Amost significant byteB
and 40 Aleast significant byteB'
"hat1s all about it'
"he program demonstrates the simulation in
the 8tudio' +t multiplies decimal 2H0 Ahe6 -AB
by decimal #00 Ahe6 6JB( in the registers 4#6
and 4#I'
After e6ecution( the
registers 40 A;89B and
4# A289B hold the result
he6 6#A8 or decimal
2H(000'
And$ yes( that re)uires
only t&o cycles( or 2
microseconds &ith a #
2cs%s cloc.'
Hardware multiplication of a 16- by an 8-bit-binary
0ou have a larger binary to multiply, <ard&are is limited to 8( so &e need to invest some genius ideas
instead' "o solve the problem &ith larger binaries( &e ?ust loo. at this combination of #6 and 8 first'
>nderstanding this concept helps understanding the method( so you &ill be able to solve the 2!by!6J!bit
multiplication problem later'
-irst the math$ a #6!bit!binary m#2$m#; are simply t&o 8!bit!binaries m#2 and m#;( &here the most
significant one m#2 of these t&o is multiplied by decimal 2H6 or he6 #00' A-or those &ho need a reminder$
the decimal #2J is simply A#2 multiplied by #00B plus J( or A# multiplied by #000B plus A2 multiplied by
#00B plus A multiplied by #0B plus J'
8o the #6!bit!binary m# is e)ual to 2H6Om#2
plus m#;( &here m#2 is the 289 and m#; is
the ;89' 2ultiplying m# by 8!bit!binary m2 so
is( mathematically formulated$
m# O m2 V A2H6Om#2 G m#;B O m2( or
2H6Om#2Om2 G m#;Om2'
8o &e ?ust need to do t&o multiplications and
to add both results' 8orry( if you see three
asteris.s in the formula$ the multiplication &ith 2H6 in the binary &orld doesn1t re)uire any hard&are at all(
because it is a simple move to the ne6t higher byte' Just li.e the multiplication by #0 in the decimal &orld is
simply moving the number one left and &rite a 5ero to the least significant digit'
8o let1s go to a practical e6ample' -irst &e need some registers to
load the numbers m# and m2(
provide space for the result( &hich might have 2J bits length'
Avr!Asm!"utorial H0 http$%%&&&'avr!asm!tutorial'net
'
' >est h%rd;%re <:-tiE-i,%tion 16()y(9()it
'
' Register definitions@
'
.def Res1 = R!
.def Res! = R6
.def Res6 = R7
.def <1L = R16
.def <1M = R18
.def <! = R19
-irst &e load the numbers$
'
' Lo%d Registers
'
.eN: <1 = 10000
'
-di <1M,/I0/1<12 ' :EEer 9 )its of <1 to <1M
-di <1L,LO41<12 ' -o;er 9 )its of <1 to <1L
-di <!,!50 ' 9()it ,onst%nt to <!
"he t&o numbers are loaded into 4#I$4#6 Adec #0000 V he6
2I#0B and 4#8 Adec 2H0 V he6 -AB'
"hen &e multiply the ;89 first$
'
' M:-tiE-y
'
<:- <1L,<! ' M:-tiE-y L*3
<oC Res1,R0 ' ,oEy res:-t to res:-t register
<oC Res!,R1
"he ;89 multiplication of he6 2I by he6 -A yields he6 0-0A(
&ritten to the registers 400 A;89( he6 A0B and 40# A289(
he6 0-B' "he result is copied to the lo&er t&o bytes of the
result register( 4$42'
7o& the multiplication of the 289 of m# &ith m2 follo&s$
<:- <1M,<! ' M:-tiE-y M*3
"he multiplication of the 289 of m#( he6 #0( &ith m2( he6 -A(
yields he6 26#6 in 4#$40'
7o& t&o steps are performed at once$ multiplication by 2H6
and adding the result to the previous result' "his is done by
adding 4#$40 to 4es$4es2 instead of 4es2$4es#' 4# can
?ust be copied to 4es' 40 is added to 4es2 then' +f the carry
is set after adding( the ne6t higher byte 4es is increased by
one'
<oC Res6,R1 ' ,oEy M*3 res:-t to res:-t )yte 6
%dd Res!,R0 ' %dd L*3 res:-t to res:-t )yte !
)r,, &oIn, ' if not ,%rry, Q:<E
in, Res6
&oIn,@
"he result in 4J$4$42 is he6 262HA0( &hich is decimal
2H00000 Aas everybody .no&sB( and is obviously correct'
Avr!Asm!"utorial H# http$%%&&&'avr!asm!tutorial'net
"he cycle counter of the multiplication points to #0( at # 2<5
cloc. a total of #0 microseconds' 3ery much faster than
soft&are multiplication@
Hardware multiplication of a 16- by a 16-bit-binary
7o& that &e have understood the principle( it should be easy to do #6!by!#6' "he result re)uires four bytes
no& A4esJ$4es$4es2$4es#( located in 4H$4J$4$42B' "he formula is$
m# O m2 V A2H6Om#2 G m#;B O
A2H6Om22 G m2;B
V 6HH6Om#2Om22 G
2H6Om#2Om2; G
2H6Om#;Om22 G
m#;Om2;
Obviously four multiplications no&' *e start &ith the first and the last as the t&o easiest ones$ their results
are simply copied to the correct result register positions' "he results of the t&o multiplications in the middle
of the formula have to be added to the middle of our result registers( &ith possible carry overflo&s to the
most significant byte of the result' "o do that( you &ill see a simple tric. that is easy to understand' "he
soft&are$
'
' >est /%rd;%re M:-tiE-i,%tion 16 )y 16
'
' Define Registers
'
.def Res1 = R!
.def Res! = R6
.def Res6 = R7
.def Res7 = R5
.def <1L = R16
.def <1M = R18
.def <!L = R19
.def <!M = R19
.def t<E = R!0
'
' Lo%d inE:t C%-:es
'
.eN: <1 = 10000
.eN: <! = !5000
'
-di <1M,/I0/1<12
-di <1L,LO41<12
-di <!M,/I0/1<!2
-di <!L,LO41<!2
'
' M:-tiE-y
'
,-r R!0 ' ,-e%r for ,%rry oEer%tions
<:- <1M,<!M ' M:-tiE-y M*3s
<oC Res6,R0 ' ,oEy to M*4 Res:-t
<oC Res7,R1
<:- <1L,<!L ' M:-tiE-y L*3s
<oC Res1,R0 ' ,oEy to L*4 Res:-t
<oC Res!,R1
<:- <1M,<!L ' M:-tiE-y 1M ;ith !L
%dd Res!,R0 ' Add to Res:-t
%d, Res6,R1
%d, Res7,t<E ' %dd ,%rry
Avr!Asm!"utorial H2 http$%%&&&'avr!asm!tutorial'net
<:- <1L,<!M ' M:-tiE-y 1L ;ith !M
%dd Res!,R0 ' Add to Res:-t
%d, Res6,R1
%d, Res7,t<E
'
' M:-tiE-i,%tion done
'
8imulation sho&s the follo&ing steps'
;oading the t&o constants #0000 Ahe6 2I#0B and 2H000 Ahe6
6#A8B to the registers in the upper register space '''
2ultiplying the t&o 289s Ahe6 2I and 6#B and copying the
result in 4#$40 to the t&o most upper result registers
4H$4J '''
2ultiplying the t&o ;89s Ahe6 #0 and A8B and copying the
result in 4#$40 to the t&o lo&er result registers 4$42 '''
2ultiplying the 289 of m# &ith the ;89 of m2 and adding the
result in 4#$40 to the result register1s t&o middle bytes( no
carry occurred '''
2ultiplying the ;89 of m# &ith the 289 of m2 and adding the
result in 4#$40 to the result register1s t&o middle bytes( no
carry occurred' "he result is he6 0//69280( &hich is
2H0000000 and obviously correct '''
2ultiplication
needed #9 cloc. cycles( &hich is very much faster than &ith
soft&are multiplication' Another advantage here$ the re)uired
time is A;*A08 e6actly #9 cycles( and it doesn1t depend on
the input numbers Ali.e is the case &ith soft&are multiplication
and on overflo& occurrences Athan.s to our small tric. of
adding 5ero &ith carryB' 8o you can rely on this '''
Avr!Asm!"utorial H http$%%&&&'avr!asm!tutorial'net
Hardware multiplication of a 16- by a 24-bit-binary
"he multiplication of a #6 bit
binary ZaZ &ith a 2J bit binary ZbZ
leads to results &ith up to J0 bit
length' "he multiplication
scheme re)uires si6 8!by!8!bit
multiplications and adding the
results to the appropriate
position in the result registers'
"he assembler source code for
this$
' /%rd;%re M:-tiE-i,%tion 16 )y !7 )it
.in,-:de =<9def.in,=
'
' Register definitions
.def %1 = R! ' define 16()it register
.def %! = R6
.def )1 = R7 ' define !7()it register
.def )! = R5
.def )6 = R6
.def e1 = R8 ' define 70()it res:-t register
.def e! = R9
.def e6 = R9
.def e7 = R10
.def e5 = R11
.def ,0 = R1! ' he-E register for %dding
.def r- = R16 ' -o%d register
'
' Lo%d ,onst%nts
.eN: % = 10000 ' <:-tiE-i,%tor %, he? !810
.eN: ) = 1000000 ' <:-tiE-i,%tor ), he? 0F7!70
-di r-,3.>E11%2 ' -o%d %
<oC %1,r-
-di r-,3.>E!1%2
<oC %!,r-
-di r-,3.>E11)2 ' -o%d )
<oC )1,r-
-di r-,3.>E!1)2
<oC )!,r-
-di r-,3.>E61)2
<oC )6,r-
'
' "-e%r registers
,-r e1 ' ,-e%r res:-t registers
,-r e!
,-r e6
,-r e7
,-r e5
,-r ,0 ' ,-e%r he-E register
'
' M:-tiE-y
<:- %!,)6 ' ter< 1
%dd e7,R0 ' %dd to res:-t
%d, e5,R1
<:- %!,)! ' ter< !
%dd e6,R0
%d, e7,R1
%d, e5,,0 ' 1%dd Eossi)-e ,%rry2
<:- %!,)1 ' ter< 6
%dd e!,R0
%d, e6,R1
%d, e7,,0
%d, e5,,0
<:- %1,)6 ' ter< 7
%dd e6,R0
%d, e7,R1
%d, e5,,0
<:- %1,)! ' ter< 5
%dd e!,R0
%d, e6,R1
%d, e7,,0
%d, e5,,0
<:- %1,)1 ' ter< 6
Avr!Asm!"utorial HJ http$%%&&&'avr!asm!tutorial'net
%dd e1,R0
%d, e!,R1
%d, e6,,0
%d, e7,,0
%d, e5,,0
'
' done.
noE
' Res:-t sho:-d )e he? 0!5703E700
"he complete e6ecution re)uires
#0 cloc. cycles for loading the constants(
6 cloc. cycles for clearing registers( and
cloc. cycles for multiplication'
Division
7o( unfortunately there is no hard&are division' 0ou need to do this in soft&are@
Decimal division
Again &e start &ith the decimal division( to better understand the binary division' *e assume a division of
H6I8 by #2' "his is done li.e this$
5678 : 12 = ?
--------------------------
- 4 * 1200 = 4800
----
878
- 7 * 120 = 840
---
38
- 3 * 12 = 36
--
2
Result: 5678 : 12 = 473 Remainder 2
===================================
Binary division
+n binary the multiplication of the second number in the above decimal e6ample AJ O #200( etc'B is not
necessary( due to the fact that &e have only 0 and # as digits' >nfortunately binary numbers have much
more single digits than their decimal e)uivalent( so transferring the decimal division to its binary e)uivalent
is a little bit inconvenient' 8o the program &or.s a bit different than that'
"he division of a #6!bit binary number by a 8!bit binary in A34 assembler is listed in the follo&ing section'
' DiC9 diCides % 16()it(n:<)er )y % 9()it(n:<)er 1>est@ 16()it(n:<)er@ 0?AAAA, 9()it(n:<)er@ 0?552
.&OLI*>
.I&"L$DE ="@F%Crtoo-sF%EEnotesF9515def.in,= ' %dQ:st the ,orre,t E%th to yo:r syste<U
.LI*>
' Registers
.DEF rd1- = R0 ' L*3 16()it(n:<)er to )e diCided
.DEF rd1h = R1 ' M*3 16()it(n:<)er to )e diCided
.DEF rd1: = R! ' interi< register
.DEF rd! = R6 ' 9()it(n:<)er to diCide ;ith
.DEF re- = R7 ' L*3 res:-t
.DEF reh = R5 ' M*3 res:-t
.DEF r<E = R16' <:-tiE:rEose register for -o%ding
'
."*E0
.OR0 0
rQ<E st%rt
st%rt@
' Lo%d the test n:<)ers to the %EEroEri%te registers
-di r<E,0?AA ' 0?AAAA to )e diCided
<oC rd1h,r<E
<oC rd1-,r<E
-di r<E,0?55 ' 0?55 to )e diCided ;ith
<oC rd!,r<E
' DiCide rd1h@rd1- )y rd!
diC9@
,-r rd1: ' ,-e%r interi< register
,-r reh ' ,-e%r res:-t 1the res:-t registers
,-r re- ' %re %-so :sed to ,o:nt to 16 for the
in, re- ' diCision steEs, is set to 1 %t st%rt2
' /ere the diCision -ooE st%rts
diC9%@
Avr!Asm!"utorial HH http$%%&&&'avr!asm!tutorial'net
,-, ' ,-e%r ,%rry()it
ro- rd1- ' rot%te the ne?t(:EEer )it of the n:<)er
ro- rd1h ' to the interi< register 1<:-tiE-y )y !2
ro- rd1:
)r,s diC9) ' % one h%s ro--ed -eft, so s:)tr%,t
,E rd1:,rd! ' DiCision res:-t 1 or 0T
)r,s diC9, ' Q:<E oCer s:)tr%,tion, if s<%--er
diC9)@
s:) rd1:,rd!' s:)tr%,t n:<)er to diCide ;ith
se, ' set ,%rry()it, res:-t is % 1
rQ<E diC9d ' Q:<E to shift of the res:-t )it
diC9,@
,-, ' ,-e%r ,%rry()it, res:-ting )it is % 0
diC9d@
ro- re- ' rot%te ,%rry()it into res:-t registers
ro- reh
)r,, diC9% ' %s -ong %s Dero rot%te o:t of the res:-t registers@ go on ;ith the diCision -ooE
' End of the diCision re%,hed
stoE@
rQ<E stoE ' end-ess -ooE
Program steps during division
During e6ecution of the program the follo&ing steps are ran$
Definition and preset of the registers &ith the test binaries(
presetting the interim register and the result register pair Athe result registers are presetted to
06000#@ After #6 rotations the rolling out of the one stops further division steps'B(
the #6!bit!binary in rd#h$rd#l is rotated bit&ise to the interim register rd#u Amultiplication by 2B( if a #
is rotated out of rd#u( the program branches to the subtraction step in step J immediately(
the content of the interim register is compared &ith the 8!bit binary in rd2( if rd2 is smaller it is
subtracted from the interim register and the carry!bit is set to one( if rd2 is greater the subtraction is
s.ipped and a 5ero is set to the carry flag(
the content of the carry flag is rotated into the result register reh$rel from the right(
if a 5ero rotated out of the result register( &e have to repeat the division loop( if it &as a one the
division is completed'
+f you don1t understand rotation yet you1ll find this operation discussed in the multiplication section'
Division in the simulator
"he follo&ing screen shots demonstrate the
program steps in the studio Ahere in version
( so it loo.s differentB' "o do this( you have
to assemble the source code and open the
resulting ob?ect file in the studio'
"he ob?ect code has been started( the
cursor Ayello& arro&B is on the first
e6ecutable instruction' "he .ey -##
performs single steps'

"he test binaries 06AAAA and
06HH( to be divided( have
been &ritten to the registers
4#$40 and 4'
Avr!Asm!"utorial H6 http$%%&&&'avr!asm!tutorial'net

"he interim register 42 and
the result register pair are set
to their predefined values'
4#$40 &as rotated left to 42(
from 06AAAA the doubled
value of 060#HHHJ &as
yielded'
7o overflo& from rotation
into carry has occurred and
060# in 42 &as smaller than
06HH in 4( so subtraction
&as s.ipped' A 5ero in the
carry is rotated into the result
register 4H$4J' "he former
content of the result register(
a single #!bit in position 0
has rotated to position #
Acontent no&$ 060002B' As a
5ero &as rotated out of the
result register pair( the ne6t
step to be e6ecuted is a
branch to the beginning of
the division loop start
and the loop is repeated'
After e6ecuting the loop
#6 times &e have
reached the brea.point
set at the end of the
division routine' "he
result register in 4H$4J
holds 060202( the result
of the division' "he
registers 42$4#$40 are
empty( so &e do not
have a remainder left' +f
a remainder &ould have
been resulted &e can
use it to decide &hether
an incrementation of the
result should ta.e place(
rounding of the result up'
"his step is not coded
here'

Avr!Asm!"utorial HI http$%%&&&'avr!asm!tutorial'net
"he &hole division needs 60 micro!seconds
processor time Aopen a processor vie& in
the studio menuB' A rather long time for a
division'


Number conversion
7umber conversion routines are not included here' =lease refer to the &ebsite at
http$%%&&&'avr!asm!tutorial'net%avrQen
if you need the source code or a better understanding'
Decimal Fractions
-irst$ Do not use any floating points( unless you really need them' -loating points are resource .illers in an
A34( lame duc.s and need e6treme e6ecution times' 4un into this dilemma( if you thin. assembler is too
complicated( and you prefer 9asic or other languages li.e C or =ascal'
7ot so( if you use assembler' 0ou1ll be sho&n here( ho& you can perform the multiplication of a fi6ed point
real number in less than 60 micro!seconds( in special cases even &ithin #8 micro!seconds( at J 2<5 cloc.
fre)uency' *ithout any floating point processor e6tensions and other e6pensive tric.s for people too la5y
to use their brain'
<o& to do that, 9ac. to the roots of math@ 2ost tas.s &ith floating point reals can be done using integer
numbers' +ntegers are easy to program in assembler and perform fast' "he decimal point is only in the
brain of the programmer( and is added some&here in the decimal digit stream' 7o one reali5es( that this is
a tric.'
Linear conversions
As an e6ample the follo&ing tas.$ an 8!9it!AD!Converter measures an input signal in the range from 0'00
to 2'HH 3olt( and returns as the result a binary in the range from Y00 and Y--' "he result( a voltage( is to
be displayed on a ;CD display' 8illy e6ample( as it is so easy$ "he binary is converted to a decimal A8C++
string bet&een 000 and 2HH( and ?ust behind the first digit the decimal point has to be inserted' Done@
"he electronics &orld sometimes is more complicated' /' g'( the AD!Converter returns an 8!9it!<e6 for
input voltages bet&een 0'00 and H'00 3olt' 7o& &e1re tric.ed and do not .no& ho& to proceed' "o display
the correct result on the ;CD &e &ould have to multiply the binary by H00%2HH( &hich is #'9608' "his is a
silly number( as it is almost 2( but only almost' And &e don1t &ant that .ind of inaccuracy of 2:( &hile &e
have an AD!converter &ith around 0'2H: accuracy'
"o cope &ith this( &e multiply the input by H00%2HHO2H6 or H0#'96 and divide the result by 2H6' *hy first
multiply by 2H6 and then divide by 2H6, +t1s ?ust for enhanced accuracy' +f &e multiply the input by H02
instead of H0#'96( the error is ?ust in the order of 0'008:' "hat is good enough for our AD!converter( &e
can live &ith that' And dividing by 2H6 is an easy tas.( because it is a &ell!.no&n po&er of 2' 9y dividing
&ith numbers that are a po&er of 2( the A34 feels very comfortable and performs very fast' 9y dividing
&ith 2H6( the A34 is even faster( because &e ?ust have to s.ip the last byte of the binary number' 7ot even
shift and rotate@
"he multiplication of an 8!bit!binary &ith the 9!bit!binary H02 Ahe6 #-6B can have a result larger than #6
bits' 8o &e have to reserve 2J bits or registers for the result' During multiplication( the constant H02 has
to be shifted left Amultiplication by 2B to add these numbers to the result each time a one rolls out of the
shifted input number' As this might need eight shifts left( &e need further three bytes for this constant' 8o
&e chose the follo&ing combination of registers for the multiplication$
Num(er Value .example/ Register
+nput value 2HH 4#
2ultiplicand H02 4J $ 4 $ 42
4esult #28(0#0 4I $ 46 $ 4H
Avr!Asm!"utorial H8 http$%%&&&'avr!asm!tutorial'net
After filling the value H02 A00'0#'-6B to 4J $ 4 $ 42 and clearing the result registers 4I $ 46 $ 4H( the
multiplication goes li.e this$
#' "est( if the input number is already 5ero' +f yes( &e1re done'
2' +f no( one bit of the input number is shifted out of the register to the right( into the carry( &hile a 5ero
is stuffed into bit I' "his instruction is named ;ogical!8hift!4ight or ;84'
' +f the bit in carry is a one( &e add the multiplicand Aduring step # the value H02( in step 2 it1s #00J(
a' s' o'B to the result' During adding( &e care for any carry Aadding 42 to 4H by ADD( adding 4 to
46 and 4J to 4I &ith the ADC instruction@B' +f the bit in the carry &as a 5ero( &e ?ust don1t add the
multiplicand to the result and ?ump to the ne6t step'
J' 7o& the multiplicand is multiplied by 2( because the ne6t bit shifted out of the input number is &orth
double as much' 8o &e shift 42 to the left Aby inserting a 5ero in bit 0B using ;8;' 9it I is shifted to
the carry' "hen &e rotate this carry into 4( rotating its content left one bit( and bit I to the carry' "he
same &ith 4J'
H' 7o& &e1re done &ith one digit of the input number( and &e proceed &ith step # again'

"he result of the multiplication by H02 no& is in the result registers 4I $ 46 $ 4H' +f &e ?ust ignore register
4H Adivision by 2H6B( &e have our desired result' "o enhance accuracy( &e can use bit I in 4H to round the
result' 7o& &e ?ust have to convert the result from its binary form to decimal A8C++ Asee Conversion bin to
decimal!A8C++ on the &ebsiteB' +f &e ?ust add a decimal point in the right place in the A8C++ string( our
voltage string is ready for the display'
"he &hole program( from the input number to the resulting A8C++ string( re)uires bet&een I9 and 228
cloc. cycles( depending from the input number' "hose &ho &ant to beat this &ith the floating point routine
of a more sophisticated language than assembler( feel free to mail me your conversion time Aand program
flash and memory usageB'
Example 1: 8-bit-AD-converter with fixed decimal output
' De<onstr%tes f-o%ting Eoint ,onCersion in Asse<)-er, 1"2!006 ;;;.%Cr(%s<(t:tori%-.net
'
' >he t%sM@ .o: re%d in %n 9()it res:-t of %n %n%-og:e(digit%-(,onCerter, n:<)er is in the r%nge fro< he? 00 to FF.
' .o: need to ,onCert this into % f-o%ting Eoint n:<)er in the r%nge fro< 0.00 to 5.00 o-t
' >he Erogr%< s,he<e@
' 1. M:-tiE-i,%tion )y 50! 1he? 01F62.>h%t steE <:-tiE-ies )y 500, !56 %nd diCides )y !55 in one steEU
' !. Ro:nd the res:-t %nd ,:t the -%st )yte of the res:-t. >his steE diCides )y !56 )y ignoring the -%st )yte of the res:-t.
' 3efore doing th%t, )it 8 is :sed to ro:nd the res:-t.
' 6. "onCert the res:-ting ;ord to A*"II %nd set the ,orre,t de,i<%- sign. >he res:-ting ;ord in the r%nge fro< 0 to 500
' is disE-%yed in A*"II(,h%r%,ters %s 0.00 to 5.00.
' >he registers :sed@
' >he ro:tines :se the registers R9..R1 ;itho:t s%Cing these )efore. A-so reN:ired is % <:-tiE:rEose register ,%--ed r<E,
' -o,%ted in the :EEer h%-f of the registers. P-e%se t%Me ,%re th%t these registers donSt ,onf-i,t ;ith the register :se in the
' rest of yo:r Erogr%<.
' 4hen entering the ro:tine the 9()it n:<)er is e?Ee,ted in the register R1. >he <:-tiE-i,%tion :ses R7@R6@R! to ho-d
' the <:-tiE-i,%tor 50! 1is shifted -eft <%?. eight ti<es d:ring <:-tiE-i,%tion2. >he res:-t of the <:-tiE-i,%tion is ,%-,:-%ted
' in the registers R8@R6@R5. >he res:-t of the so ,%--ed diCision )y !56 )y Q:st ignoring R5 in the res:-t, is in R8@R6. R8@R6
' is ro:nded, deEending on the highest )it of R5, %nd the res:-t is ,oEied to R!@R1.
' "onCersion to %n A*"II(string :ses the inE:t in R!@R1, the register E%ir R7@R6 %s % diCisor for ,onCersion, %nd E-%,es the
' A*"II res:-t string to R5@R6@R8@R9 1R6 is the de,i<%- ,h%r2.
' Other ,onCentions@
' >he ,onCersion :ses s:)ro:tines %nd the st%,M.>he st%,M <:st ;orM fine for the :se of three -eCe-s 1si? )ytes *RAM2.
' "onCersion ti<es@
' >he ;ho-e ro:tine reN:ires !!9 ,-o,M ,y,-es <%?i<:< 1,onCerting OFF2, %nd 89 ,-o,M ,y,-es <ini<:< 1,onCerting O002.
' At 7 M/D the ti<es %re 56.85 <i,rose,onds resE. 18.85 <i,rose,onds.
' Definitions@
' Registers
.DEF r<E = R16 ' :sed %s <:-ti(E:rEose register
' AR tyEe@ >ested for tyEe A>90*9515, on-y reN:ired for st%,M setting, ro:tines ;orM fine ;ith other A>90*(tyEes %-so
.&OLI*>
.I&"L$DE =9515def.in,=
.LI*>
' *t%rt of test Erogr%<
' P:st ;rites % n:<)er to R1 %nd st%rts the ,onCersion ro:tine, for test E:rEoses on-y
."*E0
.OR0 O0000
rQ<E <%in
<%in@
-di r<E,/I0/1RAME&D2 ' *et the st%,M
o:t *P/,r<E
-di r<E,LO41RAME&D2
o:t *PL,r<E
-di r<E,OFF ' "onCert OFF
<oC R1,r<E
r,%-- fE,onC9 ' ,%-- the ,onCersion ro:tine
noKend@ ' :n-i<ited -ooE, ;hen done
Avr!Asm!"utorial H9 http$%%&&&'avr!asm!tutorial'net
rQ<E noKend
' "onCersion ro:tine ;r%EEer, ,%--s the different ,onCersion steEs
fE,onC9@
r,%-- fE,onC9< ' <:-tiE-i,%te )y 50!
r,%-- fE,onC9r ' ro:nd %nd diCide )y !56
r,%-- fE,onC9% ' ,onCert to A*"II string
-di r<E,S.S ' set de,i<%- ,h%r
<oC R6,r<E
ret ' %-- done
' *:)ro:tine <:-tiE-i,%tion )y 50!
fE,onC9<@
,-r R7 ' set the <:-tiE-i,%nt to 50!
-di r<E,O01
<oC R6,r<E
-di r<E,OF6
<oC R!,r<E
,-r R8 ' ,-e%r the res:-t
,-r R6
,-r R5
fE,onC9<1@
or R1,R1 ' ,he,M if the n:<)er is %-- Deros
)rne fE,onC9<! ' sti-- oneSs, go on ,onCert
ret ' re%dy, ret:rn )%,M
fE,onC9<!@
-sr R1 ' shift n:<)er to the right 1diC )y !2
)r,, fE,onC9<6 ' if the -o;est )it ;%s 0, then sMiE %dding
%dd R5,R! ' %dd the n:<)er in R6@R5@R7@R6 to the res:-t
%d, R6,R6
%d, R8,R7
fE,onC9<6@
-s- R! ' <:-tiE-y R7@R6@R! )y !
ro- R6
ro- R7
rQ<E fE,onC9<1 ' reEe%t for ne?t )it
' Ro:nd the C%-:e in R8@R6 ;ith the C%-:e in )it 8 of R5
fE,onC9r@
,-r r<E ' E:t Dero to r<E
-s- R5 ' rot%te )it 8 to ,%rry
%d, R6,r<E ' %dd L*3 ;ith ,%rry
%d, R8,r<E ' %dd M*3 ;ith ,%rry
<oC R!,R8 ' ,oEy the C%-:e to R!@R1 1diCide )y !562
<oC R1,R6
ret
' "onCert the ;ord in R!@R1 to %n A*"II string in R5@R6@R8@R9
fE,onC9%@
,-r R7 ' *et the de,i<%- diCider C%-:e to 100
-di r<E,100
<oC R6,r<E
r,%-- fE,onC9d ' get A*"II digit )y reEe%ted s:)tr%,tion
<oC R5,r<E ' set h:ndreds string ,h%r
-di r<E,10 ' *et the de,i<%- diCider C%-:e to 10
<oC R6,r<E
r,%-- fE,onC9d ' get the ne?t A*"II digit
<oC R8,r<E ' set tens string ,h%r
-di r<E,S0S ' ,onCert the rest to %n A*"II ,h%r
%dd r<E,R1
<oC R9,r<E ' set ones string ,h%r
ret
' "onCert )in%ry ;ord in R!@R1 to % de,i<%- digit )y s:)str%,ting the de,i<%- diCider C%-:e in R7@R6 1100, 102
fE,onC9d@
-di r<E,S0S ' st%rt ;ith de,i<%- C%-:e 0
fE,onC9d1@
,E R1,R6 ' "o<E%re ;ord ;ith de,i<%- diCider C%-:e
,E, R!,R7
)r,, fE,onC9d! ' "%rry ,-e%r, s:)tr%,t diCider C%-:e
ret ' done s:)tr%,tion
fE,onC9d!@
s:) R1,R6 ' s:)tr%,t diCider C%-:e
s), R!,R7
in, r<E ' :E one digit
rQ<E fE,onC9d1 ' on,e %g%in
' End of ,onCersion test ro:tine

Example 2: 10-bit-AD-converter with fixed decimal output
"his e6ample is a bit more complicated' 4efer to the &ebsite if you need it'
Avr!Asm!"utorial 60 http$%%&&&'avr!asm!tutorial'net
Annex
Instructions sorted by function
-or the abbreviations used see the list of abbreviations'
0unction Su( function instruction 0lags Cl1
4egister
set
0 C;4 r# P 7 3 #
2HH 8/4 rh #
Constant ;D+ rh(c2HH #
Copy
4egister VT 4egister 2O3 r#(r2 #
84A2 VT 4egister( direct ;D8 r#(c6HHH 2
84A2 VT 4egister ;D r#(rp 2
84A2 VT 4egister and +7C ;D r#(rpG 2
D/C( 84A2 VT 4egister ;D r#(!rp 2
84A2( displaced VT 4egister ;DD r#(ryG.6 2
=ort VT 4egister +7 r#(p# #
8tac. VT 4egister =O= r# 2
=rogram storage P VT 40 ;=2
4egister VT 84A2( direct 8"8 c6HHH(r# 2
4egister VT 84A2 8" rp(r# 2
4egister VT 84A2 and +7C 8" rpG(r# 2
D/C( 4egister VT 84A2 8" !rp(r# 2
4egister VT 84A2( displaced 8"D ryG.6(r# 2
4egister VT =ort O>" p#(r# #
4egister VT 8tac. =>8< r# 2
Add
8 9it( G# +7C r# P 7 3 #
8 9it ADD r#(r2 P C 7 3 < #
8 9it G Carry ADC r#(r2 P C 7 3 < #
#6 9it( constant AD+* rd(.6 P C 7 3 8 2
8ubtract
8 9it( !# D/C r# P 7 3 #
8 9it 8>9 r#(r2 P C 7 3 < #
8 9it( constant 8>9+ rh(c2HH P C 7 3 < #
8 9it ! Carry 89C r#(r2 P C 7 3 < #
8 9it ! Carry( constant 89C+ rh(c2HH P C 7 3 < #
#6 9it 89+* rd(.6 P C 7 3 8 2
8hift
logic( left ;8; r# P C 7 3 #
logic( right ;84 r# P C 7 3 #
4otate( left over Carry 4O; r# P C 7 3 #
4otate( right over Carry 4O4 r# P C 7 3 #
Arithmetic( right A84 r# P C 7 3 #
7ibble e6change 8*A= r# #
9inary
And A7D r#(r2 P 7 3 #
And( constant A7D+ rh(c2HH P 7 3 #
Or O4 r#(r2 P 7 3 #
Or( constant O4+ rh(c2HH P 7 3 #
/6clusive!Or /O4 r#(r2 P 7 3 #
Ones!complement CO2 r# P C 7 3 #
"&os!complement 7/F r# P C 7 3 < #
Avr!Asm!"utorial 6# http$%%&&&'avr!asm!tutorial'net
0unction Su( function instruction 0lags Cl1
9its
change
4egister( set 894 rh(c2HH P 7 3 #
4egister( clear C94 rh(2HH P 7 3 #
4egister( copy to "!-lag 98" r#(bI " #
4egister( copy from "!-lag 9;D r#(bI #
=ort( set 89+ pl(bI 2
=ort( clear C9+ pl(bI 2
8tatus bit
set
Pero!-lag 8/P P #
Carry -lag 8/C C #
7egative -lag 8/7 7 #
"&os complement carry -lag 8/3 3 #
<alf carry -lag 8/< < #
8igned -lag 8/8 8 #
"ransfer -lag 8/" " #
+nterrupt /nable -lag 8/+ + #
8tatus bit
clear
Pero!-lag C;P P #
Carry -lag C;C C #
7egative -lag C;7 7 #
"&os complement carry -lag C;3 3 #
<alf carry -lag C;< < #
8igned -lag C;8 8 #
"ransfer -lag C;" " #
+nterrupt /nable -lag C;+ + #
Compare
4egister( 4egister C= r#(r2 P C 7 3 < #
4egister( 4egister G Carry C=C r#(r2 P C 7 3 < #
4egister( constant C=+ rh(c2HH P C 7 3 < #
4egister( 0 "8" r# P 7 3 #
+mmediate
Jump
4elative 4J2= cJ096 2
+ndirect( Address in P +J2= 2
8ubroutine( relative 4CA;; cJ096
8ubroutine( Address in P +CA;;
4eturn from 8ubroutine 4/" J
4eturn from +nterrupt 4/"+ + J
Avr!Asm!"utorial 62 http$%%&&&'avr!asm!tutorial'net
0unction Su( function instruction 0lags Cl1
Conditional
Jump
8tatus bit set 9498 bI(c#2I #%2
8tatus bit clear 949C bI(c#2I #%2
Jump if e)ual 94/L c#2I #%2
Jump if not e)ual 947/ c#2I #%2
Jump if carry set 94C8 c#2I #%2
Jump if carry clear 94CC c#2I #%2
Jump if e)ual or greater 948< c#2I #%2
Jump if lo&er 94;O c#2I #%2
Jump if negative 942+ c#2I #%2
Jump if positive 94=; c#2I #%2
Jump if greater or e)ual A8ignedB 94F/ c#2I #%2
Jump if lo&er than 5ero A8ignedB 94;" c#2I #%2
Jump on half carry set 94<8 c#2I #%2
Jump if half carry clear 94<C c#2I #%2
Jump if "!-lag set 94"8 c#2I #%2
Jump if "!-lag clear 94"C c#2I #%2
Jump if "&os complement carry set 9438 c#2I #%2
Jump if "&os complement carry clear 943C c#2I #%2
Jump if +nterrupts enabled 94+/ c#2I #%2
Jump if +nterrupts disabled 94+D c#2I #%2
Conditioned
Jumps
4egister bitV0 894C r#(bI #%2%
4egister bitV# 8948 r#(bI #%2%
=ort bitV0 89+C pl(bI #%2%
=ort bitV# 89+8 pl(bI #%2%
Compare( ?ump if e)ual C=8/ r#(r2 #%2%
Others
7o Operation 7O= #
8leep 8;//= #
*atchdog 4eset *D4 #
Directives and Instruction lists in alphabetic order
Assembler directives in alphabetic order
-irecti*e 222 means 222
."*E0 Asse<)-e to the "ode seg<ent
.D3 Insert d%t% )yte1s2
.DEF Define % register n%<e
.D4 Insert d%t% ;ord1s2
.E&DMA"RO M%,ro is ,o<E-ete, stoE re,ording
.E*E0 Asse<)-e to the EEPROM seg<ent
.E#$ Define % ,onst%nt )y n%<e %nd set its C%-:e
.I&"L$DE Insert % fi-eSs ,ontent %t this E-%,e %s if it ;o:-d )e E%rt of this fi-e
.MA"RO *t%rt to re,ord the fo--o;ing instr:,tions %s % <%,ro definition
.OR0 *et the %sse<)-er o:tE:t %ddress to the fo--o;ing n:<)er
Avr!Asm!"utorial 6 http$%%&&&'avr!asm!tutorial'net
Instructions in alphabetic order
Instruction 222 performs 222
AD" r1,r! Add r! ;ith "%rry to r1 %nd store res:-t in r1
ADD r1,r! Add r! to r1 %nd store res:-t in r1
ADI4 rd,M66 Add the i<<edi%te ;ord ,onst%nt M66 to the do:)-e register rdJ1@rd 1rd = R!7, R!6, R!9, R602
A&D r1,r! And )it ;ise r1 ;ith the C%-:e in r! %nd store the res:-t in r1
A&DI rh,,!55 And )it ;ise the :EEer register rh ;ith the ,onst%nt ,!55 %nd store the res:-t in rh
A*R r1 Arith<eti, shift the register r1 right
3LD r1,)8 "oEy the >(f-%g in the st%t:s register to )it )8 in register r1
3R"" ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the ,%rry f-%g in the st%t:s register is ,-e%r
3R"* ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the ,%rry f-%g in the st%t:s register is set
3RE# ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the Dero f-%g in the st%t:s register is set
3R0E ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the ,%rry f-%g in the st%t:s register is ,-e%r
3R/" ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the h%-f ,%rry f-%g in the st%t:s register is ,-e%r
3R/* ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the h%-f ,%rry f-%g in the st%t:s register is set
3RID ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the interr:Et f-%g in the st%t:s register is ,-e%r
3RIE ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the interr:Et f-%g in the st%t:s register is set
3RLO ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the ,%rry f-%g in the st%t:s register is set
3RL> ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the neg%tiCe %nd oCerf-o; f-%g in the st%t:s register %re
set
3RMI ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the neg%tiCe f-%g in the st%t:s register is set
3R&E ,1!8 3r%n,h )y ,1!8 instr:,tions for or )%,M;%rds if the Dero f-%g in the st%t:s register is set
3RPL ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the neg%tiCe f-%g in the st%t:s register is ,-e%r
3R*/ ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the ,%rry f-%g in the st%t:s register is ,-e%r
3R>" ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the tr%nsfer f-%g in the st%t:s register is ,-e%r
3R>* ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the tr%nsfer f-%g in the st%t:s register is set
3R" ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the oCerf-o; f-%g in the st%t:s register is ,-e%r
3R* ,1!8 3r%n,h )y ,1!8 instr:,tions for( or )%,M;%rds if the oCerf-o; f-%g in the st%t:s register is set
3*> r1,)8 "oEy the )it )8 in register r1 to the tr%nsfer f-%g in the st%t:s register
"3I E-,)8 "-e%r )it )8 in the -o;er Eort E-
"3R rh,M!55 "-e%r %-- the )its in the :EEer register rh, th%t %re set in the ,onst%nt M!55 1<%sM2
"L" "-e%r the ,%rry )it in the st%t:s register
"L/ "-e%r the h%-f ,%rry )it in the st%t:s register
"LI "-e%r the interr:Et )it in the st%t:s register, dis%)-e interr:Et e?e,:tion
"L& "-e%r the neg%tiCe )it in the st%t:s register
"LR r1 "-e%r the register r1
"L* "-e%r the signed f-%g in the st%t:s register
"L> "-e%r the tr%nsfer f-%g in the st%t:s register
"L "-e%r the oCerf-o; f-%g in the st%t:s register
"L5 "-e%r the Dero f-%g in the st%t:s register
"OM r1 "o<E-e<ent register r1 1ones ,o<E-e<ent2
"P r1,r! "o<E%re register r1 ;ith register r!
"P" r1,r! "o<E%re register r1 ;ith register r! %nd the ,%rry f-%g
"PI rh,,!55 "o<E%re the :EEer register rh ;ith the i<<edi%te ,onst%nt ,!55
"P*E r1,r! "o<E%re r1 ;ith r! %nd Q:<E oCer the ne?t instr:,tion if eN:%-
DE" r1 De,re<ent register r1 )y 1
EOR r1,r! E?,-:siCe )it ;ise Or register r1 ;ith register r! %nd store res:-t in r1
I"ALL "%-- the s:)ro:tine %t the %ddress in register E%ir 5 15/@5L, R61@R602
IPMP I& r1,E1 P:<E to the %ddress in register E%ir 5 15/@5L, R61@R602
I&" r1 In,re<ent register r1 )y 1
LD r1,1rE,rEJ,(rE2 Lo%d the register r1 ;ith the ,ontent %t the -o,%tion th%t register E%ir rE 1L, . or 52 Eoints to 1rEJ
in,re<ents the register E%ir %fter -o%ding, (rE de,re<ents the register E%ir Erior to -o%ding2
LDD r1,ryJM66 Lo%d the register r1 ;ith the ,ontent %t the -o,%tion th%t register E%ir ry 1. or 52, disE-%,ed )y the
,onst%nt M66, Eoints to
Avr!Asm!"utorial 6J http$%%&&&'avr!asm!tutorial'net
LDI rh,,!55 Lo%d the :EEer register rh ;ith the ,onst%nt ,!55
LD* r1,,65565 Lo%d register r1 ;ith the ,ontent %t -o,%tion ,65565
LPM
LPM r1
LPM r1,5J
LPM r1,(5
Lo%d register R0 ;ith the ,ontent of the f-%sh <e<ory %t the -o,%tion th%t register E%ir 5 15/@5L,
R61@R602, diCided )y !, Eoints to, )it 0 in 5 Eoints to -o;er 102 or :EEer 112 )yte in f-%sh 1Lo%d register
r1, 5J in,re<ent 5 %fter -o%ding, (5 de,re<ent 5 Erior to -o%ding2
L*L r1 Logi,%- shift -eft register r1
L*R r1 Logi,%- shift right register r1
MO r1,r! MoCe register r! to register r1
&E0 r1 *:)tr%,t register r1 fro< 5ero
&OP &o oEer%tion
OR r1,r! 3it ;ise or register r1 ;ith register r! %nd store res:-t in register r1
ORI rh,,!55 3it ;ise or the :EEer register r1 ;ith the ,onst%nt ,!55
O$> E1,r1 "oEy register r1 to IRO Eort E1
POP r1 In,re%se the st%,M Eointer %nd EoE the -%st )yte on st%,M to register r1
P$*/ r1 P:sh register r1 to the st%,M %nd de,re%se the st%,M Eointer
R"ALL ,7096 P:sh Erogr%< ,o:nter on st%,M %nd %dd signed ,onst%nt ,7096 to the Erogr%< ,o:nter 1re-%tiCe ,%--2
RE> PoE Erogr%< ,o:nter fro< st%,M 1ret:rn to ,%-- %ddress2
RE>I En%)-e interr:Ets %nd EoE Erogr%< ,o:nter fro< st%,M 1ret:rn fro< interr:Et2
RPMP ,7096 Re-%tiCe Q:<E, %dd signed ,onst%nt ,7096 to Erogr%< %ddress
ROL r1 Rot%te register r1 -eft, ,oEy ,%rry f-%g to )it 0
ROR r1 Rot%te register r1 right, ,oEy ,%rry f-%g to )it 8
*3" r1,r! *:)tr%,t r! %nd the ,%rry f-%g fro< register r1 %nd ;rite res:-t to r1
*3"I rh,,!55 *:)tr%,t ,onst%nt ,!55 %nd ,%rry f-%g fro< the :EEer register rh %nd ;rite res:-t to rh
*3I E-,)8 *et )it )8 in the -o;er Eort E-
*3I" E-,)8 If )it )8 in the -o;er Eort E- is ,-e%r, Q:<E oCer the ne?t instr:,tion
*3I* E-,)8 If )it )8 in the -o;er Eort E- is set, Q:<E oCer the ne?t instr:,tion
*3I4 rd,M66 *:)tr%,t the ,onst%nt M66 fro< the register E%ir rd 1rdJ1@rd, rd = R!7, R!6, R!9, R602
*3R rh,,!55 *et the )its in the :EEer register rh, th%t %re one in ,onst%nt ,!55
*3R" r1,)8 If )it )8 in register r1 is ,-e%r, Q:<E oCer ne?t instr:,tion
*3R* r1,)8 If )it )8 in register r1 is set, Q:<E oCer ne?t instr:,tion
*E" *et ,%rry f-%g in st%t:s register
*E/ *et h%-f ,%rry f-%g in st%t:s register
*EI *et interr:Et f-%g in st%t:s register, en%)-e interr:Et e?e,:tion
*E& *et neg%tiCe f-%g in st%t:s register
*ER rh *et %-- )its in the :EEer register rh
*E* *et sign f-%g in st%t:s register
*E> *et tr%nsfer f-%g in st%t:s register
*E *et oCerf-o; f-%g in st%t:s register
*E5 *et Dero f-%g in st%t:s register
*LEEP P:t ,ontro--er to the se-e,ted s-eeE <ode
*> 1rERrEJR(rE2,r1 *tore ,ontent in register r1 to the <e<ory -o,%tion in register E%ir rE 1rE = L, ., 5' rEJ@ in,re<ent
register E%ir %fter store' (rE@ de,re<ent register E%ir Erior to store2
*>D ryJM66,r1 *tore the ,ontent of register r1 %t the -o,%tion th%t register E%ir ry 1. or 52, disE-%,ed )y the ,onst%nt
M66, Eoints to
*>* ,65565,r1 *tore the ,ontent of register r1 %t the -o,%tion ,65565
*$3 r1,r! *:)tr%,t register r! fro< register r1 %nd ;rite res:-t to r1
*$3I rh,,!55 *:)tr%,t the ,onst%nt ,!55 fro< the :EEer register rh
*4AP r1 E?,h%nge :EEer %nd -o;er ni))-e in register r1
>*> r1 "o<E%re register r1 ;ith 5ero
4DR 4%t,hdog reset
Avr!Asm!"utorial 6H http$%%&&&'avr!asm!tutorial'net
Port details
"he table of the relevant ports in the A"2/; A34 types A"9082#( 22 and 8H#H' 9yte &ise accessible
ports or register pairs are not displayed in detail' 7o &arranty for correctness( see the original data sheets@
Status-Register, Accumulator flags
Port 0unction Port-!!ress R3-!!ress
84/F 8tatus 4egister Accumulator 06- 06H-
4 + & , # " $ 5
+ " < 8 3 7 P C
Bit Name 3eaning Opportunities Conmman!
I + Flobal +nterrupt -lag
0$ +nterrupts disabled C;+
#$ +nterrupts enabled 8/+
6 " 9it storage
0$ 8tored bit is 0 C;"
#$ 8tored bit is # 8/"
H < <alfcarry!-lag
0$ 7o halfcarry occurred C;<
#$ <alfcarry occurred 8/<
J 8 8ign!-lag
0$ 8ign positive C;8
#$ 8ign negative 8/8
3 "&o1s complement!-lag
0$ 7o carry occurred C;3
#$ Carry occurred 8/3
2 7 7egative!-lag
0$ 4esult &as not negative%smaller C;7
#$ 4esult &as negative%smaller 8/7
# P Pero!-lag
0$ 4esult &as not 5ero%une)ual C;P
#$ 4esult &as 5ero%e)ual 8/P
0 C Carry!-lag
0$ 7o carry occurred C;C
#$ Carry occurred 8/C
Stackpointer
Port 0unction Port-!!ress R3-!!ress
8=;%8=
<
8tac.pointer 00D%06/ 06HD%06H/
Name 3eaning *aila(ilit)
8=;
;o&!9yte of 8tac.
pointer
-rom A"9082# up&ards( not in #200
8=<
<igh!9yte of 8tac.
pointer
-rom A"9088H#H up&ards( only in devices &ith T2H6 bytes internal 84A2
SRAM and External Interrupt control
Port 0unction Port-!!ress R3-!!ress
2C>C4 2C> Feneral Control 4egister 06H 06HH
4 + & , # " $ 5
84/ 84* 8/ 82 +8C## +8C#0 +8C0# +8C00
Bit Name 3eaning Opportunities
I 84/ /6t' 84A2 /nable
0V7o e6ternal 84A2 connected
#V/6ternal 84A2 connected
Avr!Asm!"utorial 66 http$%%&&&'avr!asm!tutorial'net
Bit Name 3eaning Opportunities
6 84* /6t' 84A2 *ait 8tates
0V7o e6tra &ait state on e6ternal 84A2
#VAdditional &ait state on e6ternal 84A2
H 8/ 8leep /nable
0V+gnore 8;//= instructions
#V8;//= on instruction
J 82 8leep 2ode
0V+dle 2ode A<alf sleepB
#V=o&er Do&n 2ode A-ull sleepB
+8C##
2 +8C#0
+nterrupt control =in +7"#
Aconnected to F+28EB
00$ ;o&!level initiates +nterrupt
0#$ >ndefined
#0$ -alling edge triggers interrupt
##$ 4ising edge triggers interrupt
# +8C0#
0 +8C00
+nterrupt control =in +7"0
Aconnected to F+28EB
00$ ;o&!level initiates interrupt
0#$ >ndefined
#0$ -alling edge triggers interrupt
##$ 4ising edge triggers interrupt
External Interrupt Control
Port 0unction Port-!!ress R3-!!ress
F+28E Feneral +nterrupt 2as.register 069 06H9
4 + & , # " $ 5
+7"# +7"0 ! ! ! ! ! !
Bit Name 3eaning Opportunities
I +7"#
+nterrupt by e6ternal pin +7"#
Aconnected to mode in 2C>C4B
0$ /6ternal +7"# disabled
#$ /6ternal +7"# enabled
6 +7"0
+nterrupt by e6ternal =in +7"0
Aconnected to mode in 2C>C4B
0$ /6ternal +7"0 disabled
#$ /6ternal +7"0 enabled
0'''H A7ot usedB
Port 0unction Port-!!ress R3-!!ress
F+-4 Feneral +nterrupt -lag 4egister 06A 06HA
4 + & , # " $ 5
+7"-# +7"-0 ! ! ! ! ! !
Bit Name 3eaning Opportunities
I +7"-# +nterrupt by e6ternal pin +7"# occurred
6 +7"-0 +nterrupt by e6ternal pin +7"0 occurred
Automatic clear by e6ecution of the +nt!4outine or
Clear by instruction
0'''H A7ot usedB
Timer Interrupt Control
Port 0unction Port-!!ress R3-!!ress
"+28E "imer +nterrupt 2as.register 069 06H9
4 + & , # " $ 5
"O+/# OC+/#A OC+/#9 ! "+C+/# ! "O+/0 !
Avr!Asm!"utorial 6I http$%%&&&'avr!asm!tutorial'net
Bit Name 3eaning Opportunities
I "O+/# "imer%Counter # Overflo&!+nterrupt
0$ 7o +nt at overflo&
#$ +nt at overflo&
6 OC+/#A "imer%Counter # Compare A +nterrupt
0$ 7o +nt at e)ual A
#$ +nt at e)ual A
H OC+/#9 "imer%Counter # Compare 9 +nterrupt
0$ 7o +nt at 9
#$ +nt at e)ual 9
J A7ot usedB
"+C+/# "imer%Counter # Capture +nterrupt
0$ 7o +nt at Capture
#$ +nt at Capture
2 A7ot usedB
# "O+/0 "imer%Counter 0 Overflo&!+nterrupt
0$ 7o +nt at overflo&
#$ +nt at overflo&
0 A7ot usedB
Port 0unction Port-!!ress R3-!!ress
"+-4 "imer +nterrupt -lag 4egister 068 06H8
4 + & , # " $ 5
"O3# OC-#A OC-#9 ! +C-# ! "O30 !
Bit Name 3eaning Opportunities
I "O3# "imer%Counter # Overflo& reached
6 OC-#A "imer%Counter # Compare A reached
H OC-#9 "imer%Counter # Compare 9 reached
J A7ot usedB
+C-# "imer%Counter # Capture!/vent occurred
2 Anot usedB
# "O30 "imer%Counter 0 Overflo& occurred
0 Anot usedB
+nterrupt!2ode$
Automatic Clear
by e6ecution of the
+nt!4outine
O4
=olling!2ode$
Clear by
instruction
Timer/Counter 0
Port 0unction Port-!!ress R3-!!ress
"CC40 "imer%Counter 0 Control 4egister 06 06H
4 + & , # " $ 5
! ! ! ! ! C802 C80# C800
Bit Name 3eaning Opportunities
2''0 C802''C800 "imer Cloc.
000$ 8top "imer
00#$ Cloc. V Chip cloc.
0#0$ Cloc. V Chip cloc. % 8
0##$ Cloc. V Chip cloc. % 6J
#00$ Cloc. V Chip cloc. % 2H6
#0#$ Cloc. V Chip cloc. % #02J
##0$ Cloc. V falling edge of e6ternal =in "0
###$ Cloc. V rising edge of e6ternal =in "0
''I Anot usedB
Avr!Asm!"utorial 68 http$%%&&&'avr!asm!tutorial'net
Port 0unction Port-!!ress R3-!!ress
"C7"0 "imer%Counter 0 count register 062 06H2
Timer/Counter 1
Port 0unction Port-!!ress R3-!!ress
"CC4#A "imer%Counter # Control 4egister A 062- 06J-
4 + & , # " $ 5
CO2#A# CO2#A0 CO2#9# CO2#90 ! ! =*2## =*2#0
Bit Name 3eaning Opportunities
I CO2#A#
6 CO2#A0
Compare Output A
H CO2#9#
J CO2#90
Compare Output 9
00$ OC#A%9 not connected
0#$ OC#A%9 changes polarity
#0$ OC#A%9 to 5ero
##$ OC#A%9 to one

2
Anot usedB
#''0
=*2##
=*2#0
=ulse &idth modulator
00$ =*2 off
0#$ 8!9it =*2
#0$ 9!9it =*2
##$ #0!9it =*2
Port 0unction Port-!!ress R3-!!ress
"CC4#9 "imer%Counter # Control 4egister 9 062/ 06J/
4 + & , # " $ 5
+C7C# +C/8# ! ! C"C# C8#2 C8## C8#0
Bit Name 3eaning Opportunities
I +C7C#
7oise Canceler
on +C=!=in
0$ disabled( first edge starts sampling
#$ enabled( min four cloc. cycles
6 +C/8#
/dge selection
on Capture
0$ falling edge triggers Capture
#$ rising edge triggers Capture
H''J Anot usedB
C"C#
Clear at
Compare 2atch A
#$ Counter set to 5ero if e)ual
2''0 C8#2''C8#0 Cloc. select
000$ Counter stopped
00#$ Cloc.
0#0$ Cloc. % 8
0##$ Cloc. % 6J
#00$ Cloc. % 2H6
#0#$ Cloc. % #02J
##0$ falling edge e6ternal =in "#
###$ rising edge e6ternal =in "#
Port 0unction Port-!!ress R3-!!ress
"C7"#;%< "imer%Counter # count register 062C%062D 06JC%06JD
Avr!Asm!"utorial 69 http$%%&&&'avr!asm!tutorial'net
Port 0unction Port-!!ress R3-!!ress
OC4#A;%< "imer%Counter # Output Compare register A 062A%0629 06JA%06J9 he6
Port 0unction Port-!!ress R3-!!ress
OC4#9;%< "imer%Counter # Output Compare register 9 0628%0629 06J8%06J9
Port 0unction Port-!!ress R3-!!ress
+C4#;%< "imer%Counter # +nput Capture 4egister 062J%062H 06JJ%06JH
Watchdog-Timer
Port 0unction Port-!!ress R3-!!ress
*D"C4 *atchdog "imer Control 4egister 062# 06J#
4 + & , # " $ 5
! ! ! *D"O/ *D/ *D=2 *D=# *D=0
Bit Name 3eaning 6-'-c)cle at &25 Volt
I''H Anot usedB
J *D"O/ *atchdog "urnoff /nable
=revious set to
disabling of *D/ re)uired
*D/ *atchdog /nable #$ *atchdog active
2''0 *D=2''*D=0 *atchdog "imer =rescaler
000$ #H ms
00#$ 0 ms
0#0$ 60 ms
0##$ #20 ms
#00$ 2J0 ms
#0#$ J90 ms
##0$ 9I0 ms
###$ #(9 s
EEPROM
Port 0unction Port-!!ress R3-!!ress
//A4;%< //=4O2 Address 4egister 06#/%06#- 06/%06-
//A4< only in types &ith more than 2H6 9ytes //=4O2 Afrom A"9088H#H up&ardsB
Port 0unction Port-!!ress R3-!!ress
//D4 //=4O2 Data 4egister 06#D 06D
Port 0unction Port-!!ress R3-!!ress
//C4 //=4O2 Control 4egister 06#C 06C
4 + & , # " $ 5
! ! ! ! ! //2*/ //*/ //4/
Avr!Asm!"utorial I0 http$%%&&&'avr!asm!tutorial'net
Bit Name 3eaning 0unction
I''

Anot usedB
2 //2*/ //=4O2 2aster *rite /nable =revious set enables &rite cycle
# //*/ //=4O2 *rite /nable 8et to initiate &rite
0 //4/ //=4O2 4ead /nable 8et initiates read
Serial Peripheral Interface SPI
Port 0unction Port-!!ress R3-!!ress
8=C4 8=+ Control 4egister 060D 062D
4 + & , # " $ 5
8=+/ 8=/ DO4D 28"4 C=O; C=<A 8=4# 8=40
Bit Name 3eaning 0unction
I 8=+/ 8=+ +nterrupt /nable
0$ +nterrupts disabled
#$ +nterrupts enabled
6 8=/ 8=+ /nable
0$ 8=+ disabled
#$ 8=+ enabled
H DO4D Data Order
0$ 289 first
#$ ;89 first
J 28"4 2aster%8lave 8elect
0$ 8lave
#$ 2aster
C=O; Cloc. =olarity
0$ =ositive Cloc. =hase
#$ 7egative Cloc. =hase
2 C=<A Cloc. =hase
0$ 8ampling at beginning of Cloc. =hase
#$ 8ampling at end of Cloc. =hase
# 8=4#
0 8=40
8CE cloc. fre)uency
00$ Cloc. % J
0#$ Cloc. % #6
#0$ Cloc. % 6J
##$ Cloc. % #28
Port 0unction Port-!!ress R3-!!ress
8=84 8=+ 8tatus 4egister 060/ 062/
4 + & , # " $ 5
8=+- *CO; ! ! ! ! ! !
Bit Name 3eaning 0unction
I 8=+- 8=+ +nterrupt -lag +nterrupt re)uest
6 *CO; *rite Collision -lag *rite collission occurred
H''0 Anot usedB
Port 0unction Port-!!ress R3-!!ress
8=D4 8=+ Data 4egister 060- 062-
Avr!Asm!"utorial I# http$%%&&&'avr!asm!tutorial'net
UART
Port 0unction Port-!!ress R3-!!ress
>D4 >A4" +%O Data 4egister 060C 062C
Port 0unction Port-!!ress R3-!!ress
>84 >A4" 8tatus 4egister 0609 0629
4 + & , # " $ 5
4KC "KC >D4/ -/ O4 ! ! !
Bit Name 3eaning 0unction
I 4KC >A4" 4eceive Complete #$ Char received
6 "KC >A4" "ransmit Complete #$ 8hift register empty
H >D4/ >A4" Data 4egister /mpty #$ "ransmit register available
J -/ -raming /rror #$ +llegal 8top!9it
O4 Overrun #$ ;ost char
2''0 Anot usedB
Port 0unction Port-!!ress R3-!!ress
>C4 >A4" Control 4egister 060A 062A
4 + & , # " $ 5
4KC+/ "KC+/ >D4+/ 4K/7 "K/7 C<49 4K98 "K98
Bit Name 3eaning 0unction
I 4KC+/ 4K Complete +nterrupt /nable #$ +nterrupt on received char
6 "KC+/ "K Complete +nterrupt /nable #$ +nterrupt at transmit complete
H >D4+/ Data 4egister /mpty +nterrupt /nable #$ +nterrupt on transmit buffer empty
J 4K/7 4eceiver /nable #$ 4eceiver enabled
"K/7 "ransmitter /nable #$ "ransmitter enabled
2 C<49 9!bit Characters #$ Char length 9 9it
# 4K98 4eceive Data 9it 8 Aholds 9
th
data bit on receiveB
0 "K98 "ransmit Data 9it 8 A&rite 9
th
data bit for transmit hereB
Port 0unction Port-!!ress R3-!!ress
>944 >A4" 9aud 4ate 4egister 0609 0629
Analog Comparator
Port 0unction Port-!!ress R3-!!ress
AC84 Analog Comparator Control and 8tatus 4egister 0608 0628
4 + & , # " $ 5
ACD ! ACO AC+ AC+/ AC+C AC+8# AC+80
Bit Name 3eaning 0unction
I ACD Disable Disable Comparators
6 Anot usedB
H ACO Comparator Output 4ead$ Output of the Comparators
J AC+ +nterrupt -lag #$ +nterrupt re)uest
Avr!Asm!"utorial I2 http$%%&&&'avr!asm!tutorial'net
Bit Name 3eaning 0unction
AC+/ +nterrupt /nable #$ +nterrupts enabled
2 AC+C +nput Capture /nable #$ Connect to "imer # Capture
# AC+8#
0 AC+80
+nput Capture /nable
00$ +nterrupt on edge change
0#$ Anot usedB
#0$ +nterrupt on falling edge
##$ +nterrupt on rising edge
I/O Ports
Port Register 0unction Port-!!ress R3-!!ress
A
=O4"A Data 4egister 06#9 069
DD4A Data Direction 4egister 06#A 06A
=+7A +nput =ins Address 06#9 069
9
=O4"9 Data 4egister 06#8 068
DD49 Data Direction 4egister 06#I 06I
=+79 +nput =ins Address 06#6 066
C
=O4"C Data 4egister 06#H 06H
DD4C Data Direction 4egister 06#J 06J
=+7C +nput =ins Address 06# 06
D
=O4"D Data 4egister 06#2 062
DD4D Data Direction 4egister 06## 06#
=+7D +nput =ins Address 06#0 060
Ports, alphabetic order
A"*R, An%-og "o<E%r%tor "ontro- %nd *t%t:s Register
DDR?, Port ? D%t% Dire,tion Register
EEAR, EEPROM %ddress Register
EE"R, EEPROM "ontro- Register
EEDR, EEPROM D%t% Register
0IFR, 0ener%- Interr:Et F-%g Register
0IM*V, 0ener%- Interr:Et M%sM Register
I"R1LR/, InE:t "%Et:re Register 1
M"$"R, M"$ 0ener%- "ontro- Register
O"R1A, O:tE:t "o<E%re Register 1 A
O"R13, O:tE:t "o<E%re Register 1 3
PI&?, Port InE:t A,,ess
POR>?, Port ? O:tE:t Register
*PLR*P/, *t%,MEointer
*P"R, *eri%- PeriEher%- "ontro- Register
*PDR, *eri%- PeriEher%- D%t% Register
*P*R, *eri%- PeriEher%- *t%t:s Register
*RE0, *t%t:s Register
>""R0, >i<erR"o:nter "ontro- Register, >i<er 0
>""R1A, >i<erR"o:nter "ontro- Register 1 A
>""R13, >i<erR"o:nter "ontro- Register 1 3
>"&>0, >i<erR"o:nter Register, "o:nter 0
>"&>1, >i<erR"o:nter Register, "o:nter 1
>IFR, >i<er Interr:Et F-%g Register
>IM*V, >i<er Interr:Et M%sM Register
$3RR, $AR> 3%:d R%te Register
$"R, $AR> "ontro- Register
$DR, $AR> D%t% Register
4D>"R, 4%t,hdog >i<er "ontro- Register
Avr!Asm!"utorial I http$%%&&&'avr!asm!tutorial'net
List of abbreviations
"he abbreviations used are chosen to include the value range' 4egister pairs are named by the lo&er of
the t&o registers' Constants in ?ump instructions are automatically calculated from the respective labels
during assembly'
Categor) ((re*2 3eans 222 Value range
4egister
r# Ordinary 8ource and "arget register
r2 Ordinary 8ource register
40''4#
rh >pper page register 4#6''4#
rd "&in register 42JA42HB( 426A42IB( 428A429B( 40A4#B
rp =ointer register KV426A42IB( 0V428A429B( PV40A4#B
ry =ointer register &ith displacement 0V428A429B( PV40A4#B
Constant
.6 =ointer!constant 0''6
c#2I Conditioned ?ump distance !6J''G6
c2HH 8!9it!Constant 0''2HH
cJ096 4elative ?ump distance !20J8''G20JI
c6HHH #6!9it!Address 0''6HHH
9it bI 9it position 0''I
=ort
p# Ordinary =ort 0''6
pl ;o&er page port 0''#

You might also like