You are on page 1of 81

Beginners Introduction to the

Assembly Language of
ATMEL-AVR-Microprocessors
by
Gerhard Schmidt
http://www.avr-asm-tutorial.net
February 2011
History:
Added page on assembler concept in February 2011
Added chapter on code structures in April 2009
Additional corrections and updates as of January 2008
Corrected version as of July 2006
riginal version as of !ecember 200"
Avr-Asm-Tutorial 1 http://www.avr-asm-tutorial.net
Content
1 Why learning Assembler?......................................................................................................................1
2 The concept behind the language assembler in micro-controllers.........................................................2
2.1 The hardware of micro-controllers.................................................................................................2
2.2 How the C! wor"s.......................................................................................................................2
2.# $nstructions in assembler................................................................................................................#
2.% &ifference to high-le'el languages.................................................................................................#
2.( Assembler is not machine language...............................................................................................#
2.) $nterpreting and assembler..............................................................................................................%
2.* High le'el languages and Assembler..............................................................................................%
2.+ What is really easier in assembler?................................................................................................(
# Hardware for A,--Assembler-rogramming.......................................................................................)
#.1 The $. $nterface of the A,- processor family.............................................................................)
#.2 rogrammer for the C-arallel-ort.............................................................................................)
#.# /0perimental boards.......................................................................................................................*
#.#.1 /0perimental board with an ATtiny1#...................................................................................*
#.#.2 /0perimental board with an AT12.2#1#3ATmega2#1#........................................................+
#.% -eady-to-use commercial programming boards for the A,--family............................................1
#.%.1 .T4222...................................................................................................................................1
#.%.2 .T4(22...................................................................................................................................1
#.%.# A,- &ragon.........................................................................................................................12
% Tools for A,- assembly programming...............................................................................................11
%.1 The editor.....................................................................................................................................11
%.1.1 A simple typewriter..............................................................................................................11
%.1.2 .tructuring assembler code...................................................................................................12
%.2 The assembler...............................................................................................................................1(
%.# rogramming the chips.................................................................................................................1)
%.% .imulation in the studio................................................................................................................1)
( What is a register?................................................................................................................................21
(.1 &ifferent registers.........................................................................................................................22
(.2 ointer-registers............................................................................................................................22
(.2.1 Accessing memory locations with pointers..........................................................................22
(.2.2 -eading program flash memory with the 5 pointer..............................................................22
(.2.# Tables in the program flash memory....................................................................................2#
(.2.% Accessing registers with pointers.........................................................................................2#
(.# -ecommendation for the use of registers.....................................................................................2%
) orts.....................................................................................................................................................2(
).1 What is a ort?.............................................................................................................................2(
).2 Write access to ports.....................................................................................................................2(
).# -ead access to ports......................................................................................................................2)
).% -ead-6odify-Write access to ports..............................................................................................2)
).( 6emory mapped port access........................................................................................................2)
).) &etails of rele'ant ports in the A,-............................................................................................2)
).* The status register as the most used port......................................................................................2*
).+ ort details....................................................................................................................................2+
* .-A6..................................................................................................................................................21
*.1 What is .-A6?...........................................................................................................................21
*.2 7or what purposes can $ use .-A6?...........................................................................................21
*.# How to use .-A6?......................................................................................................................21
*.#.1 &irect addressing..................................................................................................................21
*.#.2 ointer addressing.................................................................................................................#2
*.#.# ointer with offset.................................................................................................................#2
*.% !se of .-A6 as stac"..................................................................................................................#2
*.%.1 &efining .-A6 as stac"......................................................................................................#2
*.%.2 !se of the stac".....................................................................................................................#1
*.%.# Common bugs with the stac" operation................................................................................#1
+ 8umping and branching........................................................................................................................##
+.1 Controlling se9uential e0ecution of the program.........................................................................##
+.2 :inear program e0ecution and branches.......................................................................................#%
+.# Timing during program e0ecution................................................................................................#(
+.% 6acros and program e0ecution....................................................................................................#(
+.( .ubroutines...................................................................................................................................#(
Avr-Asm-Tutorial 2 http://www.avr-asm-tutorial.net
+.) $nterrupts and program e0ecution.................................................................................................#*
1 Calculations..........................................................................................................................................#1
1.1 ;umber systems in assembler......................................................................................................#1
1.1.1 ositi'e whole numbers <bytes= words= etc.>........................................................................#1
1.1.2 .igned numbers <integers>....................................................................................................#1
1.1.# ?inary Coded &igits= ?C&...................................................................................................#1
1.1.% ac"ed ?C&s........................................................................................................................%2
1.1.( ;umbers in A.C$$-format....................................................................................................%2
1.2 ?it manipulations.........................................................................................................................%2
1.# .hift and rotate.............................................................................................................................%1
1.% Adding= subtracting and comparing..............................................................................................%2
1.%.1 Adding and subtracting 1)-bit numbers................................................................................%2
1.%.2 Comparing 1)-bit numbers...................................................................................................%2
1.%.# Comparing with constants....................................................................................................%2
1.%.% ac"ed ?C& math.................................................................................................................%#
1.( 7ormat con'ersion for numbers....................................................................................................%#
1.(.1 Con'ersion of pac"ed ?C&s to ?C&s= A.C$$ or ?inaries...................................................%#
1.(.2 Con'ersion of ?inaries to ?C&............................................................................................%%
1.) 6ultiplication...............................................................................................................................%%
1.).1 &ecimal multiplication.........................................................................................................%%
1.).2 ?inary multiplication............................................................................................................%%
1.).# A,- assembler program......................................................................................................%(
1.).% ?inary rotation......................................................................................................................%)
1.).( 6ultiplication in the studio...................................................................................................%)
1.* Hardware multiplication...............................................................................................................%+
1.*.1 Hardware multiplication of +-by-+-bit binaries....................................................................%+
1.*.2 Hardware multiplication of a 1)- by an +-bit-binary............................................................%1
1.*.# Hardware multiplication of a 1)- by a 1)-bit-binary............................................................(2
1.*.% Hardware multiplication of a 1)- by a 2%-bit-binary............................................................(2
1.+ &i'ision........................................................................................................................................(#
1.+.1 &ecimal di'ision...................................................................................................................(#
1.+.2 ?inary di'ision......................................................................................................................(%
1.+.# rogram steps during di'ision..............................................................................................(%
1.+.% &i'ision in the simulator......................................................................................................((
1.1 ;umber con'ersion......................................................................................................................()
1.12 &ecimal 7ractions.......................................................................................................................(*
1.12.1 :inear con'ersions..............................................................................................................(*
1.12.2 /0ample 1@ +-bit-A&-con'erter with fi0ed decimal output................................................(+
1.12.# /0ample 2@ 12-bit-A&-con'erter with fi0ed decimal output..............................................(1
12 roAect planning.................................................................................................................................)2
12.1 How to plan an A,- proAect in assembler.................................................................................)2
12.2 Hardware considerations............................................................................................................)2
12.# Considerations on interrupt operation........................................................................................)2
12.#.1 ?asic re9uirements of interrupt-dri'en operation...............................................................)1
12.#.2 /0ample for an interrupt-dri'en assembler program..........................................................)1
12.% Considerations on timing............................................................................................................)#
11 Anne0.................................................................................................................................................)%
11.1 $nstructions sorted by function...................................................................................................)%
11.2 &irecti'es and $nstruction lists in alphabetic order....................................................................))
11.2.1 Assembler directi'es in alphabetic order............................................................................))
11.2.2 $nstructions in alphabetic order...........................................................................................)*
11.# ort details..................................................................................................................................)1
11.#.1 .tatus--egister= Accumulator flags....................................................................................)1
11.#.2 .tac"pointer........................................................................................................................)1
11.#.# .-A6 and /0ternal $nterrupt control................................................................................)1
11.#.% /0ternal $nterrupt Control...................................................................................................*2
11.#.( Timer $nterrupt Control......................................................................................................*2
11.#.) Timer3Counter 2..................................................................................................................*1
11.#.* Timer3Counter 1..................................................................................................................*2
11.#.+ Watchdog-Timer.................................................................................................................*#
11.#.1 //-B6............................................................................................................................*#
11.#.12 .erial eripheral $nterface .$..........................................................................................*%
11.#.11 !A-T...............................................................................................................................*(
Avr-Asm-Tutorial 3 http://www.avr-asm-tutorial.net
11.#.12 Analog Comparator..........................................................................................................*(
11.#.1# $3B orts............................................................................................................................*)
11.% orts= alphabetic order................................................................................................................*)
11.( :ist of abbre'iations...................................................................................................................**
Avr-Asm-Tutorial 1 http://www.avr-asm-tutorial.net
!hy 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 France you are able to get through by spea,ing -nglish# but
you +ill never feel at home then# and life remains complicated% .ou can get through +ith this# but it is rather
inappropriate% 'f things need a hurry# you should use the country/s language%
0any people that are deeper into programming A12s and use higher3level 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 analy4ed#
if the program e5ecutes different than designed and e5pected#
if the higher3level language doesn/t support the use of certain hard+are features#
if time3critical in line routines re$uire assembly language portions#
it is necessary to understand assembly language# e% g% to understand +hat the higher3level 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 e5ecuted machine instructions% )he processor needs only to e5ecute +hat
you +ant it to do and +hat is necessary to perform the tas,% 6o e5tra loops and unnecessary features blo+ up the
generated code% 'f your program storage is short and limited and you have to optimi4e your program to fit into memory#
assembler is choice 1% 7horter programs are easier to debug# every step ma,es sense%
Fast and quick
8ecause only necessary code steps are e5ecuted# 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 e5cellent# must
be +ritten in assembler% 'f you have more time and don/t mind if your chip remains 999 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+are3dependent 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 controller/s 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 100 additional lines programmed it loo,s better% <erfect
programs re$uire some thousand lines of code of e5ercise# and optimi4ation 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% 7ome assembler
instructions need some months of e5perience%
AVRs are ideal for learning assembler
Assembler programs are a little bit silly* the chip e5ecutes 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 e5actly anything li,e it is told#
even if it doesn/t ma,e any sense% 6o +indo+ +arns you# unless you programmed it before%
)o correct typing errors is as easy or complicated as in any other language% 8asic design errors# the more tric,y type of
errors# are also as complicated to debug li,e in any other computer language% 8ut* testing programs on A)0-: chips is very
easy% 'f it does not do +hat you e5pect it to do# you can easily add some diagnostic lines to the code# reprogram the chip
and test it% 8ye# bye to you -<20 programmers# to the =1 lamps used to erase your test program# to you pins that don/t
fit into the soc,et after having them removed some do4en times%
Changes are no+ programmed fast# compiled in no time# and either simulated in the studio or chec,ed in3circuit% 6o pin is
removed# and no =1 lamp gives up >ust in the moment +hen you had your e5cellent idea about that bug%
Test it!
8e patient doing your first steps? 'f you are familiar +ith another @high3levelA language* forget it for the first time% 8ehind
every assembler language there is a certain hard+are concept% 0ost of the special features of other computer languages
don/t 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%
7erious +arning* !on/t try to program a mega3machine to start +ith% )his does not ma,e sense in any computer language#
and >ust produces frustration% 7tart +ith the small B;ello +orldC3li,e e5amples# e% g% turning some :-!s on and off for a
certain time# then e5plore the hard+are features a bit deeper%
2ecommendation* 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-Tutorial 2 http://www.avr-asm-tutorial.net
# The concept behind the language
assembler in micro-controllers
Attention? )hese pages are on programming micro3controllers# not on <Cs +ith :inu53 or &indo+s operating systems and
similar elephants# but on a small mice% 't is not on programming -thernet mega3machines# but on the $uestion +hy a
beginner should start +ith assembler and not +ith a comple5 high3level language%
)his page sho+s the concept behind assembler# +hat those familiar +ith high3level languages have to give up to learn
assembler and +hy assembler is not machine language%
2.1 The hardware of micro-controllers
&hat has the hard+are to do +ith assembler( 0uch# as can be seen from the follo+ing%
)he concept behind assembler is to ma,e the hard+are resources of the processor accessible% 2esources means all
hard+are components# li,e
D the central processing unit @C<=A and its math servant# the arithmetic and logic unit @A:=A#
D the diverse storage units @internal and e5ternal 2A0# --<20 storageA#
D the ports that control characteristics of port3bits# timers# A! converters# and other devices%
Accessible means directly accessible and not via drivers or other interfaces# that an operating system provides% )hat
means# you control the serial interface or the A! converter# not some other layer bet+een you and the hard+are% As
a+ard for your efforts# the complete hard+are is at your command# not only the part that the compiler designer and the
operating system programmer provides for you%
2.2 How the CPU works
0ost important for understanding assembler is to understand ho+ the C<= +or,s% )he C<= reads instructions @instruction
fetchA from the program storage @the flashA# translates those into e5ecutable steps and e5ecutes those% 'n A12s# those
instructions are +ritten as 16 bit numbers to the flash storage# and are read from there @first stepA% )he number read then
translates @second stepA e% g% to transporting the content of the t+o registers 20 and 21 to the A:= @third stepA# to add
those @fourth stepA and to +rite the result into the register 20 @fifth stepA% 2egisters are simple 8 bit +ide storages that can
directly be tied to the A:= to be read from and to be +ritten to%
)he coding of instructions is demonstrated by some e5amples%
CPU operation Code (binary Code (he!
7end C<= to sleep 1001%0101%1000%1000 9E88
Add register 21 to register 20 0000%1100%0000%0001 0C01
7ubtract register 21 from register 20 0001%1000%0000%0001 1801
&rite constant 1F0 to register 216 1110%1010%0000%1010 -A0A
0ultiply register 2" +ith register 22 and +rite the result to registers 21 @078A and
20 @:78A
1001%1100%0011%0010 9C"2
7o# if the C<= reads he5 9E88 from the flash storage# it stops its operation and does not fetch instructions any more% !on/t
be afraid# there is another mechanism necessary before the C<= e5ecutes this% And you can +a,e up the C<= from that%
Executing instructions
'f the C<= reads he5 0C01# 20 and 21 is added and the result is +ritten to register 20% )his is e5ecuted li,e demonstrated in
the picture%
First the
instruction
+ord @16 bitA
is read from
the flash and
translated to
e5ecutable
steps @1A%
)he ne5t step
connects the
registers to
the A:=
inputs# and
adds their content @2A%
6e5t# the result is +ritten to the register @"A%
Avr-Asm-Tutorial 3 http://www.avr-asm-tutorial.net
'f the C<= reads he5 9C2" from the flash# the registers 2" and 22 are muliplied and the result is +ritten to 21 @upper 8 bitsA
and 20 @lo+er 8 bitsA% 'f the A:= is not e$uipped +ith hard+are for multiplication @e% g% in an A)tiny1"A# the 9C2" does
nothing at all% 't doesn/t even open an error +indo+ @the tiny1" doesn/t have that hard+areA?
'n principle the C<= can e5ecute 6E#E"6 @163bitA different instructions% 8ut because not only 1F0 should be +ritten to a
specific register# but values bet+een 0 and 2EE to any register bet+een 216 and 2"1# this load instruction re$uires 2E6D16
G H#096 of the 6E#E"6 theoretically possible instructions% )he direct load instruction for the constant c @cF%%c0A and registers
r @r"%%r0# rH is al+ays 1 and not encodedA is coded li,e this*
8it 1E 1H 1" 12 11 10 9 8 F 6 E H " 2 1 0
:!' 2#C 1 1 1 0 cF c6 cE cH r" r2 r1 r0 c" c2 c1 c0
&hy those bits are placed li,e this in the instruction +ord remains A)0-:/s secret%
Addition and subtraction re$uire "2D"2 G 1#02H combinations and the target registers 20%%2"1 @tH%%t0A and source registers
20%%2"1 @sH%%s0A are coded li,e this*
8it 1E 1H 1" 12 11 10 9 8 F 6 E H " 2 1 0
A!! 2t#2s 0 0 0 0 1 1 sH tH t" t2 t1 t0 s" s2 s1 70
7=8 2t#2s 0 0 0 1 1 0 sH tH t" t2 t1 t0 s" s2 s1 s0
<lease# do not learn these bit placements# you +ill not need them later% Just understand ho+ an instruction +ord is coded
and e5ecuted%
2." #nstr$ctions in assembler
)here is no need to learn 163bit numbers and the cra4y placement of bits +ithin those# because in assembler you/ll use
human3readable abbreviations for that# so3called mnemonics# an aid to memory% )he assembler representation for he5
9E88 is simply the abbreviation I7:--<I% 'n contrast to 9E88# 7:--< is easy to remember% -ven for someone li,e me that
has difficulties in remembering its o+n phone number%
Adding simply is IA!!I% For naming the t+o registers# that are to be added# they are +ritten as parameters% @6o# not in
brac,ets% C programmers# forget those brac,ets% .ou don/t need those in assembler%A 7imply type IA!! 20#21I% )he line
translates to a single 16 bit +ord# 0C01% )he translation is done by the assembler%
)he C<= only understands 0C01% )he assembler translates the line to this 16 bit +ord# +hich is +ritten to the flash storage#
read from the C<= from there and e5ecuted% -ach instruction that the C<= understands has such a mnemonic% And vice
versa* each mnemonic has e5actly one corresponding C<= instruction +ith a certain course of actions% )he ability of the
C<= determines the e5tent of instructions that are available in assembler% )he language of the C<= is the base# the
mnemonics only represent the abilities of the C<= itself%
2.% &ifference to hi'h-le(el lan'$a'es
;ere some hints for high3level programmers% 'n high3level languages the constructions are not depending from the
hard+are or the abilities of a C<=% )hose constructions +or, on very different processors# if there is a compiler for that
language and for the processor family available% )he compiler translates those language constructions to the processor/s
binary language% A J) in 8asic loo,s li,e a J0< in assembler# but there is a difference in the +hole concept bet+een
those t+o%
A transfer of program code to another processor hard+are does only +or, if the hard+are is able to do the same% 'f a
processor C<= doesn/t have access to a 16 bit timer# the compiler for a high3level language has to simulate one# using an 83
bit timer and some time3consuming code% 'f three timers are available# and the compiler is +ritten for only t+o or a single
timer# the available hard+are remains unused% 7o you totally depend on the compiler/s abilities# not on the C<=/s abilities%
Another e5ample +ith the above sho+n instruction I0=:I% 'n assembler# the target processor determines if you can use
this instruction or if you have to +rite a multiplication routine% 'f# in a high3level language# you use a multiplication the
compiler inserts a math library that multiplies every ,ind of numbers# even if you have only 83by383bit numbers and 0=:
alone +ould do it% )he lib offers an integer# a long3+ord and some other routines for multiplications that you don/t need% A
+hole pac,age of things you don/t really need% 7o you run out of flash in a small tiny A12# and you change to a mega +ith
"E unused port pins% r an 5mega# >ust to get your elefant lib +ith superfluous routines into the flash% )hat is +hat you get
from a simple IDI# +ithout even being as,ed%
2.) *ssembler is not machine lan'$a'e
8ecause assembler is closer to the hard+are than any other language# it is often called machine language% )his is not e5act
because the C<= only understands 16 bit instruction +ords in binary form% )he string IA!! 20#21I cannot be e5ecuted%
And assembler is much simpler than machine language% 7imilarities bet+een machine language and assembler are a
feature# not a bug%
Avr-Asm-Tutorial 4 http://www.avr-asm-tutorial.net
2.+ #nterpretin' and assembler
&ith an interpreter the C<= first translates the human3readable code into binary +ords that can be e5ecuted then% )he
interpreter +ould
D first read the te5t stream IA G A K 8I @nine characters of one byte eachA#
D strip the four blan,s from the te5t#
D locate the variables A and 8 @location in registers or in 72A0# precisionLlength# etc%A#
D identify the plus sign as operator#
D prepare a machine e5ecutable se$uence that is e$uivalent to the formulation in the te5t%
'n the conse$uence# probably a simple machine code li,e IA!! 20#21I @in AssemblerA +ould result% 8ut most probably the
resulting machine code +ould be multiple +ords long @read and +rite variables fromLto 72A0# 163bit3integer adding#
register savingLrestoring on stac,# etc%# etc%A%
)he difference bet+een the interpreter and the assembling is that# after assembling# the C<= gets its favored meal#
e5ecutable +ords# directly% &hen interpreting the C<= is# during most of the time# performing the translation tas,%
)ranslation probably re$uires 20 or 200 C<= steps# before the three or four +ords can be e5ecuted% -5ecution speed so is
more than lame% &hile this is no problem if one uses a fast cloc, speed# it is inappropriate in time critical situations# +here
fast response to an event is re$uired% 6o one ,no+s +hat the C<= is >ust doing and ho+ long this re$uires%
6ot having to thin, about timing issues leads to the inability of the human programmer to resolve timing issues# and
missing information on timing ,eeps him unable to do those things# if re$uired%
2., Hi'h le(el lan'$a'es and *ssembler
;igh level languages insert additional nontransparent separation levels bet+een the C<= and the source code% An e5ample
for such an nontransparent concept are variables% )hese variables are storages that can store a number# a te5t string or a
single 8oolean value% 'n the source code# a variable name represents a place +here the variable is located# and# by
declaring variables# the type @numbers and their format# strings and their length# etc%A%
For learning assembler# >ust forget the high level language concept of variables% Assembler only ,no+s bits# bytes# registers
and 72A0 bytes% )he term IvariableI has no meaning in assembler% Also# related terms li,e ItypeI are useless and do not
ma,e any sense here%
;igh level languages re$uire you to declare variables prior to their first use in the source code# e% g% as 8yte @83bitA# double
+ord @163bitA# integer @1E3bit plus 1 sign bitA% Compilers for that language place such declared variables some+here in the
available storage space# including the "2 registers% 'f this placement is selected rather blind by the compiler or if there is
some priority rule used# li,e the assembler programmer carefully does it# is depending more from the price of the
compiler% )he programmer can only try to understand +hat the compiler IthoughtI +hen he placed the variable% )he
po+er to decide has been given to the compiler% )hat IrelievesI the programmer from the trouble of that decision# but
ma,es him a slave of the compiler%
)he instruction IA G A K 8I is no+ type3proofed* if A is defined as a character and 8 a number @e% g% G 2A# the formulation
isn/t accepted because character codes cannot be added +ith numbers% <rogrammers in high level languages believe that
this type chec, prevents them from programming nonsense% )he protection# that the compiler provides in this case by
prohibiting your type error# is rather useless* adding 2 to the character IFI of course should yield a I;I as result# +hat
else( Assembler allo+s you to do that# but not a compiler%
Assembler allo+s you to add numbers li,e F or H8 to add and subtract to every byte storage# no matter +hat type of thing
is in the byte storage% &hat is in that storage# is a matter of decision by the programmer# not by a compiler% 'f an operation
+ith that content ma,es sense is a matter of decision by the programmer# not by the compiler% 'f four registers represent a
"23bit3value or four A7C'' characters# if those four bytes are placed lo+3to3high# high3to3lo+ or completely mi5ed# is >ust up
to the programmer% ;e is the master of placement# no one else% )ypes are un,no+n# all consists of bits and bytes
some+here in the available storage place% )he programmer has the tas, of organi4ing# but also the chance of optimi4ing%
f a similar effect are all the other rules# that the high level programmer is limited to% 't is al+ays claimed that it is saver
and of a better overvie+ to program anything in subroutines# to not >ump around in the code# to hand over variables as
parameters# and to give bac, results from functions% Forget most of those rules in assembler# they don/t ma,e much sense%
Jood assembler programming re$uires some rules# too# but very different ones% And# +hat/s the best* most of them have
to be created by yourself to help yourself% 7o* +elcome in the +orld of freedom to do +hat you +ant# not +hat the
compiler decides for you or +hat theoretical professors thin, +ould be good programming rules%
;igh level programmers are addicted to a number of concepts that stand in the +ay of learning assembler* separation in
different access levels# in hard+are# drivers and other interfaces% 'n assembler this separation is complete nonsense#
separation +ould urge you to numerous +or,arounds# if you +ant to solve your problem in an optimal +ay%
8ecause most of the high level programming rules don/t ma,e sense# and because even puristic high level programmers
brea, their o+n rules# +henever appropriate# see those rules as a nice cage# preventing you from being creative% )hose
$uestions don/t play a role here% -verything is direct access# every storage is available at any time# nothing prevents your
access to hard+are# anything can be changed 3 and even can be corrupted% 2esponsibility remains by the programmer
only# that has to use his brain to avoid conflicts +hen accessing hard+are%
)he other side of missing protection mechanisms is the freedom to do everything at any time% 7o# smash your ties a+ay to
start learning assembler% .ou +ill develop your o+n ties later on to prevent yourself from running into errors%
Avr-Asm-Tutorial 5 http://www.avr-asm-tutorial.net
2.- .hat is really easier in assembler/
All +ords and concepts that the assembler programmer needs is in the datasheet of the processor* the instruction and the
port table% !one? &ith the +ords found there anything can be constructed% 6o other documents necessary% ;o+ the timer
is started @is +riting I)imer%7tart@8AI someho+ easier to understand than I:!' 216#0502M and C=) )CC20#216I(A# ho+ the
timer is restarted at 4ero @IC:2 216M and C=) )CC20#216IA# it is all in the data sheet% 6o need to consult a more or less
good documentation on ho+ a compiler defines this or that% 6o special# compiler3designed +ords and concepts to be
learned here# all is in the datasheet% 'f you +ant to use a certain timer in the processor for a certain purpose in a certain
mode of the 1E different possible modes# nothing is in the +ay to access the timer# to stop and start it# etc%
&hat is in a high level language easier to +rite IA G A K 8I instead of I0=: 216#21FI( 6ot much% 'f A and 8 aren/t defined
as bytes or if the processor type is tiny and doesn/t understand 0=:# the simple 0=: has to be e5changed +ith some
other source code# as designed by the assembler programmer or copyLpasted and adapted to the needs% 6o reason to
import an nontransparent library instead# >ust because you/re to la4y to start your brain and learn%
Assembler teaches you directly ho+ the processor +or,s% 8ecause no compiler ta,es over your tas,s# you are completely
the master of the processor% )he re+ard for doing this +or,# you are granted full access to everything% 'f you +ant# you can
program a baud3rate of HE%HE bps on the =A2)% A speed setting that no &indo+s <C allo+s# because the operating system
allo+s only multiples of FE @&hy( 8ecause some historic mechanical teletype +riters had those special mechanical gear
bo5es# allo+ing $uic, selection of either FE or "00 bps%A% 'f# in addition# you +ant 1 and a half stop bytes instead of either 1
or 2# +hy not programming your o+n serial device +ith assembler soft+are% 6o reason to give things up%
&ho is able to program in assembler has a feeling for +hat the processor allo+s% &ho changes from assembler to a higher
level language later on# e% g% in case of very comple5 tas,s# has made the decision to select that on a rational basis% 'f
someone s,ips learning assembler he has to do +hat he can# stic,s to the available libraries and programs creative
+or,arounds for things that the compiler doesn/t allo+# and in a +ay that assembler programmers +ould laugh at loud%
)he +hole +orld of the processor is at the assembler programmer/s command# so +hy do complicated and highly sensitive
+or,arounds on something you can formulate in a nice# lean# esthetic +ay(
Avr-Asm-Tutorial 6 http://www.avr-asm-tutorial.net
$ %ard&are for AVR-Assembler-
'rogramming
: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 e5periments# leave some more space for future e5tensions on your e5perimental
board%
'f you don/t li,e the smell of soldering# you can buy a ready3to3use board# too% )he available boards are characteri4ed in
this section belo+%
".1 The #0P #nterface of the *12 processor family
8efore going into practice# +e have to learn a fe+ essentials on the serial programming mode of the A12 family% 6o# you
don/t need three different voltages to program and read an A12 flash memory% 6o# you don/t need another pre3
programmed microprocessor to program the A12s% 6o# you don/t need 10 'L lines to tell the chip +hat you li,e it to do%
And you don/t even have to remove the A12 from the soc,et on your your e5perimental board# before programming it% 't/s
even easier than that%
All this is done by a build3in interface in the A12 chips# that enable you to +rite and read the content of the program flash
and the built3in3--<20% )his interface +or,s serially and needs only three signal lines*
7CN* 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#
07'* )he data signal that sends the bits to be +ritten to the A12#
0'7* )he data signal that receives the bits read from the A12%
)hese three signal pins are internally connected to the programming machine only if you change
the 2-7-) @sometimes also called 27) or restartA pin to 4ero% ther+ise# during normal operation
of the A12# these pins are programmable 'L lines li,e all the others%
'f you li,e to use these pins for other purposes during normal operation# and for in3system3
programming# you/ll 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 multiple5er% &hat is necessary in your case# depends
from your use of the pins in the normal operation mode% .ou/re luc,y# if you can use them for in3
system3programming e5clusively%
6ot necessary# but recommendable for in3system3programming 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 A12 board% J6! is the common
ground or negative pole of the supply voltage# 1)J @target voltageA the supply voltage @usually
KE%0 voltsA% )his adds up to 6 lines bet+een the programmer hard+are and the A12 board% )he
resulting '7<6 connection# as defined by A)0-:# is sho+n on the left%
7tandards 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
'7<10 and +as used on the 7)N200 board# sometimes also called CA6!A interface% 't/s still a very
+idespread standard# and even the more recent 7)NE00 board is e$uipped +ith it% '7<10 has an
additional signal to drive a red :-!% )his :-! signals that the programmer is doing his >ob% A
good idea% Just connect the :-! to a resistor and clamp it the positive supply voltage%
".2 Pro'rammer for the PC-Parallel-Port
6o+# heat up your soldering iron and build up your programmer% 't is a $uite easy schematic and +or,s +ith standard
parts from your +ell3sorted e5periments bo5%
.es# that/s all you need to program an A12% )he 2E3pin plug goes into the parallel port of your <C# the 103pin '7< goes to
your A12 e5perimental board% 'f your bo5 doesn/t have a FH:72HE# you can also use a FH;C2HE @+ith no hard+are
changesA or a FH:72HHLFH;C2HH @by changing some pins and signalsA% 'f you use ;C# don/t forget to tie unused inputs
either to J6! or the supply voltage# other+ise the buffers might produce e5tra noise by capacitive s+itching%
)he necessary program algorithm is done by the '7< soft+are% 8e a+are that this parallel port interface is not supported by
A)0-:/s studio soft+are any more% 7o# if you +ant to program your A12 directly from +ithin the studio# use different
programmers% )he 'nternet provides several solutions%
Avr-Asm-Tutorial 7 http://www.avr-asm-tutorial.net
'f you already have a programming board# you +ill not need to build this programmer# because you/ll find the '7< interface
on some pins% Consult your handboo, to locate these%
"." 3!perimental boards
.ou probably +ant to do your first programming steps +ith a self3made A12 board% ;ere are t+o versions offered*
A very small one +ith an A)tiny1"# or
a more complicated one +ith an A)9072"1" or A)mega2"1"# including a serial 272"2 interface%
$($( E)perimental board &ith an ATtiny$
)his is a very small board that allo+s e5periments +ith the A)tiny1"/s internal hard+are% )he picture sho+s
the '7<10 programming interface on the left# +ith a programming :-! attached via a resistor of "90 hms#
the A)tiny1" +ith a pull3up of 10, on its 2-7-) pin @pin 1A#
the supply part +ith a bridge rectifier# to be supplied +ith 9%%1E1 from an AC or !C source# and a small E1
regulator%
)he A)tiny1" re$uires no e5ternal O)A: or cloc, generator# because it +or,s +ith its internal 9%6 0;4 2C generator and# by
default# +ith a cloc, divider of 8 @cloc, fre$uency 1%2 0;4A%
)he hard+are can be build on a small board li,e the one sho+n in the picture% All pins of the tiny1" are accessible# and
e5ternal hard+are components# li,e the :-! sho+n# can be easily plugged in%
Avr-Asm-Tutorial 8 http://www.avr-asm-tutorial.net
)his board allo+s the use of the
A)tiny1"/s hard+are components li,e
'L3ports# timers# A! converters# etc%
$($(# E)perimental board &ith an AT*+,#$$-ATmega#$$
For test purposes# +ere more 'L3pins or a serial communication interface is necessary# +e can use a A)9072"1" or
A)mega2"1" on an e5perimental board% )he schematic sho+s
a small voltage supply for connection to an AC transformer and a voltage regulator E1L1A#
a O)A: cloc, generator @here +ith a 10 0;4 O)A:# all other fre$uencies belo+ the ma5imum for the 2"1" +ill
also +or,A#
the necessary parts for a safe reset during supply voltage s+itching#
the '7<3<rogramming3'nterface @here +ith a '7<10<'63connectorA%
7o that/s +hat you need to start +ith% Connect other peripheral add3ons to the numerous free 'L pins of the 2"1"%
)he easiest output device can be a :-!# connected via a resistor to the positive supply voltage% &ith that# you can start
+riting your first assembler program s+itching the :-! on and off%
'f you
do not need the serial communication interface# >ust s,ip the hard+are connected to pins 2L" and 1HL16#
Avr-Asm-Tutorial 9 http://www.avr-asm-tutorial.net
do not need hard+are handsha,e signals# s,ip the hard+are on the pins 1HL16 and connect 2)7 on the 93pin3
connector over a 2%2, resistor to K91%
'f you use an A)mega2"1" instead of an A)9072"1"# the
follo+ing changes are resulting*
the e5ternal O)A: is not necessary# as the A)mega has
an internal 2C cloc, generator# so >ust s,ip all
connections to pins H and E#
if you +ant to use the e5ternal O)A: instead of the
build3in 2C as cloc, source# you +ill have to program
the fuses of the A)mega accordingly%
".% 2eady-to-$se commercial pro'rammin' boards for the *12-
family
'f you do not li,e home3bre+ed hard+are# and if have some e5tra money left that you don/t ,no+ +hat to do +ith# you
can buy a commercial programming board% !epending from the amount of e5tra money you/d li,e to spend# you can select
bet+een more or less costly versions% For the amateur the follo+ing selection criteria should be loo,ed at*
price#
<C interface @preferably =78# less convenient or durable* 93pin 272"2# re$uiring additional soft+are* interfaces for
the parallel port of the <CA#
support reliability for ne+er devices @updates are re$uired from time to time# other+ise you sit on a nearly dead
horseA#
hard+are features @depends on your foreseeable re$uirements in the ne5t five yearsA%
)he follo+ing section describes the three standard boards of A)0-:# the 7)N200# the 7)NE00 and the !ragon% )he
selection is based on my o+n e5periences and is not a recommendation%
$(.( ,T/#++
)he 7)N200 from A)0-: is a historic board% 'f you grab a used one you/ll get
a board +ith some soc,ets @for 8# 20# 28 and H0 pin devicesA#
eight ,eys and :-!s# hard connected to port ! and 8#
an :C! standard 1H3pin interface#
an option for attaching a 283pin 72A0#
a 272"2 interface for communication#
a cable interface for a <C parallel port on one side and a 103pin '7< on the other side%
;igh voltage programming is not supported%
)he board cannot be programmed from +ithin the 7tudio# the programming soft+are is no longer maintained# and you
must use e5ternal programs capable of driving the <C parallel port%
'f someone offers you such a board# ta,e it only for free and if you/re used to operate soft+are of the necessary ,ind%
$(.(# ,T/0++
-asy to get is the 7)NE00 @e% g% from A)0-:A% 't has the follo+ing hard+are*
7oc,ets for programming most of the A12 types @e% g% 1H3pin devices or )PF< pac,ages re$uire additional
hard+areA#
serial and parallel programming in normal mode or +ith high voltage @;1 programming brings devices bac, to
life even if their 2-7-) pin has been fuse3programmed to be normal port inputA#
'7<6<'63 and '7<10<'63connection for e5ternal 'n37ystem3<rogramming#
programmable oscillator fre$uency and supply voltages#
plug3in s+itches and :-!s#
a plugged 272"2C3connector @=A2)A#
a serial Flash3--<20 @only older boards have thisA#
access to all port pins via 103pin connectors%
A ma>or disadvantage of the board is that# before programming a device# several connections have to be made manually
Avr-Asm-Tutorial 10 http://www.avr-asm-tutorial.net
+ith the delivered cables%
)he board is connected to the <C using a serial port @C05A% 'f your laptop doesn/t have a serial interface# you can use one
of the common =783to37erial3'nterface cables +ith a soft+are driver% 'n that case the driver must be ad>usted to use
bet+een C01 and C08 and a baud rate of 11E, to be automatically detected by the 7tudio soft+are%
<rogramming is performed and controlled by recent versions of A12 studio# +hich is available for free from A)0-:/s +eb
page after registration% =pdates of the device list and programming algorithm are provided +ith the 7tudio versions# so
the support for ne+er devices is more li,ely than +ith other boards and programming soft+are%
-5periments can start +ith the also supplied A12 @older versions* A)9078E1E# ne+er boards versions include different
typesA% )his covers all hard+are re$uirements that the beginner might have%
$(.($ AVR 1ragon
)he A12 dragon is a very small board% 't has an =78 interface# +hich also supplies the board and the 63pin3'7< interface%
)he 63pin3'7<3'nterface is accompanied by a 203pin ;1 programming interface% )he board is prepared for adding some
soc,ets on board# but doesn/t have soc,ets for target devices and other hard+are on board%
)he dragon is supported by the 7tudio soft+are and is a updated automatically%
'ts price and design ma,es it a nice gift for an A12 amateur% )he bo5 fits nicely in a ro+ +ith other precious and carefully
designed bo5es%
Avr-Asm-Tutorial 11 http://www.avr-asm-tutorial.net
. Tools for AVR assembly programming
Four 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*
1% anything necessary in one pac,age#
2% each tas, is performed +ith a specific program# the results are stored as specific files%
=sually route Q1 is chosen% 8ut because this is a tutorial# and you are to understand the underlying mechanism first# +e
start +ith the description of route Q2 first% )his sho+s the +ay from a te5t file to instruction +ords in the flash memory
%.1 The editor
.(( A simple type&riter
Assembler programs are +ritten +ith an editor% )he editor >ust has to be able to create and edit A7C'' te5t files% 7o#
basically# any simple editor does it%
7ome features of the editor can have positive effects*
-rrors# that the assembler later detects# are reported along +ith the line number in the te5t file% :ine numbers are
also a po+erful invention of the computer3age +hen it comes to discussions on your code +ith someone else%
)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% 0ore or less intelligent recognition of errors ease typing%
8ut this is a feature that ' don/t really miss%
'f your editor allo+s the selection of fonts# chose a font +ith fi5ed spacing# li,e Courier% ;eaders loo, nicer +ith
that%
.our editor should be capable of recogni4ing line ends +ith any combination of characters @carriage returns# line
feeds# bothA +ithout producing unacceptable screens% Another item on the +ish list for &ido+s 201"%
'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
)o3!o/s in e5tra bubble fields% 7ome disadvantages here* you have to convert your te5t to plain te5t at the end# losing all
your nice design +or,# and your resulting te5t file should not have a single control byte left% ther+ise this single byte +ill
cause an error message# +hen you assemble the te5t% And remember* :ine numbers here are only correct on page one of
your source code%
7o# +hatever te5t program you chose# it/s up
to you% )he follo+ing e5amples are +ritten in
+avrasm# an editor provided by A)0-: 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 @starting
+ith RA% :ater understanding of +hat +e/ve
planned here +ill be helpful in later
debugging%
6o+ store the program te5t# named to
something%asm into a dedicated directory#
using the file menu% )he assembly program is
complete no+%
'f you/d li,e to see +hat synta53highlighting means# ' have a snapshot of such an A12 editor here%
)he editor recogni4es instructions automatically and uses different colors @synta5 highlightingA to signal user constants and
typing errors in those instructions @in blac,A% 7toring the code in an %asm file provides nearly the same te5t file# colors are
not stored in the file%
Avr-Asm-Tutorial 12 http://www.avr-asm-tutorial.net
!on/t try to find this editor or its
authorR the editor is history and no
longer maintained%

