how to program using the program memory of an avr microcontroller tut

82
Beginners Introduction to the Assemb ly 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"

Upload: manu-krishnan-magvitron

Post on 02-Mar-2016

34 views

Category:

Documents


0 download

DESCRIPTION

The file describe about how to access the program memory of the AVR controller so that , one can access it and then upload it to the data memory and hence saving the data memory , if data memory is low, things such as strings can be added to the program memory and we can access it using simple pointers

TRANSCRIPT

Page 1: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 1/81

Beginners Introduction to theAssembly 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"

Page 2: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 2/81

 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 AT2#1#3ATmega2#1#........................................................+

 #.% eady-to-use commercial programming boards for the A,-family............................................ #.%.1 T42................................................................................................................................... #.%.2 T4(................................................................................................................................... #.%.# A, &ragon.........................................................................................................................1

 % 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..................................................................................................................................................2 *.1 What is A6?...........................................................................................................................2 *.2 7or what purposes can $ use A6?...........................................................................................2

 *.# How to use A6?......................................................................................................................2 *.#.1 &irect addressing..................................................................................................................2 *.#.2 ointer addressing.................................................................................................................# *.#.# ointer with offset.................................................................................................................#

 *.% !se of A6 as stac"..................................................................................................................# *.%.1 &efining A6 as stac"......................................................................................................# *.%.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...................................................................................................................................#(

Page 3: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 3/81

 Avr-Asm-Tutorial 2 http://www.avr-asm-tutorial.net

 +.) $nterrupts and program e0ecution.................................................................................................#*  Calculations..........................................................................................................................................#

 .1 ;umber systems in assembler......................................................................................................# .1.1 ositi'e whole numbers <bytes= words= etc.>........................................................................#

 .1.2 igned numbers <integers>....................................................................................................# .1.# inary Coded &igits= C&...................................................................................................# .1.% ac"ed C&s........................................................................................................................% .1.( ;umbers in AC$$-format....................................................................................................%

 .2 it manipulations.........................................................................................................................% .# hift and rotate.............................................................................................................................%1 .% Adding= subtracting and comparing..............................................................................................%2

 .%.1 Adding and subtracting 1)-bit numbers................................................................................%2 .%.2 Comparing 1)-bit numbers...................................................................................................%2 .%.# Comparing with constants....................................................................................................%2 .%.% ac"ed C& math.................................................................................................................%#

 .( 7ormat con'ersion for numbers....................................................................................................%# .(.1 Con'ersion of pac"ed C&s to C&s= AC$$ or inaries...................................................%# .(.2 Con'ersion of inaries to C&............................................................................................%%

  .) 6ultiplication...............................................................................................................................%% .).1 &ecimal multiplication.........................................................................................................%% .).2 inary multiplication............................................................................................................%% .).# A, assembler program......................................................................................................%( .).% inary rotation......................................................................................................................%) .).( 6ultiplication in the studio...................................................................................................%)

 .* Hardware multiplication...............................................................................................................%+ .*.1 Hardware multiplication of +-by-+-bit binaries....................................................................%+ .*.2 Hardware multiplication of a 1)- by an +-bit-binary............................................................%

 .*.# Hardware multiplication of a 1)- by a 1)-bit-binary............................................................( .*.% Hardware multiplication of a 1)- by a 2%-bit-binary............................................................(2

  .+ &i'ision........................................................................................................................................(# .+.1 &ecimal di'ision...................................................................................................................(# .+.2 inary di'ision......................................................................................................................(% .+.# rogram steps during di'ision..............................................................................................(% .+.% &i'ision in the simulator......................................................................................................((

 . ;umber con'ersion......................................................................................................................() .1 &ecimal 7ractions.......................................................................................................................(*

 .1.1 :inear con'ersions..............................................................................................................(* .1.2 /0ample 1@ +-bit-A&-con'erter with fi0ed decimal output................................................(+

 .1.# /0ample 2@ 1-bit-A&-con'erter with fi0ed decimal output..............................................( 1 roect planning.................................................................................................................................)

 1.1 How to plan an A, proect in assembler.................................................................................) 1.2 Hardware considerations............................................................................................................) 1.# Considerations on interrupt operation........................................................................................)

 1.#.1 asic re9uirements of interrupt-dri'en operation...............................................................)1 1.#.2 /0ample for an interrupt-dri'en assembler program..........................................................)1

 1.% 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..................................................................................................................................) 11.#.1 tatus-egister= Accumulator flags....................................................................................)  11.#.2 tac"pointer........................................................................................................................) 11.#.# A6 and /0ternal $nterrupt control................................................................................) 11.#.% /0ternal $nterrupt Control...................................................................................................* 11.#.( Timer $nterrupt Control......................................................................................................* 11.#.) Timer3Counter ..................................................................................................................*1 11.#.* Timer3Counter 1..................................................................................................................*2 11.#.+ Watchdog-Timer.................................................................................................................*#

  11.#. //B6............................................................................................................................*# 11.#.1 erial eripheral $nterface $..........................................................................................*%  11.#.11 !AT...............................................................................................................................*(

Page 4: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 4/81

 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...................................................................................................................**

Page 5: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 5/81

 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%

any people that are deeper into programming As 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,% o 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 

ecause 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 99 in a +ait state type of operation#

you can choose any language you +ant%

 Assembler is easy to learn't is not true that assembly language is more complicated or not as easy to understand than other languages% :earning

assembly language for +hatever hard+are type brings you to understand the basic concepts of any other assembly

language dialects% Adding other dialects later is easy% As some features are hard+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% o +indo+ +arns you# unless you programmed it before%

)o correct typing errors is as easy or complicated as in any other language% asic design errors# the more tric,y type of

errors# are also as complicated to debug li,e in any other computer language% ut* testing programs on A)-: 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% ye# bye to you -< programmers# to the = 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% o pin is

removed# and no = lamp gives up >ust in the moment +hen you had your e5cellent idea about that bug%

 Test it!

e patient doing your first steps? 'f you are familiar +ith another @high3level language* forget it for the first time% ehind

every assembler language there is a certain hard+are concept% ost 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 +orld3li,e e5amples# e% g% turning some :-!s on and off for a

certain time# then e5plore the hard+are features a bit deeper%

ecommendation* Comment your subroutines and store them in a special directory# if debugged* you +ill need them againin a short time%

;ave success?

Page 6: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 6/81

 Avr-Asm-Tutorial 2 http://www.avr-asm-tutorial.net

 # The concept behind the languageassembler in micro-controllers

Attention? )hese pages are on programming micro3controllers# not on <Cs +ith :inu53 or &indo+s operating systems andsimilar 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( uch# as can be seen from the follo+ing%

)he concept behind assembler is to ma,e the hard+are resources of the processor accessible% esources means all

hard+are components# li,e

  D the central processing unit @C<= and its math servant# the arithmetic and logic unit @A:=#

  D the diverse storage units @internal and e5ternal A# --< storage#

  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

ost important for understanding assembler is to understand ho+ the C<= +or,s% )he C<= reads instructions @instruction

fetch from the program storage @the flash# translates those into e5ecutable steps and e5ecutes those% 'n As# thoseinstructions are +ritten as 16 bit numbers to the flash storage# and are read from there @first step% )he number read then

translates @second step e% g% to transporting the content of the t+o registers 0 and 1 to the A:= @third step# to add

those @fourth step and to +rite the result into the register 0 @fifth step% egisters 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 1 to register 0 0000%1100%0000%0001 0C01

7ubtract register 1 from register 0 0001%1000%0000%0001 1801

&rite constant 10 to register 16 1110%1010%0000%1010 -A0A

ultiply register " +ith register 2 and +rite the result to registers 1 @7 and

0 @:7

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# 0 and 1 is added and the result is +ritten to register 0% )his is e5ecuted li,e demonstrated in

the picture%

First theinstruction

+ord @16 bit

is read from

the flash and

translated to

e5ecutable

steps @1%

)he ne5t step

connects the

registers to

the A:=

inputs# and

adds their content @2%

e5t# the result is +ritten to the register @"%

Page 7: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 7/81

 Avr-Asm-Tutorial 3 http://www.avr-asm-tutorial.net

'f the C<= reads he5 9C2" from the flash# the registers " and 2 are muliplied and the result is +ritten to 1 @upper 8 bits

and 0 @lo+er 8 bits% 'f the A:= is not e$uipped +ith hard+are for multiplication @e% g% in an A)tiny1"# the 9C2" does

nothing at all% 't doesn/t even open an error +indo+ @the tiny1" doesn/t have that hard+are?

'n principle the C<= can e5ecute 6E#E"6 @163bit different instructions% ut because not only 10 should be +ritten to a

specific register# but values bet+een 0 and 2EE to any register bet+een 16 and "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 @c%%c0 and registers

r @r"%%r0# rH is al+ays 1 and not encoded is coded li,e this*

it 1E 1H 1" 12 11 10 9 8 6 E H " 2 1 0

:!' #C 1 1 1 0 c 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)-:/s secret%

Addition and subtraction re$uire "2D"2 G 1#02H combinations and the target registers 0%%"1 @tH%%t0 and source registers

0%%"1 @sH%%s0 are coded li,e this*

it 1E 1H 1" 12 11 10 9 8 6 E H " 2 1 0

A!! t#s 0 0 0 0 1 1 sH tH t" t2 t1 t0 s" s2 s1 70

7= t#s 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 he59E88 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% @o# not in

brac,ets% C programmers# forget those brac,ets% .ou don/t need those in assembler% 7imply type IA!! 0#1I% )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-leel 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 ) in asic loo,s li,e a J< 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 I=:I% 'n assembler# the target processor determines if you can usethis 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 =:

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 A# 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

ecause 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!! 0#1I cannot be e5ecuted%

And assembler is much simpler than machine language% 7imilarities bet+een machine language and assembler are a

feature# not a bug%

Page 8: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 8/81

 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 I @nine characters of one byte each#  D strip the four blan,s from the te5t#

  D locate the variables A and @location in registers or in 7A# precisionLlength# etc%#

  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!! 0#1I @in Assembler +ould result% ut most probably the

resulting machine code +ould be multiple +ords long @read and +rite variables fromLto 7A# 163bit3integer adding#

register savingLrestoring on stac,# etc%# etc%%

)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 ismore 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% o one ,no+s +hat the C<= is >ust doing and ho+ long this re$uires%

ot 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 leel 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 oolean 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%%

For learning assembler# >ust forget the high level language concept of variables% Assembler only ,no+s bits# bytes# registers

and 7A 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 yte @83bit# double

+ord @163bit# integer @1E3bit plus 1 sign bit% 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 I is no+ type3proofed* if A is defined as a character and a number @e% g% G 2# the formulation

isn/t accepted because character codes cannot be added +ith numbers% <rogrammers in high level languages believe thatthis 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 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%

ood 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%

ecause 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% esponsibility 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%

Page 9: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 9/81

 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% o other documents necessary% ;o+ the timer

is started @is +riting I)imer%7tart@8I someho+ easier to understand than I:!' 16#0502M and =) )CC0#16I(# ho+ the

timer is restarted at 4ero @IC: 16M and =) )CC0#16I# it is all in the data sheet% o need to consult a more or lessgood documentation on ho+ a compiler defines this or that% o 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 I instead of I=: 16#1I( ot much% 'f A and aren/t defined

as bytes or if the processor type is tiny and doesn/t understand =:# the simple =: has to be e5changed +ith some

other source code# as designed by the assembler programmer or copyLpasted and adapted to the needs% o 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% ecause 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 =A)% A speed setting that no &indo+s <C allo+s# because the operating system

allo+s only multiples of E @&hy( ecause some historic mechanical teletype +riters had those special mechanical gear

bo5es# allo+ing $uic, selection of either E or "00 bps%% '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% o 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(

Page 10: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 10/81

 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 * processor family

efore going into practice# +e have to learn a fe+ essentials on the serial programming mode of the A family% o# you

don/t need three different voltages to program and read an A flash memory% o# you don/t need another pre3

programmed microprocessor to program the As% o# 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 A 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 A chips# that enable you to +rite and read the content of the program flash

and the built3in3--<% )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#

• 7'* )he data signal that sends the bits to be +ritten to the A#

• '7* )he data signal that receives the bits read from the A%

)hese three signal pins are internally connected to the programming machine only if you change

the -7-) @sometimes also called 7) or restart pin to 4ero% ther+ise# during normal operation

of the A# 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%

ot 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 A board% ! is the common

ground or negative pole of the supply voltage# ) @target voltage the supply voltage @usually

KE%0 volts% )his adds up to 6 lines bet+een the programmer hard+are and the A board% )heresulting '7<6 connection# as defined by A)-:# 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 CA!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

o+# 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 A% )he 2E3pin plug goes into the parallel port of your <C# the 103pin '7< goes to

your A e5perimental board% 'f your bo5 doesn/t have a H:72HE# you can also use a H;C2HE @+ith no hard+are

changes or a H:72HHLH;C2HH @by changing some pins and signals% 'f you use ;C# don/t forget to tie unused inputs

either to ! 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% e a+are that this parallel port interface is not supported by

A)-:/s studio soft+are any more% 7o# if you +ant to program your A directly from +ithin the studio# use different

programmers% )he 'nternet provides several solutions%

Page 11: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 11/81

 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 A 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 72"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 -7-) pin @pin 1#

● the supply part +ith a bridge rectifier# to be supplied +ith 9%%1E from an AC or !C source# and a small E

regulator%

)he A)tiny1" re$uires no e5ternal O)A: or cloc, generator# because it +or,s +ith its internal 9%6 ;4 C generator and# by

default# +ith a cloc, divider of 8 @cloc, fre$uency 1%2 ;4%

)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%

Page 12: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 12/81

 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 EL1A#

• a O)A: cloc, generator @here +ith a 10 ;4 O)A:# all other fre$uencies belo+ the ma5imum for the 2"1" +ill

also +or,#

• the necessary parts for a safe reset during supply voltage s+itching#

• the '7<3<rogramming3'nterface @here +ith a '7<10<'3connector%

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#

Page 13: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 13/81

 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 )7 on the 93pin3

connector over a 2%2, resistor to K9%

'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 hasan internal C 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 C as cloc, source# you +ill have to program

the fuses of the A)mega accordingly%

 ".% eady-to-$se commercial pro'rammin' boards for the *-

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 =7# less convenient or durable* 93pin 72"2# re$uiring additional soft+are* interfaces for

the parallel port of the <C#

● support reliability for ne+er devices @updates are re$uired from time to time# other+ise you sit on a nearly dead

horse#

● hard+are features @depends on your foreseeable re$uirements in the ne5t five years%

)he follo+ing section describes the three standard boards of A)-:# 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)-: 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 devices#

● eight ,eys and :-!s# hard connected to port ! and #

● an :C! standard 1H3pin interface#

● an option for attaching a 283pin 7A#

● a 72"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)-:% 't has the follo+ing hard+are*

• 7oc,ets for programming most of the A types @e% g% 1H3pin devices or )PF< pac,ages re$uire additionalhard+are#

• serial and parallel programming in normal mode or +ith high voltage @; programming brings devices bac, to

life even if their -7-) pin has been fuse3programmed to be normal port input#

• '7<6<'3 and '7<10<'3connection for e5ternal 'n37ystem3<rogramming#

• programmable oscillator fre$uency and supply voltages#

• plug3in s+itches and :-!s#

• a plugged 72"2C3connector @=A)#

• a serial Flash3--< @only older boards have this#

• 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

Page 14: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 14/81

 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 @C5% 'f your laptop doesn/t have a serial interface# you can use one

of the common =73to37erial3'nterface cables +ith a soft+are driver% 'n that case the driver must be ad>usted to use

bet+een C1 and C8 and a baud rate of 11E, to be automatically detected by the 7tudio soft+are%

<rogramming is performed and controlled by recent versions of A studio# +hich is available for free from A)-:/s +ebpage 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 A @older versions* A)9078E1E# ne+er boards versions include different

types% )his covers all hard+are re$uirements that the beginner might have%

 $(.($ AVR 1ragon

)he A dragon is a very small board% 't has an =7 interface# +hich also supplies the board and the 63pin3'7< interface%

)he 63pin3'7<3'nterface is accompanied by a 203pin ; 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 A amateur% )he bo5 fits nicely in a ro+ +ith other precious and carefully

