Assembler Beginner

Embed Size (px)

Citation preview

  • 8/20/2019 Assembler Beginner

    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"

    http://www.avr-asm-tutorial.net/http://www.avr-asm-tutorial.net/

  • 8/20/2019 Assembler Beginner

    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...................................................................................................................................#(

  • 8/20/2019 Assembler Beginner

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

     .1.2 igned numbers ....................................................................................................# .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...............................................................................................................................*(

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    7/81

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

    'f the C

  • 8/20/2019 Assembler Beginner

    8/81

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

     2.+ #nterpretin' and assembler

    &ith an interpreter the C

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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#

  • 8/20/2019 Assembler Beginner

    14/81

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

    +ith the delivered cables%

    )he board is connected to the

  • 8/20/2019 Assembler Beginner

    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%

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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 ?@T

    http://www.avr-asm-download.de/avr_head.ziphttp://www.avr-asm-download.de/avr_head.ziphttp://www.avr-asm-download.de/avr_head.zip

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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*

  • 8/20/2019 Assembler Beginner

    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%

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

    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%

  • 8/20/2019 Assembler Beginner

    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 ust

    advance simulation one step further to

    e5ecute the =) instruction @e% g% by pushing

    the ,ey F11%

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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 deihis 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 sohe 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 '

  • 8/20/2019 Assembler Beginner

    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%

  • 8/20/2019 Assembler Beginner

    29/81

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

     2 'orts

     +.1 hat is a Port/

  • 8/20/2019 Assembler Beginner

    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, (1he )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 @

  • 8/20/2019 Assembler Beginner

    31/81

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

    Component Port name Port-Register  

    Accumulator 7- 7tatus egister

    7tac, 7

    !!5

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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*

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

    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 "@soust add the follo+ing instruction*

    POP MyPreferredRegister ' Re%d )% the C%-:e fro< the to of the st% 

    &ith ust get the value that +as last pushed on top of the stac,% umps to the subroutine% After its e5ecution the subroutine pops the return address from the stac,

    and loads it bac, into the program counter%

  • 8/20/2019 Assembler Beginner

    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?

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

    38/81

  • 8/20/2019 Assembler Beginner

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

  • 8/20/2019 Assembler Beginner

    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 soump to it# here named !elay10*M% )hree ump directly to some+here else in the code you have to use the >ump instruction*

    ...B soump 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 Jumped 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! ' "oump 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; 

  • 8/20/2019 Assembler Beginner

    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 ' :I 

  • 8/20/2019 Assembler Beginner

    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 JI ' 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(*eghe 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

  • 8/20/2019 Assembler Beginner

    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*

  • 8/20/2019 Assembler Beginner

    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 

  • 8/20/2019 Assembler Beginner

    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! ' :

  • 8/20/2019 Assembler Beginner

    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

  • 8/20/2019 Assembler Beginner

    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 ' :

  • 8/20/2019 Assembler Beginner

    48/81

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

    7&A

  • 8/20/2019 Assembler Beginner

    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< )@'' *te 7@ M:-ti-y r

  • 8/20/2019 Assembler Beginner

    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%

     

  • 8/20/2019 Assembler Beginner

    51/81

  • 8/20/2019 Assembler Beginner

    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)90ust type

  • 8/20/2019 Assembler Beginner

    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

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

  • 8/20/2019 Assembler Beginner

    54/81

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

    '' M:-ti-y '

    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*

    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*

  • 8/20/2019 Assembler Beginner

    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 reg