.((# ,tructuring assembler code
This page shows the basic structure of an assembler program. These structures are typical for A,-
assembler. This te0t 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* don/t 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% 7o each assembler program should start li,e that*

"li#$.asm% &ro'ram to swit#h a relais on an( o)) ea#h two se#on(s


*ritten +, -..#hmi(t% last #han'e: 7.10.2001

<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# pre3conditions 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 e5tend the routine later% 7ingle line comments are defined by
adding a semicolon behind the command on the line% :i,e this*
L1I R23+)+A /ere somethin' is loa(e(
M4V R53R2 an( #opie( somewhere else
Things to be ritten on to!
<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 --<20 and internal 72A0% All
these special features are included in a header file that is named 5555def%inc# +ith 5555 being the chip type# e% g% 2"1"#
tn2"2"# or m8E1E% )hese files are available by A)0-:% 't is good style to include this file at the beginning of each program%
)his is done li,e that*
(64LI,T 0on1t list the )ollowin' in the list )ile
(I6CL71E 8m900def(inc8 2mport o) the )ile
(LI,T .wit#h list on a'ain
)he path# +here this file can be found# is only necessary if you don/t +or, +ith A)0-:/s 7tudio% f course you have to
include the correct path to fit to your place +here these files are located% !uring assembling# the output of a list file listing
the results is s+itched on by default% ;aving listing ob might result in very long list file @D%lstA if you include the header file%
)he directive %6:'7) turns off this listing for a +hile# :'7) turns it on again% :et/s have a short loo, at the header file% First
these files define the processor type*
(1EVICE ATME:A900 The tar'et (evi#e t,pe
)he directive %!-1'C- advices the assembler to chec, all instructions if these are available for that A12 type% 't results in an
error message# if you use code se$uences that are not defined for this type of processor% .ou don/t need to define this
+ithin your program as this is already defined +ithin the header file% )he header file also defines the registers O;# O:# .;#
.:# S; and S:% )hese are needed if you use the 163bit3pointers O# . or S to access the higher or lo+er byte of the pointer
separately% All port locations are also defined in the header file# so <2)8 translates to a he5 number +here this port is
Avr-Asm-Tutorial 13 http://www.avr-asm-tutorial.net
located on the defined device% )he port/s 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% 2ead access to port 8# 8it "# can be done using its bit
name <'68"# 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% thers things that should be on top of your programs are the register definitions you +or, +ith# e% g%*
(1E; mpr < R2 0e)ine a new name )or re'ister 316
)his has the advantage of having a complete list of registers# and to see +hich registers are still available and unused%
2enaming registers avoids conflicts in the use of these registers and the names are easier to remember% Further on +e
define the constants on top of the source file# especially those that have a relevant role in different parts of the program%
7uch a constant +ould# e% g%# be the Otal fre$uency that the program is ad>usted for# if you use the serial interface on
board% &ith
(E=7 f> < .++++++ 4Tal )re5uen#, (e)inition
at the beginning of the source code you immediately see for +hich cloc, you +rote the program% 1ery much easier than
searching for this information +ithin 1H82 lines of source code%
Things that should be done at !rogram start
After you have done the header# the program code should start% At the beginning of the code the reset3 and interrupt3
vectors @their function see in the J=0< sectionA 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=0< 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 initiali4ation 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%
Tool for structuring of !rogram code
)he described standardi4ed structure is included in a program +ritten for &indo+s perating 7ystems# +hich can be
do+nloaded at http*LL+++%avr3asm3do+nload%deLavrThead%4ip%
=n4ip the e5ecutable file# and
simply run it% 't sho+s this* ;ere
you can choose *Ttiny by
clic,ing on it# and then select
*Ttiny1" in the dropdo+n field
*12-Type%
.ou are no+ as,ed to navigate
to its respective include3file
tn1"def%inc% 7ho+ the program
the +ay +here the header file is
located%
;ere you can enter your desired
multi purpose register# the
output configuration on ports A
and 8# 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
.riteTo4ile to +rite this to an
assembler code file instead%
'f you don/t ,no+ +hat it is for
and +hat to do# press the Help
button%
)his produces the follo+ing
code*