designed bo5es%

Page 15: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 15/81

 Avr-Asm-Tutorial 11 http://www.avr-asm-tutorial.net

 . Tools for AVR assembly programmingFour 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% ut 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% ore or less intelligent recognition of errors ease typing%ut 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# both +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)-: 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 R% :ater understanding of +hat +e/ve

planned here +ill be helpful in later

debugging%

o+ 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 A editor here%

)he editor recogni4es instructions automatically and uses different colors @synta5 high lighting to signal user constants and

typing errors in those instructions @in blac,% 7toring the code in an %asm file provides nearly the same te5t file# colors are

not stored in the file%

Page 16: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 16/81

 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 codeThis 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 multiplelines# 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 --< and internal 7A% 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)-:% 't is good style to include this file at the beginning of each program%

)his is done li,e that*

(64LI,T  ont list the )ollowin' in the list )ile

(I6CL71E 8m900def(inc8  mport 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)-:/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%lst if you include the header file%

)he directive %:'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 %!-'C- advices the assembler to chec, all instructions if these are available for that A 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 <) translates to a he5 number +here this port is

Page 17: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 17/81

 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% ead access to port # it "# can be done using its bit

name <'"# 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  e)ine a new name )or re'ister 16

)his has the advantage of having a complete list of registers# and to see +hich registers are still available and unused%

enaming 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> < .++++++  Tal )reuen#, (e)inition

at the beginning of the source code you immediately see for +hich cloc, you +rote the program% ery 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=< section 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=< 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

*-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 # 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*

A(( &roe#t title here A(( more in)o on so)tware version here ";20<< +, A(( "op,ri'ht n)o here

n#lu(e( hea(er )ile )or tar'et A= t,pe.>?@T

Page 18: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 18/81

 Avr-Asm-Tutorial 14 http://www.avr-asm-tutorial.net

.>"@B Ctn13(e).in#C ea(er )or ATT>D13

.@T EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A * A B > F ? G A T ? > EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A(( all har(ware in)ormation here EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE & ? T A > & > EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A(( names )or har(ware ports an( pins here Format: .BH "ontrolportout E &?TA .BH "ontrolportin E &>A .BH @e(?utput&in E &?TA2 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

" ? > T A > T T ? " A > B EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A(( all #onstants here that #an +e su+e#t to #han'e +, the user Format: .BH #onst E IAJ" EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE F K B = B " ? > T A > T EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A(( all #onstants here that are not su+e#t to #han'e or #al#ulate( )rom #onstants Format: .BH #onst E IAJ"

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE B T B B F > T ? > EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A(( all re'ister names here% in#lu(e in)o on all use( re'isters without spe#i)i# names Format: .BF rmp E 16.BF rmp E 16 Gultipurpose re'ister  EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A G B F > T ? > EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

.B

.? 00060 Format: @a+el: .JDTB > reserve > J,tes )rom @a+el: EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE B B T A > > T = B " T ? EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE."B.? I0000  rmp Gain eset ve#tor   reti nt ve#tor 1  reti nt ve#tor 2  reti nt ve#tor 3

  reti nt ve#tor 4  reti nt ve#tor 5  reti nt ve#tor 6  reti nt ve#tor 7  reti nt ve#tor 8  reti nt ve#tor 9 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE > T B & T B = " B EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE A(( all interrupt servi#e routines here EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

G A > & ? A G > T EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

Page 19: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 19/81

 Avr-Asm-Tutorial 15 http://www.avr-asm-tutorial.net

Gain: nit sta#$  l(i rmp% @?*AGB>; nit @J sta#$  out &@%rmp nit &ort J  l(i rmp%1LLJ2;M1LLJ1;M1LLJ0; ire#tion o) &ort J  out J%rmp A(( all other init routines here  l(i rmp%1LLB ena+le sleep  out G""%rmp  sei EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE & ? A G @ ? ? & EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE@oop:  sleep 'o to sleep  nop (umm, )or wa$e up

  rmp loop 'o +a#$ to loop Bn( o) sour#e #o(e

 %.2 The assembler

o+ +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 A chip% !oing this is called assembling# +hich means Bput together the right instruction +ords%

)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 2010# it is more convenient to +rite a short batch file @again using an editor% )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+# 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 J< instruction

that +e used% Assembling our single asm te5tfile no+ has produced four other files @not all

apply here%

)he first of these four ne+ files# )-7)%--<# holds

the content that should be +ritten to the

--< of the A% )his is not very interesting

in our case# because +e didn/t program any

content for the --<% )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 becausethis file holds the instructions later programmed

into the A 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%

Page 20: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 20/81

 Avr-Asm-Tutorial 16 http://www.avr-asm-tutorial.net

)he third file# )-7)%J# +ill be introduced

later# this file is needed to simulate an A%

'ts format is he5adecimal and defined by

A)-:% =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 A @a

very common error +hen starting% J files are only produced by certain A)-: 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 %:'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 A a programmer soft+are is necessary% )his

soft+are reads the %;-O3file and transfers its content# either bit3by3bit @serial programming or byte3by3byte @parallel

programming to the A/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)-:% 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)-:

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 ersion H of the 7tudio# that is available for free on A)-:/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 A type of your choice% )he studio is started and loo,s li,e this%

Page 21: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 21/81

 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+lyinstalled 7tudio e+ <ro>ectM is the correct ans+er% )he utton e5tVVM brings you to the settings dialog of your ne+

pro>ect%

;ere you select Atmel A AssemblerM as your pro>ect type# give that pro>ect a name @here test1M and let the 7tudio

crate an initial @empty 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 e5tVVM opens the platform and device selection dialog*

Page 22: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 22/81

 Avr-Asm-Tutorial 18 http://www.avr-asm-tutorial.net

As debug platform

select either A

simulatorM or A

simulator 2M% As

!evice select your

A type# here anA)mega8 +as

selected% 'f your

desired type is grayed

out# select another

simulator platform%

Close this +indo+

+ith the FinishM

button% o+ 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(% n the left bottom is a uildM 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%

Page 23: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 23/81

 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 uildM and its sub3

menu uildM% 'f you typed correctly# the result sho+s up in your uildM +indo+%

a,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 !ebugM and some +indo+s change their content# si4e and position% 'f you also push themenu item ie+M# )oolbarsM and <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 simulatedM%

)he processor +indo+ sho+s the

current program counter value

@yes# the program starts at

address 0# the stac, pointer @no

matter +hat that might be W +ait

for that later in the course# acycle counter and a stop +atch% 'f

you push on the small KM left to

the +ord egistersM# the content

of the "2 registers is displayed

@yes# they are all empty +hen you

start the processor simulation%

o+ let us proceed +ith the first

instruction% enu item !ebugM

and 7tep intoM or simply F11

e5ecutes the first instruction%

)he instruction ldi rmp#0b11111111M loads

the binary value 1111%1111 to register 16% 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%

Page 24: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 24/81

 Avr-Asm-Tutorial 20 http://www.avr-asm-tutorial.net

)he instruction ut !!#rmpM +rites 05FF to a port named !!% o+ the action is on the 'L vie+ +indo+% 'f you push

on <) and the small KM left of it# this +indo+ displays the value 05FF in the port !! 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 <)%

As e5pected# the

port <) changes

its content and has

four blac, and four

+hite s$uares no+%

Another t+o F11#

+riting 05AA to

<)# changes the

blac, and +hite

s$uares to the

opposite color%

All +hat has been

e5pected# but +hat

happened to port

<'( &e didn/t

+rite something to

<'# but it has theopposite colors than

<)# >ust li,e the

colors before in

<)%

<' is an input

port for e5ternal

pins% ecause the

direction ports in

!! are set to be

outputs# <'

follo+s the pin

status of <)# >ust one cycle later%

othing +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% isit 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%

Page 25: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 25/81

 Avr-Asm-Tutorial 21 http://www.avr-asm-tutorial.net

 0 !hat is a register"egisters are special storages +ith 8 bits capacity and they loo, li,e this*

it it 6 it E it H it " it 2 it 1 it 0

ote the numeration of these bits* the least significant bit starts +ith 4ero @mathematically* 20 G 1%

A register can either store numbers from 0 to 2EE @positive number# no negative values# or numbers from 3128 to K12

@+hole number +ith a sign bit# located in bit # or a value representing an A7C''3coded character @e% g% /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 decisions%

)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 registerfor a calculation or transfer#

• operations +ith their content re$uire only a single instruction +ord%

)here are "2 registers in an A% )hey are originally named 0 to "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 -- start +ith a dot% ote that assembler

directives li,e this are only meaningful for the assembler but do not produce any code that is e5ecutable in the A target

chip% )he name y<referredegisterM +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 16 +e can no+ use our o+n name y<referredegisterM# if +e +ant to use 16

+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 16# :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 A 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% Allnumbers are in he5 format* )he first he5 number is the address @000000# +here the instruction is +ritten to in the

program flash memory of the A# the second is the instruction code @-906% -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 @16 +here the value 1E0 is to be +ritten to#

● the value of the constant @1E0%

!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 A e5ecutes it%

&ithin one instruction t+o different registers can play a role% )he easiest instruction of this type is the copy instruction#

% )he naming of this instruction deserves a price for the most confusing definition# because the content of aregister cannot be moved @+hat +ould be left in a register# if you - its content to some+here else(% '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 16 and 1E for the

assembler% Again# these lines do not produce any code for the A% )he instruction lines +ith :!' and produce code*

000000 E906 000001 !F01

)he instruction +rite the value 1E0 into register 16 and copy its content to the target register 1E% ery '<)A))'C-*

Page 26: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 26/81

 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%

 ).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 16 to "1 load a constant immediately +ith the :!' instruction# 0 to 1E don/t do

that% )his restriction is not very fine# but could not be avoided during construction of the instruction set for the As%

)here is one e5ception from that rule* setting a register to Sero% )his instruction

"LR MyPreferredRegister 

is valid for all registers%esides the :!' instruction you +ill find this register class restriction +ith the follo+ing additional instructions*

• A!' 5#N R it3And of register 5 +ith a constant value N#

• C 5# R Clear all bits in register 5 that are set to one +ithin the constant mas, value #

• C<' 5#N R Compare the content of the register 5 +ith a constant value N#

• 7C' 5#N R 7ubtract the constant N and the current value of the carry flag from the content of register 5 and

store the result in register 5#

• 7 5# R 7et all bits in register 5 to one# that are one in the constant mas, #

• 7- 5 R 7et all bits in register 5 to one @e$ual to :!' 5#2EE#

• 7=' 5#N R 7ubtract the constant N from the content of register 5 and store the result in register 5%

'n all these instructions the register must be bet+een 16 and "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 2*26# 29*28 and "1*"2% )he role is so important that these

pairs have e5tra short names in A 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 7A locations @O# . or S or

into locations in program memory @S%

 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% oth parts have

their o+n names# e% g% the higher byte of S is named S; @G"1# the lo+er yte is S: @G"0% )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 /,/I/%ddress2 ' Lo%d the M*3 of %ddressLDI L,LO4%ddress2 ' Lo%d the L*3 of %ddress

Accesses via pointer registers are programmed +ith specially designed instructions% ead access is named :! @:oa!# +rite

access named 7) @7)ore# e% g% +ith the O3pointer*

7imilarly you can use . and S for that purpose%

Pointer Sequence Examples

O eadL&rite from address O# don/t change the pointer :! 1#O or 7) O#1

OK eadL&rite fromLto address O# and increment the pointer after+ards by one :! 1#OK or 7) OK#1

3O First decrement the pointer by one and readL+rite fromLto the ne+ address

after+ards

:! 1#3O or 7) 3O#1

 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 :< @:oad from <rogram emory% )he instruction copies the byte at program flash address S to the register 0%

Page 27: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 27/81

 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

+ord the least significant bit selects the lo+er or upper byte @0Glo+er byte# 1G upper byte% ecause of this the original

address must be multiplied by 2 and access is limited to 1E3bit or "2 , program memory% :i,e this*

LDI /,/I/!+%ddress2LDI L,LO4!+%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 L,1LPM 

A!'& means A!d 'mmediate &ord and a ma5imum of 6" can be added this +ay% ote 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

7'&# 7ubtract 'mmediate &ord% @7utract 'mmediate &ord% A!'& and 7'& are possible for the pointer register pairs O#

. and S and for the register pair 2E*2H# that does not have an e5tra name and does not allo+ access to 7A or

program memory locations% 2E*2H is ideal for handling 163bit values%As incrementation after reading is very often needed# ne+er A types have the instruction

LPM R,Z+

)his allo+s to transport the byte read to any location # and auto3increments the pointer register%

0(#($ Tables in the program flash memory

o+ 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

%! and %!&% &ith that you can insert byte +ise or +ord +ise lists of values% yte +ise organi4ed lists loo, li,e this*

.D3 1!,75,68,9 ' % -ist of fo:r )ytes, ;ritten in dei<%- 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!75,689 ' % -ist of t;o ;ord onst%nts

'nstead of constants you can also place labels @e% g% >ump targets on that list# li,e that*

L%)e-1@ ... here %re so<e instr:tions ... B L%)e-!@ ... 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 *M% ote that reading the labels from that table +ith :<

@and subse$uent incrementation of the pointer 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 05001F% )his access is only meaningful if you have to copy

the register/s content to 7A or --< or read these values from there bac, into the registers% ore 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 2E*2H*

My>%)-e@

.D4 0?1!7,0?!75,0?756,0?756,0?568 ' >he t%)-e C%-:es, ;ord ;ise

.D4 0?689,0?89A,0?9A3,0?9A3",0?A3"D ' org%nied Re%d5@ LDI /,/I/My>%)-e+!2 ' %ddress of t%)-e to ointer  

LDI L,LO4My>%)-e+!2 ' <:-ti-ied )y ! for )yte;ise %ess ADI4 L,10 ' Point to fifth C%-:e in t%)-eLPM ' Re%d -e%st signifi%nt )yte fro< rogr%< <e<ory MO R!7,R0 ' "oy L*3 to 16()it register 

 ADI4 L,1 ' Point to M*3 in rogr%< <e<ory LPM ' Re%d M*3 of t%)-e C%-:eMO R!5,R0 ' "oy 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%

Page 28: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 28/81

 Avr-Asm-Tutorial 24 http://www.avr-asm-tutorial.net

 )." ecommendation 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 5%

• 'f you need pointer access reserve 26 to "1 for that purpose%

• A 163bit3counter is best located in 2E*2H%

• 'f you need to read from the program memory# e% g% fi5ed tables# reserve S @"1*"0 and 0 for that purpose%

• 'f you plan to have access to single bits +ithin certain registers @e% g% for testing flags# use 16 to 2" for that

purpose%

• egisters necessary for math are best placed to 1 to 1E%

• '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 7A%

Page 29: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 29/81

 Avr-Asm-Tutorial 25 http://www.avr-asm-tutorial.net

 2 'orts

 +.1 hat is a Port/

<orts in the A 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 A 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 A 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+%

<orts have a fi5ed address# over +hich the C<= communicates% )he address is independent from the type of A% 7o e% g%

the port address of port is al+ays 0518 @05 stands for he5adecimal notation# 0518 is decimal 2H% .ou don/t have to

remember these port addresses# they have convenient aliases% )hese names are defined in the include files @header files

for the different A types# that are provided from the producer% )he include files have a line defining port /s address asfollo+s*

.E#$ POR>3, 0?1 

7o +e >ust have to remember the name of port # not its location in the 'L space of the chip% )he include file 8E1Edef%inc

is involved by the assembler directive

.I&"L$DE "@*o<e;here515def.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 C= eneral Control egister# called C=C# consists of a number of single control bits that control

the general property of the chip% ;ere are the details of port C=C 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# %%%% )hose +ho +ant to send their A 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-nable3it called 7-# to the port C=C% 7-

enables the A to go to sleep# +henever the 7:--< instruction sho+s up in the code% As all the other bits of C=C are

also set by the above instructions and the 7leep ode bit 7 +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 0b00100000M 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 @1M#

● to read the bit position of the 7leep -nable bit @7-M from the symbol list# as defined in the header file

8E1Edef%inc# +hich yields a value of EM in that case#

to shift @XXM the 1M five times left @1XXEM# in steps*1% initial* 0000%0001#

Page 30: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 30/81

 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 A% 't is pure

convention to increase the readability of the assembler source te5t%

;o+ does this change# if you +ant to set the 7leep ode bit @7M and the 7leep -nable bit @7-M +ithin the same :!'

instruction( 7G1 and 7-G1 enables your A 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)

o+# the assembler first calculates the value of the first brac,et# @1XX7# a 1M shifted four times left @because 7 is H

and that yields 0001%0000# then calculates the second brac,et# @1XX7-# a 1M shifted five times left @because 7- is E% )he

YM bet+een the t+o brac,ets means ')3 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@1XX7 Y @1XX7-

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 C=C are intended to be manipulated in this :!' instruction%

-specially if you have to read and understand your code some months later# 7 and 7- are a better hint that the 7leep

ode and -nable bits are targeted here% ther+ise you +ould have to consult the device/s data boo, much more often%

 +." ead access to ports

eading a port/s content is in most cases possible using the ' instruction% )he follo+ing se$uence

.DEF MyPreferredRegister = R16 I& MyPreferredRegister, M"$"R 

reads the bits in port C=C to the register named MyPreferredRegister % As many ports have undefined and unused bits

in certain ports# these bits al+ays read bac, as 4eros%

ore 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=< section%

 +.% ead-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 7' @7et it 'L and C' @Clear it 'L% -5ecution is li,e this*

.E#$ AtiCe3it=0 ' >he )it th%t is to )e h%nged *3I Port3, AtiCe3it ' >he )it GAtiCe3itH ;i-- )e set to one"3I Port3, AtiCe)it ' >he )it GAtiCe3itH ;i-- )e -e%red to ero

)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% ecause C=C in the above e5amples is at he5 address Z"8# the sleep mode and enable bits can/t

be set or cleared that +ay% ut all the port bits controlling e5ternal pins @<)5# !!5# <'5 are accessible that +ay%

 +.) 6emory mapped port access

For the more e5otic programmer and the elephant3li,eM A)mega and A)Omega @+here A)-: ran out of accessible port

addresses* the ports can also be accessed using 7A access instructions# e% g% 7) and :!% Just add 0520 to the port/saddress @remember* the first "2 addresses are associated to the registers? and access the port that +ay% :i,e

demonstrated here*

.DEF MyPreferredRegister = R16 LDI /,/I/POR>3!2LDI L,LO4POR>3!2LD MyPreferredRegister, 

)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 7A is 0560 or 05100 in some larger A types%

 +.+ &etails of releant ports in the *

)he follo+ing table holds the most used ports in a smallM A)9078E1E% ot all ports are listed here# some of the -A and

A)907HH"HL8E"E types are s,ipped% 'f in doubt see the original reference%

Page 31: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 31/81

 Avr-Asm-Tutorial 27 http://www.avr-asm-tutorial.net

Component Port name Port-Register  

Accumulator 7- 7tatus egister

7tac, 7<:L7<; 7tac,pointer

-5ternal 7AL-5ternal 'nterrupt C=C C= eneral Control egister

-5ternal 'nterrupts '7N 'nterrupt as, egister

'F 'nterrupt Flag egister

)imer 'nterrupts )'7N )imer 'nterrupt as, egister

)'F )imer 'nterrupt Flag egister

83bit )imer 0 )CC0 )imerLCounter 0 Control egister

)C)0 )imerLCounter 0

163bit )imer 1 )CC1A )imerLCounter Control egister 1 A

)CC1 )imerLCounter Control egister 1

)C)1 )imerLCounter 1

C1A utput Compare egister 1 A

C1 utput Compare egister 1

'C1:L; 'nput Capture egister

&atchdog )imer &!)C &atchdog )imer Control egister

--< Access --A --< address egister

--! --< !ata egister

--C --< Control egister

7erial <eripheral 'nterface 7<' 7<C 7erial <eripheral Control egister

7<7 7erial <eripheral 7tatus egister

7<! 7erial <eripheral !ata egister

7erial Communication =A) =! =A) !ata egister

=7 =A) 7tatus egister

=C =A) Control egister

= =A) aud ate egister

Analog Comparator AC7 Analog Comparator Control and 7tatus egister

'L3<orts <)5 <ort utput egister

!!5 <ort !irection egister

<'5 <ort 'nput egister

 +., The stat$s re'ister as the most $sed port

y 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

abbreviation% ost 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# 'C#

7=# 7='# 7C# 7C'# 7'&

A!# A!'# #

'# -# C#

-# 7# C

C<# C<C# C<' C: S# 7-) S#

C:S# 7-S# )7)

A7# :7:# :7#

:#

C:

C A!!# A!C# A!'&# 7=# 7='#

7C# 7C'# 7'&

C# - C<# C<C# C<' C: C# 7-) C#

C:C# 7-C

A7# :7:# :7#

:#

3

Page 32: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 32/81

 Avr-Asm-Tutorial 28 http://www.avr-asm-tutorial.net

Bit Calculation Logic Compare Bits Shift Other  

A!!# A!C# A!'&# !-C# 'C#

7=# 7='# 7C# 7C'# 7'&

A!# A!'# #

'# -# C#

-# 7# C

C<# C<C# C<' C: # 7-) #

C:# 7-# )7)

A7# :7:# :7#

:#

C:

A!!# A!C# A!'&# !-C# 'C#7=# 7='# 7C# 7C'# 7'&

A!# A!'# #'# -# C#

-# 7# C

C<# C<C# C<' C: # 7-) #C:# 7-# )7)

A7# :7:# :7#:#

C:

7 7'& 3 3 C: 7# 7-) 7#

C:7# 7-7

3 3

; A!!# A!C# 7=# 7='# 7C#

7C'

- C<# C<C# C<' C: ;# 7-) ;#

C:;# 7-;

3 3

) 3 3 3 C: )# 7-) )#

7)# C:)# 7-)

3 3

' 3 3 3 C: '# 7-) '#

C:'# 7-'

3 -)'

 +. Port details

<ort details of the most common ports are sho+n in an e5tra table @see anne5%

Page 33: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 33/81

 Avr-Asm-Tutorial 29 http://www.avr-asm-tutorial.net

 5 ,RAMearly all A3types have static A @7A on board @only very fe+ old devices don/t% 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 7A to utili4e more space%

,.1 hat is 0*6/

7A are memories that are not

directly accessible by the central

processing unit @Arithmetic and

:ogical =nit A:=# sometimes called

accumulator 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 7A +ill

be copied to the register 2 @1stinstruction# a calculation +ith the

value in " is made and the result is

+ritten to " @second instruction%

After that this value is +ritten bac,

to the same 7A location

@instruction "# not sho+n here%

7o it is clear that operations +ith values stored in the 7A are slo+er to perform than those using registers alone% n the

other hand* even the smallest A types have 128 bytes of 7A 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 A#

e5panding the internal E12 bytes% From the assembler point3of3vie+# e5ternal 7A is accessed li,e internal 7A% o

e5tra instructions must be learned for accessing that e5ternal 7A%

 ,.2 4or what p$rposes can # $se 0*6/

esides simple storage of values# 7A offers additional opportunities for its use% ot only access +ith fi5ed addresses is

possible# but also the use of pointers# so that floating access to subse$uent locations in 7A can be programmed% )his

+ay you can build up ring buffers for interim storage of values or calculated @variable 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%

ut the most relevant use for 7A is the so3called stac,% .ou can push values @variables to that stac,% e it the content of

a register# that is temporarily needed for another purpose% e it a return address prior to calling a subroutine# or thereturn address prior to a hard+are3triggered interrupt%

,." How to $se 0*6/

 5($( 1irect addressing

)o copy a value to a memory location in 7A you have to define the address% )he 7A addresses you can use reach

from the start address @very often 050060 in smaller As# 050100 in larger A)mega to the end of the physical 7A on

the chip @in the A)9078E1E the highest accessible internal 7A location is 0502EF# see the device data sheet of your A

type for more details on this%

&ith the instruction*>* 0?0060, R1

the content of register 1 is copied to the first 7A location in address 050060% &ith

LD* R1, 0?0060 

the 7A 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# 7AT7)A) and A-!# allo+ to place your variables +ithin the 7A

space% 7o it is better to use these definitions to access the 1E th memory byte# li,e this*

LD* R1,*RAMJ*>AR>15 

7ymbolic names can be used to avoid handling fi5ed addresses# that re$uire a lot of +or,# if you later +ant to change thestructure of your data in the 7A% )hese names are easier to handle than he5 numbers# so give that address a name li,e*

Page 34: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 34/81

 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 addressingAnother ,ind of access to 7A 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 <ointer3egister3!ivision# pointer registers are the register pairs O @O;*O:#

2*26# . @.;*.:# 29*28 and S @S;*S:# "1*"0% )hey allo+ access to the location they point to directly @e% g% +ith 7)

O# 1# after prior decrementing the address by one @e% g% 7) 3O# 1 or +ith subse$uent auto3incrementation of the address

@e% g% 7) OK# 1% 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 AndetAnotherRegister = RLDI K/, /I/MyPreferred*tor%ge"e--2LDI KL, LO4MyPreferred*tor%ge"e--2

LD MyPreferredRegister, KLD AnotherRegister, KLD AndetAnotherRegister, 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 7A 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% ot 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 location050062 +ould loo, li,e this% First# the pointer register is set to our central location 7AT7)A)*

.E#$ MyPreferred*tor%ge"e-- = *RAMJ*>AR> 

.DEF MyPreferredRegister = R1LDI /, /I/MyPreferred*tor%ge"e--2LDI L, LO4MyPreferred*tor%ge"e--2

7ome+here later in the program '/d li,e to +rite to cell 2 above 7AT7)A)*

*>D !, MyPreferredRegister 

)he corresponding instruction for reading from 7A +ith an offset

LDD MyPreferredRegister, ! 

is also possible%

ote 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 7A# but +ait* the most relevant use as stac, is still to be learned%

,.% Use of 0*6 as stack

)he most common use of 7A 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% emoval 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 @:'F 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 7A 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 A type has more than 2E6 byte 7A% 'f not# 7<; is not necessary# is undefined# and must not and

cannot be used% &e assume +e have more than 2E6 bytes 7A in the follo+ing e5amples%

)o construct the stac,# the stac, pointer is loaded +ith the highest available 7A 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?%

.DEF MyPreferredRegister = R16 LDI MyPreferredRegister, /I/RAME&D2 ' $er )yteO$> *P/,MyPreferredRegister ' to st% ointer LDI MyPreferredRegister, LO4RAME&D2 ' Lo;er )yte

Page 35: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 35/81

 Avr-Asm-Tutorial 31 http://www.avr-asm-tutorial.net

O$> *PL,MyPreferredRegister ' to st% ointer 

)he value A-! is# of course# specific for the processor type% 't is defined in the 'C:=!- file for the processor type%

)he file 8E1Edef%inc has the line*

.e: RAME&D =N!5F ' L%st On("hi *RAM Lo%tion

)he file 8E1Edef%inc is included +ith the assembler directive

.I&"L$DE "@so<e;here515def.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 to of the st% 

&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 )% the C%-:e fro< the to of the st% 

&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%

ore sense ma,es the use of the stac, in subroutines# +here you have to return to the program location that called theroutine% 'n that case the calling program code pushes the return address @the current program counter value 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 ' :< to the -%)e- Gso<e;h%t@H  ...B here ;e ;i-- -%ter ontin:e ;ith the rogr%<.

;ere the >ump to the label some+hat*M some+here in the program code#

*o<e;h%t@ ' this is the :< %ddress...B /ere ;e do so<ething ...B %nd ;e %re finished %nd ;%nt to :< )% to the %--ing -o%tion@

RE> 

!uring e5ecution of the CA:: instruction the already incremented program counter# a 163bit3address# is pushed onto the

stac,# using t+o pushes @the :7 and the 7% y reaching the -) 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 7A# 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 As +ithout having 7A

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,%

ery clever is the use of the stac, +ithout first setting the stac, pointer% ecause this pointer is set to 4ero at program

start# the pointer points to the location 050000# +here register 0 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 7A there% A CA:: and -) +ill return to a strange address in program memory% e sure* there is

no +arning# li,e a +indo+ popping up saying something li,e B'llegal access to memory location 5555%

Another opportunity to construct bugs is to forget to pop a previously pushed value# or popping a value +ithout pushingone first%

Page 36: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 36/81

 Avr-Asm-Tutorial 32 http://www.avr-asm-tutorial.net

'n a very fe+ cases the stac, overflo+s to belo+ the first 7A location% )his happens in case of a never3ending recursive

call% After reaching the lo+est 7A location the ne5t pushes +rite to the ports @0500EF do+n to 050020# then to the

registers @05001F to 050000% 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?

Page 37: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 37/81

 Avr-Asm-Tutorial 33 http://www.avr-asm-tutorial.net

 9 umping 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 haens during a reset#

&hen the po+er supply voltage of an A 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% ut 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+%

)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 byone and the ne5t +ord of code is already read to the code fetch buffer @Fetch during -5ecution% '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 As e5ecute e5tremely fast# each cloc, cycle e5ecutes one instruction @if no >umps occur%

)he first instruction of an e5ecutable is al+ays located at address 0000% )o tell the compiler @assembler program 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*

."*E

.OR 0000 

)he first directive# %C7-# 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 --<

section of the chip# +here you also can +rite bytes or +ords to%

.E*E

)he third segment is the 7A section of the chip%

.D*E

ther than +ith --< content# +here content is really going to the --< during programming of the chip# the !7-

segment content is not programmed to the chip% )here is no opportunity to burn any 7A content% 7o the %!7- is only

used for correct label calculation during the assembly process% An e5ample*

.D*E ' >he fo--o;ing %re -%)e- definitions ;ithin the *RAM seg<ent MyFirst%ri%)[email protected]>E 1 ' the D*E(Pointer <oCes one )yte :;%rdsMy*eond%ri%)-eIsA4ord@

.3>E ! ' the D*E(Pointer <oCes t;o )ytes :;%rdsMy>hird%ri%)-eIsAFie-dForA3:[email protected]>E !' the D*E(Pointer <oCes ! )ytes :;%rds

7o# only three labels are defined +ithin the assembler# no content is produced%

)he directive +ithin the code segment# %# above stands for the +ord originM and manipulates the address +ithin

the code segment# +here assembled +ords go to% As our program al+ays starts at 050000 the C7-L 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 % ut be careful +ith that* nly >ump for+ard +ith %# 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 % 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-L se$uence as a signal for yourself# even though it might not be

Page 38: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 38/81

 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+% )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 -)'

@-)urn from 'nterrupt is best placed here% )he typical program se$uence at the beginning is li,e follo+s*

."*E

.OR 0000 RMP *t%rt ' the reset Cetor RMP Int*erCRo:t1 ' the interr:t serCie ro:tine for the first interr:t RE>I ' % d:<<y for %n :n:sed interr:t RMP Int*erCRo:t ' the interr:t serCie ro:tine for the third interr:t 

...B here ;e -%e %-- the other interr:t Cetor instr:tions

...B %nd here is % good -%e for the interr:t serCie ro:tines the<se-Ces

Int*erCRo:t1@  ...B "ode of the first int serCie ro:tineRE>I ' end of serCie ro:tine 1

Int*erCRo:t!@  ...B "ode of the third int serCie ro:tine

RE>I ' end of serCie ro:tine ! ...B other ode*t%rt@ ' >his here is the rogr%< st%rt ...B /ere ;e -%e o:r <%in rogr%<

)he instruction J< 7tartM results in a >ump to the label 7tart*# located some lines belo+% emember# labels al+ays end

+ith a *M% :abels# that don/t fulfill these conditions are not ta,en for serious# but interpreted as instructions% issing labels

result in an error message @I=ndefined labelI# 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

ranching is very often depending on some condition# called conditional branching% As an e5ample +e assume +e +ant to

construct a "23bit3counter using the registers 1 to H% )he least significant byte in 1 is incremented by one% 'f the

register overflo+s during that operation @2EE K 1 G 0# +e have to increment 2 similarly% 'f 2 overflo+s# +e have to

increment "# and so on%

'ncrementation by one is done +ith the instruction 'C% 'f an overflo+ occurs during that e5ecution of 'C 1# the 4ero bit