66666666666666666666666666666666666666666666
6 7A(( &ro8e#t title here9 6
6 7A(( more in)o on so)tware version here9 6
6 :";20<< +, 7A(( "op,ri'ht 2n)o here9 6
66666666666666666666666666666666666666666666

2n#lu(e( hea(er )ile )or tar'et A=3 t,pe


.>?@2.T
Avr-Asm-Tutorial 14 http://www.avr-asm-tutorial.net
.2>"@A0B Ctn13(e).in#C /ea(er )or ATT2>D13
.@2.T

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
/ A 3 0 * A 3 B 2 > F ? 3 G A T 2 ? >
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

7A(( all har(ware in)ormation here9

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
& ? 3 T . A > 0 & 2 > .
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

7A(( names )or har(ware ports an( pins here9


Format: .BHA "ontrolportout E &?3TA
.BHA "ontrolportin E &2>A
.BHA @e(?utput&in E &?3TA2

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
" ? > . T A > T . T ? " / A > - B
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

7A(( all #onstants here that #an +e su+8e#t


to #han'e +, the user9
Format: .BHA #onst E IAJ"0

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
F 2 4 K 0 B 3 2 = B 0 " ? > . T A > T .
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

7A(( all #onstants here that are not su+8e#t


to #han'e or #al#ulate( )rom #onstants9
Format: .BHA #onst E IAJ"0

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
3 B - 2 . T B 3 0 B F 2 > 2 T 2 ? > .
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

7A(( all re'ister names here% in#lu(e in)o on


all use( re'isters without spe#i)i# names9
Format: .0BF rmp E 316
.0BF rmp E 316 Gultipurpose re'ister

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
. 3 A G 0 B F 2 > 2 T 2 ? > .
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

.0.B-
.?3- 040060
Format: @a+el: .JDTB > reserve > J,tes )rom @a+el:

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
3 B . B T A > 0 2 > T = B " T ? 3 .
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

.".B-
.?3- I0000
r8mp Gain 3eset ve#tor
reti 2nt ve#tor 1
reti 2nt ve#tor 2
reti 2nt ve#tor 3
reti 2nt ve#tor 4
reti 2nt ve#tor 5
reti 2nt ve#tor 6
reti 2nt ve#tor 7
reti 2nt ve#tor 8
reti 2nt ve#tor 9

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
2 > T B 3 3 A & T . B 3 = 2 " B .
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

7A(( all interrupt servi#e routines here9

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
G A 2 > & 3 ? - 3 A G 2 > 2 T
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

Avr-Asm-Tutorial 15 http://www.avr-asm-tutorial.net
Gain:
2nit sta#$
l(i rmp% @?*:3AGB>0; 2nit @.J sta#$
out .&@%rmp
2nit &ort J
l(i rmp%:1LL00J2;M:1LL00J1;M:1LL00J0; 0ire#tion o) &ort J
out 003J%rmp
7A(( all other init routines here9
l(i rmp%1LL.B ena+le sleep
out G"A"3%rmp
sei

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
& 3 ? - 3 A G @ ? ? &
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

@oop:
sleep 'o to sleep
nop (umm, )or wa$e up
r8mp loop 'o +a#$ to loop

Bn( o) sour#e #o(e

%.2 The assembler


6o+ +e have a te5t file# +ith blan, A7C'' characters% )he ne5t step is to translate this code to a machine3oriented form
+ell understood by the A12 chip% !oing this is called assembling# +hich means Bput together the right instruction +ordsC%
)he program that reads the te5t file and produces some ,ind of output files is called Assembler% 'n the easiest form this is a
instruction3line program that# +hen called# e5pects the address of the te5t file and some optional s+itches# and then starts
assembling the instructions found in the te5t file%
'f your editor allo+s calling e5ternal programs# this is an easy tas,% 'f not @another item on the +ish list for the editor in
&ido+s 2010A# it is more convenient to +rite a short batch file @again using an editorA% )hat batch file should have a line
li,e this*
<ath)oAssemblerUAssembler%e5e 3options <ath)o)e5tfileU)e5tfile%asm
Clic,ing on the editor/s e5ternal program caller
or on the batch file starts the command line
assembler% )hat piece of soft+are reports the
complete translation process @in the smaller
+indo+A# 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 2J0< instruction
that +e used% Assembling our single asm te5t
file no+ has produced four other files @not all
apply hereA%
)he first of these four ne+ files# )-7)%--<# holds
the content that should be +ritten to the
--<20 of the A12% )his is not very interesting
in our case# because +e didn/t program any
content for the --<20% )he assembler has
therefore deleted this file +hen he completed
the assembly run# because it is empty%
)he second file# )-7)%;-O# is more relevant because
this file holds the instructions later programmed
into the A12 chip% )his file loo,s li,e this%
)he he5 numbers are +ritten in a special A7C'' form#
together +ith address information and a chec,3sum
for each line% )his form is called 'ntel3he53format#
and is very old and stems from the early +orld of
computing% )he form is +ell understood by the
programing soft+are%
Avr-Asm-Tutorial 16 http://www.avr-asm-tutorial.net
)he third file# )-7)%8J# +ill be introduced
later# this file is needed to simulate an A12%
'ts format is he5adecimal and defined by
A)0-:% =sing a he53editor its content loo,s
li,e this% Attention* )his file format is not
compatible +ith the programmer soft+are#
don/t use this file to program the A12 @a
very common error +hen startingA% 8J files are only produced by certain A)0-: assemblers# don/t e5pect these files +ith
other assemblers%
)he fourth file# )-7)%:7)# is a te5t file% !isplay its content +ith a
simple editor% )he follo+ing results%
)he program +ith all its addresses# instructions and error
messages are displayed in a readable form% .ou +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 %6:'7) directive
doesn/t suppress listing%
%." Pro'rammin' the chips
)o program our he5 code# as coded in te5t form in the %;-O3file# to the A12 a programmer soft+are is necessary% )his
soft+are reads the %;-O3file and transfers its content# either bit3by3bit @serial programmingA or byte3by3byte @parallel
programmingA to the A12/s flash memory% &e start the programmer soft+are and load the he5 file that +e >ust generated%
'n an e5ample that loo,s li,e
this% <lease note* the displayed
+indo+ stems from '7<%e5e# a
historic program no longer
distributed by A)0-:% ther
programmer soft+are loo,s
similar%
)he soft+are +ill burn our
code in the chip/s 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 e5ample for
programming over the <C/s parallel or serial communication port# <ony<rog2000 should be mentioned here%
%.% 0im$lation in the st$dio
'n some cases self3+ritten assembly code# even assembled +ithout errors# does not e5actly 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 7tudio soft+are pac,age from A)0-:
provides ideal opportunities for debugging% )esting the soft+are or parts of it is possible# the program code could be
tested step3by3step displaying results%
)he pictures sho+n here are ta,en from 1ersion H of the 7tudio# that is available for free on A)0-:/s +ebsite% lder
versions loo,s different# but do nearly the same% )he 7tudio is a soft+are that has all you need to develop# debug# simulate
and burn your assembler programs into the A12 type of your choice% )he studio is started and loo,s li,e this%
Avr-Asm-Tutorial 17 http://www.avr-asm-tutorial.net
)he first dialog as,s +hether an e5isting pro>ect should be opened or a ne+ pro>ect is to be started% 'n case of a ne+ly
installed 7tudio C6e+ <ro>ectM is the correct ans+er% )he 8utton C6e5tVVM brings you to the settings dialog of your ne+
pro>ect%
;ere you select CAtmel A12 AssemblerM as your pro>ect type# give that pro>ect a name @here Ctest1MA and let the 7tudio
crate an initial @emptyA 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 C6e5tVVM opens the platform and device selection dialog*
Avr-Asm-Tutorial 18 http://www.avr-asm-tutorial.net
As debug platform
select either CA12
simulatorM or CA12
simulator 2M% As
!evice select your
A12 type# here an
A)mega8 +as
selected% 'f your
desired type is grayed
out# select another
simulator platform%
Close this +indo+
+ith the CFinishM
button% 6o+ a large
+indo+ pops up#
+hich has lots of
different sub3
+indo+s%
n 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 @try typing its content to your editor +indo+# don/t care about the colors W these are
added by the editor W remember synta53highlighting(A% n the left bottom is a C8uildM section# +here all your error
messages go to% n the right side is a strange 'L vie+ and belo+ a rather +hite field# +e/ll come to that later on%
All +indo+ portions can be made larger and smaller and even can be shifted around on the screen% )ry mi5ing these
+indo+s? )he ne5t pictures sho+ some differently loo,ing +indo+s# but they are all the same as here%
Avr-Asm-Tutorial 19 http://www.avr-asm-tutorial.net
After typing the source code sho+n above to your source file in the editor completely# push the menu C8uildM and its sub3
menu C8uildM% 'f you typed correctly# the result sho+s up in your C8uildM +indo+%
0a,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%
.ou can no+ push the menu item C!ebugM and some +indo+s change their content# si4e and position% 'f you also push the
menu item C1ie+M# C)oolbarsM and C<rocessorM 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 ne5t instruction that
+ill be e5ecuted @not really
e5ecuted# but rather CsimulatedMA%
)he processor +indo+ sho+s the
current program counter value
@yes# the program starts at
address 0A# the stac, pointer @no
matter +hat that might be W +ait
for that later in the courseA# a
cycle counter and a stop +atch% 'f
you push on the small CKM left to
the +ord C2egistersM# the content
of the "2 registers is displayed
@yes# they are all empty +hen you
start the processor simulationA%
6o+ let us proceed +ith the first
instruction% 0enu item C!ebugM
and C7tep intoM or simply F11
e5ecutes the first instruction%
)he instruction Cldi rmp#0b11111111M loads
the binary value 1111%1111 to register 216% 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 =)
instruction%
'n the processor +indo+# the program counter
and the cycle counter are both at 1 no+%
And register 16# do+n the list of registers# is
red no+ and sho+s 05FF# +hich is he5adecimal
for binary 1111%1111%
)o learn about another simulator +indo+ >ust
advance simulation one step further to
e5ecute the =) instruction @e% g% by pushing
the ,ey F11%
Avr-Asm-Tutorial 20 http://www.avr-asm-tutorial.net
)he instruction Cut !!28#rmpM +rites 05FF to a port named !!28% 6o+ the action is on the 'L vie+ +indo+% 'f you push
on <2)8 and the small CKM left of it# this +indo+ displays the value 05FF in the port !!28 in t+o different forms* as 05FF
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 F11 t+o times and +rite 05EE to the port <2)8%
As e5pected# the
port <2)8 changes
its content and has
four blac, and four
+hite s$uares no+%
Another t+o F11#
+riting 05AA to
<2)8# changes the
blac, and +hite
s$uares to the
opposite color%
All +hat has been
e5pected# but +hat
happened to port
<'68( &e didn/t
+rite something to
<'68# but it has the
opposite colors than
<2)8# >ust li,e the
colors before in
<2)8%
<'68 is an input
port for e5ternal
pins% 8ecause the
direction ports in
!!28 are set to be
outputs# <'68
follo+s the pin
status of <2)8#
>ust one cycle later%
6othing +rong
here% 'f you li,e to
chec, this# >ust press F11 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
e5tensively in cases of design errors% 1isit 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
7tudio aside for a +hile%
Avr-Asm-Tutorial 21 http://www.avr-asm-tutorial.net
0 !hat is a register"
2egisters are special storages +ith 8 bits capacity and they loo, li,e this*
8it F 8it 6 8it E 8it H 8it " 8it 2 8it 1 8it 0
6ote the numeration of these bits* the least significant bit starts +ith 4ero @mathematically* 2
0
G 1A%
A register can either store numbers from 0 to 2EE @positive number# no negative valuesA# or numbers from 3128 to K12F
@+hole number +ith a sign bit# located in bit FA# or a value representing an A7C''3coded character @e% g% /A/A# or >ust eight
single bits that do not have something to do +ith each other @e% g% for eight single flags# used to signal eight different
yesLno decisionsA%
)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 A12% )hey are originally named 20 to 2"1# but you can choose to name them to more
meaningful ones using a so3called assembler directive% An e5ample*
.DEF MyPreferredRegister = R16
Assembler directives al+ays start +ith a dot% 'nstructions or labels do 6-1-2 start +ith a dot% 6ote that assembler
directives li,e this are only meaningful for the assembler but do not produce any code that is e5ecutable in the A12 target
chip% )he name C0y<referred2egisterM +ill not sho+ up in the assembled he5 code# and therefore this name cannot be
derived from that he5 code%
'nstead of using the register name 216 +e can no+ use our o+n name C0y<referred2egisterM# if +e +ant to use 216
+ithin an instruction% 7o +e +rite a little bit more te5t 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 1E0 immediately to the register 216# :oa! 'mmediate% )his loads a fi5ed value or a
constant to that register% Follo+ing the assembly# or translation of this code into binary or he5# the program storage
+ritten to the A12 chip loo,s li,e this*
000000 E906
)his +ill sho+ up in the listing# a file called D%lst produced by the assembler soft+are# +hich is a simple te5t file% All
numbers are in he5 format* )he first he5 number is the address @000000A# +here the instruction is +ritten to in the
program flash memory of the A12# the second is the instruction code @-906A% -906 tells the processor three different
things in one +ord# even if you don/t see this directly*
a basic load instruction code# that stands for :!'#
the target register @216A +here the value 1E0 is to be +ritten to#
the value of the constant @1E0A%
!on/t be afraid* you don/t have to remember this coding because the assembler ,no+s ho+ to translate all this to finally
yield -906 and the A12 e5ecutes it%
&ithin one instruction t+o different registers can play a role% )he easiest instruction of this type is the copy instruction#
01% )he naming of this instruction 01 deserves a price for the most confusing definition# because the content of a
register cannot be moved @+hat +ould be left in a register# if you 01- its content to some+here else(A% 't should better
be named C<.# 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 216 and 21E for the
assembler% Again# these lines do not produce any code for the A12% )he instruction lines +ith :!' and 01 produce code*
000000 E906
000001 !F01
)he instruction +rite the value 1E0 into register 216 and copy its content to the target register 21E% 1ery '0<2)A6)
6)'C-*
Avr-Asm-Tutorial 22 http://www.avr-asm-tutorial.net
The first re'ister is always the tar'et re'ister where the res$lt is written to5
@)his is unfortunately different from +hat one e5pects or from ho+ +e spea,# thin, and +rite W 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%A
).1 &ifferent re'isters
)he beginner might +ant to +rite the above instructions li,e this*
.DEF AnotherRegister = R15
LDI AnotherRegister, 150
And* you lost% nly the registers from 216 to 2"1 load a constant immediately +ith the :!' instruction# 20 to 21E don/t do
that% )his restriction is not very fine# but could not be avoided during construction of the instruction set for the A12s%
)here is one e5ception from that rule* setting a register to Sero% )his instruction
"LR MyPreferredRegister
is valid for all registers%
8esides the :!' instruction you +ill find this register class restriction +ith the follo+ing additional instructions*
A6!' 25#N R 8it3And of register 25 +ith a constant value N#
C82 25#0 R Clear all bits in register 25 that are set to one +ithin the constant mas, value 0#
C<' 25#N R Compare the content of the register 25 +ith a constant value N#
78C' 25#N R 7ubtract the constant N and the current value of the carry flag from the content of register 25 and
store the result in register 25#
782 25#0 R 7et all bits in register 25 to one# that are one in the constant mas, 0#
7-2 25 R 7et all bits in register 25 to one @e$ual to :!' 25#2EEA#
7=8' 25#N R 7ubtract the constant N from the content of register 25 and store the result in register 25%
'n all these instructions the register must be bet+een 216 and 2"1? '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 register/s name# because you can easier change the registers location later on# if re$uired%
).2 Pointer-re'isters
A very special e5tra role is defined for the register pairs 22F*226# 229*228 and 2"1*2"2% )he role is so important that these
pairs have e5tra short names in A12 assembler* O# . and S% )hese short names are understood by the assembler% )hese
pairs are 163bit pointer registers# able to point to addresses +ith ma5% 16 bit length# e% g% into 72A0 locations @O# . or SA or
into locations in program memory @SA%
0(#( Accessing memory locations &ith pointers
)he lo+er byte of the 163bit3address is located in the lo+er register# the higher byte in the upper register% 8oth parts have
their o+n names# e% g% the higher byte of S is named S; @G2"1A# the lo+er 8yte is S: @G2"0A% )hese names are defined
+ithin the assembler% !ividing a 163bit3+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% 2ead access is named :! @:oa!A# +rite
access named 7) @7)oreA# e% g% +ith the O3pointer*
7imilarly you can use . and S for that purpose%
Pointer Sequence Examples
O 2eadL&rite from address O# don/t change the pointer :! 21#O or 7) O#21
OK 2eadL&rite fromLto address O# and increment the pointer after+ards by one :! 21#OK or 7) OK#21
3O First decrement the pointer by one and readL+rite fromLto the ne+ address
after+ards
:! 21#3O or 7) 3O#21
0(#(# Reading program flash memory &ith the ? pointer
)here is only one instruction for the read access to the program storage space% 't is defined for the pointer pair S and it is
named :<0 @:oad from <rogram 0emoryA% )he instruction copies the byte at program flash address S to the register 20%
Avr-Asm-Tutorial 23 http://www.avr-asm-tutorial.net
As the program memory is organi4ed +ord3+ise @one instruction on one address consists of 16 bits or t+o bytes or one
+ordA the least significant bit selects the lo+er or upper byte @0Glo+er byte# 1G upper byteA% 8ecause of this the original
address must be multiplied by 2 and access is limited to 1E3bit or "2 ,8 program memory% :i,e this*
LDI 5/,/I0/1!+%ddress2
LDI 5L,LO41!+%ddress2
LPM
Follo+ing this instruction the address must be incremented to point to the ne5t 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
A!'& means A!d 'mmediate &ord and a ma5imum of 6" can be added this +ay% 6ote that the assembler e5pects the
lo+er of the pointer register pair S: as first parameter% )his is some+hat confusing as addition is done as 163bit3 operation%
)he complement instruction# subtracting a constant value of bet+een 0 and 6" from a 163bit pointer register is named
78'&# 7ubtract 'mmediate &ord% @7u8tract 'mmediate &ordA% A!'& and 78'& are possible for the pointer register pairs O#
. and S and for the register pair 22E*22H# that does not have an e5tra name and does not allo+ access to 72A0 or
program memory locations% 22E*22H is ideal for handling 163bit values%
As incrementation after reading is very often needed# ne+er A12 types have the instruction
LPM R,Z+
)his allo+s to transport the byte read to any location 2# and auto3increments the pointer register%
0(#($ Tables in the program flash memory
6o+ that you ,no+ ho+ to read from flash memory you might +ish to place a list of constants or a string of te5t to the
flash and read these% ;o+ to insert that table of values in the program memory( )his is done +ith the assembler directives
%!8 and %!&% &ith that you can insert byte +ise or +ord +ise lists of values% 8yte +ise organi4ed 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
.ou should al+ays place an even number of bytes on each single line% ther+ise the assembler +ill add a 4ero 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 @e% g% >ump targetsA 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 1# but have to be ending +ith a C*M% 6ote that reading the labels from that table +ith :<0
@and subse$uent incrementation of the pointerA first yields the lo+er byte of the +ord# then the upper byte%
0(#(. Accessing registers &ith 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 chip/s address space @at address 050000 to 05001FA% )his access is only meaningful if you have to copy
the register/s content to 72A0 or --<20 or read these values from there bac, into the registers% 0ore common for the
use of pointers is the access to tables +ith fi5ed values in the program memory space% ;ere is# as an e5ample# a table +ith
10 different 163bit values# +here the fifth table value is read to 22E*22H*
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 e5ample% .ou can calculate the table address in S from some input value# leading to the respective table
values% )ables can be organi4ed byte3 or character3+ise# too%
Avr-Asm-Tutorial 24 http://www.avr-asm-tutorial.net
)." 2ecommendation for the $se of re'isters
)he follo+ing recommendations# if follo+ed# decide if you are an effective assembler programmer*
!efine names for registers +ith the %!-F directive# never use them +ith their direct name 25%
'f you need pointer access reserve 226 to 2"1 for that purpose%
A 163bit3counter is best located in 22E*22H%
'f you need to read from the program memory# e% g% fi5ed tables# reserve S @2"1*2"0A and 20 for that purpose%
'f you plan to have access to single bits +ithin certain registers @e% g% for testing flagsA# use 216 to 22" for that
purpose%
2egisters necessary for math are best placed to 21 to 21E%
'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 72A0%
Avr-Asm-Tutorial 25 http://www.avr-asm-tutorial.net
2 'orts
+.1 .hat is a Port/
<orts in the A12 are gates from the central processing unit to internal and e5ternal hard3 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 6H different ports# +hich are not physically available in all different A12 types% !epending 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 A12 type is listed in the data sheets for the processor type% :arger A)mega and A)Omega have more than 6H
ports# access to the ports beyond Q6" is different then @see belo+A%
<orts have a fi5ed address# over +hich the C<= communicates% )he address is independent from the type of A12% 7o e% g%
the port address of port 8 is al+ays 0518 @05 stands for he5adecimal notation# 0518 is decimal 2HA% .ou don/t have to
remember these port addresses# they have convenient aliases% )hese names are defined in the include files @header filesA
for the different A12 types# that are provided from the producer% )he include files have a line defining port 8/s address as
follo+s*
.E#$ POR>3, 0?19
7o +e >ust have to remember the name of port 8# not its location in the 'L space of the chip% )he include file 8E1Edef%inc
is involved by the assembler directive
.I&"L$DE ="@F*o<e;hereF9515def.in,=
and the registers of the 8E1E are all defined there and easily accessible%
<orts usually are organi4ed as 83bit numbers# but can also hold up to 8 single bits that don/t 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% !ue to that name convention you don/t 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%
+.2 .rite access to ports
As an e5ample the 0C= Jeneral Control 2egister# called 0C=C2# consists of a number of single control bits that control
the general property of the chip% ;ere are the details of port 0C=C2 in the A)9078E1E# ta,en from the device data boo,%
ther ports loo, similar%
't is a port# fully pac,ed +ith 8 control bits +ith their o+n names @'7C00# '7C01# %%%A% )hose +ho +ant to send their A12 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 ut instruction brings the content of my preferred register# a 7leep3-nable38it called 7-# to the port 0C=C2% 7-
enables the A12 to go to sleep# +henever the 7:--< instruction sho+s up in the code% As all the other bits of 0C=C2 are
also set by the above instructions and the 7leep 0ode bit 70 +as set to 4ero# a mode called half3sleep +ill result* no
further instruction e5ecution +ill be performed but the chip still reacts to timer and other hard+are interrupts% )hese
e5ternal events interrupt the big sleep of the C<= if they feel they should notify the C<=%
)he above formulation is not very transparent# because C0b00100000M is not easy to remember# and no one sees easily
+hat bit e5actly has been set to one by this instruction% 7o it is a good idea to formulate the :!' instruction as follo+s*
LDI MyPreferredRegister, 1<<SE
)his formulation tells the assembler to
ta,e a one @C1MA#
to read the bit position of the 7leep -nable bit @C7-MA from the symbol list# as defined in the header file
8E1Edef%inc# +hich yields a value of CEM in that case#
to shift @CXXMA the C1M five times left @C1XXEMA# in steps*
1% initial* 0000%0001#
Avr-Asm-Tutorial 26 http://www.avr-asm-tutorial.net
2% first shift left* 0000%0010#
"% second shift left* 0000%0100# and so on until
H% fifth shift left* 0010%0000%
to associate this value to MyPreferredRegister and to insert this :!' 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 A12% 't is pure
convention to increase the readability of the assembler source te5t%
;o+ does this change# if you +ant to set the 7leep 0ode bit @C70MA and the 7leep -nable bit @C7-MA +ithin the same :!'
instruction( 70G1 and 7-G1 enables your A12 to react to a 7:--< 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, (1<<SM) Y (1<<SE)
6o+# the assembler first calculates the value of the first brac,et# @1XX70A# a C1M shifted four times left @because 70 is HA
and that yields 0001%0000# then calculates the second brac,et# @1XX7-A# a C1M shifted five times left @because 7- is EA% )he
CYM bet+een the t+o brac,ets means 8')32 the first and the second value# each bit one by one% )he result of doing this
+ith 0001%0000 and 0010%0000 in that case is 0011%0000# and that is our desired value for the :!' instruction% -ven though
the formulation
@1XX70A Y @1XX7-A
might# on the first loo,# not be more transparent than the resulting value
0011%0000
for a beginner# it is easier to understand +hich bits of 0C=C2 are intended to be manipulated in this :!' instruction%
-specially if you have to read and understand your code some months later# 70 and 7- are a better hint that the 7leep
0ode and -nable bits are targeted here% ther+ise you +ould have to consult the device/s data boo, much more often%
+." 2ead access to ports
2eading a port/s content is in most cases possible using the '6 instruction% )he follo+ing se$uence
.DEF MyPreferredRegister = R16
I& MyPreferredRegister, M"$"R
reads the bits in port 0C=C2 to the register named MyPreferredRegister% As many ports have undefined and unused bits
in certain ports# these bits al+ays read bac, as 4eros%
0ore often than reading all 8 bits of a port one must react to a certain status bit +ithin a port% 'n that case +e don/t need
to read the +hole port and isolate the relevant bit% Certain instructions provide an opportunity to e5ecute instructions
depending on the level of a certain bit of a port @see the J=0< sectionA%
+.% 2ead-6odify-.rite access to ports
7etting 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 78' @7et 8it 'LA and C8' @Clear 8it 'LA% -5ecution is li,e this*
.E#$ A,tiCe3it=0 ' >he )it th%t is to )e ,h%nged
*3I Port3, A,tiCe3it ' >he )it GA,tiCe3itH ;i-- )e set to one
"3I Port3, A,tiCe)it ' >he )it GA,tiCe3itH ;i-- )e ,-e%red to Dero
)hese t+o instructions have a limitation* only ports +ith an address smaller than 0520 can be handled# ports above cannot
be accessed that +ay% 8ecause 0C=C2 in the above e5amples is at he5 address Z"8# the sleep mode and enable bits can/t
be set or cleared that +ay% 8ut all the port bits controlling e5ternal pins @<2)5# !!25# <'65A are accessible that +ay%
+.) 6emory mapped port access
For the more e5otic programmer and the Celephant3li,eM A)mega and A)Omega @+here A)0-: ran out of accessible port
addressesA* the ports can also be accessed using 72A0 access instructions# e% g% 7) and :!% Just add 0520 to the port/s
address @remember* the first "2 addresses are associated to the registers?A and access the port that +ay% :i,e
demonstrated here*
.DEF MyPreferredRegister = R16
LDI 5/,/I0/1POR>3I6!2
LDI 5L,LO41POR>3I6!2
LD MyPreferredRegister,5
)hat only ma,es sense in certain cases# because it re$uires more instructions# e5ecution time and assembler lines# but it is
possible% 't is also the reason +hy the first address location of the 72A0 is 0560 or 05100 in some larger A12 types%
+.+ &etails of rele(ant ports in the *12
)he follo+ing table holds the most used ports in a CsmallM A)9078E1E% 6ot all ports are listed here# some of the 0-JA and
A)907HH"HL8E"E types are s,ipped% 'f in doubt see the original reference%
Avr-Asm-Tutorial 27 http://www.avr-asm-tutorial.net
Component Port name Port-Register
Accumulator 72-J 7tatus 2egister
7tac, 7<:L7<; 7tac,pointer
-5ternal 72A0L-5ternal 'nterrupt 0C=C2 0C= Jeneral Control 2egister
-5ternal 'nterrupts J'07N 'nterrupt 0as, 2egister
J'F2 'nterrupt Flag 2egister
)imer 'nterrupts )'07N )imer 'nterrupt 0as, 2egister
)'F2 )imer 'nterrupt Flag 2egister
83bit )imer 0 )CC20 )imerLCounter 0 Control 2egister
)C6)0 )imerLCounter 0
163bit )imer 1 )CC21A )imerLCounter Control 2egister 1 A
)CC218 )imerLCounter Control 2egister 1 8
)C6)1 )imerLCounter 1
C21A utput Compare 2egister 1 A
C218 utput Compare 2egister 1 8
'C21:L; 'nput Capture 2egister
&atchdog )imer &!)C2 &atchdog )imer Control 2egister
--<20 Access --A2 --<20 address 2egister
--!2 --<20 !ata 2egister
--C2 --<20 Control 2egister
7erial <eripheral 'nterface 7<' 7<C2 7erial <eripheral Control 2egister
7<72 7erial <eripheral 7tatus 2egister
7<!2 7erial <eripheral !ata 2egister
7erial Communication =A2) =!2 =A2) !ata 2egister
=72 =A2) 7tatus 2egister
=C2 =A2) Control 2egister
=822 =A2) 8aud 2ate 2egister
Analog Comparator AC72 Analog Comparator Control and 7tatus 2egister
'L3<orts <2)5 <ort utput 2egister
!!25 <ort !irection 2egister
<'65 <ort 'nput 2egister
+., The stat$s re'ister as the most $sed port
8y 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 @using the assembler instructions 7-5 or C:5# +here 5 is the bit
abbreviationA% 0ost of these bits are set or cleared by the accumulator through bit3test# compare3 or calculation3
operations%
)he most used bits are*
S* 'f set to one# the previous instruction yielded a 4ero 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 e5ecution%
Bit Calculation Logic Compare Bits Shift Other
S A!!# A!C# A!'&# !-C# '6C#
7=8# 7=8'# 78C# 78C'# 78'&
A6!# A6!'# 2#
2'# -2# C0#
6-J# 782# C82
C<# C<C# C<' 8C:2 S# 87-) S#
C:S# 7-S# )7)
A72# :7:# :72#
2:# 22
C:2
C A!!# A!C# A!'&# 7=8# 7=8'#
78C# 78C'# 78'&
C0# 6-J C<# C<C# C<' 8C:2 C# 87-) C#
C:C# 7-C
A72# :7:# :72#
2:# 22
3
Avr-Asm-Tutorial 28 http://www.avr-asm-tutorial.net
Bit Calculation Logic Compare Bits Shift Other
6 A!!# A!C# A!'&# !-C# '6C#
7=8# 7=8'# 78C# 78C'# 78'&
A6!# A6!'# 2#
2'# -2# C0#
6-J# 782# C82
C<# C<C# C<' 8C:2 6# 87-) 6#
C:6# 7-6# )7)
A72# :7:# :72#
2:# 22
C:2
1 A!!# A!C# A!'&# !-C# '6C#
7=8# 7=8'# 78C# 78C'# 78'&
A6!# A6!'# 2#
2'# -2# C0#
6-J# 782# C82
C<# C<C# C<' 8C:2 1# 87-) 1#
C:1# 7-1# )7)
A72# :7:# :72#
2:# 22
C:2
7 78'& 3 3 8C:2 7# 87-) 7#
C:7# 7-7
3 3
; A!!# A!C# 7=8# 7=8'# 78C#
78C'
6-J C<# C<C# C<' 8C:2 ;# 87-) ;#
C:;# 7-;
3 3
) 3 3 3 8C:2 )# 87-) )#
87)# C:)# 7-)
3 3
' 3 3 3 8C:2 '# 87-) '#
C:'# 7-'
3 2-)'
+.- Port details
<ort details of the most common ports are sho+n in an e5tra table @see anne5A%
Avr-Asm-Tutorial 29 http://www.avr-asm-tutorial.net
5 ,RAM
6early all A123types have static 2A0 @72A0A on board @only very fe+ old devices don/tA% nly 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 72A0 to utili4e more space%
,.1 .hat is 02*6/
72A0 are memories that are not
directly accessible by the central
processing unit @Arithmetic and
:ogical =nit A:=# sometimes called
accumulatorA li,e the registers are%
'f you access these memory
locations you usually use a register
as interim storage% 'n the e5ample
displayed here a value in 72A0 +ill
be copied to the register 22 @1st
instructionA# a calculation +ith the
value in 2" is made and the result is
+ritten to 2" @second instructionA%
After that this value is +ritten bac,
to the same 72A0 location
@instruction "# not sho+n hereA%
7o it is clear that operations +ith values stored in the 72A0 are slo+er to perform than those using registers alone% n the
other hand* even the smallest A12 types have 128 bytes of 72A0 available# much more than the "2 registers can hold%
)he types from the old A)9078E1E up+ards offer the additional opportunity to connect additional e5ternal 2A0#
e5panding the internal E12 bytes% From the assembler point3of3vie+# e5ternal 72A0 is accessed li,e internal 72A0% 6o
e5tra instructions must be learned for accessing that e5ternal 72A0%
,.2 4or what p$rposes can # $se 02*6/
8esides simple storage of values# 72A0 offers additional opportunities for its use% 6ot only access +ith fi5ed addresses is
possible# but also the use of pointers# so that floating access to subse$uent locations in 72A0 can be programmed% )his
+ay you can build up ring buffers for interim storage of values or calculated @variableA tables% )his is not very often used
+ith registers# because they are too fe+ and prefer fi5ed access%
-ven more relative is the access using an offset to a fi5ed starting address in one of the pointer registers% 'n that case a
fi5ed address is stored in a pointer register# a constant value is added to this address and readL+rite access is made to that
address +ith an offset% &ith that ,ind of access# tables are very more effective%
8ut the most relevant use for 72A0 is the so3called stac,% .ou can push values @variablesA to that stac,% 8e it the content of
a register# that is temporarily needed for another purpose% 8e it a return address prior to calling a subroutine# or the
return address prior to a hard+are3triggered interrupt%
,." How to $se 02*6/
5($( 1irect addressing
)o copy a value to a memory location in 72A0 you have to define the address% )he 72A0 addresses you can use reach
from the start address @very often 050060 in smaller A12s# 050100 in larger A)megaA to the end of the physical 72A0 on
the chip @in the A)9078E1E the highest accessible internal 72A0 location is 0502EF# see the device data sheet of your A12
type for more details on thisA%
&ith the instruction
*>* 0?0060, R1
the content of register 21 is copied to the first 72A0 location in address 050060% &ith
LD* R1, 0?0060
the 72A0 content at address 050060 is copied to the register% )his is the direct access +ith an address that has to be
defined by the programmer%
)he symbols defined in the Ddef%inc include file# 72A0T7)A2) and 2A0-6!# allo+ to place your variables +ithin the 72A0
space% 7o it is better to use these definitions to access the 1E
th
memory byte# li,e this*
LD* R1,*RAMJ*>AR>I15
7ymbolic names can be used to avoid handling fi5ed addresses# that re$uire a lot of +or,# if you later +ant to change the
structure of your data in the 72A0% )hese names are easier to handle than he5 numbers# so give that address a name li,e*
Avr-Asm-Tutorial 30 http://www.avr-asm-tutorial.net
.E#$ MyPreferred*tor%ge"e-- = *RAMJ*>AR>
*>* MyPreferred*tor%ge"e--, R1
.es# it isn/t shorter# but easier to remember% =se +hatever name that you find to be convenient%
5($(# 'ointer addressing
Another ,ind of access to 72A0 is the use of pointers% .ou need t+o registers for that purpose# that hold the 163bit
address of the location% As +e learned in the <ointer32egister3!ivision# pointer registers are the register pairs O @O;*O:#
22F*226A# . @.;*.:# 229*228A and S @S;*S:# 2"1*2"0A% )hey allo+ access to the location they point to directly @e% g% +ith 7)
O# 21A# after prior decrementing the address by one @e% g% 7) 3O# 21A or +ith subse$uent auto3incrementation of the address
@e% g% 7) OK# 21A% A complete access to three cells in a ro+ loo,s li,e this*
.E#$ MyPreferred*tor%ge"e-- = *RAMJ*>AR>
.DEF MyPreferredRegister = R1
.DEF AnotherRegister = R!
.DEF And.etAnotherRegister = R6
LDI K/, /I0/1MyPreferred*tor%ge"e--2
LDI KL, LO41MyPreferred*tor%ge"e--2
LD MyPreferredRegister, KI
LD AnotherRegister, KI
LD And.etAnotherRegister, K
-asy to operate# those pointers% And as easy as in other languages than assembler# that claim to be easier to learn%
5($($ 'ointer &ith offset
)he third construction is a little bit more e5otic and only e5perienced programmers use this in certain cases% :et/s assume
+e very often in our program need to access three consecutive 72A0 locations% :et/s further assume that +e have a spare
pointer register pair# so +e can afford to use it e5clusively for our purpose% 'f +e +ould use the 7)L:! instructions +e
al+ays have to change the pointer if +e access another location of the three% 6ot very convenient%
)o avoid this# and to confuse the beginner# the access +ith offset +as invented% !uring that access the register value isn/t
changed% )he address is calculated by temporarily adding the fi5ed offset% 'n the above e5ample the access to location
050062 +ould loo, li,e this% First# the pointer register is set to our central location 72A0T7)A2)*
.E#$ MyPreferred*tor%ge"e-- = *RAMJ*>AR>
.DEF MyPreferredRegister = R1
LDI ./, /I0/1MyPreferred*tor%ge"e--2
LDI .L, LO41MyPreferred*tor%ge"e--2
7ome+here later in the program '/d li,e to +rite to cell 2 above 72A0T7)A2)*
*>D .I!, MyPreferredRegister
)he corresponding instruction for reading from 72A0 +ith an offset
LDD MyPreferredRegister, .I!
is also possible%
6ote that the 2 is not really added to .# >ust temporarily during the e5ecution of this instruction% )o confuse you further#
this can only be done +ith the .3 and S3register3pair# not +ith the O3pointer?
f about 100 cases# the use of this opportunity is more effective in one single case% 7o don/t care if you don/t understand
this in detail% 't is only for e5perts# and only necessary in a fe+ cases%
)hat/s it +ith the 72A0# but +ait* the most relevant use as stac, is still to be learned%
,.% Use of 02*6 as stack
)he most common use of 72A0 is its use as stac,% )he stac, is a to+er of +ooden bloc,s% -ach additional bloc, goes onto
the top of the to+er# each recall of a value removes the most upper bloc, from the to+er% 2emoval 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 :ast3'n3First3ut @:'FA or easier* the last to go on top +ill be the first coming do+n from the top%
5(.( 1efining ,RAM as stac@
)o use 72A0 as stac, re$uires the setting of the stac, pointer first% )he stac, pointer is a 163bit3pointer# accessible li,e a
port% )he double register is named 7<;*7<:% 7<; holds the most significant address byte# 7<: the least significant% )his is
only true# if the A12 type has more than 2E6 byte 72A0% 'f not# 7<; is not necessary# is undefined# and must not and
cannot be used% &e assume +e have more than 2E6 bytes 72A0 in the follo+ing e5amples%
)o construct the stac,# the stac, pointer is loaded +ith the highest available 72A0 address% @'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?A%
.DEF MyPreferredRegister = R16
LDI MyPreferredRegister, /I0/1RAME&D2 ' $EEer )yte
O$> *P/,MyPreferredRegister ' to st%,L Eointer
LDI MyPreferredRegister, LO41RAME&D2 ' Lo;er )yte
Avr-Asm-Tutorial 31 http://www.avr-asm-tutorial.net
O$> *PL,MyPreferredRegister ' to st%,L Eointer
)he value 2A0-6! is# of course# specific for the processor type% 't is defined in the '6C:=!- file for the processor type%
)he file 8E1Edef%inc has the line*
.eM: RAME&D =N!5F ' L%st On("hiE *RAM Lo,%tion
)he file 8E1Edef%inc is included +ith the assembler directive
.I&"L$DE ="@Fso<e;hereF9515def.in,=
at the beginning of our assembler source code%
7o +e defined the stac, no+# and +e don/t have to care about the stac, pointer any more# because manipulations of that
pointer are mostly automatic%
5(.(# 7se of the stac@
=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%,L
&here that value goes to is totally uninteresting% )hat the stac, pointer +as decremented after that push# +e don/t have
to care% 'f +e need the content again# +e >ust add the follo+ing instruction*
POP MyPreferredRegister ' Re%d )%,L the C%-:e fro< the toE of the st%,L
&ith << +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 e5ists 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%
0ore 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 @the current program counter valueA onto the
stac, and temporarily >umps to the subroutine% After its e5ecution the subroutine pops the return address from the stac,
and loads it bac, into the program counter% <rogram e5ecution is continued e5actly one instruction behind the instruction#
+here the call happened*
R"ALL *o<e;h%t ' O:<E to the -%)e- Gso<e;h%t@H
A...B here ;e ;i-- -%ter ,ontin:e ;ith the Erogr%<.
;ere the >ump to the label Csome+hat*M some+here in the program code#
*o<e;h%t@ ' this is the P:<E %ddress
A...B /ere ;e do so<ething
A...B %nd ;e %re finished %nd ;%nt to P:<E )%,L to the ,%--ing -o,%tion@
RE>
!uring e5ecution of the 2CA:: instruction the already incremented program counter# a 163bit3address# is pushed onto the
stac,# using t+o pushes @the :78 and the 078A% 8y reaching the 2-) instruction# the content of the previous program
counter is reloaded +ith t+o pops and e5ecution continues there%
.ou don/t need to care about the address of the stac,# +here the counter is loaded to% )his address is 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 72A0# everything is fine%
7ervicing hard+are interrupts isn/t possible +ithout the stac,% 'nterrupts stop the normal e5ecution of the program#
+herever the program currently is% After e5ecution of a specific service routine as a reaction to that interrupt program
e5ecution 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 A12s +ithout having 72A0
have at least a very small hard+are stac,%
5(.($ Common bugs &ith the stac@ operation
For the beginner there are a lot of possible bugs# if you first learn to use stac,%
1ery clever is the use of the stac, +ithout first setting the stac, pointer% 8ecause this pointer is set to 4ero at program
start# the pointer points to the location 050000# +here register 20 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 05FFFF# an undefined position @if you
don/t have e5ternal 72A0 thereA% A 2CA:: and 2-) +ill return to a strange address in program memory% 8e sure* there is
no +arning# li,e a +indo+ popping up saying something li,e B'llegal access to memory location 5555C%
Another opportunity to construct bugs is to forget to pop a previously pushed value# or popping a value +ithout pushing
one first%
Avr-Asm-Tutorial 32 http://www.avr-asm-tutorial.net
'n a very fe+ cases the stac, overflo+s to belo+ the first 72A0 location% )his happens in case of a never3ending recursive
call% After reaching the lo+est 72A0 location the ne5t pushes +rite to the ports @0500EF do+n to 050020A# then to the
registers @05001F to 050000A% Funny and unpredictable things happen +ith the chip hard+are# if this goes on% Avoid this
bug# it can even destroy your e5ternal hard+are?
Avr-Asm-Tutorial 33 http://www.avr-asm-tutorial.net
9 Aumping and branching
;ere +e discuss all instructions that control the se$uential e5ecution of a program% 't starts +ith the starting se$uence on
po+er3up of the processor# continues +ith >umps# interrupts# etc%
-.1 Controllin' se7$ential e!ec$tion of the pro'ram
"hat ha!!ens during a reset#
&hen the po+er supply voltage of an A12 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
4ero% At this address the e5ecution al+ays starts% ;ere +e have to have our first +ord of code% 8ut not only during po+er3
up this address is activated*
!uring an e5ternal reset on the reset pin of the device a restart is e5ecuted%
'f the &atchdog counter reaches its ma5imum 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%
.ou can call reset by a direct >ump to that address @see the >ump section belo+A%
)he third case is not a real reset# because the automatic resetting of register3 and port3values to a +ell3defined default
value is not e5ecuted% 7o# 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 +atchdog/s port% 7etting the +atchdog counter bac, to 4ero re$uires the e5ecution of the
instruction
4DR
to avoid a reset%
After e5ecution of a reset# +ith setting registers and ports to default values# the code at address 0000 is +ord +ise read to
the e5ecution part of the processor and is e5ecuted% !uring that e5ecution the program counter is already incremented by
one and the ne5t +ord of code is already read to the code fetch buffer @Fetch during -5ecutionA% 'f the e5ecuted
instruction does not re$uire a >ump to another location in the program the ne5t instruction is e5ecuted immediately% )hat
is +hy the A12s e5ecute e5tremely fast# each cloc, cycle e5ecutes one instruction @if no >umps occurA%
)he first instruction of an e5ecutable is al+ays located at address 0000% )o tell the compiler @assembler programA 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# %C7-J# 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 --<20
section of the chip# +here you also can +rite bytes or +ords to%
.E*E0
)he third segment is the 72A0 section of the chip%
.D*E0
ther than +ith --<20 content# +here content is really going to the --<20 during programming of the chip# the !7-J
segment content is not programmed to the chip% )here is no opportunity to burn any 72A0 content% 7o the %!7-J is only
used for correct label calculation during the assembly process% An e5ample*
.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
7o# only three labels are defined +ithin the assembler# no content is produced%
)he 2J directive +ithin the code segment# %2J# above stands for the +ord CoriginM and manipulates the address +ithin
the code segment# +here assembled +ords go to% As our program al+ays starts at 050000 the C7-JL2J directives are
trivial# you can s,ip these +ithout getting into an error% &e could start at 050100# but that ma,es no real sense as the
processor starts e5ecution at 0000% 'f you +ant to place a table e5actly to a certain location of the code segment# you can
use 2J% 8ut be careful +ith that* nly >ump for+ard +ith %2J# never bac,+ards% And be a+are that the flash memory
space that you s,ipped in bet+een your current code location and the one you forced +ith %2J is al+ays filled +ith the
instruction +ord 05FFFF% )his instruction does nothing# >ust goes to the ne5t instruction% 7o be sure your e5ecution 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 %!-F3 and %-P=3directives# use the C7-JL2J se$uence as a signal for yourself# even though it might not be
Avr-Asm-Tutorial 34 http://www.avr-asm-tutorial.net
necessary to do that%
As the first code +ord is al+ays at address 4ero# this location is also called the reset vector% Follo+ing the reset vector the
ne5t positions in the program space# addresses 050001# 050002 etc%# are interrupt vectors% )hese are the positions +here
the e5ecution >umps to if an e5ternal 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 @see belo+A% )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 2-)'
@2-)urn from 'nterruptA is best placed here% )he typical program se$uence at the beginning is li,e follo+s*
."*E0
.OR0 0000
ROMP *t%rt ' the reset Ce,tor
ROMP 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
ROMP 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 C2J0< 7tartM results in a >ump to the label 7tart*# located some lines belo+% 2emember# labels al+ays end
+ith a C*M% :abels# that don/t fulfill these conditions are not ta,en for serious# but interpreted as instructions% 0issing labels
result in an error message @I=ndefined labelIA# and compilation is interrupted%
-.2 8inear pro'ram e!ec$tion and branches
<rogram e5ecution is al+ays linear# if nothing changes the se$uential e5ecution% )hese changes are the e5ecution of an
interrupt or of branching instructions%
$ranching
8ranching is very often depending on some condition# called conditional branching% As an e5ample +e assume +e +ant to
construct a "23bit3counter using the registers 21 to 2H% )he least significant byte in 21 is incremented by one% 'f the
register overflo+s during that operation @2EE K 1 G 0A# +e have to increment 22 similarly% 'f 22 overflo+s# +e have to
increment 2"# and so on%
'ncrementation by one is done +ith the instruction '6C% 'f an overflo+ occurs during that e5ecution of '6C 21# the 4ero bit
in the status register is set to one @the result of the operation is 4eroA% )he carry bit in the status register# as usually set
+hen something overflo+s# is not changed during an '6C% )his is not to confuse the beginner# but carry can be used for
other purposes instead% )he Sero38it or Sero3flag in this case is enough to detect an overflo+% 'f no overflo+ occurs +e can
>ust leave the counting se$uence%
'f the Sero3bit is set# +e must e5ecute additional incrementation of the ne5t upper register% )o confuse the beginner the
branching instruction# that +e have to use# is not named 826S but 826- @82anch if 6ot -$ualA% A matter of taste %%%
)he +hole count se$uence of the "23bit3counter 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!@
7o that/s about it% An easy thing% )he opposite condition to 826- is 82-P or 82anch -Pual%
&hich of the status bits# also called processor flags# are changed during e5ecution of an instruction is listed in instruction
code tables# see the :ist of 'nstructions% 7imilarly to the Sero3bit you can use the other status bits li,e that*
3R"" -%)e-Q3R"* -%)e-' "%rry(f-%g 0 13R""2 or 1 13R"*2
3R*/ -%)e-' EM:%- or gre%ter
3RLO -%)e-' *<%--er
3RMI -%)e-' Min:s
3RPL -%)e-' P-:s
3R0E -%)e-' 0re%ter or eM:%- 1;ith sign )it2
3RL> -%)e-' *<%--er 1;ith sign )it2
3R/" -%)e-Q3R/* -%)e-' /%-f oCerf-o; f-%g 0 or 1
3R>" -%)e-Q3R>* -%)e-' >(3it 0 or 1
3R" -%)e-Q3R* -%)e-' >;oRs ,o<E-e<ent f-%g 0 or 1
3RIE -%)e-Q3RID -%)e-' Interr:Et en%)-ed or dis%)-ed
Avr-Asm-Tutorial 35 http://www.avr-asm-tutorial.net
to react to the different conditions% 8ranching al+ays occurs if the condition is met% !on/t be afraid# most of these
instructions are rarely used% For the beginner only Sero and Carry are relevant%
-." Timin' d$rin' pro'ram e!ec$tion
:i,e mentioned above the re$uired time to e5ecute one instruction is e$ual to the processor/s cloc, cycle% 'f the processor
runs on a H 0;4 cloc, fre$uency then one instruction re$uires 1LH [s or 2E0 ns# at 10 0;4 cloc, only 100 ns% )he re$uired
time is as e5act as the internal or e5ternal or Otal cloc, is% 'f you need e5act timing an A12 is the optimal solution for your
problem% 6ote that there are a fe+ instructions that re$uire t+o or more cycles# e% g% the branching instructions @if
branching occursA or the 72A0 readL+rite se$uence% 7ee the instruction table for details%
)o define e5act timing there must be an opportunity that does nothing else than delay program e5ecution% .ou might use
other instructions that do nothing# but more clever is the use of the no3operation instruction 6<% )his is the most useless
instruction*
&OP
)his instruction does nothing but +asting processor time% At H 0;4 cloc, +e need >ust four of these instructions to +aste
1 [s% 6o other hidden meanings here on the 6< instruction% For a signal generator +ith 1 ,;4 +e don/t need to add H000
such instructions to our source code# but +e use a soft+are counter and some branching instructions% &ith these +e
construct a loop that e5ecutes for a certain number of times and are e5actly delayed% A counter could be a 83bit3register
that is decremented +ith the !-C instruction# e% g% li,e this*
"LR R1 ' one ,-o,L ,y,-e
"o:nt@
DE" R1 ' one ,-o,L ,y,-e
3R&E "o:nt ' t;o for )r%n,hing, one for not )r%n,hing
)his se$uence +astes @1A K @2EED2A K @1D"A G E1H cloc, cycles or 128%E [s at H 0;4%
163bit counting can also be used to delay e5actly# li,e this
LDI 5/,/I0/1655652 ' one ,-o,L ,y,-e
LDI 5L,LO41655652 ' one ,-o,L ,y,-e
"o:nt@
*3I4 5L,1 ' t;o ,-o,L ,y,-es
3R&E "o:nt ' t;o for )r%n,hing, one for not )r%n,hing
)his se$uence +astes @1K1A K @6EE"HDHA K @1D"A G 262#1H1 cloc, cycles or 6E#E"E%2E [s at H 0;4%
'f you use more registers to construct nested counters you can reach any delay% And the delay is as e5act as your cloc,
source is# even +ithout a hard+are timer%
-.% 6acros and pro'ram e!ec$tion
1ery often you have to +rite identical or similar code se$uences on different occasions in your source code% 'f you don/t
+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% 0acros are code se$uences# designed and tested once# and inserted into the code by its macro
name% As an e5ample +e assume +e need to delay program e5ecution several times by 1 [s at H 0;4 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*
A...B so<e;here in the so:r,e ,ode
De-%y1
A...B ,ode goes on here
)his results in four 6< instructions inserted to the code at that location% An additional C!elay1M inserts additional four
6< 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%
8y calling a macro by its name you can add some parameters to manipulate the produced code% 8ut this is more than a
beginner has to ,no+ about macros%
-.) 0$bro$tines
'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 e5ecution of the se$uence follo+ing the
Avr-Asm-Tutorial 36 http://www.avr-asm-tutorial.net
subroutine call you need to return to the caller% For a delay of 10 cycles you need to +rite this subroutine*
De-%y10@ ' the ,%-- of the s:)ro:tine reM: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
7ubroutines al+ays start +ith a label# other+ise you +ould not be able to >ump to it# here named C!elay10*M% )hree 6<s
follo+ and a 2-) instruction% 'f you count the necessary cycles you >ust find F cycles @" for the 6<s# H for the 2-)A% )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
2CA:: 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 2-) instruction >umps bac, to the calling routine% 6ote that before you use subroutine
calls you must set the stac, pointer @see 7tac,A# because the return address must be pac,ed on top of the stac, during the
2CA:: 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
ROMP De-%y10
Ret:rn@
A...B f:rther on ;ith so:r,e ,ode
6ote that 2J0< is also a relative >ump instruction +ith limited distance% nly A)mega A12s have a J0< instruction
allo+ing >umps over the complete flash memory space# but these instructions re$uire t+o +ords and more instruction
time than 2J0<# so avoid it if possible%
)he routine that you >umped to can not use the 2-) instruction in that case# because 2J0< does not place the current
e5ecution 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 can/t call this routine
from different locations in the code%
2CA:: and 2J0< 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
@confusingA 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 ' *LiE the ne?t instr:,tion if )it 8 in register 1 is 0
R"ALL $EL%)e- ' "%-- th%t s:)ro:tine
782C reads B7,ip ne5t instruction if 8it F in 2egister 21 is Clear @GSeroAC% )he 2CA:: instruction to C=p:abel*M is only
e5ecuted if bit F in register 21 is 1# because the ne5t 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 7827% )he instruction follo+ing 7827L782C can be a single
+ord or double +ord instruction# the processor ,no+s ho+ far he has to >ump over it% 6ote that e5ecution 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 e5otic instruction*
"P*E R1,R! ' "o<E%re R1 %nd R!, sLiE ne?t instr:,tion if eM:%-
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 78'C and 78'7% )hat reads C7,ip if the 8it in 'Lo space is Clear @or 7etAM# li,e this*
*3I" PI&3,0 ' *LiE ne?t instr:,tion if 3it 0 on inE:t Eort 3 is 0
ROMP A>%rget ' O:<E to the -%)e- A>%rget
)he 2J0<3instruction is only e5ecuted if bit 0 in port 8 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%
6o+# another e5otic application for the e5pert% 7,ip this if you are a beginner% Assume +e have a bit s+itch +ith H
s+itches connected to port 8% !epending on the state of these H bits +e +ould li,e to >ump to 16 different locations in the
code% 6o+ +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 16 addresses# li,e this*
My>%)@
ROMP Ro:tine1
ROMP Ro:tine!
A...B
ROMP Ro:tine16
'n our code +e copy that address of the table to the S pointer register*
LDI 5/,/I0/1My>%)2
LDI 5L,LO41My>%)2
and add the current state of the port 8 @in 216A to this address%
ADD 5L,R16
3R"" &oOCerf-o;
Avr-Asm-Tutorial 37 http://www.avr-asm-tutorial.net
I&" 5/
&oOCerf-o;@
6o+ +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,*
IOMP ' P:<E to %ddress in 5
)he processor loads the content of the S register pair into its program counter and continues operation there% 0ore clever
than branching over and over(
-.+ #nterr$pts and pro'ram e!ec$tion
1ery often +e have to react on hard+are conditions or other events% An e5ample is a change on an input pin% .ou 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 component/s 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
Flag% -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, @+hich must be enabled first? 7ee initiation of the stac,pointer in the 7tac, section of the 72A0 descriptionA%
&ithout that# the processor +ouldn/t be able to return bac, to the location# +here the interrupt occurred @+hich could be
any time and any+here +ithin program e5ecutionA% After that# processing >umps to the predefined location# the interrupt
vector# and e5ecutes the instructions there% =sually the instruction there is a J=0< instruction to the interrupt service
routine# located some+here in the code% )he interrupt vector is a processor3specific 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 A12 types are listed in the follo+ing table% @)he first
vector isn/t an interrupt but the reset vector# performing no stac, operation?A
Name Interrupt Vector !!ress
"#$# "#"# %&$&
'riggere! ()
2-7-) 0000 0000 0000 ;ard+are 2eset# <o+er3n32eset# &atchdog 2eset
'6)0 0001 0001 0001 :evel change on the e5ternal '6)0 pin
'6)1 0002 3 0002 :evel change on the e5ternal '6)1 pin
)'0-21CA<) 000" 3 000" Capture event on )imerLCounter 1
)'0-21C0<A 3 3 000H )imerLCounter 1 G Compare value A
)'0-21 C0<8 3 3 000E )imerLCounter 1 G Compare value 8
)'0-21 C0<1 000H 3 3 )imerLCounter 1 G Compare value 1
)'0-21 1F 000E 3 0006 )imerLCounter 1 verflo+
)'0-20 1F 0006 0002 000F )imerLCounter 0 verflo+
7<' 7)C 3 3 0008 7erial )ransmit Complete
=A2) )O 000F 3 0009 =A2) char in receive buffer available
=A2) =!2- 0008 3 000A =A2) transmitter ran empty
=A2) )O 0009 3 0008 =A2) All 7ent
A6ATC0< 3 3 000C Analog Comparator
6ote 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 A12 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 e5ecution of its service routine the first e5ecuted int disables the
processor/s '3flag% )he service routine must re3enable this flag after it is done +ith its >ob%
For re3setting the ' status bit there are t+o +ays% )he service routine can end +ith the instruction*
RE>I
Avr-Asm-Tutorial 38 http://www.avr-asm-tutorial.net
)his return from the int routine restores the '3bit after the return address has been loaded to the program counter%
)he second +ay is to enable the '3bit by the instruction
*EI ' *et Interr:Et En%)-ed
RE> ' Ret:rn
)his is not the same as the 2-)'# because subse$uent interrupts are already enabled before the program counter is re3
loaded +ith the return address% 'f another int is pending# its e5ecution is already starting before the return address is
popped from the stac,% )+o or more nested addresses remain on the stac,% 6o bug is to be e5pected# but it is an
unnecessary ris, doing that% 7o >ust use the 2-)' instruction to avoid this unnecessary flo+ to the stac,%
An 'nt3vector 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 2-)' 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 e5ecution of the
respective service routine does not automatically reset the interrupt condition flag of the peripheral% 'n that case a simple
2-)' +ould reset the other+ise never3ending interrupts% )his is the case +ith some of the =A2) interrupts%
6ote that larger devices have a t+o3+ord organi4ation of the vector table% 'n this case the J0< instruction has to be used
instead of 2J0<% And 2-)' instructions must be follo+ed by an 6< to point to the ne5t vector table address%
As# after an interrupt is under service# further e5ecution of lo+er3priority 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 7-' +ithin the service routine# +henever you/re done +ith the most urgent tas,s% )his is not very
clever% 0ore 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$ction is always to sa(e the processor stat$s fla's in a re'ister or on the stack.
!o 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% Funny things +ould happen from time to time% )he last instruction before the 2-)' 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 e5amples ho+ to do that*
7aving in a register* 7aving on the stac,*
Isr@ Isr@
I& R15,*RE0 ' s%Ce f-%gs P$*/ R15 ' s%Ce register on st%,L
A... <ore instr:,tions...B I& R15, *RE0
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 e5clusively for that purpose%
Jenerally* All used registers in a service routine should either be e5clusively reserved for that purpose or saved on stac,
and restored at the end of the service routine% 6ever change the content of a register +ithin an int service routine that is
used some+here else in the normal program +ithout restoring it%
8ecause of these basic re$uirements a more sophisticated e5ample for an interrupt service routine here%
."*E0 ' "ode(*eg<ent st%rts here
.OR0 0000 ' Address is Dero
ROMP *t%rt ' >he reset(Ce,tor on Address 0000
ROMP 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%,L %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%,L
I& R16,*RE0 ' re%d st%t:s register
P$*/ R16 ' %nd E:t on st%,L
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%,L
O$> *RE0,R16 ' restore o-d st%t:s
POP R16 ' get EreCio:s ,ontent of R16 fro< the st%,L
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% 7,ip <=7; 216 and <<
216 if you can afford reserving the register for e5clusive use +ithin the service routine% As an interrupt service routine
cannot be interrupted @unless you allo+ interrupts +ithin the routineA# all different int service routines can use the same
register%
.ou understand no+# +hy allo+ing interrupts +ithin an interrupt service routine# and not at its end +ith 2-)'# is not a
good idea(
)hat/s 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-Tutorial 39 http://www.avr-asm-tutorial.net
* Calculations
;ere +e discuss all necessary instructions for calculating in A12 assembler language% )his includes number systems# setting
and clearing bits# shift and rotate# and addingLsubtractingLcomparing and the format conversion of numbers%
9.1 :$mber systems in assembler
)he follo+ing formats of numbers are common in assembler*
<ositive +hole numbers @8ytes# &ords# :ong+ords# etc%A#
7igned +hole numbers @7hort'nts# 'ntegers# :ong'nts# etc%A#
8inary Coded !igits @8C!A#
<ac,ed 8C!s#
A7C''3formatted numbers%
'f you come from a high3level language* forget pre3defined number formats% Assembler doesn/t have that concept nor its
@sometimes frustatingA limitations% &hat you earn is* you are the master of your o+n format?
*(( 'ositiBe &hole numbers Cbytes3 &ords3 etc(D
)he smallest +hole number to be handled in assembler is a byte +ith eight bits% )his codes numbers bet+een 0 and 2EE%
7uch bytes fit e5actly into one register of the 0C=% All larger numbers must be based on this basic format# using more than
one register% )+o bytes yield a +ord @range from 0 %% 6E#E"EA# three bytes form a longer +ord @range from 0 %% 16#FFF#21EA
and four bytes form a double +ord @range from 0 %% H#29H#96F#29EA%
)he single bytes of a +ord or a double +ord can be stored in +hatever register you prefer% perations +ith these single
bytes are programmed byte by byte# so you don/t 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
2egisters d+0 to d+" are in a ro+# but don/t need to be% 'f +e need to initiate this double +ord at the beginning of an
application @e% g% to H#000#000A# 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
7o +e have splitted this decimal number# called d+i# to its binary portions 8.)-H to 8.)-1 and pac,ed them into the four
byte pac,ages% 6o+ you can calculate +ith this double +ord%
*((# ,igned numbers CintegersD
7ometimes# 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 1 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 31 as a
byte integer is not +ritten as 1000%0001 but as 1111%1111 instead% )hat means* subtract 1 from 0 @and forget the
overflo+A% )he first bit is the sign bit# signaling that this is a negative number% &hy this different format @subtracting the
number from 0A is used is easy to understand* adding 31 @1111%1111A and K1 @0000%0001A yields e5actly 4ero# if you forget
the overflo+ that occurs during that operation @to the ninth bitA%
'n one byte the largest integer number to be handled is K12F @binary 01111111A# the smallest one is 3128 @binary
1#0000000A% '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 K"2#F6F %% 3"2#F68A# four bytes provide a range from
K2#1HF#H8"#6HF %% 32#1HF#H8"#6H8# in other languages called a :ong'nt or !ouble'nt%
*(($ Binary Coded 1igits3 BC1
<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 @binary values 0000 %% 1001A# the
upper four bits of the byte are al+ays 4eros# blo+ing a lot of hot air into one byte% For to handle the value 2E0 +e +ould
need at least three bytes# e% g%*
Avr-Asm-Tutorial 40 http://www.avr-asm-tutorial.net
Bit *alue $"% +, #" $+ % , " $
216# !igit 1 G2 0 0 0 0 0 0 1 0
21F# !igit 2 G E 0 0 0 0 0 1 0 1
218# !igit " G 0 0 0 0 0 0 0 0 0
'Instr:,tions to :se@
LDI R16,!
LDI R18,5
LDI R19,0

.ou 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 @if you program A12s for ban,ing applicationsA# and you can convert them
very easily to character strings%
*((. 'ac@ed BC1s
'f you pac, t+o decimal digits into one byte you don/t 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 @special instructions in A12 assembler languageA% )he decimal number 2E0
+ould loo, li,e this +hen formatted as a pac,ed 8C!*
B)te -igits Value % , " $ % , " $
2 H \ " 02 0 0 0 0 0 0 1 0
1 2 \ 1 E0 0 1 0 1 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 @0b%%%A or the he5adecimal notation @05%%%A to set the proper bits to their
correct nibble position%
Calculating +ith pac,ed 8C!s is a little more complicated compared to the binary form% Format changes to character
strings are nearly as easy as +ith 8C!s% :ength of numbers and precision of calculations is only limited by the storage
space%
*((0 6umbers in A,CII-format
1ery similar to the unpac,ed 8C! format is to store numbers in A7C'' format% )he digits 0 to 9 are stored using their A7C''
@A7C'' G American 7tandard Code for 'nformation 'nterchangeA representation% A7C'' is a very old format# developed and
optimi4ed for teletype +riters# unnecessarily very complicated for computer use @do you ,no+ +hat a char named -nd f
)ransmission -) meant +hen it +as invented(A# very limited in range for other than =7 languages @only F bits per
characterA# 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 E3bit long teletype character set
called 8audot set or the 0orse code# still used by some finger3nervous people%
&ithin the A7C'' code system the decimal digit 0 is represented by the number H8 @he5 05"0# binary 0b0011%0000A# digit 9
is EF decimal @he5 05"9# binary 0b0011%1001A% A7C'' +asn/t designed to have these numbers on the beginning of the code
set as there are already instruction chars li,e the above mentioned -) for the teletype% 7o +e still have to add H8 to a
8C! @or set bit H and E to 1A to convert a 8C! to A7C''% A7C'' formatted numbers need the same storage space li,e 8C!s%
:oading 2E0 to a register set representing that number +ould loo, li,e this*
LDI R19,R!R
LDI R18,R5R
LDI R16,R0R
)he A7C'' representation of these characters are +ritten to the registers%
9.2 ;it manip$lations
)o convert a 8C! coded digit to its A7C'' representation +e need to set bit H and E to a one% 'n other +ords +e need to 2
the 8C! +ith a constant value of he5 05"0% 'n assembler this is done li,e this*
ORI R16,0?60
'f +e have a register that is already set to he5 05"0 +e can use the 2 +ith this register to convert the 8C!*
OR R1,R!
8ac, from an A7C'' character to a 8C! is as easy% )he instruction
A&DI R16,0?0F
Avr-Asm-Tutorial 41 http://www.avr-asm-tutorial.net
isolates the lo+er four bits @G the lo+er nibbleA% 6ote that 2' and A6!' are only possible +ith registers above 21E% 'f you
need to do this# use one of the registers 216 to 2"1?
'f the he5 value 050F is already in register 22# you can A6! the A7C'' character +ith this register*
A&D R1,R!
)he other instructions for manipulating bits in a register are also limited for registers above 21E% )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 @+hich is not possible for use +ith a
constantA*
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 ne/s complement*
"OM R1
inverts the content in register 21 and replaces 4eros by one and vice versa% !ifferent from that is the )+o/s complement#
+hich converts a positive signed number to its negative complement @subtracting from 4eroA% )his is done +ith the
instruction
&E0 R1
7o K1 @decimal* 1A yields 31 @binary 1%1111111A# K2 yields 32 @binary 1%1111110A# and so on%
8esides the manipulation of the bits in a register# copying a single bit is possible using the so3called )3bit of the status
register% &ith
3*> R1,0
the )3bit is loaded +ith a copy of bit 0 in register 21% )he )3bit 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 !
9." 0hift and rotate
7hifting and rotating of binary numbers means multiplying and dividing them by 2% 7hifting has several sub3instructions%
0ultiplication +ith 2 is easily done by shifting all bits of a byte one binary digit left and +riting a 4ero to the least
significant bit% )his is called logical shift left or :7:% )he former bit F 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# :72%
L*R R1
)he former bit F# 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 @if set# add one to the resultA% -5ample# division by four +ith
rounding*
L*R R1 ' diCision )y !
3R"" DiC! ' O:<E if no ro:nd :E
I&" R1 ' ro:nd :E
DiC!@
L*R R1 ' On,e %g%in diCision )y !
3R"" DiCE ' O:<E if no ro:nd :E
I&" R1 ' Ro:nd $E
DiCE@
7o# 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 sign3bit in bit F% )he instruction Barithmetic shift
rightC A72 leaves bit F untouched and shifts the F lo+er bits# inserting a 4ero into bit location 6%
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 163bit +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 4ero# 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% !uring rotation the carry bit in the
status register is shifted to bit 0# the former bit F is shifted to the carry during rotation%
Avr-Asm-Tutorial 42 http://www.avr-asm-tutorial.net
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 F to carry# the 2: instruction rolls it to bit 0 of the upper byte%
Follo+ing the second instruction the carry bit has the former bit F of the upper byte% )he carry bit can be used to either
indicate an overflo+ @if 163bit3calculation is performedA or to roll it into more upper bytes @if more than 16 bit calculation is
doneA%
2olling to the right is also possible# dividing by 2 and shifting carry to bit F of the result*
L*R R! ' Logi,%- *hift Right, )it 0 to ,%rry
ROR R1 ' ROt%te Right %nd shift ,%rry in )it 8
't/s easy dividing +ith big numbers% .ou 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 8C!s% )his instruction shifts a +hole
nibble from the upper to the lo+er position and vice versa% 'n our e5ample +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 e5changes the upper and lo+er nibble% 6ote that the content of the upper nibble +ill be different after
applying these t+o methods%
9.% *ddin'< s$btractin' and comparin'
)he follo+ing calculation operations are too complicated for the beginners and demonstrate that assembler is only for
e5treme e5perts# hi% 2ead on your o+n ris,?
*(.( Adding and subtracting 2-bit numbers
)o start complicated +e add t+o 163bit3numbers in 21*22 and 2"*2H% @'n this notation# +e mean that the first register is
the most significant byte# the second the least significantA%
ADD R!,R7 ' first %dd the t;o -o;()ytes
AD" R1,R6 ' then the t;o high()ytes
'nstead of a second A!! +e use A!C 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 2"*2H from 21*22%
*$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 1 from the result if the result of the first
instruction had an overflo+% 7till breathing( 'f yes# handle the follo+ing?
*(.(# Comparing 2-bit numbers
6o+ +e compare a 163bit3+ord in 21*22 +ith the one in 2"*2H to evaluate +hether it is bigger than the second one%
'nstead of 7=8 +e use the compare instruction C<# instead of 78C +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+# 21*22 is smaller than 2"*2H%
*(.($ Comparing &ith constants
6o+ +e add some more complicated stuff% &e compare the content of 216 +ith a constant* 0b10101010%
"PI R16,0?AA
'f the Sero3bit in the status register is set after that# +e ,no+ that 216 is e$ual to 05AA% 'f the carry3bit is set# +e ,no+# it is
smaller% 'f Carry is not set and the Sero3bit is not set either# +e ,no+ it is larger%
And no+ the most complicated test% &e evaluate +hether 21 is 4ero or negative*
>*> R1
'f the S3bit is set# the register 21 is 4ero and +e can follo+ +ith the instructions 82-P# 826-# 820'# 82<:# 82:# 827;#
82J-# 82:)# 821C or 8217 to branch around a little bit%
Avr-Asm-Tutorial 43 http://www.avr-asm-tutorial.net
*(.(. 'ac@ed BC1 math
7till +ith us( 'f yes# here is some pac,ed 8C! calculations% Adding t+o pac,ed 8C!s 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 1E decimal% Another overflo+#
from the lo+er to the upper nibble occurs# if the t+o lo+er nibbles add to more than 1E decimal%
)o ta,e an e5ample +e add the pac,ed 8C!s H9 @Ghe5 H9A and 99 @Ghe5 99A to yield 1H8 @Ghe5 0501H8A% Adding these in
binary math# results in a byte holding he5 05-2# no byte overflo+ occurs% )he lo+er of the t+o nibbles should have an
overflo+# because 9K9G18 @more than 9A and the lo+er nibble can only handle numbers up to 1E% )he overflo+ +as added
to bit H# the lo+est significant bit of the upper nibble% &hich is correct? 8ut the lo+er nibble should be 8 and is only 2 @18 G
0b0001%0010A% &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 05- and should be " @+ith a 1 overflo+ing to the ne5t upper digit of the
pac,ed 8C!A% 'f +e add 6 to this 05- +e get to 05H and the carry is set @G051HA% 7o the tric, is to first add these t+o
numbers and then add 0566 to correct the 2 digits of the pac,ed 8C!% 8ut halt* +hat if adding the first and the second
number +ould not result in an overflo+ to the ne5t nibble( And not result in a digit above 9 in the lo+er nibble( Adding
0566 +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 0C= sets the ;3bit in the status
register# the half3carry bit% )he follo+ing sho+s the algorithm for the different cases that are possible after adding t+o
nibbles and adding he5 056 after that%
1% Add the nibbles% 'f overflo+ occurs @C for the upper nibbles# or ; for the lo+er nibblesA# add 6 to correct# if not# do step
2%
2% Add 6 to the nibble% 'f overflo+ occurs @C resp% ;A# you/re done% 'f not# subtract 6%
)o program an e5ample +e assume that the t+o pac,ed 8C!s are in 22 and 2"# 21 +ill hold the overflo+# and 216 and 21F
are available for calculations% 216 is the adding register for adding 0566 @the register 22 cannot add a constant valueA# 21F
is used to correct the result depending from the different flags% Adding 22 and 2" 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 ' P:<E if no )yte oCerf-o; o,,:rs
I&" R1 ' in,re<ent the ne?t higher )yte
A&DI R18,0?0F ' donRt s:)tr%,t 6 fro< the higher ni))-e
&o"y1@
3R/" &o/,1 ' P:<E if no h%-f(,%rry o,,:rred
A&DI R18,0?F0 ' donRt s:)tr%,t 6 fro< -o;er ni))-e
&o/,1@
ADD R!,R16 ' %dd 0?66 to res:-t
3R"" &o"y! ' P:<E if no ,%rry o,,:rred
I&" R1 ' in,re<ent the ne?t higher )yte
A&DI R18,0?0F ' donRt s:)tr%,t 6 fro< higher ni))-e
&o"y!@
3R/" &o/,! ' P:<E if no h%-f(,%rry o,,:rred
A&DI R18,0?F0 ' donRt 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
&o/,@
*$3 R!,R16
Puestion to thin, about* &hy is that e$ually correct# half as long and less complicated and +here is the tric,(
9.) 4ormat con(ersion for n$mbers
All number formats can be converted to any other format% )he conversion from 8C! to A7C'' and vice versa +as already
sho+n above @8it manipulationsA%
*(0( ConBersion of pac@ed BC1s to BC1s3 A,CII or Binaries
Conversion of pac,ed 8C!s is not very complicated either% First +e have to copy the number to another register% &ith the
copied value +e change nibbles using the 7&A< instruction to e5change the upper and the lo+er one% )he upper part is
cleared# e% g% by A6!ing +ith 050F% 6o+ +e have the 8C! of the upper nibble and +e can either use as is @8C!A or set bit H
and E to convert it to an A7C'' character% After that +e copy the byte again and treat the lo+er nibble +ithout first
Avr-Asm-Tutorial 44 http://www.avr-asm-tutorial.net
7&A<ping and get the lo+er 8C!%
A little bit more complicated is the conversion of 8C! digits to a binary% !epending 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 8C! digit% 8efore
adding this to the result +e multiply the result +ith 10% @6ote that in the first step this is not necessary# because the result
is 4ero eitherA%
'n order to do the multiplication by 10# +e copy the result to some+here else% )hen +e multiply the result by four @t+o left
shifts resp% rollsA% Adding the previously copied number to this yields a multiplication +ith E% 6o+ a multiplication +ith 2
@left shiftLrollA yields the 103fold of the result% Finally +e add the 8C! and repeat that algorithm until all decimal digits are
converted% 'f# during one of these operations# there occurs a carry of the result# the 8C! is too large to be converted% )his
algorithm handles numbers of any length# as long as the result registers are prepared%
*(0(# ConBersion of Binaries to BC1
)he conversion of a binary to 8C!s is more complicated than that% 'f +e convert a 163bit3binary +e can subtract 10#000
@052F10A# until an overflo+ occurs# yielding the first digit% )hen +e repeat that +ith 1#000 @050"-8A to yield the second
digit% And so on +ith 100 @05006HA and 10 @05000AA# then the remainder is the last digit% )he constants 10#000# 1#000# 100
and 10 can be placed to the program memory storage in a +ord +ise organi4ed table# li,e this*
DeD>%)@
.D4 10000, 1000, 100, 10
and can be read +ord3+ise +ith the :<0 instruction from the table%
An alternative is a table that holds the decimal value of each bit in the 163bit3binary# 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 :<0% )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 000001# by adding this 8C! +ith itself# each time after you
have shifted a bit from the binary to the right# and added to the 8C! result%
0any methods# much to optimi4e here%
9.+ 6$ltiplication
0ultiplication of binary numbers is e5plained here%
*(2( 1ecimal multiplication
'n order to multiply t+o 83bit3binaries +e remind ourselves# ho+ this is done +ith decimal numbers*
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 10 and then +ith the ne5t higher digit of the second number and add this
to the result%
&e multiply the first number +ith 100# then +ith the third3highest digit# and add this to the result%
*(2(# Binary multiplication
6o+ in binary% 0ultiplication +ith the single digits is not necessary# because there are only the digits 1 @add the numberA
and 0 @don/t add the numberA% 0ultiplication by 10 in decimal goes to multiplication by 2 in binary mode% 0ultiplication 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% .ou see that binary math is very much easier than decimal% &hy didn/t man,ind use this from the
beginning(
Avr-Asm-Tutorial 45 http://www.avr-asm-tutorial.net
*(2($ AVR assembler program
)he follo+ing source code demonstrates reali4ation 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
'
rP<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%@
'
' *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) ' P:<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,L if there %re sti-- oneRs in )in%ry !, if yes, go on <:-tiE-i,%ting
'
tst r<! ' %-- )its DeroS
)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@
rP<E -ooE
Avr-Asm-Tutorial 46 http://www.avr-asm-tutorial.net
*(2(. Binary rotation
For understanding the multiplication operation# it is
necessary to understand the binary rotation
instructions 2: and 22% )hese instructions shift all
bits of a register one position left @2:A resp% right
@22A% )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 05AA as an
e5ample for 2: and 05EE as an e5ample for 22%
*(2(0 Multiplication in the studio
)he follo+ing screen shots sho+ the multiplication program in the simulator @to ma,e a difference* here 7tudio version "A%
)he ob>ect3code has been opened#
the cursor is placed on the first
e5ecutable instruction% F11 does
single steps%

)he registers 20 and 22 are set to
05AA and 05EE# our test binaries# to
be multiplied%

Avr-Asm-Tutorial 47 http://www.avr-asm-tutorial.net
22 is rotated to the
right# to roll the least
significant bit into the
carry bit% 05EE
@0101%0101A yielded
052A @0010%1010A%

8ecause the carry bit
had a one# the content
of the registers 21*20 is
added to the @emptyA
register pair 2H*2"#
resulting in 0500AA
there%

6o+ the register pair
21*20 is rotated one
position left to multiply
this binary by 2% From
0500AA# multiplication
by 2 yields 0501EH%
)he +hole multipli]
cation loop is repeated
as long there is at least
one binary 1 in register
22% )hese follo+ing
loops are not sho+n
here%

Avr-Asm-Tutorial 48 http://www.avr-asm-tutorial.net
=sing ,ey FE of the
studio +e multi3
stepped over these
loops to a brea,point
at the end of the
multiplication routine%
)he result register
pair 2H*2" has the
result of the
multiplication of 05AA
by 05EE* 05"8F2%

)his +asn/t that complicated# >ust remind yourself on the similar decimal operations% 8inary multiplication is much easier
than decimal%
9., Hardware m$ltiplication
All A)mega# A)Omega# A)90CA6 and A)90<&0 have an on3board hard+are multiplicator# that performs 8 by 8 bit
multiplications in only t+o cloc, cycles% 7o +henever you have to do multiplications and you are sure that this soft+are
never ever needs not to run on an A)9073 or A)tiny3chip# you can ma,e use of this hard+are feature%
)he follo+ing sho+s ho+ to multiply
83by383binaries#
163by383binaries#
163by3163binaries#
163by32H3binaries%
*(5( %ard&are multiplication of 9-by-9-bit binaries
)he use is simple and straight3for+ard* if the t+o binaries to be multiplied are in the registers 216 and 21F# >ust type
<:- R16,R18
As the result of these t+o 83bit binaries
might be up t+o 16 bits long# the result
+ill be in the registers 21 @most
significant byteA and 20 @least significant
byteA% )hat/s all about it%
)he program demonstrates the simulation in the 7tudio% 't multiplies decimal 2E0 @he5 FAA by decimal 100 @he5 6HA# in the
registers 216 and 21F%
Avr-Asm-Tutorial 49 http://www.avr-asm-tutorial.net
After e5ecution# the registers
20 @:78A and 21 @078A hold
the result he5 61A8 or
decimal 2E#000%
And* yes# that re$uires only
t+o cycles# or 2 microseconds
+ith a 1 0csLs cloc,%
*(5(# %ard&are multiplication of a 2- by an 9-bit-binary
.ou 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 16 and 8 first% =nderstanding this concept helps
understanding the method# so you +ill be able to solve the "23by36H3bit multiplication problem later%
First the math* a 163bit3binary m10*m1: are simply t+o 83bit3binaries m10 and m1:# +here the most significant one m10
of these t+o is multiplied by decimal 2E6 or he5 100% @For those +ho need a reminder* the decimal 12"H is simply @12
multiplied by 100A plus "H# or @1 multiplied by 1000A plus @2 multiplied by 100A plus @" multiplied by 10A plus H%
7o the 163bit3binary m1 is e$ual to 2E6Dm10 plus
m1:# +here m10 is the 078 and m1: is the :78%
0ultiplying m1 by 83bit3binary m2 so is#
mathematically formulated*
m1 D m2 G @2E6Dm10 K m1:A D m2# or
2E6Dm10Dm2 K m1:Dm2%
7o +e >ust need to do t+o multiplications and to add both results% 7orry# if you see three asteris,s in the formula* the
multiplication +ith 2E6 in the binary +orld doesn/t re$uire any hard+are at all# because it is a simple move to the ne5t
higher byte% Just li,e the multiplication by 10 in the decimal +orld is simply moving the number one left and +rite a 4ero
to the least significant digit%
7o let/s go to a practical e5ample% First +e need some registers to
load the numbers m1 and m2#
provide space for the result# +hich might have 2H bits length%
'
' >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
First +e load the numbers*
'
' Lo%d Registers
'
.eM: <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 21F*216 @dec 10000 G he5 2F10A
and 218 @dec 2E0 G he5 FAA%
)hen +e multiply the :78 first*
Avr-Asm-Tutorial 50 http://www.avr-asm-tutorial.net
'
' M:-tiE-y
'
<:- <1L,<! ' M:-tiE-y L*3
<oC Res1,R0 ' ,oEy res:-t to res:-t register
<oC Res!,R1
)he :78 multiplication of he5 2F by he5 FA yields he5 0F0A# +ritten to
the registers 200 @:78# he5 A0A and 201 @078# he5 0FA% )he result is
copied to the lo+er t+o bytes of the result register# 2"*22%
6o+ the multiplication of the 078 of m1 +ith m2 follo+s*
<:- <1M,<! ' M:-tiE-y M*3
)he multiplication of the 078 of m1# he5 10# +ith m2# he5 FA# yields
he5 2616 in 21*20%
6o+ t+o steps are performed at once* multiplication by 2E6 and
adding the result to the previous result% )his is done by adding 21*20 to
2es"*2es2 instead of 2es2*2es1% 21 can >ust be copied to 2es"% 20 is
added to 2es2 then% 'f the carry is set after adding# the ne5t higher byte
2es" 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, P:<E
in, Res6
&oIn,@
)he result in 2H*2"*22 is he5 262EA0# +hich is decimal 2E00000 @as
everybody ,no+sA# and is obviously correct%
)he cycle counter of the multiplication points to 10# at 1 0;4 cloc, a
total of 10 microseconds% 1ery much faster than soft+are
multiplication?
*(5($ %ard&are multiplication of a 2- by a 2-bit-binary
6o+ that +e have understood the principle# it should be easy to do 163by316% )he result re$uires four bytes no+
@2esH*2es"*2es2*2es1# located in 2E*2H*2"*22A% )he formula is*
Avr-Asm-Tutorial 51 http://www.avr-asm-tutorial.net
m1 D m2 G @2E6Dm10 K m1:A D
@2E6Dm20 K m2:A
G 6EE"6Dm10Dm20 K
2E6Dm10Dm2: K
2E6Dm1:Dm20 K
m1:Dm2:
bviously 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
'
.eM: <1 = 10000
.eM: <! = !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
<:- <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
'
7imulation sho+s the follo+ing steps%
:oading the t+o constants 10000 @he5 2F10A and 2E000 @he5 61A8A to
the registers in the upper register space %%%
0ultiplying the t+o 078s @he5 2F and 61A and copying the result in 21*20 to the t+o most upper result registers 2E*2H %%%
Avr-Asm-Tutorial 52 http://www.avr-asm-tutorial.net
0ultiplying the t+o :78s @he5 10 and A8A and copying the result in
21*20 to the t+o lo+er result registers 2"*22 %%%
0ultiplying the 078 of m1 +ith the :78 of m2 and adding the result in
21*20 to the result register/s t+o middle bytes# no carry occurred %%%
0ultiplying the :78 of m1 +ith the 078 of m2 and adding the result in
21*20 to the result register/s t+o middle bytes# no carry occurred% )he
result is he5 0--68280# +hich is 2E0000000 and obviously correct %%%
0ultiplication
needed 19 cloc,
cycles# +hich is very much faster than +ith soft+are multiplication%
Another advantage here* the re$uired time is A:&A.7 e5actly 19
cycles# and it doesn/t depend on the input numbers @li,e is the case
+ith soft+are multiplication and on overflo+ occurrences @than,s to
our small tric, of adding 4ero +ith carryA% 7o you can rely on this %%%
*(5(. %ard&are multiplication of a 2- by a #.-bit-binary
)he multiplication of a 16 bit binary
IaI +ith a 2H bit binary IbI leads to
results +ith up to H0 bit length% )he
multiplication scheme re$uires si5 83
by383bit 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
Avr-Asm-Tutorial 53 http://www.avr-asm-tutorial.net
.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
.eM: % = 10000 ' <:-tiE-i,%tor %, he? !810
.eM: ) = 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
%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 e5ecution re$uires
10 cloc, cycles for loading the constants#
6 cloc, cycles for clearing registers# and
"" cloc, cycles for multiplication%
9.- &i(ision
6o# unfortunately there is no hard+are division% .ou need to do this in soft+are?
*(9( 1ecimal diBision
Again +e start +ith the decimal division# to better understand the binary division% &e assume a division of E6F8 by 12%
)his is done li,e this*
Avr-Asm-Tutorial 54 http://www.avr-asm-tutorial.net
5678 : 12 = ?
--------------------------
- 4 * 1200 = 4800
----
878
- 7 * 120 = 840
---
38
- 3 * 12 = 36
--
2
Result: 5678 : 12 = 473 Remainder 2
===================================
*(9(# Binary diBision
'n binary the multiplication of the second number in the above decimal e5ample @H D 1200# etc%A is not necessary# due to
the fact that +e have only 0 and 1 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% 7o the program +or,s a
bit different than that%
)he division of a 163bit binary number by a 83bit binary in A12 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,= ' %dP:st the ,orre,t E%th to yo:r syste<T
.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
rP<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%@
,-, ' ,-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 0S
)r,s diC9, ' P:<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
rP<E diC9d ' P:<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@
rP<E stoE ' end-ess -ooE
*(9($ 'rogram steps during diBision
!uring e5ecution of the program the follo+ing steps are ran*
!efinition and preset of the registers +ith the test binaries#
presetting the interim register and the result register pair @the result registers are presetted to 050001? After
16 rotations the rolling out of the one stops further division steps%A#
Avr-Asm-Tutorial 55 http://www.avr-asm-tutorial.net
the 163bit3binary in rd1h*rd1l is rotated bit+ise to the interim register rd1u @multiplication by 2A# if a 1 is
rotated out of rd1u# the program branches to the subtraction step in step H immediately#
the content of the interim register is compared +ith the 83bit binary in rd2# if rd2 is smaller it is subtracted
from the interim register and the carry3bit is set to one# if rd2 is greater the subtraction is s,ipped and a 4ero
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 4ero rotated out of the result register# +e have to repeat the division loop# if it +as a one the division is
completed%
'f you don/t understand rotation yet you/ll find this operation discussed in the multiplication section%
*(9(. 1iBision in the simulator
)he follo+ing screen shots demonstrate the
program steps in the studio @here in version "# so it
loo,s differentA% )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
@yello+ arro+A is on the first e5ecutable
instruction% )he ,ey F11 performs single steps%

)he test binaries 05AAAA and
05EE# to be divided# have been
+ritten to the registers 21*20 and
2"%

)he interim register 22 and the
result register pair are set to their
predefined values%
Avr-Asm-Tutorial 56 http://www.avr-asm-tutorial.net
21*20 +as rotated left to 22#
from 05AAAA the doubled value
of 0501EEEH +as yielded%
6o overflo+ from rotation into
carry has occurred and 0501 in
22 +as smaller than 05EE in 2"#
so subtraction +as s,ipped% A
4ero in the carry is rotated into
the result register 2E*2H% )he
former content of the result
register# a single 13bit in position
0 has rotated to position 1
@content no+* 050002A% As a 4ero
+as rotated out of the result
register pair# the ne5t step to be
e5ecuted is a branch to the
beginning of the division loop
start and the loop is
repeated%
After e5ecuting the loop 16
times +e have reached the
brea,point set at the end of
the division routine% )he
result register in 2E*2H holds
050202# the result of the
division% )he registers
22*21*20 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%

)he +hole division needs 60 micro3seconds
processor time @open a processor vie+ in the
studio menuA% A rather long time for a division%