in the status register is set to one @the result of the operation is 4ero% )he carry bit in the status register# as usually set

+hen something overflo+s# is not changed during an 'C% )his is not to confuse the beginner# but carry can be used forother purposes instead% )he Sero3it 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 S but - @anch if ot -$ual% A matter of taste %%%

)he +hole count se$uence of the "23bit3counter should then loo, li,e this*

I&" R1 ' inre%se ontent of register R13R&E oOn! ' if not ero, )r%nh to oOn!@I&" R! ' inre%se ontent of register R! 3R&E oOn! I&" R3R&E oOn! I&" R7

 oOn!@

7o that/s about it% An easy thing% )he opposite condition to - is -P or anch -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 3R""2 or 1 3R"*23R*/ -%)e-' E:%- or gre%ter 3RLO -%)e-' *<%--er 3RMI -%)e-' Min:s3RPL -%)e-' P-:s3RE -%)e-' re%ter or e:%- ;ith sign )it23RL> -%)e-' *<%--er ;ith sign )it23R/" -%)e-Q3R/* -%)e-' /%-f oCerf-o; f-%g 0 or 1

3R>" -%)e-Q3R>* -%)e-' >(3it 0 or 13R" -%)e-Q3R* -%)e-' >;os o<-e<ent f-%g 0 or 13RIE -%)e-Q3RID -%)e-' Interr:t en%)-ed or dis%)-ed 

Page 39: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 39/81

 Avr-Asm-Tutorial 35 http://www.avr-asm-tutorial.net

to react to the different conditions% ranching 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 ;4 cloc, fre$uency then one instruction re$uires 1LH [s or 2E0 ns# at 10 ;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 A is the optimal solution for your

problem% ote that there are a fe+ instructions that re$uire t+o or more cycles# e% g% the branching instructions @if

branching occurs or the 7A 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 <% )his is the most useless

instruction*

&OP 

)his instruction does nothing but +asting processor time% At H ;4 cloc, +e need >ust four of these instructions to +aste

1 [s% o other hidden meanings here on the < instruction% For a signal generator +ith 1 ,;4 +e don/t need to add H000such 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 y-e"o:nt@

DE" R1 ' one -o y-e3R&E "o:nt ' t;o for )r%nhing, one for not )r%nhing 

)his se$uence +astes @1 K @2EED2 K @1D" G E1H cloc, cycles or 128%E [s at H ;4%

163bit counting can also be used to delay e5actly# li,e this

LDI /,/I/65552 ' one -o y-e

LDI L,LO465552 ' one -o y-e"o:nt@*3I4 L,1 ' t;o -o y-es3R&E "o:nt ' t;o for )r%nhing, one for not )r%nhing 

)his se$uence +astes @1K1 K @6EE"HDH K @1D" G 262#1H1 cloc, cycles or 6E#E"E%2E [s at H ;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

ery 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% acros are code se$uences# designed and tested once# and inserted into the code by its macroname% As an e5ample +e assume +e need to delay program e5ecution several times by 1 [s at H ;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*

...B so<e;here in the so:re ode

De-%y1...B ode goes on here

)his results in four < instructions inserted to the code at that location% An additional !elay1M inserts additional four

< 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%

y calling a macro by its name you can add some parameters to manipulate the produced code% ut 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

Page 40: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 40/81

 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 re: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 !elay10*M% )hree <s

follo+ and a -) instruction% 'f you count the necessary cycles you >ust find cycles @" for the <s# H for the -)% )he

missing " are for calling that routine*

...B so<e;here in the so:re ode@R"ALL De-%y10 

...B f:rther on ;ith the so:re ode

CA:: 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 -) instruction >umps bac, to the calling routine% ote that before you use subroutine

calls you must set the stac, pointer @see 7tac,# because the return address must be pac,ed on top of the stac, during the

CA:: instruction%

'f you +ant to >ump directly to some+here else in the code you have to use the >ump instruction*

...B so<e;here in the so:re odeRMP De-%y10 

Ret:[email protected] f:rther on ;ith so:re ode

ote that J< is also a relative >ump instruction +ith limited distance% nly A)mega As have a J< instruction

allo+ing >umps over the complete flash memory space# but these instructions re$uire t+o +ords and more instruction

time than J<# so avoid it if possible%

)he routine that you >umped to can not use the -) instruction in that case# because J< 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%

CA:: and J< 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

@confusing 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 ' *i the ne?t instr:tion if )it 8 in register 1 is 0 R"ALL $L%)e- ' "%-- th%t s:)ro:tine

7C reads B7,ip ne5t instruction if it in egister 1 is Clear @GSero% )he CA:: instruction to =p:abel*M is only

e5ecuted if bit in register 1 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 77% )he instruction follo+ing 77L7C can be a single

+ord or double +ord instruction# the processor ,no+s ho+ far he has to >ump over it% ote 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<%re R1 %nd R!, si ne?t instr:tion if e:%- 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 7'C and 7'7% )hat reads 7,ip if the it in 'Lo space is Clear @or 7etM# li,e this*

*3I" PI&3,0 ' *i ne?t instr:tion if 3it 0 on in:t ort 3 is 0 RMP A>%rget ' :< to the -%)e- A>%rget 

)he J<3instruction is only e5ecuted if bit 0 in port 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%

o+# 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 % !epending on the state of these H bits +e +ould li,e to >ump to 16 different locations in thecode% o+ +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>%)@RMP Ro:tine1RMP Ro:tine! ...B RMP Ro:tine16 

'n our code +e copy that address of the table to the S pointer register*

LDI /,/I/My>%)2LDI L,LO4My>%)2

and add the current state of the port @in 16 to this address%

 ADD L,R16 3R"" &oOCerf-o; 

Page 41: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 41/81

 Avr-Asm-Tutorial 37 http://www.avr-asm-tutorial.net

I&" /  &oOCerf-o;@

o+ +e can >ump to this location in the table# either for calling a subroutine*

I"ALL ' %-- the s:)ro:tine ;hih %ddress is in  

or as a >ump +ith no +ay bac,*

IMP ' :< to %ddress in  

)he processor loads the content of the S register pair into its program counter and continues operation there% ore clever

than branching over and over(

.+ #nterr$pts and pro'ram e!ec$tion

ery 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 7A description%

&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 e5ecution% After that# processing >umps to the predefined location# the interruptvector# and e5ecutes the instructions there% =sually the instruction there is a J=< 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 A types are listed in the follo+ing table% @)he first

vector isn/t an interrupt but the reset vector# performing no stac, operation?

Name Interrupt Vector !!ress

"#$# "#"# %&$&

'riggere! () 

-7-) 0000 0000 0000 ;ard+are eset# <o+er3n3eset# &atchdog eset

')0 0001 0001 0001 :evel change on the e5ternal ')0 pin

')1 0002 3 0002 :evel change on the e5ternal ')1 pin

)'-1CA<) 000" 3 000" Capture event on )imerLCounter 1

)'-1C<A 3 3 000H )imerLCounter 1 G Compare value A

)'-1 C< 3 3 000E )imerLCounter 1 G Compare value

)'-1 C<1 000H 3 3 )imerLCounter 1 G Compare value 1

)'-1 F 000E 3 0006 )imerLCounter 1 verflo+

)'-0 F 0006 0002 000 )imerLCounter 0 verflo+

7<' 7)C 3 3 0008 7erial )ransmit Complete

=A) )O 000 3 0009 =A) char in receive buffer available

=A) =!- 0008 3 000A =A) transmitter ran empty

=A) )O 0009 3 000 =A) All 7ent

AATC< 3 3 000C Analog Comparator

ote 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 A 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 

Page 42: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 42/81

 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:t En%)-ed RE> ' Ret:rn

)his is not the same as the -)'# 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,% o bug is to be e5pected# but it is an

unnecessary ris, doing that% 7o >ust use the -)' 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 -)' 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

-)' +ould reset the other+ise never3ending interrupts% )his is the case +ith some of the =A) interrupts%

ote that larger devices have a t+o3+ord organi4ation of the vector table% 'n this case the J< instruction has to be used

instead of J<% And -)' instructions must be follo+ed by an < 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% ore 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 sae 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 -)' 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 originalcontent% )he follo+ing sho+s e5amples ho+ to do that*

7aving in a register* 7aving on the stac,*

Isr@ Isr@I& R15,*RE ' s%Ce f-%gs P$*/ R15 ' s%Ce register on st%  ... <ore instr:tions...B I& R15, *RE

...<ore instr:tions...B O$> *RE,R15 ' restore f-%gs O$> *RE,R15 ' restore f-%gs

POP R15 RE>I ' ret:rn fro< interr:t RE>I ' ret:rn fro< interr:t  

)he method on the right is slo+er# the method on the left re$uires a register e5clusively for that purpose%

enerally* 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% ever change the content of a register +ithin an int service routine that isused some+here else in the normal program +ithout restoring it%

ecause of these basic re$uirements a more sophisticated e5ample for an interrupt service routine here%

."*E ' "ode(*eg<ent st%rts here

.OR 0000 ' Address is eroRMP *t%rt ' >he reset(Cetor on Address 0000 RMP I*erCie ' 0001@ first Int(etor, I&>0 serCie ro:tine

...B here other Cetors*t%rt@ ' /ere the <%in rogr%< st%rts...B here is eno:gh s%e for defining the st% %nd other things I*erCie@ ' /ere ;e st%rt ;ith the Interr:t(*erCie(Ro:tine

P$*/ R16 ' s%Ce % register to st% I& R16,*RE ' re%d st%t:s register 

P$*/ R16 ' %nd :t on st% ...B /ere the Int(*erCie(Ro:tine does so<ething %nd :ses R16 

POP R16 ' get reCio:s f-%g register fro< st% O$> *RE,R16 ' restore o-d st%t:sPOP R16 ' get reCio:s ontent of R16 fro< the st% 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; 16 and <<

16 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 routine# 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 -)'# 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%

Page 43: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 43/81

 Avr-Asm-Tutorial 39 http://www.avr-asm-tutorial.net

 * Calculations;ere +e discuss all necessary instructions for calculating in A 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 @ytes# &ords# :ong+ords# etc%#

• 7igned +hole numbers @7hort'nts# 'ntegers# :ong'nts# etc%#

• inary Coded !igits @C!#

• <ac,ed C!s#

• A7C''3formatted numbers%

'f you come from a high3level language* forget pre3defined number formats% Assembler doesn/t have that concept nor its

@sometimes frustating limitations% &hat you earn is* you are the master of your o+n format?

 *(( 'ositie &hole numbers bytes3 &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 C=% 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"E# three bytes form a longer +ord @range from 0 %% 16##21E

and four bytes form a double +ord @range from 0 %% H#29H#96#29E%

)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 r1 = d;! 

.DEF r19 = d;

egisters 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#000# this should loo, li,e this*

.E#$ d;i = 7000000 ' define the onst%nt LDI d;0,LO4d;i2 ' >he -o;est )its to R16 LDI d;1,3>E!d;i2 ' )its .. 15 to R18 LDI d;!,3>Ed;i2 ' )its 16 .. ! to R1 LDI d;,3>E7d;i2 ' )its !7 .. 1 to R19

7o +e have splitted this decimal number# called d+i# to its binary portions .)-H to .)-1 and pac,ed them into the four

byte pac,ages% o+ you can calculate +ith this double +ord%

*((# ,igned numbers integersD

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+% )he first bit is the sign bit# signaling that this is a negative number% &hy this different format @subtracting the

number from 0 is used is easy to understand* adding 31 @1111%1111 and K1 @0000%0001 yields e5actly 4ero# if you forget

the overflo+ that occurs during that operation @to the ninth bit%

'n one byte the largest integer number to be handled is K12 @binary 01111111# the smallest one is 3128 @binary

1#0000000% '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#6 %% 3"2#68# four bytes provide a range from

K2#1H#H8"#6H %% 32#1H#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 %% 1001# 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%*

Page 44: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 44/81

 Avr-Asm-Tutorial 40 http://www.avr-asm-tutorial.net

Bit *alue $"% +, #" $+ % , " $

16# !igit 1 G2 0 0 0 0 0 0 1 0

1# !igit 2 G E 0 0 0 0 0 1 0 1

18# !igit " G 0 0 0 0 0 0 0 0 0

'Instr:tions to :se@LDI R16,! LDI R18,5 LDI R1,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 As for ban,ing applications# 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 A assembler language% )he decimal number 2E0

+ould loo, li,e this +hen formatted as a pac,ed C!*

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! ' $er )yte

LDI R16,0?50 ' Lo;er )yte

)o set this correct you can use the binary notation @0b%%% or the he5adecimal notation @05%%% to set the proper bits to their

correct nibble position%

Calculating +ith pac,ed C!s is a little more complicated compared to the binary form% Format changes to character

strings are nearly as easy as +ith C!s% :ength of numbers and precision of calculations is only limited by the storage

space%

*((0 6umbers in A,CII-format

ery similar to the unpac,ed C! 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 'nterchange 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(# very limited in range for other than =7 languages @only bits per

character# 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 audot set or the orse 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%0000# digit 9

is E decimal @he5 05"9# binary 0b0011%1001% 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

C! @or set bit H and E to 1 to convert a C! to A7C''% A7C'' formatted numbers need the same storage space li,e C!s%

:oading 2E0 to a register set representing that number +ould loo, li,e this*

LDI R1,! LDI R18,5 LDI R16,0 

)he A7C'' representation of these characters are +ritten to the registers%

9.2 ;it manip$lations

)o convert a C! coded digit to its A7C'' representation +e need to set bit H and E to a one% 'n other +ords +e need to

the C! +ith a constant value of he5 05"0% 'n assembler this is done li,e this*

ORI R16,0?0 

'f +e have a register that is already set to he5 05"0 +e can use the +ith this register to convert the C!*

OR R1,R! 

ac, from an A7C'' character to a C! is as easy% )he instruction

 A&DI R16,0?0F 

Page 45: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 45/81

 Avr-Asm-Tutorial 41 http://www.avr-asm-tutorial.net

isolates the lo+er four bits @G the lo+er nibble% ote that ' and A!' are only possible +ith registers above 1E% 'f you

need to do this# use one of the registers 16 to "1?

'f the he5 value 050F is already in register 2# you can A! 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 1E% )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 ero

'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

constant*

LDI R16,0)10101010 ' InCert %-- :neCen )itsEOR 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 1 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 4ero% )his is done +ith the

instruction

&E R1

7o K1 @decimal* 1 yields 31 @binary 1%1111111# K2 yields 32 @binary 1%1111110# and so on%

esides 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 1% )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!,! ' oy >()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%

ultiplication +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 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# :7%

L*R R1

)he former bit # 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 result% -5ample# division by four +ith

rounding*

L*R R1 ' diCision )y ! 3R"" DiC! ' :< if no ro:nd :I&" R1 ' ro:nd :

DiC!@

L*R R1 ' One %g%in diCision )y ! 3R"" DiCE ' :< if no ro:nd :I&" R1 ' Ro:nd $

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 % )he instruction Barithmetic shift

right A7 leaves bit untouched and shifts the 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 is shifted to the carry during rotation%

Page 46: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 46/81

 Avr-Asm-Tutorial 42 http://www.avr-asm-tutorial.net

L*L R1 ' Logi%- *hift Left of the -o;er )yteROL R! ' ROt%te Left of the :er )yte

)he logical shift left in the first instruction shifts bit to carry# the : instruction rolls it to bit 0 of the upper byte%

Follo+ing the second instruction the carry bit has the former bit of the upper byte% )he carry bit can be used to either

indicate an overflo+ @if 163bit3calculation is performed or to roll it into more upper bytes @if more than 16 bit calculation is

done%

olling to the right is also possible# dividing by 2 and shifting carry to bit 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 C!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 R1ROR R1

ROR R1ROR R1

+e can perform that +ith a single