9.9 :$mber con(ersion
6umber conversion routines are not included here% <lease refer to the +ebsite at
http*LL+++%avr3asm3tutorial%netLavrTen
if you need the source code or a better understanding%
Avr-Asm-Tutorial 57 http://www.avr-asm-tutorial.net
9.1= &ecimal 4ractions
First* !o not use any floating points# unless you really need them% Floating points are resource ,illers in an A12# lame duc,s
and need e5treme e5ecution times% 2un into this dilemma# if you thin, assembler is too complicated# and you prefer 8asic
or other languages li,e C or <ascal%
6ot so# if you use assembler% .ou/ll be sho+n here# ho+ you can perform the multiplication of a fi5ed point real number in
less than 60 micro3seconds# in special cases even +ithin 18 micro3seconds# at H 0;4 cloc, fre$uency% &ithout any floating
point processor e5tensions and other e5pensive tric,s for people too la4y to use their brain%
;o+ to do that( 8ac, to the roots of math? 0ost 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% 6o one reali4es# that this is a tric,%
*(+( Linear conBersions
As an e5ample the follo+ing tas,* an 838it3A!3Converter measures an input signal in the range from 0%00 to 2%EE 1olt# and
returns as the result a binary in the range from Z00 and ZFF% )he result# a voltage# is to be displayed on a :C! display% 7illy
e5ample# as it is so easy* )he binary is converted to a decimal A7C'' string bet+een 000 and 2EE# and >ust behind the first
digit the decimal point has to be inserted% !one?
)he electronics +orld sometimes is more complicated% -% g%# the A!3Converter returns an 838it3;e5 for input voltages
bet+een 0%00 and E%00 1olt% 6o+ +e/re tric,ed and do not ,no+ ho+ to proceed% )o display the correct result on the :C!
+e +ould have to multiply the binary by E00L2EE# +hich is 1%9608% )his is a silly number# as it is almost 2# but only almost%
And +e don/t +ant that ,ind of inaccuracy of 29# +hile +e have an A!3converter +ith around 0%2E9 accuracy%
)o cope +ith this# +e multiply the input by E00L2EED2E6 or E01%96 and divide the result by 2E6% &hy first multiply by 2E6
and then divide by 2E6( 't/s >ust for enhanced accuracy% 'f +e multiply the input by E02 instead of E01%96# the error is >ust
in the order of 0%0089% )hat is good enough for our A!3converter# +e can live +ith that% And dividing by 2E6 is an easy
tas,# because it is a +ell3,no+n po+er of 2% 8y dividing +ith numbers that are a po+er of 2# the A12 feels very
comfortable and performs very fast% 8y dividing +ith 2E6# the A12 is even faster# because +e >ust have to s,ip the last byte
of the binary number% 6ot even shift and rotate?
)he multiplication of an 83bit3binary +ith the 93bit3binary E02 @he5 1F6A can have a result larger than 16 bits% 7o +e have to
reserve 2H bits or " registers for the result% !uring multiplication# the constant E02 has to be shifted left @multiplication by
2A 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% 7o +e chose the follo+ing combination of registers for the
multiplication*
Num(er Value .example/ Register
'nput value 2EE 21
0ultiplicand E02 2H * 2" * 22
2esult 128#010 2F * 26 * 2E
After filling the value E02 @00%01%F6A to 2H * 2" * 22 and clearing the result registers 2F * 26 * 2E# the multiplication goes li,e
this*
1% )est# if the input number is already 4ero% 'f yes# +e/re done%
2% 'f no# one bit of the input number is shifted out of the register to the right# into the carry# +hile a 4ero is
stuffed into bit F% )his instruction is named :ogical37hift32ight or :72%
"% 'f the bit in carry is a one# +e add the multiplicand @during step 1 the value E02# in step 2 it/s 100H# a% s% o%A to
the result% !uring adding# +e care for any carry @adding 22 to 2E by A!!# adding 2" to 26 and 2H to 2F +ith
the A!C instruction?A% 'f the bit in the carry +as a 4ero# +e >ust don/t add the multiplicand to the result and
>ump to the ne5t step%
H% 6o+ the multiplicand is multiplied by 2# because the ne5t bit shifted out of the input number is +orth double
as much% 7o +e shift 22 to the left @by inserting a 4ero in bit 0A using :7:% 8it F is shifted to the carry% )hen +e
rotate this carry into 2"# rotating its content left one bit# and bit F to the carry% )he same +ith 2H%
E% 6o+ +e/re done +ith one digit of the input number# and +e proceed +ith step 1 again%

)he result of the multiplication by E02 no+ is in the result registers 2F * 26 * 2E% 'f +e >ust ignore register 2E @division by
2E6A# +e have our desired result% )o enhance accuracy# +e can use bit F in 2E to round the result% 6o+ +e >ust have to
convert the result from its binary form to decimal A7C'' @see Conversion bin to decimal3A7C'' on the +ebsiteA% 'f +e >ust
add a decimal point in the right place in the A7C'' string# our voltage string is ready for the display%
)he +hole program# from the input number to the resulting A7C'' string# re$uires bet+een F9 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 @and program flash and memory usageA%
Avr-Asm-Tutorial 58 http://www.avr-asm-tutorial.net
*(+(# E)ample E 9-bit-A1-conBerter &ith fi)ed decimal output
' De<onstr%tes f-o%ting Eoint ,onCersion in Asse<)-er, 1"2!006 ;;;.%Cr(%s<(t:tori%-.net
'
' >he t%sL@ .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 steET
' !. 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 reM:ired is % <:-tiE:rEose register ,%--ed r<E,
' -o,%ted in the :EEer h%-f of the registers. P-e%se t%Le ,%re th%t these registers donRt ,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 P: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%,L.>he st%,L <:st ;orL fine for the :se of three -eCe-s 1si? )ytes *RAM2.
' "onCersion ti<es@
' >he ;ho-e ro:tine reM:ires !!9 ,-o,L ,y,-es <%?i<:< 1,onCerting NFF2, %nd 89 ,-o,L ,y,-es <ini<:< 1,onCerting N002.
' 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 reM:ired for st%,L setting, ro:tines ;orL fine ;ith other A>90*(tyEes %-so
.&OLI*>
.I&"L$DE =9515def.in,=
.LI*>
' *t%rt of test Erogr%<
' O:st ;rites % n:<)er to R1 %nd st%rts the ,onCersion ro:tine, for test E:rEoses on-y
."*E0
.OR0 N0000
rP<E <%in
<%in@
-di r<E,/I0/1RAME&D2 ' *et the st%,L
o:t *P/,r<E
-di r<E,LO41RAME&D2
o:t *PL,r<E
-di r<E,NFF ' "onCert NFF
<oC R1,r<E
r,%-- fE,onC9 ' ,%-- the ,onCersion ro:tine
noJend@ ' :n-i<ited -ooE, ;hen done
rP<E noJend
' "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,R.R ' 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,N01
<oC R6,r<E
-di r<E,NF6
<oC R!,r<E
,-r R8 ' ,-e%r the res:-t
,-r R6
,-r R5
fE,onC9<1@
or R1,R1 ' ,he,L if the n:<)er is %-- Deros
)rne fE,onC9<! ' sti-- oneRs, go on ,onCert
ret ' re%dy, ret:rn )%,L
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 sLiE %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
rP<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
Avr-Asm-Tutorial 59 http://www.avr-asm-tutorial.net
-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,R0R ' ,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,R0R ' 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
rP<E fE,onC9d1 ' on,e %g%in
' End of ,onCersion test ro:tine

*(+($ E)ample #E +-bit-A1-conBerter &ith fi)ed decimal output
)his e5ample is a bit more complicated% 2efer to the +ebsite if you need it%
Avr-Asm-Tutorial 60 http://www.avr-asm-tutorial.net
+ 'roFect planning
1=.1 How to plan an *12 pro>ect in assembler
;ere are the basics on ho+ to plan a simple pro>ect# to be programmed in assembler% 8ecause the hard+are components
determine a lot# the hard+are considerations are discussed first% )hen a chapter on interrupt follo+s and after that timing
issues are discussed%
1=.2 Hardware considerations
)he decision# +hich type of A12 fits best to your needs# a number of considerations can play a role% ;ere are the most
relevant ones*
1% &hich port connections +ith a fi5ed location are needed( Fi5ed locations are 'L ports of internal components
that are only available on certain pins# and cannot be moved to another portpin% Components and connections of
this ,ind are*
1% 'f the processor should be programmable +ithin the circuit @'7< interfaceA# the pins 7CN# 07' and 0'7
have to be assigned for this purpose% 'f your peripheral allo+s that those can be used as inputs @e% g% 7CN
and 07'A or as outputs @by decoupling them via resistors or multiple5ersA%
2% 'f a serial interface is needed# 2O! and )O! have to be reserved for that purpose% 'f the 2)7LC)7
hard+are handsha,e protocol shall be implemented as +ell# t+o additional portpins are re$uired# but
can be placed at any other free location%
"% 'f an analog comparator is needed# A'60 and A'61 have to be reserved for that%
H% 'f e5ternal signals are to be monitored for level changes# '6)0 andLor '6)1 have to be reserved for that%
E% 'f A! converters are+ to be used# the A!C inputs have to be placed and reserved for that purpose% 'f the
converter has the e5ternal A1CC and A2-F connections# those should be used and +ired accordingly%
6% 'f e5ternal pulses are to be counted# the timer input pins )0# )1 and )2 are fi5ed and e5clusive for that
use%
F% 'f e5ternal 72A0 is to be attached# the respective address and data ports together +ith A:-# 2! and &2
have to be reserved%
8% 'f the processor cloc, should be generated from an e5ternal crystal oscillator# O)A:1 has to be reserved% 'f
an e5ternal crystal or ceramic resonator shall control the cloc, fre$uency# O)A:1 and O)A:2 are fi5ed for
that purpose%
2% Are there any e5ternal components that re$uire more than one portpin @e% g% 2# H or 8A to be +ritten or read(
)hese should be defined in an appropriate +ay @in the same port# in the right orderA%
1% 'f controlling of an e5ternal device re$uires +riting or reading of more than one bit at once# e% g% a four3
or eight3bit :C! interface# the necessary port bits should be in the right order% 'f it isn/t possible to place
the +hole interface in a single port# the interface can be divided into t+o pieces% )he soft+are is easier# if
the resulting portions are left3 or right3ad>usted in the port%
2% 'f t+o or more A!C channels are re$uired# the soft+are is easier# if those are placed in an order @e% g%
A!C2KA!C"KA!CHA%
"% At the end# all e5ternal components are placed that do not re$uire fi5ed pins%
1% 'f only a single pin causes you to select a larger device# you can consider using the 2-7-) pin for that
purpose% )his can be used as an input pin if a certain fuse is set% 7etting of that fuse disables further '7<
programming# the chip can only be programmed in high3voltage programming modes% For final
productions +ith a large number of identical devices# this is acceptable# but not for prototyping% 'n case
of prototyping a high3voltage programmer interface on the '7< pin can be used# if the component on the
2-7-) pin is protected against the 12 1 on this pin during '7< programming# e% g% +ith a resistor and a
4ener diode%
Further considerations for the decision# +hich processor type fits best# are*
;o+ many timers are needed and +hich resolution should these provide(
&hich valuesLinformations should be preserved +hen the operating voltage is shut do+n( @--<20 capacityA
;o+ much storage space is re$uired( @72A0 capacityA
7pace re$uirements on your <C8# ho+ much space for the processor fits best# +hich pac,age types are available(
perating voltages and po+er re$uirements% 'f the operating voltage comes from a battery or an accumulator#
the po+er characteristics play an important role%
<rice for the device( nly relevant for production in larger series% 6ot at all depending from the processor/s
internals# and a matter of unpredictable mar,et conditions%
Availability( 'f one starts a pro>ect +ith the A)9071200# probably from a rummage table# can ma,e it cheap% 7uch
a decision is not very sustainable% <orting such a pro>ect to a tiny3 or mega3device mostly ends up in a complete
redesign of the soft+are# that also loo,s and feels much better# +or,s better and re$uires only a fraction of code
lines%
1=." Considerations on interr$pt operation
1ery simple tas,s +or, fine +ithout interrupts% 'f po+er consumption is an issue# this ain/t true either% 6early all pro>ects
re$uire interrupts% And this should be planned thoroughly%
Avr-Asm-Tutorial 61 http://www.avr-asm-tutorial.net
+($( Basic re>uirements of interrupt-driBen operation
'f not a+are any more# here are the basics%
-nabling interrupts*
'nterrupts re$uire the stac, hard+are% 7o set 7<: @and in larger devices 7<;A at the beginning to
2A0-6!# and reserve the upper part of the 72A0 for that purpose @e% g% the last 8 to 5 bytesA%
-ach internal component and each condition that should be able to trigger an interrupt has to be
enabled to do that# by setting the respective interrupt enable flag bit% 7+itching those bits on and off is a
ris,y thing# so better design your soft+are +ithout s+itching%
)he ' flag in the status register 72-J has to be set at the begin and remains set during operation% 'f it is
necessary to clear the ' flag during an operation outside an interrupt service routine# add the set3'3flag
instruction +ithin a fe+ instruction +ords%
'nterrupt vector table*
-ach internal component and each enabled interrupt condition corresponds to a specific interrupt
vector# placed in a certain address in the flash program storage% )he instruction at this address is a single3
+ord 2J0< instruction# in large A)mega processors a t+o3+ord J0< instruction# to the respective
interrupt service routine%
)he vector addresses are type3specific% &hen porting the soft+are to a different type# those re$uire
ad>ustment%
-ach vector address in the table# that is currently not used# is given a 2-)' instruction @in large A)mega
types a 2-)'# follo+ed by an 6<A% )hat prevents erroneous ghost interrupts to be running into false
code% )he use of the %2J directive for ad>usting vector addresses does not provide safety against those
events%
'f an interrupt condition occurs# the respective flag in the control register of the internal component is
set% )his is automatically cleared# if the interrupt is e5ecuted% 'n some rare cases @e% g% in case of a )O
buffer empty interrupt condition of an =A2)# if no further character is to be sentA# the interrupt enable
flag of the component has to be cleared first and the interrupt condition flag at last%
'f the interrupt condition gets true for more than one component at a time# the interrupt +ith a lo+er
address +ins the race%
'nterrupt service routines*
-ach service routine starts +ith saving the status register 72-J in a register e5clusively reserved for that
purpose# and ends +ith restoring that status register% 8ecause interrupts can occur every time# also in
times +hile the processor is performing instructions in the main program loop# any disturbance of that
status register can cause unpredictable malfunctions%
8efore >umping to the service routine# the processor pushes the current instruction counter to the stac,%
)he interrupt and the >ump to the respective service routine disables further interrupts by temporarily
clearing the ' flag in the status register 72-J% -ach service routine ends +ith the instruction 2-)'# that
pops the instruction pointer from the stac, and sets the ' flag on again%
8ecause the e5ecution of an interrupt service routine bloc,s any further interrupt re$uests from being
served# even those of a higher priority# each service routine has to be as short as possible and performs
only the time critical portions of the tas,% :engthy response operations have to be performed outside the
interrupt service routine%
8ecause interrupting an interrupt service routine does not happen# all interrupt service routines can use
the same temporary register%
'nterfacing interrupt service routine and main program loop*
)he communication bet+een the interrupt serve routine and the main program loop is performed via
single flags# that are set +ithin the service routine and cleared in the main program loop% )he clearing of
flags is either performed in single +ord instructions or interrupts are temporarily disabled during that
step to bloc, erroneous over+riting of other flags that +ere possibly changed in bet+een the three steps
read3modify3+rite%
1alues that the interrupt service routines provides are handed over in dedicated registers or in specific
72A0 locations% -ach change of those values# that are used later on outside the service routine# have to
be chec,ed for possible corruption# if another interrupt can occur in bet+een% 7ingle byte handling is
easy# but handing over t+o or more bytes re$uires a hand3over protocol @interrupt disable during hand3
over# flag setting to prevent over+rite# etc%A% As an e5ample# the handover of a 163bit timer value re$uires
disabling of interrupts first% ther+ise the first byte read does not necessarily correspond to the second
byte read# if another interrupt happened in bet+een%
0ain program loop*
&ithin the main program loop the processor is sent to sleep# +ith the sleep mode IidleI selected% -ach
interrupt +a,es up the processor# >umps to the respective interrupt service routine and# after its return
from interrupt# continues its operation in the main program loop% 't ma,es sense to chec, for any flags
that +ere set +ithin the service routine% 'f that is the case# the treatment of the flag can be performed%
After all things +ere finali4ed# another chec, for the flag settings can be made @in case of long routinesA
and the processor can be sent bac, to sleep%
+($(# E)ample for an interrupt-driBen assembler program
)he follo+ing provides an e5ample for an interrupt3driven assembler program# that utili4es all the above mentioned rules%

3e'ister (e)initions

Avr-Asm-Tutorial 62 http://www.avr-asm-tutorial.net
.BHA rsre' E 315 savin' the status (urin' interrupts
.BHA rmp E 316 Temporar, re'ister outsi(e interrupts
.BHA rimp E 317 Temporar, re'ister insi(e interrupts
.BHA r)l' E 318 Fla' re'ister )or #ommuni#ation
.BHA +int0 E 0 Fla' +it )or si'nalin' 2>T0-.ervi#e
.BHA +t#0 E 1 Fla' +it )or si'nalin' T"0-?ver)low
...
2.3-Ta+le

.".B-
.?3- I0000
r8mp main 3eset ve#tor% e<e#ute( at start-up
r8mp isrNint0 2>T0-ve#tor% e<e#ute( on level #han'es on the 2>T0 input line
reti unuse( interrupt
reti unuse( interrupt
r8mp isrNt#0N?ver)low T"0-?ver)low-ve#tor% e<e#ute( in #ase o) a T"0 over)low
reti unuse( interrupt
reti unuse( interrupt
... other int ve#tors

2nterrupt servi#e routines

isrNint0: 2>T0-.ervi#e 3outine


in rsre'%.3B- sa)e status
in rimp%&2>J rea( port J to temp re'ister
out &?3T"%rimp write temp re'ister to port "
... (o other thin's
s+r r)l'%1LL+int0 si'nalin' 2>T0 to outsi(e
out .3B-%rsre' restore status
reti return +a#$ an( ena+le interrupts
isrNt#0N?ver)low: T"0 ?ver)low .ervi#e 3outine
in rsre'%.3B- sa)e status
in rimp%&2>J rea( port J in temp re'ister
out &?3T"%rimp write temp re'ister to port "
... (o other thin's
s+r r)l'%1LL+t#0 set T"0-)la'
out .3B-%rsre' restore status
reti return +a#$ an( ena+le interrupts

Gain pro'ram start

main:
l(i rmp%/2-/:3AGB>0; set sta#$ re'ister
out .&/%rmp
l(i rmp%@?*:3AGB>0;
out .&@%rmp
... other thin's to (o
2>T Bna+le )or T"0 over)lows
l(i rmp%1LLT?2B0 ?ver)low 2nterrupt Bna+le Timer 0
out T2G.O%rmp set interrupt-mas$ o) the timer
l(i rmp%:1LL".00;M:1LL".02; pres#aler +, 1024
out T""30%rmp start timer
2>T Bna+le o) the 2>T0 input
l(i rmp%:1LL.B;M:1LL2."00; .@BB&-Bna+le an( 2>T0 int on all level #han'es
out G"A"3%rmp to the #ontrol re'ister
l(i rmp%1LL2>T0 ena+le 2>T0 interrupts
out -2"3%rmp to the interrupt #ontrol re'ister
set interrupt status )la'
sei set interrupt )la'

Gain pro'ram loop

loop:
sleep pro#essor to sleep
nop (umm, )or wa$e-up
s+r# r)l'%+int0 2>T0 )la' not set
r#all ma#heNint0 han(le 2>T0 event
s+r# r)l'%+t#0 T"0-?ver)low )la' not set
r#all ma#heNt#0 han(le T"0 over)low
r8mp loop 'o +a#$ to sleep

/an(le event results

ma#heNint0: han(le 2>T0 result


#+r r)l'%1LL+int0 #lear 2>T0 )la'
... (o other thin's
ret rea(,% +a#$ to loop
ma#heNt#0: han(le T"0 over)low
Avr-Asm-Tutorial 63 http://www.avr-asm-tutorial.net
#+r r)l'%1LL+t#0 #lear T"0 )la'
... (o other thin's
ret rea(,% +a#$ to loop
1=.% Considerations on timin'
'f an A12 pro>ect goes beyond polling an 'L port and# depending from that result# doing something# considerations on
timing are necessary% )iming
starts +ith the selection of the processor type#
continues +ith the $uestion# +hat has be e5ecuted periodically and +ith +hich precision#
and +hich timing control opportunities e5ist#
ho+ those things can be combined%
Selection of the clock frequency of the !rocessor
)he main $uestion is on the necessary precision of the processor cloc,%
's it unnecessary in the application to perform times less than a fe+ percent inaccurate# the internal 2C oscillator of most
of the A12 types is sufficient% 'n the tiny and mega types# a oscillator calibration is built in# so that differences bet+een the
nominal and the effective fre$uency are reduced% 6ote that the default internal calibration byte +as selected at a certain
operating voltage% 'f your operating voltage is fi5ed at a different level# re+riting the calibration byte brings more accuracy%
'f the operating voltage is fluctuating# the error can be too large%
'f the internal 2C cloc, is too slo+ or too large# some device types have a cloc, prescaler on board% )his feature allo+s to
optimi4e the cloc, fre$uency# and different cloc, fre$uencies can be selected% )his is either done once +ith changing a
hard+are fuse @the !'18 fuseA or +ithin the soft+are @e% g% to reduce the supply po+er during pausesA% 8ut be a+are that
some devices +ith a limited cloc, specification @1 typesA should not be set to beyond their limit# other+ise they +on/t +or,
correct any more%
'f the internal 2C oscillator is too inaccurate# fuses can be set for e5ternal 2C combination# an e5ternal oscillator# a crystal
@OtalA or a ceramic device% 8ecause false fuse setting can cause a catastophe# a rescue board +ith an e5ternal oscillator
might be the last chance to get the device +or,ing and the fuse resetted again%
)he absolute cloc, fre$uency should be appropriate for the application% As an indicator# the repeat fre$uency of the most
often performed +or, pac,age can be used% 'f a ,ey has to be polled any 2 ms# and# after 20 times# should be debounced
long enough# there is plenty of time# if a 1 0;4 cloc, is used @2#000 cloc, cycles bet+een any t+o polls# 20#000 cloc,s for
repeated e5ecution of the ,ey commandA%
't/s only getting narro+er# if a pulse +idth modulated signal +ith high resolution and a high <&0 fre$uency has to be
reached% &ith a <&0 fre$uency of 10 ,;4 and 8 bits resolution 2%E6 0;4 are too slo+ for a soft+are3driven solution% 'f a
timer +ith some soft+are3overhead can ta,e over that burden# that/s better%
Avr-Asm-Tutorial 64 http://www.avr-asm-tutorial.net
Anne)
11.1 #nstr$ctions sorted by f$nction
For the abbreviations used see the list of abbreviations%
0unction Su( function instruction 0lags Cl1
2egister
set
0 C:2 r1 S 6 1 1
2EE 7-2 rh 1
Constant :!' rh#c2EE 1
Copy
2egister GV 2egister 01 r1#r2 1
72A0 GV 2egister# direct :!7 r1#c6EE"E 2
72A0 GV 2egister :! r1#rp 2
72A0 GV 2egister and '6C :! r1#rpK 2
!-C# 72A0 GV 2egister :! r1#3rp 2
72A0# displaced GV 2egister :!! r1#ryK,6" 2
<ort GV 2egister '6 r1#p1 1
7tac, GV 2egister << r1 2
<rogram storage S GV 20 :<0 "
2egister GV 72A0# direct 7)7 c6EE"E#r1 2
2egister GV 72A0 7) rp#r1 2
2egister GV 72A0 and '6C 7) rpK#r1 2
!-C# 2egister GV 72A0 7) 3rp#r1 2
2egister GV 72A0# displaced 7)! ryK,6"#r1 2
2egister GV <ort =) p1#r1 1
2egister GV 7tac, <=7; r1 2
Add
8 8it# K1 '6C r1 S 6 1 1
8 8it A!! r1#r2 S C 6 1 ; 1
8 8it K Carry A!C r1#r2 S C 6 1 ; 1
16 8it# constant A!'& rd#,6" S C 6 1 7 2
7ubtract
8 8it# 31 !-C r1 S 6 1 1
8 8it 7=8 r1#r2 S C 6 1 ; 1
8 8it# constant 7=8' rh#c2EE S C 6 1 ; 1
8 8it 3 Carry 78C r1#r2 S C 6 1 ; 1
8 8it 3 Carry# constant 78C' rh#c2EE S C 6 1 ; 1
16 8it 78'& rd#,6" S C 6 1 7 2
7hift
logic# left :7: r1 S C 6 1 1
logic# right :72 r1 S C 6 1 1
2otate# left over Carry 2: r1 S C 6 1 1
2otate# right over Carry 22 r1 S C 6 1 1
Arithmetic# right A72 r1 S C 6 1 1
6ibble e5change 7&A< r1 1
8inary
And A6! r1#r2 S 6 1 1
And# constant A6!' rh#c2EE S 6 1 1
r 2 r1#r2 S 6 1 1
r# constant 2' rh#c2EE S 6 1 1
-5clusive3r -2 r1#r2 S 6 1 1
nes3complement C0 r1 S C 6 1 1
)+os3complement 6-J r1 S C 6 1 ; 1
Avr-Asm-Tutorial 65 http://www.avr-asm-tutorial.net
0unction Su( function instruction 0lags Cl1
8its
change
2egister# set 782 rh#c2EE S 6 1 1
2egister# clear C82 rh#2EE S 6 1 1
2egister# copy to )3Flag 87) r1#bF ) 1
2egister# copy from )3Flag 8:! r1#bF 1
<ort# set 78' pl#bF 2
<ort# clear C8' pl#bF 2
7tatus bit
set
Sero3Flag 7-S S 1
Carry Flag 7-C C 1
6egative Flag 7-6 6 1
)+os complement carry Flag 7-1 1 1
;alf carry Flag 7-; ; 1
7igned Flag 7-7 7 1
)ransfer Flag 7-) ) 1
'nterrupt -nable Flag 7-' ' 1
7tatus bit
clear
Sero3Flag C:S S 1
Carry Flag C:C C 1
6egative Flag C:6 6 1
)+os complement carry Flag C:1 1 1
;alf carry Flag C:; ; 1
7igned Flag C:7 7 1
)ransfer Flag C:) ) 1
'nterrupt -nable Flag C:' ' 1
Compare
2egister# 2egister C< r1#r2 S C 6 1 ; 1
2egister# 2egister K Carry C<C r1#r2 S C 6 1 ; 1
2egister# constant C<' rh#c2EE S C 6 1 ; 1
2egister# ^0 )7) r1 S 6 1 1
'mmediate
Jump
2elative 2J0< cH096 2
'ndirect# Address in S 'J0< 2
7ubroutine# relative 2CA:: cH096 "
7ubroutine# Address in S 'CA:: "
2eturn from 7ubroutine 2-) H
2eturn from 'nterrupt 2-)' ' H
Avr-Asm-Tutorial 66 http://www.avr-asm-tutorial.net
0unction Su( function instruction 0lags Cl1
Conditional
Jump
7tatus bit set 8287 bF#c12F 1L2
7tatus bit clear 828C bF#c12F 1L2
Jump if e$ual 82-P c12F 1L2
Jump if not e$ual 826- c12F 1L2
Jump if carry set 82C7 c12F 1L2
Jump if carry clear 82CC c12F 1L2
Jump if e$ual or greater 827; c12F 1L2
Jump if lo+er 82: c12F 1L2
Jump if negative 820' c12F 1L2
Jump if positive 82<: c12F 1L2
Jump if greater or e$ual @7ignedA 82J- c12F 1L2
Jump if lo+er than 4ero @7ignedA 82:) c12F 1L2
Jump on half carry set 82;7 c12F 1L2
Jump if half carry clear 82;C c12F 1L2
Jump if )3Flag set 82)7 c12F 1L2
Jump if )3Flag clear 82)C c12F 1L2
Jump if )+os complement carry set 8217 c12F 1L2
Jump if )+os complement carry clear 821C c12F 1L2
Jump if 'nterrupts enabled 82'- c12F 1L2
Jump if 'nterrupts disabled 82'! c12F 1L2
Conditioned
Jumps
2egister bitG0 782C r1#bF 1L2L"
2egister bitG1 7827 r1#bF 1L2L"
<ort bitG0 78'C pl#bF 1L2L"
<ort bitG1 78'7 pl#bF 1L2L"
Compare# >ump if e$ual C<7- r1#r2 1L2L"
thers
6o peration 6< 1
7leep 7:--< 1
&atchdog 2eset &!2 1
11.2 &irecti(es and #nstr$ction lists in alphabetic order
(#( Assembler directiBes in alphabetic order
Directive ... means ...
."*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-eRs ,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-Tutorial 67 http://www.avr-asm-tutorial.net
(#(# Instructions in alphabetic order
nstruction ... per!orms ...
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,L66 Add the i<<edi%te ;ord ,onst%nt L66 to the do:)-e register rdI1@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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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 )%,L;%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,L!55 "-e%r %-- the )its in the :EEer register rh, th%t %re set in the ,onst%nt L!55 1<%sL2
"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 P:<E oCer the ne?t instr:,tion if eM:%-
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
IOMP I& r1,E1 O:<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,rEI,(rE2 Lo%d the register r1 ;ith the ,ontent %t the -o,%tion th%t register E%ir rE 1K, . or 52 Eoints to 1rEI
in,re<ents the register E%ir %fter -o%ding, (rE de,re<ents the register E%ir Erior to -o%ding2
LDD r1,ryIL66 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 L66, Eoints to
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
Avr-Asm-Tutorial 68 http://www.avr-asm-tutorial.net
LPM
LPM r1
LPM r1,5I
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, 5I 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 IQO Eort E1
POP r1 In,re%se the st%,L Eointer %nd EoE the -%st )yte on st%,L to register r1
P$*/ r1 P:sh register r1 to the st%,L %nd de,re%se the st%,L Eointer
R"ALL ,7096 P:sh Erogr%< ,o:nter on st%,L %nd %dd signed ,onst%nt ,7096 to the Erogr%< ,o:nter 1re-%tiCe ,%--2
RE> PoE Erogr%< ,o:nter fro< st%,L 1ret:rn to ,%-- %ddress2
RE>I En%)-e interr:Ets %nd EoE Erogr%< ,o:nter fro< st%,L 1ret:rn fro< interr:Et2
ROMP ,7096 Re-%tiCe P:<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, P:<E oCer the ne?t instr:,tion
*3I* E-,)8 If )it )8 in the -o;er Eort E- is set, P:<E oCer the ne?t instr:,tion
*3I4 rd,L66 *:)tr%,t the ,onst%nt L66 fro< the register E%ir rd 1rdI1@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, P:<E oCer ne?t instr:,tion
*3R* r1,)8 If )it )8 in register r1 is set, P:<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
*> 1rEQrEIQ(rE2,r1 *tore ,ontent in register r1 to the <e<ory -o,%tion in register E%ir rE 1rE = K, ., 5' rEI@ in,re<ent
register E%ir %fter store' (rE@ de,re<ent register E%ir Erior to store2
*>D ryIL66,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
L66, 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-Tutorial 69 http://www.avr-asm-tutorial.net
11." Port details
)he table of the relevant ports in the A)0-: A12 types A)9072"1"# 2"2" and 8E1E% 8yte +ise accessible ports or register
pairs are not displayed in detail% 6o +arranty for correctness# see the original data sheets?
($( ,tatus-Register3 Accumulator flags
Port 0unction Port-!!ress R2-!!ress
72-J 7tatus 2egister Accumulator 05"F 05EF
3 + & , # " $ 4
' ) ; 7 1 6 S C
Bit Name 2eaning Opportunities Conmman!
F ' Jlobal 'nterrupt Flag
0* 'nterrupts disabled C:'
1* 'nterrupts enabled 7-'
6 ) 8it storage
0* 7tored bit is 0 C:)
1* 7tored bit is 1 7-)
E ; ;alfcarry3Flag
0* 6o halfcarry occurred C:;
1* ;alfcarry occurred 7-;
H 7 7ign3Flag
0* 7ign positive C:7
1* 7ign negative 7-7
" 1 )+o/s complement3Flag
0* 6o carry occurred C:1
1* Carry occurred 7-1
2 6 6egative3Flag
0* 2esult +as not negativeLsmaller C:6
1* 2esult +as negativeLsmaller 7-6
1 S Sero3Flag
0* 2esult +as not 4eroLune$ual C:S
1* 2esult +as 4eroLe$ual 7-S
0 C Carry3Flag
0* 6o carry occurred C:C
1* Carry occurred 7-C
($(# ,tac@pointer
Port 0unction Port-!!ress R2-!!ress
7<:L7<; 7tac,pointer 00"!L05"- 05E!L05E-
Name 2eaning *aila(ilit)
7<:
:o+38yte of 7tac,
pointer
From A)9072"1" up+ards# not in 1200
7<;
;igh38yte of 7tac,
pointer
From A)9078E1E up+ards# only in devices +ith V2E6 bytes internal 72A0
($($ ,RAM and E)ternal Interrupt control
Port 0unction Port-!!ress R2-!!ress
0C=C2 0C= Jeneral Control 2egister 05"E 05EE
3 + & , # " $ 4
72- 72& 7- 70 '7C11 '7C10 '7C01 '7C00
Bit Name 2eaning Opportunities
F 72- -5t% 72A0 -nable
0G6o e5ternal 72A0 connected
1G-5ternal 72A0 connected
6 72& -5t% 72A0 &ait 7tates
0G6o e5tra +ait state on e5ternal 72A0
1GAdditional +ait state on e5ternal 72A0
Avr-Asm-Tutorial 70 http://www.avr-asm-tutorial.net
Bit Name 2eaning Opportunities
E 7- 7leep -nable
0G'gnore 7:--< instructions
1G7:--< on instruction
H 70 7leep 0ode
0G'dle 0ode @;alf sleepA
1G<o+er !o+n 0ode @Full sleepA
" '7C11
2 '7C10
'nterrupt control <in '6)1
@connected to J'07NA
00* :o+3level initiates 'nterrupt
01* =ndefined
10* Falling edge triggers interrupt
11* 2ising edge triggers interrupt
1 '7C01
0 '7C00
'nterrupt control <in '6)0
@connected to J'07NA
00* :o+3level initiates interrupt
01* =ndefined
10* Falling edge triggers interrupt
11* 2ising edge triggers interrupt
($(. E)ternal Interrupt Control
Port 0unction Port-!!ress R2-!!ress
J'07N Jeneral 'nterrupt 0as,register 05"8 05E8
3 + & , # " $ 4
'6)1 '6)0 3 3 3 3 3 3
Bit Name 2eaning Opportunities
F '6)1
'nterrupt by e5ternal pin '6)1
@connected to mode in 0C=C2A
0* -5ternal '6)1 disabled
1* -5ternal '6)1 enabled
6 '6)0
'nterrupt by e5ternal <in '6)0
@connected to mode in 0C=C2A
0* -5ternal '6)0 disabled
1* -5ternal '6)0 enabled
0%%%E @6ot usedA
Port 0unction Port-!!ress R2-!!ress
J'F2 Jeneral 'nterrupt Flag 2egister 05"A 05EA
3 + & , # " $ 4
'6)F1 '6)F0 3 3 3 3 3 3
Bit Name 2eaning Opportunities
F '6)F1 'nterrupt by e5ternal pin '6)1 occurred
6 '6)F0 'nterrupt by e5ternal pin '6)0 occurred
Automatic clear by e5ecution of the 'nt32outine or
Clear by instruction
0%%%E @6ot usedA
($(0 Timer Interrupt Control
Port 0unction Port-!!ress R2-!!ress
)'07N )imer 'nterrupt 0as,register 05"9 05E9
3 + & , # " $ 4
)'-1 C'-1A C'-18 3 )'C'-1 3 )'-0 3
Avr-Asm-Tutorial 71 http://www.avr-asm-tutorial.net
Bit Name 2eaning Opportunities
F )'-1 )imerLCounter 1 verflo+3'nterrupt
0* 6o 'nt at overflo+
1* 'nt at overflo+
6 C'-1A )imerLCounter 1 Compare A 'nterrupt
0* 6o 'nt at e$ual A
1* 'nt at e$ual A
E C'-18 )imerLCounter 1 Compare 8 'nterrupt
0* 6o 'nt at 8
1* 'nt at e$ual 8
H @6ot usedA
" )'C'-1 )imerLCounter 1 Capture 'nterrupt
0* 6o 'nt at Capture
1* 'nt at Capture
2 @6ot usedA
1 )'-0 )imerLCounter 0 verflo+3'nterrupt
0* 6o 'nt at overflo+
1* 'nt at overflo+
0 @6ot usedA
Port 0unction Port-!!ress R2-!!ress
)'F2 )imer 'nterrupt Flag 2egister 05"8 05E8
3 + & , # " $ 4
)11 CF1A CF18 3 'CF1 3 )10 3
Bit Name 2eaning Opportunities
F )11 )imerLCounter 1 verflo+ reached
6 CF1A )imerLCounter 1 Compare A reached
E CF18 )imerLCounter 1 Compare 8 reached
H @6ot usedA
" 'CF1 )imerLCounter 1 Capture3-vent occurred
2 @not usedA
1 )10 )imerLCounter 0 verflo+ occurred
0 @not usedA
'nterrupt30ode*
Automatic Clear
by e5ecution of the
'nt32outine
2
<olling30ode*
Clear by
instruction
($(2 Timer-Counter +
Port 0unction Port-!!ress R2-!!ress
)CC20 )imerLCounter 0 Control 2egister 05"" 05E"
3 + & , # " $ 4
3 3 3 3 3 C702 C701 C700
Bit Name 2eaning Opportunities
2%%0 C702%%C700 )imer Cloc,
000* 7top )imer
001* Cloc, G Chip cloc,
010* Cloc, G Chip cloc, L 8
011* Cloc, G Chip cloc, L 6H
100* Cloc, G Chip cloc, L 2E6
101* Cloc, G Chip cloc, L 102H
110* Cloc, G falling edge of e5ternal <in )0
111* Cloc, G rising edge of e5ternal <in )0
"%%F @not usedA
Avr-Asm-Tutorial 72 http://www.avr-asm-tutorial.net
Port 0unction Port-!!ress R2-!!ress
)C6)0 )imerLCounter 0 count register 05"2 05E2
($(5 Timer-Counter
Port 0unction Port-!!ress R2-!!ress
)CC21A )imerLCounter 1 Control 2egister A 052F 05HF
3 + & , # " $ 4
C01A1 C01A0 C0181 C0180 3 3 <&011 <&010
Bit Name 2eaning Opportunities
F C01A1
6 C01A0
Compare utput A
E C0181
H C0180
Compare utput 8
00* C1AL8 not connected
01* C1AL8 changes polarity
10* C1AL8 to 4ero
11* C1AL8 to one
"
2
@not usedA
1%%0
<&011
<&010
<ulse +idth modulator
00* <&0 off
01* 838it <&0
10* 938it <&0
11* 1038it <&0
Port 0unction Port-!!ress R2-!!ress
)CC218 )imerLCounter 1 Control 2egister 8 052- 05H-
3 + & , # " $ 4
'C6C1 'C-71 3 3 C)C1 C712 C711 C710
Bit Name 2eaning Opportunities
F 'C6C1
6oise Canceler
on 'C<3<in
0* disabled# first edge starts sampling
1* enabled# min four cloc, cycles
6 'C-71
-dge selection
on Capture
0* falling edge triggers Capture
1* rising edge triggers Capture
E%%H @not usedA
" C)C1
Clear at
Compare 0atch A
1* Counter set to 4ero if e$ual
2%%0 C712%%C710 Cloc, select
000* Counter stopped
001* Cloc,
010* Cloc, L 8
011* Cloc, L 6H
100* Cloc, L 2E6
101* Cloc, L 102H
110* falling edge e5ternal <in )1
111* rising edge e5ternal <in )1
Port 0unction Port-!!ress R2-!!ress
)C6)1:L; )imerLCounter 1 count register 052CL052! 05HCL05H!
Avr-Asm-Tutorial 73 http://www.avr-asm-tutorial.net
Port 0unction Port-!!ress R2-!!ress
C21A:L; )imerLCounter 1 utput Compare register A 052AL0528 05HAL05H8 he5
Port 0unction Port-!!ress R2-!!ress
C218:L; )imerLCounter 1 utput Compare register 8 0528L0529 05H8L05H9
Port 0unction Port-!!ress R2-!!ress
'C21:L; )imerLCounter 1 'nput Capture 2egister 052HL052E 05HHL05HE
($(9 !atchdog-Timer
Port 0unction Port-!!ress R2-!!ress
&!)C2 &atchdog )imer Control 2egister 0521 05H1
3 + & , # " $ 4
3 3 3 &!)- &!- &!<2 &!<1 &!<0
Bit Name 2eaning 5-'-c)cle at &64 Volt
F%%E @not usedA
H &!)- &atchdog )urnoff -nable
<revious set to
disabling of &!- re$uired
" &!- &atchdog -nable 1* &atchdog active
2%%0 &!<2%%&!<0 &atchdog )imer <rescaler
000* 1E ms
001* "0 ms
010* 60 ms
011* 120 ms
100* 2H0 ms
101* H90 ms
110* 9F0 ms
111* 1#9 s
($(* EE'R4M
Port 0unction Port-!!ress R2-!!ress
--A2:L; --<20 Address 2egister 051-L051F 05"-L05"F
--A2; only in types +ith more than 2E6 8ytes --<20 @from A)9078E1E up+ardsA
Port 0unction Port-!!ress R2-!!ress
--!2 --<20 !ata 2egister 051! 05"!
Port 0unction Port-!!ress R2-!!ress
--C2 --<20 Control 2egister 051C 05"C
3 + & , # " $ 4
3 3 3 3 3 --0&- --&- --2-
Avr-Asm-Tutorial 74 http://www.avr-asm-tutorial.net
Bit Name 2eaning 0unction
F%%" @not usedA
2 --0&- --<20 0aster &rite -nable <revious set enables +rite cycle
1 --&- --<20 &rite -nable 7et to initiate +rite
0 --2- --<20 2ead -nable 7et initiates read
($(+ ,erial 'eripheral Interface ,'I
Port 0unction Port-!!ress R2-!!ress
7<C2 7<' Control 2egister 050! 052!
3 + & , # " $ 4
7<'- 7<- !2! 07)2 C<: C<;A 7<21 7<20
Bit Name 2eaning 0unction
F 7<'- 7<' 'nterrupt -nable
0* 'nterrupts disabled
1* 'nterrupts enabled
6 7<- 7<' -nable
0* 7<' disabled
1* 7<' enabled
E !2! !ata rder
0* 078 first
1* :78 first
H 07)2 0asterL7lave 7elect
0* 7lave
1* 0aster
" C<: Cloc, <olarity
0* <ositive Cloc, <hase
1* 6egative Cloc, <hase
2 C<;A Cloc, <hase
0* 7ampling at beginning of Cloc, <hase
1* 7ampling at end of Cloc, <hase
1 7<21
0 7<20
7CN cloc, fre$uency
00* Cloc, L H
01* Cloc, L 16
10* Cloc, L 6H
11* Cloc, L 128
Port 0unction Port-!!ress R2-!!ress
7<72 7<' 7tatus 2egister 050- 052-
3 + & , # " $ 4
7<'F &C: 3 3 3 3 3 3
Bit Name 2eaning 0unction
F 7<'F 7<' 'nterrupt Flag 'nterrupt re$uest
6 &C: &rite Collision Flag &rite collission occurred
E%%0 @not usedA
Port 0unction Port-!!ress R2-!!ress
7<!2 7<' !ata 2egister 050F 052F
Avr-Asm-Tutorial 75 http://www.avr-asm-tutorial.net
($( 7ART
Port 0unction Port-!!ress R2-!!ress
=!2 =A2) 'L !ata 2egister 050C 052C
Port 0unction Port-!!ress R2-!!ress
=72 =A2) 7tatus 2egister 0508 0528
3 + & , # " $ 4
2OC )OC =!2- F- 2 3 3 3
Bit Name 2eaning 0unction
F 2OC =A2) 2eceive Complete 1* Char received
6 )OC =A2) )ransmit Complete 1* 7hift register empty
E =!2- =A2) !ata 2egister -mpty 1* )ransmit register available
H F- Framing -rror 1* 'llegal 7top38it
" 2 verrun 1* :ost char
2%%0 @not usedA
Port 0unction Port-!!ress R2-!!ress
=C2 =A2) Control 2egister 050A 052A
3 + & , # " $ 4
2OC'- )OC'- =!2'- 2O-6 )O-6 C;29 2O88 )O88
Bit Name 2eaning 0unction
F 2OC'- 2O Complete 'nterrupt -nable 1* 'nterrupt on received char
6 )OC'- )O Complete 'nterrupt -nable 1* 'nterrupt at transmit complete
E =!2'- !ata 2egister -mpty 'nterrupt -nable 1* 'nterrupt on transmit buffer empty
H 2O-6 2eceiver -nable 1* 2eceiver enabled
" )O-6 )ransmitter -nable 1* )ransmitter enabled
2 C;29 93bit Characters 1* Char length 9 8it
1 2O88 2eceive !ata 8it 8 @holds 9
th
data bit on receiveA
0 )O88 )ransmit !ata 8it 8 @+rite 9
th
data bit for transmit hereA
Port 0unction Port-!!ress R2-!!ress
=822 =A2) 8aud 2ate 2egister 0509 0529
($(# Analog Comparator
Port 0unction Port-!!ress R2-!!ress
AC72 Analog Comparator Control and 7tatus 2egister 0508 0528
3 + & , # " $ 4
AC! 3 AC AC' AC'- AC'C AC'71 AC'70
Bit Name 2eaning 0unction
F AC! !isable !isable Comparators
6 @not usedA
E AC Comparator utput 2ead* utput of the Comparators
H AC' 'nterrupt Flag 1* 'nterrupt re$uest
Avr-Asm-Tutorial 76 http://www.avr-asm-tutorial.net
Bit Name 2eaning 0unction
" AC'- 'nterrupt -nable 1* 'nterrupts enabled
2 AC'C 'nput Capture -nable 1* Connect to )imer 1 Capture
1 AC'71
0 AC'70
'nput Capture -nable
00* 'nterrupt on edge change
01* @not usedA
10* 'nterrupt on falling edge
11* 'nterrupt on rising edge
($($ I-4 'orts
Port Register 0unction Port-!!ress R2-!!ress
A
<2)A !ata 2egister 0518 05"8
!!2A !ata !irection 2egister 051A 05"A
<'6A 'nput <ins Address 0519 05"9
8
<2)8 !ata 2egister 0518 05"8
!!28 !ata !irection 2egister 051F 05"F
<'68 'nput <ins Address 0516 05"6
C
<2)C !ata 2egister 051E 05"E
!!2C !ata !irection 2egister 051H 05"H
<'6C 'nput <ins Address 051" 05""
!
<2)! !ata 2egister 0512 05"2
!!2! !ata !irection 2egister 0511 05"1
<'6! 'nput <ins Address 0510 05"0
11.% 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*U, 0ener%- Interr:Et M%sL Register
I"R1LQ/, 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
*PLQ*P/, *t%,LEointer
*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<erQ"o:nter "ontro- Register, >i<er 0
>""R1A, >i<erQ"o:nter "ontro- Register 1 A
>""R13, >i<erQ"o:nter "ontro- Register 1 3
>"&>0, >i<erQ"o:nter Register, "o:nter 0
>"&>1, >i<erQ"o:nter Register, "o:nter 1
>IFR, >i<er Interr:Et F-%g Register
>IM*U, >i<er Interr:Et M%sL 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-Tutorial 77 http://www.avr-asm-tutorial.net
11.) 8ist of abbre(iations
)he abbreviations used are chosen to include the value range% 2egister 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*6 2eans 666 Value range
2egister
r1 rdinary 7ource and )arget register
r2 rdinary 7ource register
20%%2"1
rh =pper page register 216%%2"1
rd )+in register 22H@22EA# 226@22FA# 228@229A# 2"0@2"1A
rp <ointer register OG226@22FA# .G228@229A# SG2"0@2"1A
ry <ointer register +ith displacement .G228@229A# SG2"0@2"1A
Constant
,6" <ointer3constant 0%%6"
c12F Conditioned >ump distance 36H%%K6"
c2EE 838it3Constant 0%%2EE
cH096 2elative >ump distance 320H8%%K20HF
c6EE"E 1638it3Address 0%%6EE"E
8it bF 8it position 0%%F
<ort
p1 rdinary <ort 0%%6"
pl :o+er page port 0%%"1

You might also like