*4AP R1

)his instruction e5changes the upper and lo+er nibble% ote 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% ead on your o+n ris,?

 *(.( Adding and subtracting 2-bit numbers

)o start complicated +e add t+o 163bit3numbers in 1*2 and "*H% @'n this notation# +e mean that the first register is

the most significant byte# the second the least significant%

 ADD R!,R7 ' first %dd the t;o -o;()ytes AD" R1,R ' 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 "*H from 1*2%

*$3 R!,R7 ' first the -o;()yte

*3" R1,R ' 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

o+ +e compare a 163bit3+ord in 1*2 +ith the one in "*H to evaluate +hether it is bigger than the second one%

'nstead of 7= +e use the compare instruction C<# instead of 7C +e use C<C*

"P R!,R7 ' o<%re -o;er )ytes"P" R1,R ' o<%re :er )ytes

'f the carry flag is set no+# 1*2 is smaller than "*H%

 *(.($ Comparing &ith constants

o+ +e add some more complicated stuff% &e compare the content of 16 +ith a constant* 0b10101010%

"PI R16,0?AA

'f the Sero3bit in the status register is set after that# +e ,no+ that 16 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 1 is 4ero or negative*

>*> R1

'f the S3bit is set# the register 1 is 4ero and +e can follo+ +ith the instructions -P# -# '# <:# :# 7;#

-# :)# C or 7 to branch around a little bit%

Page 47: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 47/81

 Avr-Asm-Tutorial 43 http://www.avr-asm-tutorial.net

 *(.(. 'ac@ed BC1 math

7till +ith us( 'f yes# here is some pac,ed C! calculations% Adding t+o pac,ed C!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 C!s H9 @Ghe5 H9 and 99 @Ghe5 99 to yield 1H8 @Ghe5 0501H8% Adding these inbinary 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 9 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? ut the lo+er nibble should be 8 and is only 2 @18 G

0b0001%0010% &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 C!% 'f +e add 6 to this 05- +e get to 05H and the carry is set @G051H% 7o the tric, is to first add these t+o

numbers and then add 0566 to correct the 2 digits of the pac,ed C!% ut 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 C= 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 nibbles# add 6 to correct# if not# do step

2%

2% Add 6 to the nibble% 'f overflo+ occurs @C resp% ;# you/re done% 'f not# subtract 6%

)o program an e5ample +e assume that the t+o pac,ed C!s are in 2 and "# 1 +ill hold the overflo+# and 16 and 1

are available for calculations% 16 is the adding register for adding 0566 @the register 2 cannot add a constant value# 1

is used to correct the result depending from the different flags% Adding 2 and " 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!,R ' %dd the t;o t;o(digit(3"Ds3R"" &o"y1 ' :< if no )yte oCerf-o; o:rsI&" R1 ' inre<ent the ne?t higher )yte

 A&DI R18,0?0F ' dont s:)tr%t 6 fro< the higher ni))-e&o"y1@

3R/" &o/1 ' :< if no h%-f(%rry o:rred  A&DI R18,0?F0 ' dont s:)tr%t 6 fro< -o;er ni))-e

&o/1@ ADD R!,R16 ' %dd 0?66 to res:-t 3R"" &o"y! ' :< if no %rry o:rred I&" R1 ' inre<ent the ne?t higher )yte

 A&DI R18,0?0F ' dont s:)tr%t 6 fro< higher ni))-e&o"y!@

3R/" &o/! ' :< if no h%-f(%rry o:rred  A&DI R18,0?F0 ' dont s:)tr%t 6 fro< -o;er ni))-e

&o/!@*$3 R!,R18 ' s:)tr%t orretion

 A little bit shorter than that*

LDI R16,0?66  ADD R!,R16  ADD R!,R3R"" &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 conersion for n$mbers

All number formats can be converted to any other format% )he conversion from C! to A7C'' and vice versa +as already

sho+n above @it manipulations%

*(0( Conersion of pac@ed BC1s to BC1s3 A,CII or Binaries

Conversion of pac,ed C!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 A!ing +ith 050F% o+ +e have the C! of the upper nibble and +e can either use as is @C! 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

Page 48: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 48/81

 Avr-Asm-Tutorial 44 http://www.avr-asm-tutorial.net

7&A<ping and get the lo+er C!%

A little bit more complicated is the conversion of C! 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 C! digit% efore

adding this to the result +e multiply the result +ith 10% @ote that in the first step this is not necessary# because the result

is 4ero either%

'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% rolls% Adding the previously copied number to this yields a multiplication +ith E% o+ a multiplication +ith 2

@left shiftLroll yields the 103fold of the result% Finally +e add the C! and repeat that algorithm until all decimal digits are

converted% 'f# during one of these operations# there occurs a carry of the result# the C! is too large to be converted% )his

algorithm handles numbers of any length# as long as the result registers are prepared%

 *(0(# Conersion of Binaries to BC1

)he conversion of a binary to C!s is more complicated than that% 'f +e convert a 163bit3binary +e can subtract 10#000

@05210# until an overflo+ occurs# yielding the first digit% )hen +e repeat that +ith 1#000 @050"-8 to yield the second

digit% And so on +ith 100 @05006H and 10 @05000A# 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*

De>%)@.D4 10000, 1000, 100, 10 

and can be read +ord3+ise +ith the :< instruction from the table%

An alternative is a table that holds the decimal value of each bit in the 163bit3binary# e% g%

.D3 0,,!,8,6, 

.D3 0,1,6,,,7

.D3 0,0,,1,9,! 

.D3 0,0,7,0,9,6 

.D3 0,0,!,0,7, ' %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 :<% )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 C! +ith itself# each time after you

have shifted a bit from the binary to the right# and added to the C! result%

any methods# much to optimi4e here%

 9.+ 6$ltiplication

ultiplication 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

o+ in binary% ultiplication +ith the single digits is not necessary# because there are only the digits 1 @add the number

and 0 @don/t add the number% ultiplication by 10 in decimal goes to multiplication by 2 in binary mode% ultiplication 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(

Page 49: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 49/81

 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:-t.%s< <:-ti-ies t;o ()it(n:<)ers to yie-d % 16()it(res:-t '

.&OLI*> .I&"L$DE "@%Crtoo-s%notes515def.in 

.LI*> '' F-o; of <:-ti-i%tion'' 1.>he )in%ry to )e <:-ti-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 <:-ti-ied )y ! )y rot%ting it one osition -eft, shifting % 0 into the Coid osition.' .If the )in%ry to )e <:-ti-ied ;ith is not ero, the <:-ti-i%tion -oo is ree%ted. If it is ero, the <:-ti-i%tion is done.'' $sed registers'.DEF r<1 = R0 ' 3in%ry n:<)er to )e <:-ti-i%ted 3it2.DEF r<h = R1 ' Interi< stor%ge

.DEF r<! = R! ' 3in%ry n:<)er to )e <:-ti-i%ted ;ith 3it2.DEF re- = R ' Res:-t, L*3 16 3it2

.DEF reh = R7 ' Res:-t, M*3

.DEF r< = R16 ' M:-ti :rose register for -o%ding '."*E.OR 0000 '  r< *>AR> '*>AR>@  -di r<,0?AA ' e?%<-e )in%ry 1010.1010   <oC r<1,r< ' to the first )in%ry register   -di r<,0?55 ' e?%<-e )in%ry 0101.0101  <oC r<!,r< ' to the seond )in%ry register '' /ere ;e st%rt ;ith the <:-ti-i%tion of the t;o )in%ries in r<1 %nd r<!, the res:-t ;i-- go to reh@re- 16 3it2'M$L>@'' "-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 <:-ti-i%tion -oo'M$L>%@'' *te 1@ Rot%te -o;est )it of )in%ry n:<)er ! to the %rry f-%g diCide )y !, rot%te % ero into )it 82'  - ' -e%r %rry )it   ror r<! ' )it 0 to %rry, )it 1 to 8 one osition to the right, %rry )it to )it 8 '' *te !@ 3r%nh deending if % 0 or 1 h%s )een rot%ted to the %rry )it '  )r M$L>) ' :< oCer %dding, if %rry h%s % 0 '' *te @ 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>)@'' *te 7@ M:-ti-y r<h@r<1 )y ! 16 )its, shift -eft2

'  - ' -e%r %rry )it   ro- r<1 ' rot%te L*3 -eft <:-ti-y )y !2  ro- r<h ' rot%te %rry into M*3 %nd M*3 one -eft '' *te 5@ "he if there %re sti-- ones in )in%ry !, if yes, go on <:-ti-i%ting '  tst r<! ' %-- )its eroS  )rne M$L>% ' if not, go on in the -oo'' End of the <:-ti-i%tion, res:-t in reh@re- '' End-ess -oo'LOOP@

  r< -oo

Page 50: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 50/81

 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 : and % )hese instructions shift all

bits of a register one position left @: resp% right@% )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 : and 05EE as an e5ample for %

 *(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 "%

)he ob>ect3code has been opened#

the cursor is placed on the first

e5ecutable instruction% F11 does

single steps%

 

)he registers 0 and 2 are set to

05AA and 05EE# our test binaries# tobe multiplied%

 

Page 51: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 51/81

 Avr-Asm-Tutorial 47 http://www.avr-asm-tutorial.net

2 is rotated to the

right# to roll the least

significant bit into the

carry bit% 05EE

@0101%0101 yielded

052A @0010%1010%

 

ecause the carry bit

had a one# the content

of the registers 1*0 is

added to the @empty

register pair H*"#

resulting in 0500AA

there%

 

o+ the register pair

1*0 is rotated one

position left to multiply

this binary by 2% From

0500AA# multiplication

by 2 yields 0501EH%

)he +hole multipli]

cation loop is repeatedas long there is at least

one binary 1 in register

2% )hese follo+ing

loops are not sho+n

here%

 

Page 52: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 52/81

 Avr-Asm-Tutorial 48 http://www.avr-asm-tutorial.net

=sing ,ey FE of the

studio +e multi3

stepped over theseloops to a brea,point

at the end of the

multiplication routine%

)he result register

pair H*" has the

result of the

multiplication of 05AA

by 05EE* 05"82%

 

)his +asn/t that complicated# >ust remind yourself on the similar decimal operations% inary multiplication is much easier

than decimal%

 9., Hardware m$ltiplication

All A)mega# A)Omega# A)90CA and A)90<& 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 16 and 1# >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 1 @most

significant byte and 0 @least significant

byte% )hat/s all about it%

)he program demonstrates the simulation in the 7tudio% 't multiplies decimal 2E0 @he5 FA by decimal 100 @he5 6H# in the

registers 16 and 1%

Page 53: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 53/81

 Avr-Asm-Tutorial 49 http://www.avr-asm-tutorial.net

After e5ecution# the registers

0 @:7 and 1 @7 hold

the result he5 61A8 or

decimal 2E#000%

And* yes# that re$uires only

t+o cycles# or 2 microseconds

+ith a 1 csLs 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 solvethe 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 m1*m1: are simply t+o 83bit3binaries m1 and m1:# +here the most significant one m1

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 100 plus "H# or @1 multiplied by 1000 plus @2 multiplied by 100 plus @" multiplied by 10 plus H%

7o the 163bit3binary m1 is e$ual to 2E6Dm1 plus

m1:# +here m1 is the 7 and m1: is the :7%

ultiplying m1 by 83bit3binary m2 so is#

mathematically formulated*

● m1 D m2 G @2E6Dm1 K m1: D m2# or

● 2E6Dm1Dm2 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 <:-ti-i%tion 16()y(()it '' Register definitions@'.def Res1 = R! .def Res! = R.def Res = R7.def <1L = R16 .def <1M = R18 .def <! = R1 

First +e load the numbers*

'' Lo%d Registers'.e: <1 = 10000 '

-di <1M,/I/<12 ' :er )its of <1 to <1M -di <1L,LO4<12 ' -o;er )its of <1 to <1L-di <!,!50 ' ()it onst%nt to <! 

)he t+o numbers are loaded into 1*16 @dec 10000 G he5 210

and 18 @dec 2E0 G he5 FA%

)hen +e multiply the :7 first*

Page 54: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 54/81

 Avr-Asm-Tutorial 50 http://www.avr-asm-tutorial.net

'' M:-ti-y '

<:- <1L,<! ' M:-ti-y L*3<oC Res1,R0 ' oy res:-t to res:-t register <oC Res!,R1

)he :7 multiplication of he5 2 by he5 FA yields he5 0F0A# +ritten to

the registers 00 @:7# he5 A0 and 01 @7# he5 0F% )he result is

copied to the lo+er t+o bytes of the result register# "*2%

o+ the multiplication of the 7 of m1 +ith m2 follo+s*

<:- <1M,<! ' M:-ti-y M*3

)he multiplication of the 7 of m1# he5 10# +ith m2# he5 FA# yields

he5 2616 in 1*0%

o+ t+o steps are performed at once* multiplication by 2E6 and

adding the result to the previous result% )his is done by adding 1*0 to

es"*es2 instead of es2*es1% 1 can >ust be copied to es"% 0 is

added to es2 then% 'f the carry is set after adding# the ne5t higher bytees" is increased by one%

<oC Res,R1 ' oy M*3 res:-t to res:-t )yte %dd Res!,R0 ' %dd L*3 res:-t to res:-t )yte ! )r &oIn ' if not %rry, :<in Res

&oIn@

)he result in H*"*2 is he5 262EA0# +hich is decimal 2E00000 @as

everybody ,no+s# and is obviously correct%

)he cycle counter of the multiplication points to 10# at 1 ;4 cloc, a

total of 10 microseconds% ery much faster than soft+are

multiplication?

 *(5($ %ard&are multiplication of a 2- by a 2-bit-binary

o+ that +e have understood the principle# it should be easy to do 163by316% )he result re$uires four bytes no+

@esH*es"*es2*es1# located in E*H*"*2% )he formula is*

Page 55: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 55/81

 Avr-Asm-Tutorial 51 http://www.avr-asm-tutorial.net

m1 D m2 G @2E6Dm1 K m1: D

@2E6Dm2 K m2:

G 6EE"6Dm1Dm2 K

2E6Dm1Dm2: K

2E6Dm1:Dm2 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:-ti-i%tion 16 )y 16 '' Define Registers'.def Res1 = R! .def Res! = R.def Res = R7.def Res7 = R5 .def <1L = R16 .def <1M = R18 .def <!L = R1 .def <!M = R19.def t< = R!0 '' Lo%d in:t C%-:es'

.e: <1 = 10000 

.e: <! = !5000 '

-di <1M,/I/<12-di <1L,LO4<12-di <!M,/I/<!2-di <!L,LO4<!2

'' M:-ti-y '

-r R!0 ' -e%r for %rry oer%tions<:- <1M,<!M ' M:-ti-y M*3s<oC Res,R0 ' oy to M*4 Res:-t <oC Res7,R1<:- <1L,<!L ' M:-ti-y L*3s

<oC Res1,R0 ' oy to L*4 Res:-t <oC Res!,R1<:- <1M,<!L ' M:-ti-y 1M ;ith !L%dd Res!,R0 ' Add to Res:-t %d Res,R1%d Res7,t< ' %dd %rry <:- <1L,<!M ' M:-ti-y 1L ;ith !M %dd Res!,R0 ' Add to Res:-t %d Res,R1%d Res7,t<

'' M:-ti-i%tion done'

7imulation sho+s the follo+ing steps%

:oading the t+o constants 10000 @he5 210 and 2E000 @he5 61A8 to

the registers in the upper register space %%%

ultiplying the t+o 7s @he5 2 and 61 and copying the result in 1*0 to the t+o most upper result registers E*H %%%

Page 56: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 56/81

 Avr-Asm-Tutorial 52 http://www.avr-asm-tutorial.net

ultiplying the t+o :7s @he5 10 and A8 and copying the result in

1*0 to the t+o lo+er result registers "*2 %%%

ultiplying the 7 of m1 +ith the :7 of m2 and adding the result in

1*0 to the result register/s t+o middle bytes# no carry occurred %%%

ultiplying the :7 of m1 +ith the 7 of m2 and adding the result in

1*0 to the result register/s t+o middle bytes# no carry occurred% )he

result is he5 0--6280# +hich is 2E0000000 and obviously correct %%%

ultiplicationneeded 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 carry% 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 83by383bit multiplications and adding

the results to the appropriate position

in the result registers%

)he assembler source code for this*

' /%rd;%re M:-ti-i%tion 16 )y !7 )it .in-:de <def.in '

' Register definitions.def %1 = R! ' define 16()it register .def %! = R

Page 57: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 57/81

 Avr-Asm-Tutorial 53 http://www.avr-asm-tutorial.net

.def )1 = R7 ' define !7()it register 

.def )! = R5 

.def ) = R6 

.def e1 = R8 ' define 70()it res:-t register 

.def e! = R 

.def e = R9

.def e7 = R10 .def e5 = R11

.def 0 = R1! ' he- register for %dding 

.def r- = R16 ' -o%d register '' Lo%d onst%nts.e: % = 10000 ' <:-ti-i%tor %, he? !810 .e: ) = 1000000 ' <:-ti-i%tor ), he? 0F7!70 

-di r-,3>E1%2 ' -o%d %<oC %1,r- -di r-,3>E!%2<oC %!,r- -di r-,3>E1)2 ' -o%d )<oC )1,r- -di r-,3>E!)2

<oC )!,r- -di r-,3>E)2<oC ),r- 

'' "-e%r registers

-r e1 ' -e%r res:-t registers-r e! -r e-r e7-r e5 -r 0 ' -e%r he- register 

'' M:-ti-y 

<:- %!,) ' ter< 1%dd e7,R0 ' %dd to res:-t 

%d e5,R1<:- %!,)! ' ter< ! %dd e,R0 %d e7,R1%d e5,0 ' %dd ossi)-e %rry2<:- %!,)1 ' ter< %dd e!,R0 %d e,R1%d e7,0 %d e5,0 <:- %1,) ' ter< 7%dd e,R0 %d e7,R1%d e5,0 <:- %1,)! ' ter< 5 %dd e!,R0 %d e,R1%d e7,0 %d e5,0 <:- %1,)1 ' ter< 6 %dd e1,R0 %d e!,R1%d e,0 %d e7,0 %d e5,0 

'' done.

no' 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. &iision

o# unfortunately there is no hard+are division% .ou need to do this in soft+are?

 *(9( 1ecimal diision

Again +e start +ith the decimal division# to better understand the binary division% &e assume a division of E68 by 12%

)his is done li,e this*

Page 58: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 58/81

 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 diision

'n binary the multiplication of the second number in the above decimal e5ample @H D 1200# etc% 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 A assembler is listed in the follo+ing section%

' DiC diCides % 16()it(n:<)er )y % ()it(n:<)er >est@ 16()it(n:<)er@ 0?AAAA, ()it(n:<)er@ 0?552.&OLI*> .I&"L$DE "@%Crtoo-s%notes515def.in ' %d:st the orret %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! = R ' ()it(n:<)er to diCide ;ith.DEF re- = R7 ' L*3 res:-t .DEF reh = R5 ' M*3 res:-t .DEF r< = R16' <:-ti:rose register for -o%ding 

'."*E.OR 0   r< st%rt st%rt@' Lo%d the test n:<)ers to the %rori%te registers  -di r<,0?AA ' 0?AAAA to )e diCided   <oC rd1h,r<  <oC rd1-,r<  -di r<,0?55 ' 0?55 to )e diCided ;ith  <oC rd!,r<' DiCide rd1h@rd1- )y rd! diC@  -r rd1: ' -e%r interi< register   -r reh ' -e%r res:-t the res:-t registers

  -r re- ' %re %-so :sed to o:nt to 16 for the  in re- ' diCision stes, is set to 1 %t st%rt2' /ere the diCision -oo st%rtsdiC%@  - ' -e%r %rry()it   ro- rd1- ' rot%te the ne?t(:er )it of the n:<)er   ro- rd1h ' to the interi< register <:-ti-y )y !2  ro- rd1:  )rs diC) ' % one h%s ro--ed -eft, so s:)tr%t   rd1:,rd! ' DiCision res:-t 1 or 0S  )rs diC ' :< oCer s:)tr%tion, if s<%--er diC)@  s:) rd1:,rd!' s:)tr%t n:<)er to diCide ;ith  se ' set %rry()it, res:-t is % 1  r< diCd ' :< to shift of the res:-t )it 

diC@  - ' -e%r %rry()it, res:-ting )it is % 0 diCd@  ro- re- ' rot%te %rry()it into res:-t registers  ro- reh  )r diC% ' %s -ong %s ero rot%te o:t of the res:-t registers@ go on ;ith the diCision -oo' End of the diCision re%hed sto@  r< sto ' end-ess -oo

 *(9($ 'rogram steps during diision

!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%#

Page 59: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 59/81

 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 2# 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(. 1iision in the simulator 

)he follo+ing screen shots demonstrate the

program steps in the studio @here in version "# so it

loo,s different% )o do this# you have to assemble

the source code and open the resulting ob>ect filein the studio%

)he ob>ect code has been started# the cursor

@yello+ arro+ 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 1*0 and

"%

 

)he interim register 2 and the

result register pair are set to their

predefined values%

Page 60: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 60/81

 Avr-Asm-Tutorial 56 http://www.avr-asm-tutorial.net

1*0 +as rotated left to 2#

from 05AAAA the doubled value

of 0501EEEH +as yielded%

o overflo+ from rotation into

carry has occurred and 0501 in

2 +as smaller than 05EE in "#

so subtraction +as s,ipped% A

4ero in the carry is rotated intothe result register E*H% )he

former content of the result

register# a single 13bit in position

0 has rotated to position 1

@content no+* 050002% 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 16times +e have reached the

brea,point set at the end of

the division routine% )he

result register in E*H holds

050202# the result of the

division% )he registers

2*1*0 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 menu% A rather long time for a division%

 

9.9 $mber conersion

umber 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%

Page 61: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 61/81

 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 A# lame duc,s

and need e5treme e5ecution times% un into this dilemma# if you thin, assembler is too complicated# and you prefer asic

or other languages li,e C or <ascal%

ot 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 ;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( ac, to the roots of math? ost 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% o one reali4es# that this is a tric,%

 *(+( Linear conersions

As an e5ample the follo+ing tas,* an 83it3A!3Converter measures an input signal in the range from 0%00 to 2%EE olt# 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 83it3;e5 for input voltages

bet+een 0%00 and E%00 olt% o+ +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 2# +hile +e have an A!3converter +ith around 0%2E 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%008% )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% y dividing +ith numbers that are a po+er of 2# the A feels very

comfortable and performs very fast% y dividing +ith 2E6# the A is even faster# because +e >ust have to s,ip the last byte

of the binary number% ot even shift and rotate?

)he multiplication of an 83bit3binary +ith the 93bit3binary E02 @he5 1F6 can have a result larger than 16 bits% 7o +e have toreserve 2H bits or " registers for the result% !uring multiplication# the constant E02 has to be shifted left @multiplication by

2 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 1

ultiplicand E02 H * " * 2

esult 128#010 * 6 * E

After filling the value E02 @00%01%F6 to H * " * 2 and clearing the result registers * 6 * E# 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 % )his instruction is named :ogical37hift3ight or :7%

"% '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% to

the result% !uring adding# +e care for any carry @adding 2 to E by A!!# adding " to 6 and H to +ith

the A!C instruction?% '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% o+ the multiplicand is multiplied by 2# because the ne5t bit shifted out of the input number is +orth double

as much% 7o +e shift 2 to the left @by inserting a 4ero in bit 0 using :7:% it is shifted to the carry% )hen +e

rotate this carry into "# rotating its content left one bit# and bit to the carry% )he same +ith H%

E% o+ +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 * 6 * E% 'f +e >ust ignore register E @division by

2E6# +e have our desired result% )o enhance accuracy# +e can use bit in E to round the result% o+ +e >ust have to

convert the result from its binary form to decimal A7C'' @see Conversion bin to decimal3A7C'' on the +ebsite% '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 9 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 usage%

Page 62: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 62/81

 Avr-Asm-Tutorial 58 http://www.avr-asm-tutorial.net

 *(+(# E)ample 9-bit-A1-conerter &ith fi)ed decimal output

' De<onstr%tes f-o%ting oint onCersion in Asse<)-er, "2!00 ;;;.%Cr(%s<(t:tori%-.net '' >he t%s@ o: re%d in %n ()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 oint n:<)er in the r%nge fro< 0.00 to 5.00 o-t 

' >he rogr%< she<e@' 1. M:-ti-i%tion )y 50! he? 01F62.>h%t ste <:-ti-ies )y 500, !56 %nd diCides )y !55 in one steT ' !. Ro:nd the res:-t %nd :t the -%st )yte of the res:-t. >his ste 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.' . "onCert the res:-ting ;ord to A*"II %nd set the orret dei<%- sign. >he res:-ting ;ord in the r%nge fro< 0 to 500 ' is dis-%yed in A*"II(h%r%ters %s 0.00 to 5.00.' >he registers :sed@' >he ro:tines :se the registers R..R1 ;itho:t s%Cing these )efore. A-so re:ired is % <:-ti:rose register %--ed r<,' -o%ted in the :er h%-f of the registers. P-e%se t%e %re th%t these registers dont onf-it ;ith the register :se in the' rest of yo:r rogr%<.' 4hen entering the ro:tine the ()it n:<)er is e?eted in the register R1. >he <:-ti-i%tion :ses R7@R@R! to ho-d ' the <:-ti-i%tor 50! is shifted -eft <%?. eight ti<es d:ring <:-ti-i%tion2. >he res:-t of the <:-ti-i%tion is %-:-%ted ' in the registers R8@R6@R5. >he res:-t of the so %--ed diCision )y !56 )y :st ignoring R5 in the res:-t, is in R8@R6. R8@R6 ' is ro:nded, deending on the highest )it of R5, %nd the res:-t is oied to R!@R1.' "onCersion to %n A*"II(string :ses the in:t in R!@R1, the register %ir R7@R %s % diCisor for onCersion, %nd -%es the

' A*"II res:-t string to R5@R6@R8@R R6 is the dei<%- h%r2.' Other onCentions@' >he onCersion :ses s:)ro:tines %nd the st%.>he st% <:st ;or fine for the :se of three -eCe-s si? )ytes *RAM2.' "onCersion ti<es@' >he ;ho-e ro:tine re:ires !! -o y-es <%?i<:< onCerting NFF2, %nd 89 -o y-es <ini<:< onCerting N002.' At 7 M/ the ti<es %re 56.85 <iroseonds res. 18.85 <iroseonds.' Definitions@' Registers.DEF r< = R16 ' :sed %s <:-ti(:rose register ' AR tye@ >ested for tye A>90*515, on-y re:ired for st% setting, ro:tines ;or fine ;ith other A>90*(tyes %-so.&OLI*> .I&"L$DE 515def.in .LI*> ' *t%rt of test rogr%<' :st ;rites % n:<)er to R1 %nd st%rts the onCersion ro:tine, for test :roses on-y 

."*E.OR N0000   r< <%in<%in@  -di r<,/I/RAME&D2 ' *et the st%   o:t *P/,r<  -di r<,LO4RAME&D2  o:t *PL,r<  -di r<,NFF ' "onCert NFF   <oC R1,r<  r%-- fonC ' %-- the onCersion ro:tinenoJend@ ' :n-i<ited -oo, ;hen done  r< noJend ' "onCersion ro:tine ;r%er, %--s the different onCersion stesfonC@

  r%-- fonC< ' <:-ti-i%te )y 50!   r%-- fonCr ' ro:nd %nd diCide )y !56   r%-- fonC% ' onCert to A*"II string   -di r<,. ' set dei<%- h%r   <oC R6,r<  ret ' %-- done' *:)ro:tine <:-ti-i%tion )y 50! fonC<@  -r R7 ' set the <:-ti-i%nt to 50!   -di r<,N01  <oC R,r<  -di r<,NF6   <oC R!,r<  -r R8 ' -e%r the res:-t   -r R6   -r R5 fonC<1@  or R1,R1 ' he if the n:<)er is %-- eros  )rne fonC<! ' sti-- ones, go on onCert   ret ' re%dy, ret:rn )% fonC<!@  -sr R1 ' shift n:<)er to the right diC )y !2  )r fonC< ' if the -o;est )it ;%s 0, then si %dding   %dd R5,R! ' %dd the n:<)er in R6@R5@R7@R to the res:-t   %d R6,R  %d R8,R7fonC<@  -s- R! ' <:-ti-y R7@R@R! )y !   ro- R  ro- R7  r< fonC<1 ' ree%t for ne?t )it ' Ro:nd the C%-:e in R8@R6 ;ith the C%-:e in )it 8 of R5 fonCr@  -r r< ' :t ero to r<

Page 63: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 63/81

 Avr-Asm-Tutorial 59 http://www.avr-asm-tutorial.net

  -s- R5 ' rot%te )it 8 to %rry   %d R6,r< ' %dd L*3 ;ith %rry   %d R8,r< ' %dd M*3 ;ith %rry   <oC R!,R8 ' oy the C%-:e to R!@R1 diCide )y !562  <oC R1,R6   ret 

' "onCert the ;ord in R!@R1 to %n A*"II string in R5@R6@R8@R fonC%@  -r R7 ' *et the dei<%- diCider C%-:e to 100   -di r<,100   <oC R,r<  r%-- fonCd ' get A*"II digit )y ree%ted s:)tr%tion  <oC R5,r< ' set h:ndreds string h%r   -di r<,10 ' *et the dei<%- diCider C%-:e to 10   <oC R,r<  r%-- fonCd ' get the ne?t A*"II digit   <oC R8,r< ' set tens string h%r   -di r<,0 ' onCert the rest to %n A*"II h%r   %dd r<,R1  <oC R,r< ' set ones string h%r   ret 

' "onCert )in%ry ;ord in R!@R1 to % dei<%- digit )y s:)str%ting the dei<%- diCider C%-:e in R7@R 100, 102fonCd@  -di r<,0 ' st%rt ;ith dei<%- C%-:e 0 fonCd1@  R1,R ' "o<%re ;ord ;ith dei<%- diCider C%-:e  R!,R7  )r fonCd! ' "%rry -e%r, s:)tr%t diCider C%-:e  ret ' done s:)tr%tionfonCd!@  s:) R1,R ' s:)tr%t diCider C%-:e  s) R!,R7  in r< ' : one digit   r< fonCd1 ' one %g%in' End of onCersion test ro:tine 

*(+($ E)ample # +-bit-A1-conerter &ith fi)ed decimal output

)his e5ample is a bit more complicated% efer to the +ebsite if you need it%

Page 64: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 64/81

 Avr-Asm-Tutorial 60 http://www.avr-asm-tutorial.net

 + 'roFect planning

 1=.1 How to plan an * pro>ect in assembler

;ere are the basics on ho+ to plan a simple pro>ect# to be programmed in assembler% ecause 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 A 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< interface# the pins 7CN# 7' and '7

have to be assigned for this purpose% 'f your peripheral allo+s that those can be used as inputs @e% g% 7CN

and 7' or as outputs @by decoupling them via resistors or multiple5ers%

2% 'f a serial interface is needed# O! and )O! have to be reserved for that purpose% 'f the )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'0 and A'1 have to be reserved for that%

H% 'f e5ternal signals are to be monitored for level changes# ')0 andLor ')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 ACC and A-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 e5ternal 7A is to be attached# the respective address and data ports together +ith A:-# ! and &

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 8 to be +ritten or read(

)hese should be defined in an appropriate +ay @in the same port# in the right order%

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!CH%

"% 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 -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

-7-) pin is protected against the 12 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( @--< capacity

• ;o+ much storage space is re$uired( @7A capacity

7pace re$uirements on your <C# 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% ot 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

ery simple tas,s +or, fine +ithout interrupts% 'f po+er consumption is an issue# this ain/t true either% early all pro>ects

re$uire interrupts% And this should be planned thoroughly%

Page 65: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 65/81

 Avr-Asm-Tutorial 61 http://www.avr-asm-tutorial.net

 +($( Basic re>uirements of interrupt-drien 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<; at the beginning to

A-!# and reserve the upper part of the 7A for that purpose @e% g% the last 8 to 5 bytes%• -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 7- 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 J< instruction# in large A)mega processors a t+o3+ord J< instruction# to the respective

interrupt service routine%

)he vector addresses are type3specific% &hen porting the soft+are to a different type# those re$uiread>ustment%

• -ach vector address in the table# that is currently not used# is given a -)' instruction @in large A)mega

types a -)'# follo+ed by an <% )hat prevents erroneous ghost interrupts to be running into false

code% )he use of the % 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 =A)# if no further character is to be sent# 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 7- in a register e5clusively reserved for thatpurpose# and ends +ith restoring that status register% ecause 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%

• efore >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 7-% -ach service routine ends +ith the instruction -)'# that

pops the instruction pointer from the stac, and sets the ' flag on again%

• ecause 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%

• ecause 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%

• alues that the interrupt service routines provides are handed over in dedicated registers or in specific

7A 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%% 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 secondbyte read# if another interrupt happened in bet+een%

• ain 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 routines

and the processor can be sent bac, to sleep%

+($(# E)ample for an interrupt-drien assembler program

)he follo+ing provides an e5ample for an interrupt3driven assembler program# that utili4es all the above mentioned rules%

e'ister (e)initions

Page 66: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 66/81

 Avr-Asm-Tutorial 62 http://www.avr-asm-tutorial.net

.BH rsre' E 15 savin' the status (urin' interrupts

.BH rmp E 16 Temporar, re'ister outsi(e interrupts

.BH rimp E 17 Temporar, re'ister insi(e interrupts

.BH r)l' E 18 Fla' re'ister )or #ommuni#ation

.BH +int0 E 0 Fla' +it )or si'nalin' >T0-ervi#e

.BH +t#0 E 1 Fla' +it )or si'nalin' T"0-?ver)low ... -Ta+le."B.? I0000  rmp main eset ve#tor% e<e#ute( at start-up  rmp isrNint0 >T0-ve#tor% e<e#ute( on level #han'es on the >T0 input line

reti unuse( interrupt  reti unuse( interrupt  rmp 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

nterrupt servi#e routinesisrNint0: >T0-ervi#e outine  in rsre'%B sa)e status  in rimp%&>J rea( port J to temp re'ister   out &?T"%rimp write temp re'ister to port "

... (o other thin's  s+r r)l'%1LL+int0 si'nalin' >T0 to outsi(eout B%rsre' restore status

reti return +a#$ an( ena+le interruptsisrNt#0N?ver)low: T"0 ?ver)low ervi#e outine

in rsre'%B sa)e statusin rimp%&>J rea( port J in temp re'ister 

out &?T"%rimp write temp re'ister to port " ... (o other thin'ss+r r)l'%1LL+t#0 set T"0-)la'out B%rsre' restore statusreti return +a#$ an( ena+le interrupts

Gain pro'ram startmain:

l(i rmp%AGB>; set sta#$ re'ister out &%rmpl(i rmp%@?*AGB>;out &@%rmp ... other thin's to (o

>T Bna+le )or T"0 over)lowsl(i rmp%1LLT?B0 ?ver)low nterrupt Bna+le Timer 0out TGO%rmp set interrupt-mas$ o) the timerl(i rmp%1LL"00;M1LL"02; pres#aler +, 1024out T""0%rmp start timer  >T Bna+le o) the >T0 inputl(i rmp%1LLB;M1LL"00; @BB&-Bna+le an( >T0 int on all level #han'esout G""%rmp to the #ontrol re'ister l(i rmp%1LL>T0 ena+le >T0 interruptsout "%rmp to the interrupt #ontrol re'ister  set interrupt status )la'sei set interrupt )la'

Gain pro'ram loop

loop:

sleep pro#essor to sleepnop (umm, )or wa$e-ups+r# r)l'%+int0 >T0 )la' not setr#all ma#heNint0 han(le >T0 events+r# r)l'%+t#0 T"0-?ver)low )la' not setr#all ma#heNt#0 han(le T"0 over)lowrmp loop 'o +a#$ to sleep

an(le event resultsma#heNint0: han(le >T0 result

#+r r)l'%1LL+int0 #lear >T0 )la'

... (o other thin'sret rea(,% +a#$ to loop

ma#heNt#0: han(le T"0 over)low

Page 67: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 67/81

 Avr-Asm-Tutorial 63 http://www.avr-asm-tutorial.net

#+r r)l'%1LL+t#0 #lear T"0 )la' ... (o other thin'sret rea(,% +a#$ to loop

 1=.% Considerations on timin'

'f an A 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 C oscillator of most

of the A types is sufficient% 'n the tiny and mega types# a oscillator calibration is built in# so that differences bet+een thenominal and the effective fre$uency are reduced% ote 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 C 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 !'8 fuse or +ithin the soft+are @e% g% to reduce the supply po+er during pauses% ut be a+are that

some devices +ith a limited cloc, specification @ types should not be set to beyond their limit# other+ise they +on/t +or,

correct any more%

'f the internal C oscillator is too inaccurate# fuses can be set for e5ternal C combination# an e5ternal oscillator# a crystal

@Otal or a ceramic device% ecause 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 ;4 cloc, is used @2#000 cloc, cycles bet+een any t+o polls# 20#000 cloc,s for

repeated e5ecution of the ,ey command%

't/s only getting narro+er# if a pulse +idth modulated signal +ith high resolution and a high <& fre$uency has to be

reached% &ith a <& fre$uency of 10 ,;4 and 8 bits resolution 2%E6 ;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%

Page 68: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 68/81

 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  

egister

set

0 C: r1 S 1

2EE 7- rh   1

Constant :!' rh#c2EE   1

Copy

egister GV egister r1#r2   1

7A GV egister# direct :!7 r1#c6EE"E   2

7A GV egister :! r1#rp   2

7A GV egister and 'C :! r1#rpK   2

!-C# 7A GV egister :! r1#3rp   2

7A# displaced GV egister :!! r1#ryK,6"   2

<ort GV egister ' r1#p1   1

7tac, GV egister << r1   2

<rogram storage S GV 0 :<   "

egister GV 7A# direct 7)7 c6EE"E#r1   2

egister GV 7A 7) rp#r1   2

egister GV 7A and 'C 7) rpK#r1   2

!-C# egister GV 7A 7) 3rp#r1   2egister GV 7A# displaced 7)! ryK,6"#r1   2

egister GV <ort =) p1#r1   1

egister GV 7tac, <=7; r1   2

Add

8 it# K1 'C r1 S 1

8 it A!! r1#r2 S C ; 1

8 it K Carry A!C r1#r2 S C ; 1

16 it# constant A!'& rd#,6" S C 7 2

7ubtract

8 it# 31 !-C r1 S 1

8 it 7= r1#r2 S C ; 1

8 it# constant 7=' rh#c2EE S C ; 1

8 it 3 Carry 7C r1#r2 S C ; 1

8 it 3 Carry# constant 7C' rh#c2EE S C ; 1

16 it 7'& rd#,6" S C 7 2

7hift

logic# left :7: r1 S C 1

logic# right :7 r1 S C 1

otate# left over Carry : r1 S C 1

otate# right over Carry r1 S C 1

Arithmetic# right A7 r1 S C 1

ibble e5change 7&A< r1   1

inary

And A! r1#r2 S 1

And# constant A!' rh#c2EE S 1

r r1#r2 S 1

r# constant ' rh#c2EE S 1

-5clusive3r - r1#r2 S 1

nes3complement C r1 S C 1

)+os3complement - r1 S C ; 1

Page 69: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 69/81

 Avr-Asm-Tutorial 65 http://www.avr-asm-tutorial.net

0unction Su( function instruction 0lags Cl1  

itschange

egister# set 7 rh#c2EE S 1

egister# clear C rh#2EE S 1

egister# copy to )3Flag 7) r1#b ) 1egister# copy from )3Flag :! r1#b   1

<ort# set 7' pl#b   2

<ort# clear C' pl#b   2

7tatus bit

set

Sero3Flag 7-S S 1

Carry Flag 7-C C 1

egative Flag 7- 1

)+os complement carry Flag 7- 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

egative Flag C: 1

)+os complement carry Flag C: 1

;alf carry Flag C:; ; 1

7igned Flag C:7 7 1

)ransfer Flag C:) ) 1

'nterrupt -nable Flag C:' ' 1

Compare

egister# egister C< r1#r2 S C ; 1

egister# egister K Carry C<C r1#r2 S C ; 1

egister# constant C<' rh#c2EE S C ; 1

egister# ̂ 0 )7) r1 S 1

'mmediateJump

elative J< cH096   2

'ndirect# Address in S 'J<   2

7ubroutine# relative CA:: cH096   "

7ubroutine# Address in S 'CA::   "

eturn from 7ubroutine -)   H

eturn from 'nterrupt -)' ' H

Page 70: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 70/81

 Avr-Asm-Tutorial 66 http://www.avr-asm-tutorial.net

0unction Su( function instruction 0lags Cl1  

Conditional

Jump

7tatus bit set 7 b#c12   1L2

7tatus bit clear C b#c12   1L2

Jump if e$ual -P c12   1L2Jump if not e$ual - c12   1L2

Jump if carry set C7 c12   1L2

Jump if carry clear CC c12   1L2

Jump if e$ual or greater 7; c12   1L2

Jump if lo+er : c12   1L2

Jump if negative ' c12   1L2

Jump if positive <: c12   1L2

Jump if greater or e$ual @7igned - c12   1L2

Jump if lo+er than 4ero @7igned :) c12   1L2

Jump on half carry set ;7 c12   1L2

Jump if half carry clear ;C c12   1L2

Jump if )3Flag set )7 c12   1L2

Jump if )3Flag clear )C c12   1L2

Jump if )+os complement carry set 7 c12   1L2

Jump if )+os complement carry clear C c12   1L2

Jump if 'nterrupts enabled '- c12   1L2

Jump if 'nterrupts disabled '! c12   1L2

Conditioned

Jumps

egister bitG0 7C r1#b   1L2L"

egister bitG1 77 r1#b   1L2L"

<ort bitG0 7'C pl#b   1L2L"

<ort bitG1 7'7 pl#b   1L2L"

Compare# >ump if e$ual C<7- r1#r2   1L2L"

thers

o peration <   1

7leep 7:--<   1

&atchdog eset &!   1

 11.2 &irecties and #nstr$ction lists in alphabetic order

 (#( Assembler directies in alphabetic order 

Directive ... means ...

."*E  Asse<)-e to the "ode seg<ent 

.D3 Insert d%t% )ytes2

.DEF  Define % register n%<e

.D4  Insert d%t% ;ords2

.E&DMA"RO M%ro is o<-ete, sto reording 

.E*E  Asse<)-e to the EEPROM seg<ent 

.E#$  Define % onst%nt )y n%<e %nd set its C%-:e

.I&"L$DE  Insert % fi-es ontent %t this -%e %s if it ;o:-d )e %rt of this fi-e

.MA"RO *t%rt to reord the fo--o;ing instr:tions %s % <%ro definition

.OR *et the %sse<)-er o:t:t %ddress to the fo--o;ing n:<)er 

Page 71: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 71/81

 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,6  Add the i<<edi%te ;ord onst%nt 6 to the do:)-e register rd1@rd rd = R!7, R!6, R!, R02

 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 :er 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  "oy the >(f-%g in the st%t:s register to )it )8 in register r1

3R"" 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the %rry f-%g in the st%t:s register is -e%r 

3R"* 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the %rry f-%g in the st%t:s register is set 

3RE# 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the ero f-%g in the st%t:s register is set 

3RE 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the %rry f-%g in the st%t:s register is -e%r 

3R/" 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the h%-f %rry f-%g in the st%t:s register is -e%r 3R/* 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the h%-f %rry f-%g in the st%t:s register is set 

3RID 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the interr:t f-%g in the st%t:s register is -e%r 

3RIE 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the interr:t f-%g in the st%t:s register is set 

3RLO 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the %rry f-%g in the st%t:s register is set 

3RL> 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the neg%tiCe %nd oCerf-o; f-%g in the st%t:s register %reset 

3RMI 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the neg%tiCe f-%g in the st%t:s register is set 

3R&E 1!8  3r%nh )y 1!8 instr:tions for or )%;%rds if the ero f-%g in the st%t:s register is set 

3RPL 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the neg%tiCe f-%g in the st%t:s register is -e%r 

3R*/ 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the %rry f-%g in the st%t:s register is -e%r 3R>" 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the tr%nsfer f-%g in the st%t:s register is -e%r 

3R>* 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the tr%nsfer f-%g in the st%t:s register is set 

3R" 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the oCerf-o; f-%g in the st%t:s register is -e%r 

3R* 1!8  3r%nh )y 1!8 instr:tions for( or )%;%rds if the oCerf-o; f-%g in the st%t:s register is set 

3*> r1,)8  "oy the )it )8 in register r1 to the tr%nsfer f-%g in the st%t:s register 

"3I -,)8  "-e%r )it )8 in the -o;er ort - 

"3R rh,!55  "-e%r %-- the )its in the :er register rh, th%t %re set in the onst%nt !55 <%s2

"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:t )it in the st%t:s register, dis%)-e interr:t 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 

"L  "-e%r the ero f-%g in the st%t:s register 

"OM r1 "o<-e<ent register r1 ones o<-e<ent2

"P r1,r!  "o<%re register r1 ;ith register r! 

"P" r1,r!  "o<%re register r1 ;ith register r! %nd the %rry f-%g 

"PI rh,!55  "o<%re the :er register rh ;ith the i<<edi%te onst%nt !55 

"P*E r1,r!  "o<%re r1 ;ith r! %nd :< oCer the ne?t instr:tion if e:%- 

DE" r1 Dere<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 %ir /@L, R1@R02

IMP I& r1,1 :< to the %ddress in register %ir /@L, R1@R02

I&" r1 Inre<ent register r1 )y 1

LD r1,r,r,(r2 Lo%d the register r1 ;ith the ontent %t the -o%tion th%t register %ir r K, or 2 oints to rinre<ents the register %ir %fter -o%ding, (r dere<ents the register %ir rior to -o%ding2

LDD r1,ry6 Lo%d the register r1 ;ith the ontent %t the -o%tion th%t register %ir ry or 2, dis-%ed )y the

onst%nt 6, oints toLDI rh,!55  Lo%d the :er register rh ;ith the onst%nt !55 

LD* r1,6555  Lo%d register r1 ;ith the ontent %t -o%tion 6555 

Page 72: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 72/81

 Avr-Asm-Tutorial 68 http://www.avr-asm-tutorial.net

LPM LPM r1LPM r1,LPM r1,( 

Lo%d register R0 ;ith the ontent of the f-%sh <e<ory %t the -o%tion th%t register %ir /@L,R1@R02, diCided )y !, oints to, )it 0 in oints to -o;er 02 or :er 12 )yte in f-%sh Lo%d registerr1, inre<ent %fter -o%ding, ( dere<ent rior 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

&E r1 *:)tr%t register r1 fro< ero

&OP  &o oer%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 :er register r1 ;ith the onst%nt !55 

O$> 1,r1 "oy register r1 to IQO ort 1

POP r1 Inre%se the st% ointer %nd o the -%st )yte on st% to register r1

P$*/ r1 P:sh register r1 to the st% %nd dere%se the st% ointer 

R"ALL 7096  P:sh rogr%< o:nter on st% %nd %dd signed onst%nt 7096 to the rogr%< o:nter re-%tiCe %--2

RE>  Po rogr%< o:nter fro< st% ret:rn to %-- %ddress2

RE>I  En%)-e interr:ts %nd o rogr%< o:nter fro< st% ret:rn fro< interr:t2

RMP 7096  Re-%tiCe :<, %dd signed onst%nt 7096 to rogr%< %ddress

ROL r1 Rot%te register r1 -eft, oy %rry f-%g to )it 0 

ROR r1 Rot%te register r1 right, oy %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 :er register rh %nd ;rite res:-t to rh

*3I -,)8  *et )it )8 in the -o;er ort - 

*3I" -,)8  If )it )8 in the -o;er ort - is -e%r, :< oCer the ne?t instr:tion

*3I* -,)8  If )it )8 in the -o;er ort - is set, :< oCer the ne?t instr:tion

*3I4 rd,6 *:)tr%t the onst%nt 6 fro< the register %ir rd rd1@rd, rd = R!7, R!6, R!, R02

*3R rh,!55  *et the )its in the :er register rh, th%t %re one in onst%nt !55 

*3R" r1,)8  If )it )8 in register r1 is -e%r, :< oCer ne?t instr:tion

*3R* r1,)8  If )it )8 in register r1 is set, :< 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:t f-%g in st%t:s register, en%)-e interr:t e?e:tion

*E&  *et neg%tiCe f-%g in st%t:s register 

*ER rh *et %-- )its in the :er 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 

*E  *et ero f-%g in st%t:s register 

*LEEP  P:t ontro--er to the se-eted s-ee <ode

*> rQrQ(r2,r1 *tore ontent in register r1 to the <e<ory -o%tion in register %ir r r = K, , ' r@ inre<entregister %ir %fter store' (r@ dere<ent register %ir rior to store2

*>D ry6,r1 *tore the ontent of register r1 %t the -o%tion th%t register %ir ry or 2, dis-%ed )y the onst%nt6, oints to

*>* 6555,r1 *tore the ontent of register r1 %t the -o%tion 6555 

*$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 :er register rh

*4AP r1 E?h%nge :er %nd -o;er ni))-e in register r1

>*> r1 "o<%re register r1 ;ith ero

4DR  4%thdog reset 

Page 73: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 73/81

 Avr-Asm-Tutorial 69 http://www.avr-asm-tutorial.net

 11." Port details)he table of the relevant ports in the A)-: A types A)9072"1"# 2"2" and 8E1E% yte +ise accessible ports or register

pairs are not displayed in detail% o +arranty for correctness# see the original data sheets?

 ($( ,tatus-Register3 Accumulator flags

Port 0unction Port-!!ress R2-!!ress

7- 7tatus egister Accumulator 05"F 05EF

3 + & , # " $ 4  

' ) ; 7 S C

Bit Name 2eaning Opportunities Conmman!  

' lobal 'nterrupt Flag0* 'nterrupts disabled C:'

1* 'nterrupts enabled 7-'

6 ) it storage0* 7tored bit is 0 C:)

1* 7tored bit is 1 7-)

E ; ;alfcarry3Flag0* o halfcarry occurred C:;

1* ;alfcarry occurred 7-;

H 7 7ign3Flag0* 7ign positive C:7

1* 7ign negative 7-7

" )+o/s complement3Flag0* o carry occurred C:

1* Carry occurred 7-

2 egative3Flag0* esult +as not negativeLsmaller C:

1* esult +as negativeLsmaller 7-

1 S Sero3Flag0* esult +as not 4eroLune$ual C:S

1* esult +as 4eroLe$ual 7-S

0 C Carry3Flag0* o 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+3yte of 7tac,

pointerFrom A)9072"1" up+ards# not in 1200

7<;;igh3yte of 7tac,

pointerFrom A)9078E1E up+ards# only in devices +ith V2E6 bytes internal 7A

 ($($ ,RAM and E)ternal Interrupt controlPort 0unction Port-!!ress R2-!!ress

C=C C= eneral Control egister 05"E 05EE

3 + & , # " $ 4  

7- 7& 7- 7 '7C11 '7C10 '7C01 '7C00

Bit Name 2eaning Opportunities

7- -5t% 7A -nable0Go e5ternal 7A connected

1G-5ternal 7A connected

6 7& -5t% 7A &ait 7tates0Go e5tra +ait state on e5ternal 7A

1GAdditional +ait state on e5ternal 7A

Page 74: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 74/81

 Avr-Asm-Tutorial 70 http://www.avr-asm-tutorial.net

Bit Name 2eaning Opportunities

E 7- 7leep -nable0G'gnore 7:--< instructions

1G7:--< on instruction

H 7 7leep ode 0G'dle ode @;alf sleep1G<o+er !o+n ode @Full sleep

" '7C11

2 '7C10

'nterrupt control <in ')1

@connected to '7N

00* :o+3level initiates 'nterrupt

01* =ndefined

10* Falling edge triggers interrupt

11* ising edge triggers interrupt

1 '7C01

0 '7C00

'nterrupt control <in ')0

@connected to '7N

00* :o+3level initiates interrupt

01* =ndefined

10* Falling edge triggers interrupt

11* ising edge triggers interrupt

 ($(. E)ternal Interrupt Control

Port 0unction Port-!!ress R2-!!ress

'7N eneral 'nterrupt as,register 05" 05E

3 + & , # " $ 4  

')1 ')0 3 3 3 3 3 3

Bit Name 2eaning Opportunities

')1'nterrupt by e5ternal pin ')1

@connected to mode in C=C

0* -5ternal ')1 disabled

1* -5ternal ')1 enabled

6 ')0'nterrupt by e5ternal <in ')0

@connected to mode in C=C

0* -5ternal ')0 disabled

1* -5ternal ')0 enabled

0%%%E @ot used

Port 0unction Port-!!ress R2-!!ress

'F eneral 'nterrupt Flag egister 05"A 05EA

3 + & , # " $ 4  

')F1 ')F0 3 3 3 3 3 3

Bit Name 2eaning Opportunities

')F1 'nterrupt by e5ternal pin ')1 occurred

6 ')F0 'nterrupt by e5ternal pin ')0 occurred

Automatic clear by e5ecution of the 'nt3outine or

Clear by instruction

0%%%E @ot used

 ($(0 Timer Interrupt Control

Port 0unction Port-!!ress R2-!!ress

)'7N )imer 'nterrupt as,register 05"9 05E9

3 + & , # " $ 4  

)'-1 C'-1A C'-1 3 )'C'-1 3 )'-0 3

Page 75: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 75/81

 Avr-Asm-Tutorial 71 http://www.avr-asm-tutorial.net

Bit Name 2eaning Opportunities

)'-1 )imerLCounter 1 verflo+3'nterrupt0* o 'nt at overflo+

1* 'nt at overflo+

6 C'-1A )imerLCounter 1 Compare A 'nterrupt 0* o 'nt at e$ual A1* 'nt at e$ual A

E C'-1 )imerLCounter 1 Compare 'nterrupt0* o 'nt at

1* 'nt at e$ual

H @ot used

" )'C'-1 )imerLCounter 1 Capture 'nterrupt0* o 'nt at Capture

1* 'nt at Capture

2 @ot used

1 )'-0 )imerLCounter 0 verflo+3'nterrupt0* o 'nt at overflo+

1* 'nt at overflo+

0 @ot used

Port 0unction Port-!!ress R2-!!ress

)'F )imer 'nterrupt Flag egister 05"8 05E8

3 + & , # " $ 4  

)1 CF1A CF1 3 'CF1 3 )0 3

Bit Name 2eaning Opportunities

)1 )imerLCounter 1 verflo+ reached

6 CF1A )imerLCounter 1 Compare A reached

E CF1 )imerLCounter 1 Compare reached

H @ot used

" 'CF1 )imerLCounter 1 Capture3-vent occurred

2 @not used

1 )0 )imerLCounter 0 verflo+ occurred

0 @not used

'nterrupt3ode*

Automatic Clear

by e5ecution of the

'nt3outine

<olling3ode*

Clear by

instruction

 ($(2 TimerCounter +

Port 0unction Port-!!ress R2-!!ress

)CC0 )imerLCounter 0 Control egister 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

"%% @not used

Page 76: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 76/81

 Avr-Asm-Tutorial 72 http://www.avr-asm-tutorial.net

Port 0unction Port-!!ress R2-!!ress

)C)0 )imerLCounter 0 count register 05"2 05E2

 ($(5 TimerCounter

Port 0unction Port-!!ress R2-!!ress

)CC1A )imerLCounter 1 Control egister A 052F 05HF

3 + & , # " $ 4  

C1A1 C1A0 C11 C10 3 3 <&11 <&10

Bit Name 2eaning Opportunities

C1A1

6 C1A0Compare utput A

E C11

H C10Compare utput

00* C1AL not connected

01* C1AL changes polarity

10* C1AL to 4ero

11* C1AL to one

"

2@not used

1%%0<&11

<&10<ulse +idth modulator

00* <& off 

01* 83it <&

10* 93it <&

11* 103it <&

Port 0unction Port-!!ress R2-!!ress

)CC1 )imerLCounter 1 Control egister 052- 05H-

3 + & , # " $ 4  

'CC1 'C-71 3 3 C)C1 C712 C711 C710

Bit Name 2eaning Opportunities

'CC1oise 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 used

" C)C1Clear at

Compare atch A1* 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

)C)1:L; )imerLCounter 1 count register 052CL052! 05HCL05H!

Page 77: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 77/81

 Avr-Asm-Tutorial 73 http://www.avr-asm-tutorial.net

Port 0unction Port-!!ress R2-!!ress

C1A:L; )imerLCounter 1 utput Compare register A 052AL052 05HAL05H he5

Port 0unction Port-!!ress R2-!!ress

C1:L; )imerLCounter 1 utput Compare register 0528L0529 05H8L05H9

Port 0unction Port-!!ress R2-!!ress

'C1:L; )imerLCounter 1 'nput Capture egister 052HL052E 05HHL05HE

 ($(9 !atchdog-Timer 

Port 0unction Port-!!ress R2-!!ress

&!)C &atchdog )imer Control egister 0521 05H1

3 + & , # " $ 4  

3 3 3 &!)- &!- &!<2 &!<1 &!<0

Bit Name 2eaning 5'-c)cle at &64 Volt  

%%E @not used

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* 90 ms

111* 1#9 s

 ($(* EE'R4M

Port 0unction Port-!!ress R2-!!ress

--A:L; --< Address egister 051-L051F 05"-L05"F

--A; only in types +ith more than 2E6 ytes --< @from A)9078E1E up+ards

Port 0unction Port-!!ress R2-!!ress

--! --< !ata egister 051! 05"!

Port 0unction Port-!!ress R2-!!ress

--C --< Control egister 051C 05"C

3 + & , # " $ 4  

3 3 3 3 3 --&- --&- ---

Page 78: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 78/81

 Avr-Asm-Tutorial 74 http://www.avr-asm-tutorial.net

Bit Name 2eaning 0unction

%%" @not used

2 --&- --< aster &rite -nable <revious set enables +rite cycle

1 --&- --< &rite -nable 7et to initiate +rite0 --- --< ead -nable 7et initiates read

 ($(+ ,erial 'eripheral Interface ,'I

Port 0unction Port-!!ress R2-!!ress

7<C 7<' Control egister 050! 052!

3 + & , # " $ 4  

7<'- 7<- !! 7) C<: C<;A 7<1 7<0

Bit Name 2eaning 0unction

7<'- 7<' 'nterrupt -nable0* 'nterrupts disabled

1* 'nterrupts enabled

6 7<- 7<' -nable0* 7<' disabled

1* 7<' enabled

E !! !ata rder0* 7 first

1* :7 first

H 7) asterL7lave 7elect0* 7lave

1* aster

" C<: Cloc, <olarity0* <ositive Cloc, <hase

1* egative Cloc, <hase

2 C<;A Cloc, <hase0* 7ampling at beginning of Cloc, <hase

1* 7ampling at end of Cloc, <hase

1 7<1

0 7<07CN 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<7 7<' 7tatus egister 050- 052-

3 + & , # " $ 4  

7<'F &C: 3 3 3 3 3 3

Bit Name 2eaning 0unction

7<'F 7<' 'nterrupt Flag 'nterrupt re$uest

6 &C: &rite Collision Flag &rite collission occurred

E%%0 @not used

Port 0unction Port-!!ress R2-!!ress

7<! 7<' !ata egister 050F 052F

Page 79: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 79/81

 Avr-Asm-Tutorial 75 http://www.avr-asm-tutorial.net

 ($( 7ART

Port 0unction Port-!!ress R2-!!ress

=! =A) 'L !ata egister 050C 052C

Port 0unction Port-!!ress R2-!!ress

=7 =A) 7tatus egister 050 052

3 + & , # " $ 4  

OC )OC =!- F- 3 3 3

Bit Name 2eaning 0unction

OC =A) eceive Complete 1* Char received

6 )OC =A) )ransmit Complete 1* 7hift register empty

E =!- =A) !ata egister -mpty 1* )ransmit register available

H F- Framing -rror 1* 'llegal 7top3it

" verrun 1* :ost char

2%%0 @not used

Port 0unction Port-!!ress R2-!!ress

=C =A) Control egister 050A 052A

3 + & , # " $ 4  

OC'- )OC'- =!'- O- )O- C;9 O8 )O8

Bit Name 2eaning 0unction

OC'- O Complete 'nterrupt -nable 1* 'nterrupt on received char

6 )OC'- )O Complete 'nterrupt -nable 1* 'nterrupt at transmit complete

E =!'- !ata egister -mpty 'nterrupt -nable 1* 'nterrupt on transmit buffer empty

H O- eceiver -nable 1* eceiver enabled

" )O- )ransmitter -nable 1* )ransmitter enabled

2 C;9 93bit Characters 1* Char length 9 it

1 O8 eceive !ata it 8 @holds 9th data bit on receive

0 )O8 )ransmit !ata it 8 @+rite 9th data bit for transmit here

Port 0unction Port-!!ress R2-!!ress

= =A) aud ate egister 0509 0529

 ($(# Analog Comparator 

Port 0unction Port-!!ress R2-!!ress

AC7 Analog Comparator Control and 7tatus egister 0508 0528

3 + & , # " $ 4  

AC! 3 AC AC' AC'- AC'C AC'71 AC'70

Bit Name 2eaning 0unction

AC! !isable !isable Comparators

6 @not used

E AC Comparator utput ead* utput of the Comparators

H AC' 'nterrupt Flag 1* 'nterrupt re$uest

Page 80: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 80/81

 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 change01* @not used

10* 'nterrupt on falling edge

11* 'nterrupt on rising edge

 ($($ I4 'orts

Port Register 0unction Port-!!ress R2-!!ress

A

<)A !ata egister 051 05"

!!A !ata !irection egister 051A 05"A

<'A 'nput <ins Address 0519 05"9

<) !ata egister 0518 05"8

!! !ata !irection egister 051 05"

<' 'nput <ins Address 0516 05"6

C

<)C !ata egister 051E 05"E

!!C !ata !irection egister 051H 05"H

<'C 'nput <ins Address 051" 05""

!

<)! !ata egister 0512 05"2

!!! !ata !irection egister 0511 05"1

<'! 'nput <ins Address 0510 05"0

 11.% Ports< alphabetic order A"*R, An%-og "o<%r%tor "ontro- %nd *t%t:s Register DDR?, Port ? D%t% Diretion Register EEAR, EEPROM %ddress Register EE"R, EEPROM "ontro- Register 

EEDR, EEPROM D%t% Register IFR, ener%- Interr:t F-%g Register IM*U, ener%- Interr:t M%s Register I"R1LQ/, In:t "%t:re Register 1M"$"R, M"$ ener%- "ontro- Register O"R1A, O:t:t "o<%re Register 1 AO"R13, O:t:t "o<%re Register 1 3PI&?, Port In:t AessPOR>?, Port ? O:t:t Register *PLQ*P/, *t%ointer *P"R, *eri%- Periher%- "ontro- Register *PDR, *eri%- Periher%- D%t% Register *P*R, *eri%- Periher%- *t%t:s Register *RE, *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:t F-%g Register >IM*U, >i<er Interr:t M%s Register $3RR, $AR> 3%:d R%te Register $"R, $AR> "ontro- Register $DR, $AR> D%t% Register 4D>"R, 4%thdog >i<er "ontro- Register 

Page 81: How to program using the program memory of an AVR microcontroller TUT

7/18/2019 How to program using the program memory of an AVR microcontroller TUT

http://slidepdf.com/reader/full/how-to-program-using-the-program-memory-of-an-avr-microcontroller-tut 81/81

 Avr-Asm-Tutorial 77 http://www.avr-asm-tutorial.net

 11.) 8ist of abbreiations

)he abbreviations used are chosen to include the value range% egister 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

egister

r1 rdinary 7ource and )arget register

r2 rdinary 7ource register0%%"1

rh =pper page register 16%%"1

rd )+in register 2H@2E# 26@2# 28@29# "0@"1

rp <ointer register OG26@2# .G28@29# SG"0@"1

ry <ointer register +ith displacement .G28@29# SG"0@"1

Constant

,6" <ointer3constant 0%%6"

c12 Conditioned >ump distance 36H%%K6"

c2EE 83it3Constant 0%%2EE

cH096 elative >ump distance 320H8%%K20H

c6EE"E 163it3Address 0%%6EE"E

it b it position 0%%

<ortp1 rdinary <ort 0%%6"

pl :o+er page port 0%%"1