Professional Documents
Culture Documents
Beginners Introduction To The Assembly Language of ATMEL-AVR-Microprocessors
Beginners Introduction To The Assembly Language of ATMEL-AVR-Microprocessors
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
Content
1 Why learning Assembler?......................................................................................................................1 2 The concept behind the language assembler in micro-controllers.........................................................2 2.1 The hardware of micro-controllers.................................................................................................2 2.2 How the C ! wor"s.......................................................................................................................2 2.# $nstructions in assembler................................................................................................................# 2.% &ifference to high-le'el languages.................................................................................................# 2.( Assembler is not machine language...............................................................................................# 2.) $nterpreting and assembler..............................................................................................................% 2.* High le'el languages and Assembler..............................................................................................% 2.+ What is really easier in assembler?................................................................................................( # Hardware for A,--Assembler- rogramming.......................................................................................) #.1 The $. $nterface of the A,- processor family.............................................................................) #.2 rogrammer for the C- arallel- ort.............................................................................................) #.# /0perimental boards.......................................................................................................................* #.#.1 /0perimental board with an ATtiny1#...................................................................................* #.#.2 /0perimental board with an AT12.2#1#3ATmega2#1#........................................................+ #.% -eady-to-use commercial programming boards for the A,--family............................................1 #.%.1 .T4222...................................................................................................................................1 #.%.2 .T4(22...................................................................................................................................1 #.%.# A,- &ragon.........................................................................................................................12 % Tools for A,- assembly programming...............................................................................................11 %.1 The editor.....................................................................................................................................11 %.1.1 A simple typewriter..............................................................................................................11 %.1.2 .tructuring assembler code...................................................................................................12 %.2 The assembler...............................................................................................................................1( %.# rogramming the chips.................................................................................................................1) %.% .imulation in the studio................................................................................................................1) ( What is a register?................................................................................................................................21 (.1 &ifferent registers.........................................................................................................................22 (.2 ointer-registers............................................................................................................................22 (.2.1 Accessing memory locations with pointers..........................................................................22 (.2.2 -eading program flash memory with the 5 pointer..............................................................22 (.2.# Tables in the program flash memory....................................................................................2# (.2.% Accessing registers with pointers.........................................................................................2# (.# -ecommendation for the use of registers.....................................................................................2% ) orts.....................................................................................................................................................2( ).1 What is a ort?.............................................................................................................................2( ).2 Write access to ports.....................................................................................................................2( ).# -ead access to ports......................................................................................................................2) ).% -ead-6odify-Write access to ports..............................................................................................2) ).( 6emory mapped port access........................................................................................................2) ).) &etails of rele'ant ports in the A,-............................................................................................2) ).* The status register as the most used port......................................................................................2* ).+ ort details....................................................................................................................................2+ * .-A6..................................................................................................................................................21 *.1 What is .-A6?...........................................................................................................................21 *.2 7or what purposes can $ use .-A6?...........................................................................................21 *.# How to use .-A6?......................................................................................................................21 *.#.1 &irect addressing..................................................................................................................21 *.#.2 ointer addressing.................................................................................................................#2 *.#.# ointer with offset.................................................................................................................#2 *.% !se of .-A6 as stac"..................................................................................................................#2 *.%.1 &efining .-A6 as stac"......................................................................................................#2 *.%.2 !se of the stac".....................................................................................................................#1 *.%.# Common bugs with the stac" operation................................................................................#1 + 8umping and branching........................................................................................................................## +.1 Controlling se9uential e0ecution of the program.........................................................................## +.2 :inear program e0ecution and branches.......................................................................................#% +.# Timing during program e0ecution................................................................................................#( +.% 6acros and program e0ecution....................................................................................................#( +.( .ubroutines...................................................................................................................................#(
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
+.) $nterrupts and program e0ecution.................................................................................................#* 1 Calculations..........................................................................................................................................#1 1.1 ;umber systems in assembler......................................................................................................#1 1.1.1 ositi'e whole numbers <bytes= words= etc.>........................................................................#1 1.1.2 .igned numbers <integers>....................................................................................................#1 1.1.# ?inary Coded &igits= ?C&...................................................................................................#1 1.1.% ac"ed ?C&s........................................................................................................................%2 1.1.( ;umbers in A.C$$-format....................................................................................................%2 1.2 ?it manipulations.........................................................................................................................%2 1.# .hift and rotate.............................................................................................................................%1 1.% Adding= subtracting and comparing..............................................................................................%2 1.%.1 Adding and subtracting 1)-bit numbers................................................................................%2 1.%.2 Comparing 1)-bit numbers...................................................................................................%2 1.%.# Comparing with constants....................................................................................................%2 1.%.% ac"ed ?C& math.................................................................................................................%# 1.( 7ormat con'ersion for numbers....................................................................................................%# 1.(.1 Con'ersion of pac"ed ?C&s to ?C&s= A.C$$ or ?inaries...................................................%# 1.(.2 Con'ersion of ?inaries to ?C&............................................................................................%% 1.) 6ultiplication...............................................................................................................................%% 1.).1 &ecimal multiplication.........................................................................................................%% 1.).2 ?inary multiplication............................................................................................................%% 1.).# A,- assembler program......................................................................................................%( 1.).% ?inary rotation......................................................................................................................%) 1.).( 6ultiplication in the studio...................................................................................................%) 1.* Hardware multiplication...............................................................................................................%+ 1.*.1 Hardware multiplication of +-by-+-bit binaries....................................................................%+ 1.*.2 Hardware multiplication of a 1)- by an +-bit-binary............................................................%1 1.*.# Hardware multiplication of a 1)- by a 1)-bit-binary............................................................(2 1.*.% Hardware multiplication of a 1)- by a 2%-bit-binary............................................................(2 1.+ &i'ision........................................................................................................................................(# 1.+.1 &ecimal di'ision...................................................................................................................(# 1.+.2 ?inary di'ision......................................................................................................................(% 1.+.# rogram steps during di'ision..............................................................................................(% 1.+.% &i'ision in the simulator......................................................................................................(( 1.1 ;umber con'ersion......................................................................................................................() 1.12 &ecimal 7ractions.......................................................................................................................(* 1.12.1 :inear con'ersions..............................................................................................................(* 1.12.2 /0ample 1@ +-bit-A&-con'erter with fi0ed decimal output................................................(+ 1.12.# /0ample 2@ 12-bit-A&-con'erter with fi0ed decimal output..............................................(1 12 roAect planning.................................................................................................................................)2 12.1 How to plan an A,- proAect in assembler.................................................................................)2 12.2 Hardware considerations............................................................................................................)2 12.# Considerations on interrupt operation........................................................................................)2 12.#.1 ?asic re9uirements of interrupt-dri'en operation...............................................................)1 12.#.2 /0ample for an interrupt-dri'en assembler program..........................................................)1 12.% Considerations on timing............................................................................................................)# 11 Anne0.................................................................................................................................................)% 11.1 $nstructions sorted by function...................................................................................................)% 11.2 &irecti'es and $nstruction lists in alphabetic order....................................................................)) 11.2.1 Assembler directi'es in alphabetic order............................................................................)) 11.2.2 $nstructions in alphabetic order...........................................................................................)* 11.# ort details..................................................................................................................................)1 11.#.1 .tatus--egister= Accumulator flags....................................................................................)1 11.#.2 .tac"pointer........................................................................................................................)1 11.#.# .-A6 and /0ternal $nterrupt control................................................................................)1 11.#.% /0ternal $nterrupt Control...................................................................................................*2 11.#.( Timer $nterrupt Control......................................................................................................*2 11.#.) Timer3Counter 2..................................................................................................................*1 11.#.* Timer3Counter 1..................................................................................................................*2 11.#.+ Watchdog-Timer.................................................................................................................*# 11.#.1 // -B6............................................................................................................................*# 11.#.12 .erial eripheral $nterface . $..........................................................................................*% 11.#.11 !A-T...............................................................................................................................*(
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
11.#.12 Analog Comparator..........................................................................................................*( 11.#.1# $3B orts............................................................................................................................*) 11.% orts= alphabetic order................................................................................................................*) 11.( :ist of abbre'iations...................................................................................................................**
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
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%
Test it!
8e patient doing your first steps? 'f you are familiar +ith another @high3levelA language* forget it for the first time% 8ehind every assembler language there is a certain hard+are concept% 0ost of the special features of other computer languages don/t ma,e any sense in assembler% )he first five instructions are not easy to learn# after that your learning speed rises fast% After you had your first lines* grab the instruction set list and lay bac, in the bathtub# +ondering +hat all the other instructions are li,e% 7erious +arning* !on/t try to program a mega3machine to start +ith% )his does not ma,e sense in any computer language# and >ust produces frustration% 7tart +ith the small B;ello +orldC3li,e e5amples# e% g% turning some :-!s on and off for a certain time# then e5plore the hard+are features a bit deeper% 2ecommendation* Comment your subroutines and store them in a special directory# if debugged* you +ill need them again in a short time% ;ave success?
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
0ultiply register 2" +ith register 22 and +rite the result to registers 21 @078A and 1001%1100%0011%0010 20 @:78A
7o# if the C<= reads he5 9E88 from the flash storage# it stops its operation and does not fetch instructions any more% !on/t be afraid# there is another mechanism necessary before the C<= e5ecutes this% And you can +a,e up the C<= from that%
Executing instructions
'f the C<= reads he5 0C01# 20 and 21 is added and the result is +ritten to register 20% )his is e5ecuted li,e demonstrated in the picture% First the instruction +ord @16 bitA is read from the flash and translated to e5ecutable steps @1A% )he ne5t step connects the registers to the A:= inputs# and
adds their content @2A% 6e5t# the result is +ritten to the register @"A%
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
'f the C<= reads he5 9C2" from the flash# the registers 2" and 22 are muliplied and the result is +ritten to 21 @upper 8 bitsA and 20 @lo+er 8 bitsA% 'f the A:= is not e$uipped +ith hard+are for multiplication @e% g% in an A)tiny1"A# the 9C2" does nothing at all% 't doesn/t even open an error +indo+ @the tiny1" doesn/t have that hard+areA? 'n principle the C<= can e5ecute 6E#E"6 @163bitA different instructions% 8ut because not only 1F0 should be +ritten to a specific register# but values bet+een 0 and 2EE to any register bet+een 216 and 2"1# this load instruction re$uires 2E6D16 G H#096 of the 6E#E"6 theoretically possible instructions% )he direct load instruction for the constant c @cF%%c0A and registers r @r"%%r0# rH is al+ays 1 and not encodedA is coded li,e this* 8it :!' 2#C 1E 1 1H 1 1" 1 12 0 11 cF 10 c6 9 cE 8 cH F r" 6 r2 E r1 H r0 " c" 2 c2 1 c1 0 c0
&hy those bits are placed li,e this in the instruction +ord remains A)0-:/s secret% Addition and subtraction re$uire "2D"2 G 1#02H combinations and the target registers 20%%2"1 @tH%%t0A and source registers 20%%2"1 @sH%%s0A are coded li,e this* 8it A!! 2t#2s 7=8 2t#2s 1E 0 0 1H 0 0 1" 0 0 12 0 1 11 1 1 10 1 0 9 sH sH 8 tH tH F t" t" 6 t2 t2 E t1 t1 H t0 t0 " s" s" 2 s2 s2 1 s1 s1 0 70 s0
<lease# do not learn these bit placements# you +ill not need them later% Just understand ho+ an instruction +ord is coded and e5ecuted%
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
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# 0 7'* )he data signal that sends the bits to be +ritten to the A12# 0'7 * )he data signal that receives the bits read from the A12%
)hese three signal pins are internally connected to the programming machine only if you change the 2-7-) @sometimes also called 27) or restartA pin to 4ero% ther+ise# during normal operation of the A12# these pins are programmable 'L lines li,e all the others% 'f you li,e to use these pins for other purposes during normal operation# and for in3system3 programming# you/ll have to ta,e care# that these t+o purposes do not conflict% =sually you then decouple these by resistors or by use of a multiple5er% &hat is necessary in your case# depends from your use of the pins in the normal operation mode% .ou/re luc,y# if you can use them for in3 system3programming e5clusively% 6ot necessary# but recommendable for in3system3programming is# that you supply the programming hard+are out of the supply voltage of your system% )hat ma,es it easy# and re$uires t+o additional lines bet+een the programmer and the A12 board% J6! is the common ground or negative pole of the supply voltage# 1)J @target voltageA the supply voltage @usually KE%0 voltsA% )his adds up to 6 lines bet+een the programmer hard+are and the A12 board% )he resulting '7<6 connection# as defined by A)0-:# is sho+n on the left% 7tandards al+ays have alternative standards# that +ere used earlier% )his is the technical basis that constitutes the adapter industry% 'n our case the alternative standard +as designed as '7<10 and +as used on the 7)N200 board# sometimes also called CA6!A interface% 't/s still a very +idespread standard# and even the more recent 7)NE00 board is e$uipped +ith it% '7<10 has an additional signal to drive a red :-!% )his :-! signals that the programmer is doing his >ob% A good idea% Just connect the :-! to a resistor and clamp it the positive supply voltage%
Avr-Asm-Tutorial
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%
A very small one +ith an A)tiny1"# or a more complicated one +ith an A)9072"1" or A)mega2"1"# including a serial 272"2 interface%
the '7<10 programming interface on the left# +ith a programming :-! attached via a resistor of "90 hms# the A)tiny1" +ith a pull3up of 10, on its 2-7-) pin @pin 1A# the supply part +ith a bridge rectifier# to be supplied +ith 9%%1E1 from an AC or !C source# and a small E1 regulator%
)he A)tiny1" re$uires no e5ternal O)A: or cloc, generator# because it +or,s +ith its internal 9%6 0;4 2C generator and# by default# +ith a cloc, divider of 8 @cloc, fre$uency 1%2 0;4A% )he hard+are can be build on a small board li,e the one sho+n in the picture% All pins of the tiny1" are accessible# and e5ternal hard+are components# li,e the :-! sho+n# can be easily plugged in%
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
)his board allo+s the use of the A)tiny1"/s hard+are components li,e 'L 3ports# timers# A! converters# etc%
a small voltage supply for connection to an AC transformer and a voltage regulator E1L1A# a O)A: cloc, generator @here +ith a 10 0;4 O)A:# all other fre$uencies belo+ the ma5imum for the 2"1" +ill also +or,A# the necessary parts for a safe reset during supply voltage s+itching# the '7<3<rogramming3'nterface @here +ith a '7<10<'63connectorA%
7o that/s +hat you need to start +ith% Connect other peripheral add3ons to the numerous free 'L pins of the 2"1"%
)he easiest output device can be a :-!# connected via a resistor to the positive supply voltage% &ith that# you can start +riting your first assembler program s+itching the :-! on and off% 'f you
do not need the serial communication interface# >ust s,ip the hard+are connected to pins 2L" and 1HL16#
Avr-Asm-Tutorial
http://www.avr-asm-tutorial.net
do not need hard+are handsha,e signals# s,ip the hard+are on the pins 1HL16 and connect 2)7 on the 93pin3 connector over a 2%2, resistor to K91% 'f you use an A)mega2"1" instead of an A)9072"1"# the follo+ing changes are resulting*
the e5ternal O)A: is not necessary# as the A)mega has an internal 2C cloc, generator# so >ust s,ip all connections to pins H and E# if you +ant to use the e5ternal O)A: instead of the build3in 2C as cloc, source# you +ill have to program the fuses of the A)mega accordingly%
price# <C interface @preferably =78# less convenient or durable* 93pin 272"2# re$uiring additional soft+are* interfaces for the parallel port of the <CA# support reliability for ne+er devices @updates are re$uired from time to time# other+ise you sit on a nearly dead horseA# hard+are features @depends on your foreseeable re$uirements in the ne5t five yearsA%
)he follo+ing section describes the three standard boards of A)0-:# the 7)N200# the 7)NE00 and the !ragon% )he selection is based on my o+n e5periences and is not a recommendation%
$(.( ,T/#++
)he 7)N200 from A)0-: is a historic board% 'f you grab a used one you/ll get
a board +ith some soc,ets @for 8# 20# 28 and H0 pin devicesA# eight ,eys and :-!s# hard connected to port ! and 8# an :C! standard 1H3pin interface# an option for attaching a 283pin 72A0# a 272"2 interface for communication# a cable interface for a <C parallel port on one side and a 103pin '7< on the other side%
;igh voltage programming is not supported% )he board cannot be programmed from +ithin the 7tudio# the programming soft+are is no longer maintained# and you must use e5ternal programs capable of driving the <C parallel port% 'f someone offers you such a board# ta,e it only for free and if you/re used to operate soft+are of the necessary ,ind%
$(.(# ,T/0++
-asy to get is the 7)NE00 @e% g% from A)0-:A% 't has the follo+ing hard+are*
7oc,ets for programming most of the A12 types @e% g% 1H3pin devices or )PF< pac,ages re$uire additional hard+areA# serial and parallel programming in normal mode or +ith high voltage @;1 programming brings devices bac, to life even if their 2-7-) pin has been fuse3programmed to be normal port inputA# '7<6<'63 and '7<10<'63connection for e5ternal 'n37ystem3<rogramming# programmable oscillator fre$uency and supply voltages# plug3in s+itches and :-!s# a plugged 272"2C3connector @=A2)A# a serial Flash3--<2 0 @only older boards have thisA# access to all port pins via 103pin connectors%
A ma>or disadvantage of the board is that# before programming a device# several connections have to be made manually
Avr-Asm-Tutorial
10
http://www.avr-asm-tutorial.net
+ith the delivered cables% )he board is connected to the <C using a serial port @C 05A% 'f your laptop doesn/t have a serial interface# you can use one of the common =783to37erial3'nterface cables +ith a soft+are driver% 'n that case the driver must be ad>usted to use bet+een C 01 and C 08 and a baud rate of 11E, to be automatically detected by the 7tudio soft+are% <rogramming is performed and controlled by recent versions of A12 studio# +hich is available for free from A)0-:/s +eb page after registration% =pdates of the device list and programming algorithm are provided +ith the 7tudio versions# so the support for ne+er devices is more li,ely than +ith other boards and programming soft+are% -5periments can start +ith the also supplied A12 @older versions* A)9078E1E# ne+er boards versions include different typesA% )his covers all hard+are re$uirements that the beginner might have%
Avr-Asm-Tutorial
11
http://www.avr-asm-tutorial.net
the editor# the assembler program# the chip programing interface# and the simulator%
1% 2% anything necessary in one pac,age# each tas, is performed +ith a specific program# the results are stored as specific files%
=sually route Q1 is chosen% 8ut because this is a tutorial# and you are to understand the underlying mechanism first# +e start +ith the description of route Q2 first% )his sho+s the +ay from a te5t file to instruction +ords in the flash memory
-rrors# that the assembler later detects# are reported along +ith the line number in the te5t file% :ine numbers are also a po+erful invention of the computer3age +hen it comes to discussions on your code +ith someone else% )yping errors are largely reduced# if those errors are mar,ed +ith colors% 't is a nice feature of an editor to highlight the components of a line in different colors% 0ore or less intelligent recognition of errors ease typing% 8ut this is a feature that ' don/t really miss% 'f your editor allo+s the selection of fonts# chose a font +ith fi5ed spacing# li,e Courier% ;eaders loo, nicer +ith that% .our editor should be capable of recogni4ing line ends +ith any combination of characters @carriage returns# line feeds# bothA +ithout producing unacceptable screens% Another item on the +ish list for &ido+s 201"%
'f you prefer shooting +ith cannons to ,ill sparro+s# you can use a mighty +ord processing soft+are to +rite assembler programs% 't might loo, nicer# +ith large bold headings# gray comments# red +arnings# changes mar,ed# and reminders on )o3!o/s in e5tra bubble fields% 7ome disadvantages here* you have to convert your te5t to plain te5t at the end# losing all your nice design +or,# and your resulting te5t file should not have a single control byte left% ther+ise this single byte +ill cause an error message# +hen you assemble the te5t% And remember* :ine numbers here are only correct on page one of your source code% 7o# +hatever te5t program you chose# it/s up to you% )he follo+ing e5amples are +ritten in +avrasm# an editor provided by A)0-: in earlier days% 'n the plain editor field +e type in our directives and assembly instructions% 't is highly recommended that lines come together +ith some comments @starting +ith RA% :ater understanding of +hat +e/ve planned here +ill be helpful in later debugging% 6o+ store the program te5t# named to something%asm into a dedicated directory# using the file menu% )he assembly program is complete no+% 'f you/d li,e to see +hat synta53highlighting means# ' have a snapshot of such an A12 editor here% )he editor recogni4es instructions automatically and uses different colors @synta5 high lightingA to signal user constants and typing errors in those instructions @in blac,A% 7toring the code in an %asm file provides nearly the same te5t file# colors are not stored in the file%
Avr-Asm-Tutorial
12
http://www.avr-asm-tutorial.net
!on/t try to find this editor or its authorR the editor is history and no longer maintained%
comments# header informations# code at program start and the general structure of programs%
Comments
)he most helpful things in assembler programs are comments% 'f you need to understand older code that you +rote# sometimes years after# you +ill be happy about having some or more hints +hat is going on in that line% 'f you li,e to ,eep your ideas secret# and to hide them against yourself and others* don/t use comments% A comment starts +ith a semicolon% All that follo+s behind on the same line +ill be ignored by the compiler% 'f you need to +rite a comment over multiple lines# start each line +ith a semicolon% 7o each assembler program should start li,e that* !"li#$.asm%!&ro'ram!to!swit#h!a!relais!on!an(!o))!ea#h!two!se#on(s !*ritten!+,!-..#hmi(t%!last!#han'e:!7.10.2001
<ut comments around all parts of the program# be it a complete subroutine or a table% &ithin the comment mention the special nature of the routine# pre3conditions necessary to call or run the routine% Also mention the results of the subroutine in case you later +ill have to find errors or to e5tend the routine later% 7ingle line comments are defined by adding a semicolon behind the command on the line% :i,e this* !!!L1I R 23+)+A! !/ere!somethin'!is!loa(e( !!!M4V R 53R 2! !an(!#opie(!somewhere!else
Avr-Asm-Tutorial
13
http://www.avr-asm-tutorial.net
located on the defined device% )he port/s names are defined +ith the same names that are used in the data sheets for the respective processor type% )his also applies to single bits in the ports% 2ead access to port 8# 8it "# can be done using its bit name <'68"# as defined in the data sheet% 'n other +ords* if you forget to include the header file you +ill run into a lot of error messages during assembly% )he resulting error messages are in some cases not necessarily related to the missing header file% thers things that should be on top of your programs are the register definitions you +or, +ith# e% g%* (1E; mpr < R 2! !0e)ine!a!new!name!)or!re'ister!316 )his has the advantage of having a complete list of registers# and to see +hich registers are still available and unused% 2enaming registers avoids conflicts in the use of these registers and the names are easier to remember% Further on +e define the constants on top of the source file# especially those that have a relevant role in different parts of the program% 7uch a constant +ould# e% g%# be the Otal fre$uency that the program is ad>usted for# if you use the serial interface on board% &ith (E=7 f> < .++++++! !4Tal!)re5uen#,!(e)inition at the beginning of the source code you immediately see for +hich cloc, you +rote the program% 1ery much easier than searching for this information +ithin 1H82 lines of source code%
Avr-Asm-Tutorial
14
http://www.avr-asm-tutorial.net
.2>"@A0B!Ctn13(e).in#C! !/ea(er!)or!ATT2>D13 .@2.T !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!/!A!3!0!*!A!3!B!!!2!>!F!?!3!G!A!T!2!?!>!!! !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !7A((!all!har(ware!in)ormation!here9 !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!!!&!?!3!T!.!!!A!>!0!!!&!2!>!.! !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !7A((!names!)or!har(ware!ports!an(!pins!here9 !Format:!.BHA!"ontrolportout!E!&?3TA !!!!!!!!!.BHA!"ontrolportin!E!&2>A !!!!!!!!!.BHA!@e(?utput&in!E!&?3TA2 !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!"!?!>!.!T!A!>!T!.!!!T!?!!!"!/!A!>!-!B! !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !7A((!all!#onstants!here!that!#an!+e!su+8e#t !!to!#han'e!+,!the!user9 !Format:!.BHA!#onst!E!IAJ"0 !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!F!2!4!K!0!B!3!2!=!B!0!!!"!?!>!.!T!A!>!T!.! !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !7A((!all!#onstants!here!that!are!not!su+8e#t !!to!#han'e!or!#al#ulate(!)rom!#onstants9 !Format:!.BHA!#onst!E!IAJ"0 !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!3!B!-!2!.!T!B!3!!!0!B!F!2!>!2!T!2!?!>!. !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !7A((!all!re'ister!names!here%!in#lu(e!in)o!on !!all!use(!re'isters!without!spe#i)i#!names9 !Format:!.0BF!rmp!E!316 .0BF!rmp!E!316! !Gultipurpose!re'ister !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!!!!.!3!A!G!!!0!B!F!2!>!2!T!2!?!>!. !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE .0.B.?3-!!040060 !Format:!@a+el:!.JDTB!>! !reserve!>!J,tes!)rom!@a+el: !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!3!B!.!B!T!!!A!>!0!!!2!>!T!!!=!B!"!T!?!3!. !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE .".B.?3-!I0000 !!!!!!!!r8mp!Gain! !3eset!ve#tor !!!!!!!!reti! !2nt!ve#tor!1 !!!!!!!!reti! !2nt!ve#tor!2 !!!!!!!!reti! !2nt!ve#tor!3 !!!!!!!!reti! !2nt!ve#tor!4 !!!!!!!!reti! !2nt!ve#tor!5 !!!!!!!!reti! !2nt!ve#tor!6 !!!!!!!!reti! !2nt!ve#tor!7 !!!!!!!!reti! !2nt!ve#tor!8 !!!!!!!!reti! !2nt!ve#tor!9 !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!!2!>!T!B!3!3!A!&!T!!!.!B!3!=!2!"!B!. !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !7A((!all!interrupt!servi#e!routines!here9 !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!!G!A!2!>!!!!&!3!?!-!3!A!G!!!!2!>!2!T !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
Avr-Asm-Tutorial
15
http://www.avr-asm-tutorial.net
Gain: !2nit!sta#$ !!!!!!!!l(i!rmp%!@?*:3AGB>0;! !2nit!@.J!sta#$ !!!!!!!!out!.&@%rmp !2nit!&ort!J !!!!!!!!l(i!rmp%:1LL00J2;M:1LL00J1;M:1LL00J0;! !0ire#tion!o)!&ort!J !!!!!!!!out!003J%rmp !7A((!all!other!init!routines!here9 !!!!!!!!l(i!rmp%1LL.B! !ena+le!sleep !!!!!!!!out!G"A"3%rmp !!!!!!!!sei !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!!!!!!&!3!?!-!3!A!G!!!!@!?!?!& !EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE @oop: !!!!!!!!sleep! !'o!to!sleep !!!!!!!!nop! !(umm,!)or!wa$e!up !!!!!!!!r8mp!loop! !'o!+a#$!to!loop !Bn(!o)!sour#e!#o(e
Avr-Asm-Tutorial
16
http://www.avr-asm-tutorial.net
)he third file# )-7)% 8J# +ill be introduced later# this file is needed to simulate an A12% 'ts format is he5adecimal and defined by A)0-:% =sing a he53editor its content loo,s li,e this% Attention* )his file format is not compatible +ith the programmer soft+are# don/t use this file to program the A12 @a very common error +hen startingA% 8J files are only produced by certain A)0-: assemblers# don/t e5pect these files +ith other assemblers% )he fourth file# )-7)%:7)# is a te5t file% !isplay its content +ith a simple editor% )he follo+ing results% )he program +ith all its addresses# instructions and error messages are displayed in a readable form% .ou +ill need that file in some cases to debug errors% :istfiles are generated only if the appropriate option is selected on the command line options and if the %6 :'7) directive doesn/t suppress listing%
Avr-Asm-Tutorial
17
http://www.avr-asm-tutorial.net
)he first dialog as,s +hether an e5isting pro>ect should be opened or a ne+ pro>ect is to be started% 'n case of a ne+ly installed 7tudio C6e+ <ro>ectM is the correct ans+er% )he 8utton C6e5tVVM brings you to the settings dialog of your ne+ pro>ect%
;ere you select CAtmel A12 AssemblerM as your pro>ect type# give that pro>ect a name @here Ctest1MA and let the 7tudio crate an initial @emptyA file for your source code# let it create a folder and select a location for that pro>ect# +here you have +rite access to% )he button C6e5tVVM opens the platform and device selection dialog*
Avr-Asm-Tutorial
18
http://www.avr-asm-tutorial.net
As debug platform select either CA12 simulatorM or CA12 simulator 2M% As !evice select your A12 type# here an A)mega8 +as selected% 'f your desired type is grayed out# select another simulator platform% Close this +indo+ +ith the CFinishM button% 6o+ a large +indo+ pops up# +hich has lots of different sub3 +indo+s%
n the left# the pro>ect +indo+ allo+s you to manipulate and vie+ all your pro>ect files% 'n the middle# the editor +indo+# allo+s you to +rite your source code @try typing its content to your editor +indo+# don/t care about the colors W these are added by the editor W remember synta53highlighting(A% n the left bottom is a C8uildM section# +here all your error messages go to% n the right side is a strange 'L vie+ and belo+ a rather +hite field# +e/ll come to that later on%
All +indo+ portions can be made larger and smaller and even can be shifted around on the screen% )ry mi5ing these +indo+s? )he ne5t pictures sho+ some differently loo,ing +indo+s# but they are all the same as here%
Avr-Asm-Tutorial
19
http://www.avr-asm-tutorial.net
After typing the source code sho+n above to your source file in the editor completely# push the menu C8uildM and its sub3 menu C8uildM% 'f you typed correctly# the result sho+s up in your C8uildM +indo+% 0a,e sure# you read all +indo+ content once for the first time# because it gives you a lot more info besides the small green circle% All that should be fine# other+ise you typed errors into the code and the circle is red% .ou can no+ push the menu item C!ebugM and some +indo+s change their content# si4e and position% 'f you also push the menu item C1ie+M# C)oolbarsM and C<rocessorM and shift around +indo+s# it should loo, li,e this* )he former editor +indo+ has a yello+ arro+ no+% )his arro+ points to the ne5t instruction that +ill be e5ecuted @not really e5ecuted# but rather CsimulatedMA% )he processor +indo+ sho+s the current program counter value @yes# the program starts at address 0A# the stac, pointer @no matter +hat that might be W +ait for that later in the courseA# a cycle counter and a stop +atch% 'f you push on the small CKM left to the +ord C2egistersM# the content of the "2 registers is displayed @yes# they are all empty +hen you start the processor simulationA% 6o+ let us proceed +ith the first instruction% 0enu item C!ebugM and C7tep intoM or simply F11 e5ecutes the first instruction%
)he instruction Cldi rmp#0b11111111M loads the binary value 1111%1111 to register 216% An instruction +e +ill learn more about later on in the course% )he yello+ arro+ no+ has advanced one instruction do+n# is no+ at the =) instruction% 'n the processor +indo+# the program counter and the cycle counter are both at 1 no+% And register 16# do+n the list of registers# is red no+ and sho+s 05FF# +hich is he5adecimal for binary 1111%1111% )o learn about another simulator +indo+ >ust advance simulation one step further to e5ecute the =) instruction @e% g% by pushing the ,ey F11%
Avr-Asm-Tutorial
20
http://www.avr-asm-tutorial.net
)he instruction C ut !!28#rmpM +rites 05FF to a port named !!28% 6o+ the action is on the 'L vie+ +indo+% 'f you push on < 2)8 and the small CKM left of it# this +indo+ displays the value 05FF in the port !!28 in t+o different forms* as 05FF in the upper +indo+ portion and as 8 blac, s$uares in the lo+er +indo+ section% )o ma,e it even more blac,# +e push F11 t+o times and +rite 05EE to the port < 2)8% As e5pected# the port < 2)8 changes its content and has four blac, and four +hite s$uares no+% Another t+o F11# +riting 05AA to < 2)8# changes the blac, and +hite s$uares to the opposite color%
All +hat has been e5pected# but +hat happened to port <'68( &e didn/t +rite something to <'68# but it has the opposite colors than < 2)8# >ust li,e the colors before in < 2)8% <'68 is an input port for e5ternal pins% 8ecause the direction ports in !!28 are set to be outputs# <'68 follo+s the pin status of < 2)8# >ust one cycle later% 6othing +rong here% 'f you li,e to
chec, this# >ust press F11 several times and you see that this is correct%
)hat is our short trip through the simulator soft+are +orld% )he simulator is capable to much more# so it should be applied e5tensively in cases of design errors% 1isit the different menu items# there is much more than can be sho+n here% 'n the mean time# instead of playing +ith the simulator# some basic things have to learned about assembler language# so put the 7tudio aside for a +hile%
Avr-Asm-Tutorial
21
http://www.avr-asm-tutorial.net
0 !hat is a register"
2egisters are special storages +ith 8 bits capacity and they loo, li,e this* 8it F 8it 6 8it E 8it H 8it " 8it 2 8it 1 8it 0
6ote the numeration of these bits* the least significant bit starts +ith 4ero @mathematically* 2 0 G 1A% A register can either store numbers from 0 to 2EE @positive number# no negative valuesA# or numbers from 3128 to K12F @+hole number +ith a sign bit# located in bit FA# or a value representing an A7C''3coded character @e% g% /A/A# or >ust eight single bits that do not have something to do +ith each other @e% g% for eight single flags# used to signal eight different yesLno decisionsA% )he special character of registers# compared to other storage sites# is that
they are connected directly to the central processing unit called the accumulator# they can be used directly in assembler instructions# either as target register for the result or as read register for a calculation or transfer# operations +ith their content re$uire only a single instruction +ord%
)here are "2 registers in an A12% )hey are originally named 20 to 2"1# but you can choose to name them to more meaningful ones using a so3called assembler directive% An e5ample*
.DEF MyPreferredRegister = R16
Assembler directives al+ays start +ith a dot% 'nstructions or labels do 6-1-2 start +ith a dot% 6ote that assembler directives li,e this are only meaningful for the assembler but do not produce any code that is e5ecutable in the A12 target chip% )he name C0y<referred2egisterM +ill not sho+ up in the assembled he5 code# and therefore this name cannot be derived from that he5 code% 'nstead of using the register name 216 +e can no+ use our o+n name C0y<referred2egisterM# if +e +ant to use 216 +ithin an instruction% 7o +e +rite a little bit more te5t each time +e use this register# but +e have an association +hat might be the content of this register% =sing the instruction line
LDI MyPreferredRegister, 150
+hich means* load the number 1E0 immediately to the register 216# :oa! 'mmediate% )his loads a fi5ed value or a constant to that register% Follo+ing the assembly# or translation of this code into binary or he5# the program storage +ritten to the A12 chip loo,s li,e this*
000000 E906
)his +ill sho+ up in the listing# a file called D%lst produced by the assembler soft+are# +hich is a simple te5t file% All numbers are in he5 format* )he first he5 number is the address @000000A# +here the instruction is +ritten to in the program flash memory of the A12# the second is the instruction code @-906A% -906 tells the processor three different things in one +ord# even if you don/t see this directly*
a basic load instruction code# that stands for :!'# the target register @216A +here the value 1E0 is to be +ritten to# the value of the constant @1E0A%
!on/t be afraid* you don/t have to remember this coding because the assembler ,no+s ho+ to translate all this to finally yield -906 and the A12 e5ecutes it% &ithin one instruction t+o different registers can play a role% )he easiest instruction of this type is the copy instruction# 0 1% )he naming of this instruction 0 1 deserves a price for the most confusing definition# because the content of a register cannot be moved @+hat +ould be left in a register# if you 0 1- its content to some+here else(A% 't should better be named C <.# because it copies the content of one register to another register% :i,e this*
.DEF MyPreferredRegister = R16 .DEF AnotherRegister = R15 LDI MyPreferredRegister, 150 MO AnotherRegister, MyPreferredRegister
)he first t+o lines of this monster program are directives that define the ne+ names of the registers 216 and 21E for the assembler% Again# these lines do not produce any code for the A12% )he instruction lines +ith :!' and 0 1 produce code*
000000 E906 000001 !F01
)he instruction +rite the value 1E0 into register 216 and copy its content to the target register 21E% 1ery '0< 2)A6) 6 )'C-*
Avr-Asm-Tutorial
22
http://www.avr-asm-tutorial.net
The first re'ister is always the tar'et re'ister where the res$lt is written to5 @)his is unfortunately different from +hat one e5pects or from ho+ +e spea,# thin, and +rite W left to right% 't is a simple convention# probably inspired by some Asian languages +here +riting is from right to left% )hat +as once defined that +ay to confuse the beginners learning assembler% )hat is +hy assembly language is that complicated%A
And* you lost% nly the registers from 216 to 2"1 load a constant immediately +ith the :!' instruction# 20 to 21E don/t do that% )his restriction is not very fine# but could not be avoided during construction of the instruction set for the A12s% )here is one e5ception from that rule* setting a register to Sero% )his instruction
"LR MyPreferredRegister
is valid for all registers% 8esides the :!' instruction you +ill find this register class restriction +ith the follo+ing additional instructions*
A6!' 25#N R 8it3And of register 25 +ith a constant value N# C82 25#0 R Clear all bits in register 25 that are set to one +ithin the constant mas, value 0# C<' 25#N R Compare the content of the register 25 +ith a constant value N# 78C' 25#N R 7ubtract the constant N and the current value of the carry flag from the content of register 25 and store the result in register 25# 782 25#0 R 7et all bits in register 25 to one# that are one in the constant mas, 0# 7-2 25 R 7et all bits in register 25 to one @e$ual to :!' 25#2EEA# 7=8' 25#N R 7ubtract the constant N from the content of register 25 and store the result in register 25%
'n all these instructions the register must be bet+een 216 and 2"1? 'f you plan to use these instructions you should select one of these registers for that operation% 't is shorter and easier to program% )his is an additional reason +hy you should use the directive to define a register/s name# because you can easier change the registers location later on# if re$uired%
).2 Pointer-re'isters
A very special e5tra role is defined for the register pairs 22F*226# 229*228 and 2"1*2"2% )he role is so important that these pairs have e5tra short names in A12 assembler* O# . and S% )hese short names are understood by the assembler% )hese pairs are 163bit pointer registers# able to point to addresses +ith ma5% 16 bit length# e% g% into 72A0 locations @O# . or SA or into locations in program memory @SA%
Accesses via pointer registers are programmed +ith specially designed instructions% 2ead access is named :! @:oa!A# +rite access named 7) @7)oreA# e% g% +ith the O3pointer* 7imilarly you can use . and S for that purpose%
Pointer O OK 3O
Sequence 2eadL&rite from address O# don/t change the pointer 2eadL&rite fromLto address O# and increment the pointer after+ards by one
First decrement the pointer by one and readL+rite fromLto the ne+ address :! 21#3O or 7) 3O#21 after+ards
Avr-Asm-Tutorial
23
http://www.avr-asm-tutorial.net
As the program memory is organi4ed +ord3+ise @one instruction on one address consists of 16 bits or t+o bytes or one +ordA the least significant bit selects the lo+er or upper byte @0Glo+er byte# 1G upper byteA% 8ecause of this the original address must be multiplied by 2 and access is limited to 1E3bit or "2 ,8 program memory% :i,e this*
LDI 5/,/I0/1!+%ddress2 LDI 5L,LO41!+%ddress2 LPM
Follo+ing this instruction the address must be incremented to point to the ne5t byte in program memory% As this is used very often a special pointer incrementation instruction has been defined to do this*
ADI4 5L,1 LPM
A!'& means A!d 'mmediate &ord and a ma5imum of 6" can be added this +ay% 6ote that the assembler e5pects the lo+er of the pointer register pair S: as first parameter% )his is some+hat confusing as addition is done as 163bit3 operation% )he complement instruction# subtracting a constant value of bet+een 0 and 6" from a 163bit pointer register is named 78'&# 7ubtract 'mmediate &ord% @7u8tract 'mmediate &ordA% A!'& and 78'& are possible for the pointer register pairs O# . and S and for the register pair 22E*22H# that does not have an e5tra name and does not allo+ access to 72A0 or program memory locations% 22E*22H is ideal for handling 163bit values% As incrementation after reading is very often needed# ne+er A12 types have the instruction LPM R,Z+ )his allo+s to transport the byte read to any location 2# and auto3increments the pointer register%
.ou should al+ays place an even number of bytes on each single line% ther+ise the assembler +ill add a 4ero byte at the end# +hich might be un+anted% )he similar list of +ords loo,s li,e this*
.D4 1!675,6899 ' % -ist of t;o ;ord ,onst%nts
'nstead of constants you can also place labels @e% g% >ump targetsA on that list# li,e that*
L%)e-1@ A ... here %re so<e instr:,tions ... B L%)e-!@ A ... here %re so<e <ore instr:,tions ... B >%)-e@ .D4 L%)e-1,L%)e-! ' % ;ord ;ise -ist of -%)e-s
:abels should start in column 1# but have to be ending +ith a C*M% 6ote that reading the labels from that table +ith :<0 @and subse$uent incrementation of the pointerA first yields the lo+er byte of the +ord# then the upper byte%
)his is only an e5ample% .ou can calculate the table address in S from some input value# leading to the respective table values% )ables can be organi4ed byte3 or character3+ise# too%
Avr-Asm-Tutorial
24
http://www.avr-asm-tutorial.net
!efine names for registers +ith the %!-F directive# never use them +ith their direct name 25% 'f you need pointer access reserve 226 to 2"1 for that purpose% A 163bit3counter is best located in 22E*22H% 'f you need to read from the program memory# e% g% fi5ed tables# reserve S @2"1*2"0A and 20 for that purpose% 'f you plan to have access to single bits +ithin certain registers @e% g% for testing flagsA# use 216 to 22" for that purpose% 2egisters necessary for math are best placed to 21 to 21E% 'f you have more than enough registers available# place all your variables in registers% 'f you get short in registers# place as many variables as necessary to 72A0%
Avr-Asm-Tutorial
25
http://www.avr-asm-tutorial.net
2 'orts
+.1 .hat is a Port/
<orts in the A12 are gates from the central processing unit to internal and e5ternal hard3 and soft+are components% )he C<= communicates +ith these components# reads from them or +rites to them# e% g% to the timers or the parallel ports% )he most used port is the flag register# +here flags from previous operations are +ritten to and branching conditions are read from% )here are 6H different ports# +hich are not physically available in all different A12 types% !epending on the storage space and other internal hard+are the different ports are either available and accessible or not% &hich of the ports can be used in a certain A12 type is listed in the data sheets for the processor type% :arger A)mega and A)Omega have more than 6H ports# access to the ports beyond Q6" is different then @see belo+A% <orts have a fi5ed address# over +hich the C<= communicates% )he address is independent from the type of A12% 7o e% g% the port address of port 8 is al+ays 0518 @05 stands for he5adecimal notation# 0518 is decimal 2HA% .ou don/t have to remember these port addresses# they have convenient aliases% )hese names are defined in the include files @header filesA for the different A12 types# that are provided from the producer% )he include files have a line defining port 8/s address as follo+s*
.E#$ POR>3, 0?19
7o +e >ust have to remember the name of port 8# not its location in the 'L space of the chip% )he include file 8E1Edef%inc is involved by the assembler directive
.I&"L$DE ="@F*o<e;hereF9515def.in,=
and the registers of the 8E1E are all defined there and easily accessible% <orts usually are organi4ed as 83bit numbers# but can also hold up to 8 single bits that don/t have much to do +ith each other% 'f these single bits have a meaning they have their o+n name associated in the include file# e% g% to enable the manipulation of a single bit% !ue to that name convention you don/t have to remember these bit positions% )hese names are defined in the data sheets and are given in the include file# too% )hey are provided here in the port tables%
't is a port# fully pac,ed +ith 8 control bits +ith their o+n names @'7C00# '7C01# %%%A% )hose +ho +ant to send their A12 to a deep sleep need to ,no+ from the data sheet ho+ to set the respective bits% :i,e this*
.DEF MyPreferredRegister = R16 LDI MyPreferredRegister, 0)00100000 O$> M"$"R, MyPreferredRegister *LEEP
)he ut instruction brings the content of my preferred register# a 7leep3-nable38it called 7-# to the port 0C=C2% 7enables the A12 to go to sleep# +henever the 7:--< instruction sho+s up in the code% As all the other bits of 0C=C2 are also set by the above instructions and the 7leep 0ode bit 70 +as set to 4ero# a mode called half3sleep +ill result* no further instruction e5ecution +ill be performed but the chip still reacts to timer and other hard+are interrupts% )hese e5ternal events interrupt the big sleep of the C<= if they feel they should notify the C<=% )he above formulation is not very transparent# because C0b00100000M is not easy to remember# and no one sees easily +hat bit e5actly has been set to one by this instruction% 7o it is a good idea to formulate the :!' instruction as follo+s* LDI MyPreferredRegister, 1<<SE )his formulation tells the assembler to
ta,e a one @C1MA# to read the bit position of the 7leep -nable bit @C7-MA from the symbol list# as defined in the header file 8E1Edef%inc# +hich yields a value of CEM in that case# to shift @CXXMA the C1M five times left @C1XXEMA# in steps* 1% initial* 0000%0001#
Avr-Asm-Tutorial
26
http://www.avr-asm-tutorial.net
2% "% H%
first shift left* 0000%0010# second shift left* 0000%0100# and so on until fifth shift left* 0010%0000%
to associate this value to MyPreferredRegister and to insert this :!' instruction into the code%
)o ma,e it clear again* )his shifting is done by the assembler soft+are only# not +ithin the code in the A12% 't is pure convention to increase the readability of the assembler source te5t% ;o+ does this change# if you +ant to set the 7leep 0ode bit @C70MA and the 7leep -nable bit @C7-MA +ithin the same :!' instruction( 70G1 and 7-G1 enables your A12 to react to a 7:--< instruction by going to a big sleep# so only do this if you understand +hat the conse$uences are% )he formulation is li,e this* LDI MyPreferredRegister, (1<<SM) Y (1<<SE) 6o+# the assembler first calculates the value of the first brac,et# @1XX70A# a C1M shifted four times left @because 70 is HA and that yields 0001%0000# then calculates the second brac,et# @1XX7-A# a C1M shifted five times left @because 7- is EA% )he CYM bet+een the t+o brac,ets means 8')3 2 the first and the second value# each bit one by one% )he result of doing this +ith 0001%0000 and 0010%0000 in that case is 0011%0000# and that is our desired value for the :!' instruction% -ven though the formulation @1XX70A Y @1XX7-A might# on the first loo,# not be more transparent than the resulting value 0011%0000 for a beginner# it is easier to understand +hich bits of 0C=C2 are intended to be manipulated in this :!' instruction% -specially if you have to read and understand your code some months later# 70 and 7- are a better hint that the 7leep 0ode and -nable bits are targeted here% ther+ise you +ould have to consult the device/s data boo, much more often%
reads the bits in port 0C=C2 to the register named MyPreferredRegister% As many ports have undefined and unused bits in certain ports# these bits al+ays read bac, as 4eros% 0ore often than reading all 8 bits of a port one must react to a certain status bit +ithin a port% 'n that case +e don/t need to read the +hole port and isolate the relevant bit% Certain instructions provide an opportunity to e5ecute instructions depending on the level of a certain bit of a port @see the J=0< sectionA%
)hese t+o instructions have a limitation* only ports +ith an address smaller than 0520 can be handled# ports above cannot be accessed that +ay% 8ecause 0C=C2 in the above e5amples is at he5 address Z"8# the sleep mode and enable bits can/t be set or cleared that +ay% 8ut all the port bits controlling e5ternal pins @< 2)5# !!25# <'65A are accessible that +ay%
)hat only ma,es sense in certain cases# because it re$uires more instructions# e5ecution time and assembler lines# but it is possible% 't is also the reason +hy the first address location of the 72A0 is 0560 or 05100 in some larger A12 types%
Avr-Asm-Tutorial
27
http://www.avr-asm-tutorial.net
Component Accumulator 7tac, -5ternal 72A0L-5ternal 'nterrupt -5ternal 'nterrupts )imer 'nterrupts 83bit )imer 0 163bit )imer 1
Port name 72-J 7<:L7<; 0C=C2 J'07N J'F2 )'07N )'F2 )CC20 )C6)0 )CC21A )CC218 )C6)1 C21A C218 'C21:L; 7tatus 2egister 7tac,pointer
Port-Register
0C= Jeneral Control 2egister 'nterrupt 0as, 2egister 'nterrupt Flag 2egister )imer 'nterrupt 0as, 2egister )imer 'nterrupt Flag 2egister )imerLCounter 0 Control 2egister )imerLCounter 0 )imerLCounter Control 2egister 1 A )imerLCounter Control 2egister 1 8 )imerLCounter 1 utput Compare 2egister 1 A utput Compare 2egister 1 8 'nput Capture 2egister &atchdog )imer Control 2egister --<2 0 address 2egister --<2 0 !ata 2egister --<2 0 Control 2egister 7erial <eripheral Control 2egister 7erial <eripheral 7tatus 2egister 7erial <eripheral !ata 2egister =A2) !ata 2egister =A2) 7tatus 2egister =A2) Control 2egister =A2) 8aud 2ate 2egister Analog Comparator Control and 7tatus 2egister <ort utput 2egister <ort !irection 2egister <ort 'nput 2egister
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 S Calculation A!!# A!C# A!'&# !-C# '6C# 7=8# 7=8'# 78C# 78C'# 78'& A!!# A!C# A!'&# 7=8# 7=8'# 78C# 78C'# 78'& Logic A6!# A6!'# 2# 2'# - 2# C 0# 6-J# 782# C82 C 0# 6-J Compare Bits Shift Other
C<# C<C# C<' 8C:2 S# 87-) S# C:S# 7-S# )7) C<# C<C# C<' 8C:2 C# 87-) C# C:C# 7-C
Avr-Asm-Tutorial
28
http://www.avr-asm-tutorial.net
Bit 6
Calculation A!!# A!C# A!'&# !-C# '6C# 7=8# 7=8'# 78C# 78C'# 78'& A!!# A!C# A!'&# !-C# '6C# 7=8# 7=8'# 78C# 78C'# 78'& 78'& A!!# A!C# 7=8# 7=8'# 78C# 78C' 3 3
Logic A6!# A6!'# 2# 2'# - 2# C 0# 6-J# 782# C82 A6!# A6!'# 2# 2'# - 2# C 0# 6-J# 782# C82 3 6-J 3 3
Compare
Bits
Shift
Other
C<# C<C# C<' 8C:2 6# 87-) 6# A72# :7:# :72# C:2 C:6# 7-6# )7) 2 :# 2 2 C<# C<C# C<' 8C:2 1# 87-) 1# C:1# 7-1# )7) 3 8C:2 7# 87-) 7# C:7# 7-7 A72# :7:# :72# C:2 2 :# 2 2 3 3 3 3 2-)'
7 ; ) '
C<# C<C# C<' 8C:2 ;# 87-) ;# 3 C:;# 7-; 3 3 8C:2 )# 87-) )# 87)# C:)# 7-) 8C:2 '# 87-) '# C:'# 7-' 3 3
Avr-Asm-Tutorial
29
http://www.avr-asm-tutorial.net
5 ,RAM
6early all A123types have static 2A0 @72A0A on board @only very fe+ old devices don/tA% nly very simple assembler programs can avoid using this memory space by putting all necessary information into registers% 'f you run out of registers you should be able to program the 72A0 to utili4e more space%
the content of register 21 is copied to the first 72A0 location in address 050060% &ith
LD* R1, 0?0060
the 72A0 content at address 050060 is copied to the register% )his is the direct access +ith an address that has to be defined by the programmer% )he symbols defined in the Ddef%inc include file# 72A0T7)A2) and 2A0-6!# allo+ to place your variables +ithin the 72A0 space% 7o it is better to use these definitions to access the 1Eth memory byte# li,e this*
LD* R1,*RAMJ*>AR>I15
7ymbolic names can be used to avoid handling fi5ed addresses# that re$uire a lot of +or,# if you later +ant to change the structure of your data in the 72A0% )hese names are easier to handle than he5 numbers# so give that address a name li,e*
30
http://www.avr-asm-tutorial.net
.es# it isn/t shorter# but easier to remember% =se +hatever name that you find to be convenient%
-asy to operate# those pointers% And as easy as in other languages than assembler# that claim to be easier to learn%
7ome+here later in the program '/d li,e to +rite to cell 2 above 72A0T7)A2)*
*>D .I!, MyPreferredRegister
is also possible% 6ote that the 2 is not really added to .# >ust temporarily during the e5ecution of this instruction% )o confuse you further# this can only be done +ith the .3 and S3register3pair# not +ith the O3pointer? f about 100 cases# the use of this opportunity is more effective in one single case% 7o don/t care if you don/t understand this in detail% 't is only for e5perts# and only necessary in a fe+ cases% )hat/s it +ith the 72A0# but +ait* the most relevant use as stac, is still to be learned%
31
http://www.avr-asm-tutorial.net
)he value 2A0-6! is# of course# specific for the processor type% 't is defined in the '6C:=!- file for the processor type% )he file 8E1Edef%inc has the line*
.eM: RAME&D =N!5F ' L%st On("hiE *RAM Lo,%tion
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%
&here that value goes to is totally uninteresting% )hat the stac, pointer +as decremented after that push# +e don/t have to care% 'f +e need the content again# +e >ust add the follo+ing instruction*
POP MyPreferredRegister ' Re%d )%,L the C%-:e fro< the toE of the st%,L
&ith < < +e >ust get the value that +as last pushed on top of the stac,% <ushing and popping registers ma,es sense# if
the content is again needed some lines of the code later# all registers are in use# and if no other opportunity e5ists to store that value some+here else%
'f these conditions are not given# the use of the stac, for saving registers is useless and >ust +astes processor time% 0ore sense ma,es the use of the stac, in subroutines# +here you have to return to the program location that called the routine% 'n that case the calling program code pushes the return address @the current program counter valueA onto the stac, and temporarily >umps to the subroutine% After its e5ecution the subroutine pops the return address from the stac, and loads it bac, into the program counter% <rogram e5ecution is continued e5actly one instruction behind the instruction# +here the call happened*
R"ALL *o<e;h%t ' O:<E to the -%)e- Gso<e;h%t@H A...B here ;e ;i-- -%ter ,ontin:e ;ith the Erogr%<.
;ere the >ump to the label Csome+hat*M some+here in the program code#
*o<e;h%t@ ' this is the P:<E %ddress A...B /ere ;e do so<ething A...B %nd ;e %re finished %nd ;%nt to P:<E )%,L to the ,%--ing -o,%tion@ RE>
!uring e5ecution of the 2CA:: instruction the already incremented program counter# a 163bit3address# is pushed onto the stac,# using t+o pushes @the :78 and the 078A% 8y reaching the 2-) instruction# the content of the previous program counter is reloaded +ith t+o pops and e5ecution continues there% .ou don/t need to care about the address of the stac,# +here the counter is loaded to% )his address is automatically generated% -ven if you call a subroutine +ithin that subroutine the stac, function is fine% )his >ust pac,s t+o return addresses on top of the stac,# the nested subroutine removes the first one# the calling subroutine the remaining one% As long as there is enough 72A0# everything is fine% 7ervicing hard+are interrupts isn/t possible +ithout the stac,% 'nterrupts stop the normal e5ecution of the program# +herever the program currently is% After e5ecution of a specific service routine as a reaction to that interrupt program e5ecution must return to the previous location# to before the interrupt occurred% )his +ould not be possible if the stac, is not able to store the return address% )he enormous advances of having a stac, for interrupts are the reason# +hy even the smallest A12s +ithout having 72A0 have at least a very small hard+are stac,%
Avr-Asm-Tutorial
32
http://www.avr-asm-tutorial.net
'n a very fe+ cases the stac, overflo+s to belo+ the first 72A0 location% )his happens in case of a never3ending recursive call% After reaching the lo+est 72A0 location the ne5t pushes +rite to the ports @0500EF do+n to 050020A# then to the registers @05001F to 050000A% Funny and unpredictable things happen +ith the chip hard+are# if this goes on% Avoid this bug# it can even destroy your e5ternal hard+are?
Avr-Asm-Tutorial
33
http://www.avr-asm-tutorial.net
!uring an e5ternal reset on the reset pin of the device a restart is e5ecuted% 'f the &atchdog counter reaches its ma5imum count# a reset is initiated% A +atchdog timer is an internal cloc, that must be reseted from time to time by the program# other+ise it restarts the processor% .ou can call reset by a direct >ump to that address @see the >ump section belo+A%
)he third case is not a real reset# because the automatic resetting of register3 and port3values to a +ell3defined default value is not e5ecuted% 7o# forget that for no+% )he second option# the +atchdog reset# must first be enabled by the program% 't is disabled by default% -nabling re$uires +rite instructions to the +atchdog/s port% 7etting the +atchdog counter bac, to 4ero re$uires the e5ecution of the instruction
4DR
to avoid a reset% After e5ecution of a reset# +ith setting registers and ports to default values# the code at address 0000 is +ord +ise read to the e5ecution part of the processor and is e5ecuted% !uring that e5ecution the program counter is already incremented by one and the ne5t +ord of code is already read to the code fetch buffer @Fetch during -5ecutionA% 'f the e5ecuted instruction does not re$uire a >ump to another location in the program the ne5t instruction is e5ecuted immediately% )hat is +hy the A12s e5ecute e5tremely fast# each cloc, cycle e5ecutes one instruction @if no >umps occurA% )he first instruction of an e5ecutable is al+ays located at address 0000% )o tell the compiler @assembler programA that our source code starts no+ and here# a special directive can be placed at the beginning# before the first code in the source is +ritten*
."*E0 .OR0 0000
)he first directive# %C7-J# lets the compiler s+itch his output to the code section% All follo+ing is translated as code and is later +ritten to the program flash memory section of the processor% Another target segment +ould be the --<2 0 section of the chip# +here you also can +rite bytes or +ords to%
.E*E0
ther than +ith --<2 0 content# +here content is really going to the --<2 0 during programming of the chip# the !7-J segment content is not programmed to the chip% )here is no opportunity to burn any 72A0 content% 7o the %!7-J is only used for correct label calculation during the assembly process% An e5ample*
.D*E0 ' >he fo--o;ing %re -%)e- definitions ;ithin the *RAM seg<ent MyFirst %ri%)-eIsA3yte@ .3.>E 1 ' the D*E0(Pointer <oCes one )yte :E;%rds My*e,ond %ri%)-eIsA4ord@ .3.>E ! ' the D*E0(Pointer <oCes t;o )ytes :E;%rds My>hird %ri%)-eIsAFie-dForA3:ffer@ .3.>E 6!' the D*E0(Pointer <oCes 6! )ytes :E;%rds
7o# only three labels are defined +ithin the assembler# no content is produced% )he 2J directive +ithin the code segment# % 2J# above stands for the +ord CoriginM and manipulates the address +ithin the code segment# +here assembled +ords go to% As our program al+ays starts at 050000 the C7-JL 2J directives are trivial# you can s,ip these +ithout getting into an error% &e could start at 050100# but that ma,es no real sense as the processor starts e5ecution at 0000% 'f you +ant to place a table e5actly to a certain location of the code segment# you can use 2J% 8ut be careful +ith that* nly >ump for+ard +ith % 2J# never bac,+ards% And be a+are that the flash memory space that you s,ipped in bet+een your current code location and the one you forced +ith % 2J is al+ays filled +ith the instruction +ord 05FFFF% )his instruction does nothing# >ust goes to the ne5t instruction% 7o be sure your e5ecution never >umps into such undefined space in bet+een% 'f on the beginning of your code section you +ant to set a clear sign +ithin your code# after first defining a lot of other things +ith %!-F3 and %-P=3directives# use the C7-JL 2J se$uence as a signal for yourself# even though it might not be
Avr-Asm-Tutorial
34
http://www.avr-asm-tutorial.net
necessary to do that% As the first code +ord is al+ays at address 4ero# this location is also called the reset vector% Follo+ing the reset vector the ne5t positions in the program space# addresses 050001# 050002 etc%# are interrupt vectors% )hese are the positions +here the e5ecution >umps to if an e5ternal or internal interrupt has been enabled and occurs% )hese positions called vectors are specific for each processor type and depend on the internal hard+are available @see belo+A% )he instructions to react to such an interrupt have to be placed to the proper vector location% 'f you use interrupts# the first code# at the reset vector# must be a >ump instruction# to >ump over the other vectors% -ach interrupt vector# that is planned to be enabled# must hold a >ump instruction to the respective interrupt service routine% 'f the vector is not used# a dummy instruction li,e 2-)' @2-)urn from 'nterruptA is best placed here% )he typical program se$uence at the beginning is li,e follo+s*
."*E0 .OR0 0000 ROMP *t%rt ' the reset Ce,tor ROMP Int*erCRo:t1 ' the interr:Et serCi,e ro:tine for the first interr:Et RE>I ' % d:<<y for %n :n:sed interr:Et ROMP Int*erCRo:t6 ' the interr:Et serCi,e ro:tine for the third interr:Et A...B here ;e E-%,e %-- the other interr:Et Ce,tor instr:,tions A...B %nd here is % good E-%,e for the interr:Et serCi,e ro:tines the<se-Ces Int*erCRo:t1@ A...B "ode of the first int serCi,e ro:tine RE>I ' end of serCi,e ro:tine 1 Int*erCRo:t!@ A...B "ode of the third int serCi,e ro:tine RE>I ' end of serCi,e ro:tine ! A...B other ,ode *t%rt@ ' >his here is the Erogr%< st%rt A...B /ere ;e E-%,e o:r <%in Erogr%<
)he instruction C2J0< 7tartM results in a >ump to the label 7tart*# located some lines belo+% 2emember# labels al+ays end +ith a C*M% :abels# that don/t fulfill these conditions are not ta,en for serious# but interpreted as instructions% 0issing labels result in an error message @I=ndefined labelIA# and compilation is interrupted%
$ranching
8ranching is very often depending on some condition# called conditional branching% As an e5ample +e assume +e +ant to construct a "23bit3counter using the registers 21 to 2H% )he least significant byte in 21 is incremented by one% 'f the register overflo+s during that operation @2EE K 1 G 0A# +e have to increment 22 similarly% 'f 22 overflo+s# +e have to increment 2"# and so on% 'ncrementation by one is done +ith the instruction '6C% 'f an overflo+ occurs during that e5ecution of '6C 21# the 4ero bit in the status register is set to one @the result of the operation is 4eroA% )he carry bit in the status register# as usually set +hen something overflo+s# is not changed during an '6C% )his is not to confuse the beginner# but carry can be used for other purposes instead% )he Sero38it or Sero3flag in this case is enough to detect an overflo+% 'f no overflo+ occurs +e can >ust leave the counting se$uence% 'f the Sero3bit is set# +e must e5ecute additional incrementation of the ne5t upper register% )o confuse the beginner the branching instruction# that +e have to use# is not named 826S but 826- @82anch if 6ot -$ualA% A matter of taste %%% )he +hole count se$uence of the "23bit3counter should then loo, li,e this*
I&" R1 ' in,re%se ,ontent of register R1 3R&E 0oOn6! ' if not Dero, )r%n,h to 0oOn6!@ I&" R! ' in,re%se ,ontent of register R! 3R&E 0oOn6! I&" R6 3R&E 0oOn6! I&" R7 0oOn6!@
7o that/s about it% An easy thing% )he opposite condition to 826- is 82-P or 82anch -Pual% &hich of the status bits# also called processor flags# are changed during e5ecution of an instruction is listed in instruction code tables# see the :ist of 'nstructions% 7imilarly to the Sero3bit you can use the other status bits li,e that*
3R"" -%)e-Q3R"* -%)e-' "%rry(f-%g 0 13R""2 or 1 13R"*2 3R*/ -%)e-' EM:%- or gre%ter 3RLO -%)e-' *<%--er 3RMI -%)e-' Min:s 3RPL -%)e-' P-:s 3R0E -%)e-' 0re%ter or eM:%- 1;ith sign )it2 3RL> -%)e-' *<%--er 1;ith sign )it2 3R/" -%)e-Q3R/* -%)e-' /%-f oCerf-o; f-%g 0 or 1 3R>" -%)e-Q3R>* -%)e-' >(3it 0 or 1 3R " -%)e-Q3R * -%)e-' >;oRs ,o<E-e<ent f-%g 0 or 1 3RIE -%)e-Q3RID -%)e-' Interr:Et en%)-ed or dis%)-ed
Avr-Asm-Tutorial
35
http://www.avr-asm-tutorial.net
to react to the different conditions% 8ranching al+ays occurs if the condition is met% !on/t be afraid# most of these instructions are rarely used% For the beginner only Sero and Carry are relevant%
)his instruction does nothing but +asting processor time% At H 0;4 cloc, +e need >ust four of these instructions to +aste 1 [s% 6o other hidden meanings here on the 6 < instruction% For a signal generator +ith 1 ,;4 +e don/t need to add H000 such instructions to our source code# but +e use a soft+are counter and some branching instructions% &ith these +e construct a loop that e5ecutes for a certain number of times and are e5actly delayed% A counter could be a 83bit3register that is decremented +ith the !-C instruction# e% g% li,e this*
"LR R1 ' one ,-o,L ,y,-e "o:nt@ DE" R1 ' one ,-o,L ,y,-e 3R&E "o:nt ' t;o for )r%n,hing, one for not )r%n,hing
)his se$uence +astes @1A K @2EED2A K @1D"A G E1H cloc, cycles or 128%E [s at H 0;4% 163bit counting can also be used to delay e5actly# li,e this
LDI 5/,/I0/1655652 ' one ,-o,L ,y,-e LDI 5L,LO41655652 ' one ,-o,L ,y,-e "o:nt@ *3I4 5L,1 ' t;o ,-o,L ,y,-es 3R&E "o:nt ' t;o for )r%n,hing, one for not )r%n,hing
)his se$uence +astes @1K1A K @6EE"HDHA K @1D"A G 262#1H1 cloc, cycles or 6E#E"E%2E [s at H 0;4% 'f you use more registers to construct nested counters you can reach any delay% And the delay is as e5act as your cloc, source is# even +ithout a hard+are timer%
)his definition of the macro does not yet produce any code# it is silent% Code is produced only if you call that macro by its name*
A...B so<e;here in the so:r,e ,ode De-%y1 A...B ,ode goes on here
)his results in four 6 < instructions inserted to the code at that location% An additional C!elay1M inserts additional four 6 < instructions% 'f your macro has longer code se$uences# or if you are short in code storage space# you should avoid the use of macros and use subroutines instead% 8y calling a macro by its name you can add some parameters to manipulate the produced code% 8ut this is more than a beginner has to ,no+ about macros%
-.) 0$bro$tines
'n contrary to macros a subroutine does save program storage space% )he respective se$uence is only once stored in the code and is called from +hatever part of the code% )o ensure continued e5ecution of the se$uence follo+ing the
Avr-Asm-Tutorial
36
http://www.avr-asm-tutorial.net
subroutine call you need to return to the caller% For a delay of 10 cycles you need to +rite this subroutine*
De-%y10@ ' the ,%-- of the s:)ro:tine reM:ires so<e ,y,-es &OP ' de-%y one ,y,-e &OP ' de-%y one ,y,-e &OP ' de-%y one ,y,-e RE> ' ret:rn to the ,%--er
7ubroutines al+ays start +ith a label# other+ise you +ould not be able to >ump to it# here named C!elay10*M% )hree 6 <s follo+ and a 2-) instruction% 'f you count the necessary cycles you >ust find F cycles @" for the 6 <s# H for the 2-)A% )he missing " are for calling that routine*
A...B so<e;here in the so:r,e ,ode@ R"ALL De-%y10 A...B f:rther on ;ith the so:r,e ,ode
2CA:: is a relative call% )he call is coded as relative >ump# the relative distance from the calling routine to the subroutine is calculated by the compiler% )he 2-) instruction >umps bac, to the calling routine% 6ote that before you use subroutine calls you must set the stac, pointer @see 7tac,A# because the return address must be pac,ed on top of the stac, during the 2CA:: instruction% 'f you +ant to >ump directly to some+here else in the code you have to use the >ump instruction*
A...B so<e;here in the so:r,e ,ode ROMP De-%y10 Ret:rn@ A...B f:rther on ;ith so:r,e ,ode
6ote that 2J0< is also a relative >ump instruction +ith limited distance% nly A)mega A12s have a J0< instruction allo+ing >umps over the complete flash memory space# but these instructions re$uire t+o +ords and more instruction time than 2J0<# so avoid it if possible% )he routine that you >umped to can not use the 2-) instruction in that case# because 2J0< does not place the current e5ecution address to the stac,% )o return bac, to the calling location in the source re$uires to add another label and the called routine to >ump bac, to this label% Jumping li,e this is not li,e calling a subroutine because you can/t call this routine from different locations in the code% 2CA:: and 2J0< are unconditioned branches% )o >ump to another location# depending on some condition# you have to combine these +ith branching instructions% Conditioned calling of a subroutine can best be done +ith the follo+ing @confusingA instructions% 'f you +ant to call a subroutine depending on a certain bit in a register use the follo+ing se$uence*
*3R" R1,8 ' *LiE the ne?t instr:,tion if )it 8 in register 1 is 0 R"ALL $EL%)e- ' "%-- th%t s:)ro:tine
782C reads B7,ip ne5t instruction if 8it F in 2egister 21 is Clear @GSeroAC% )he 2CA:: instruction to C=p:abel*M is only e5ecuted if bit F in register 21 is 1# because the ne5t instruction is s,ipped if it +ould be 0% 'f you li,e to call the subroutine in case this bit is 0 then you use the corresponding instruction 7827% )he instruction follo+ing 7827L782C can be a single +ord or double +ord instruction# the processor ,no+s ho+ far he has to >ump over it% 6ote that e5ecution times are different then% )o >ump over more than one follo+ing instruction these instructions cannot be used% 'f you have to s,ip an instruction in case t+o registers have the same value you can use the follo+ing e5otic instruction*
"P*E R1,R! ' "o<E%re R1 %nd R!, sLiE ne?t instr:,tion if eM:%R"ALL *o<e*:)ro:tine ' "%-- *o<e*:)ro:tine
A rarely used instruction# forget it for the beginning% 'f you li,e to s,ip the follo+ing instruction depending on a certain bit in a port use the follo+ing instructions 78'C and 78'7% )hat reads C7,ip if the 8it in 'Lo space is Clear @or 7etAM# li,e this*
*3I" PI&3,0 ' *LiE ne?t instr:,tion if 3it 0 on inE:t Eort 3 is 0 ROMP A>%rget ' O:<E to the -%)e- A>%rget
)he 2J0<3instruction is only e5ecuted if bit 0 in port 8 is high% )his is something confusing for the beginner% )he access to the port bits is limited to the lo+er half of ports# the upper "2 ports are not usable here% 6o+# another e5otic application for the e5pert% 7,ip this if you are a beginner% Assume +e have a bit s+itch +ith H s+itches connected to port 8% !epending on the state of these H bits +e +ould li,e to >ump to 16 different locations in the code% 6o+ +e can read the port and use several branching instructions to find out# +here +e have to >ump to today% As alternative you can +rite a table holding the 16 addresses# li,e this*
My>%)@ ROMP Ro:tine1 ROMP Ro:tine! A...B ROMP Ro:tine16
'n our code +e copy that address of the table to the S pointer register*
LDI 5/,/I0/1My>%)2 LDI 5L,LO41My>%)2
and add the current state of the port 8 @in 216A to this address%
ADD 5L,R16 3R"" &oOCerf-o;
37
http://www.avr-asm-tutorial.net
6o+ +e can >ump to this location in the table# either for calling a subroutine*
I"ALL ' ,%-- the s:)ro:tine ;hi,h %ddress is in 5
)he processor loads the content of the S register pair into its program counter and continues operation there% 0ore clever than branching over and over(
-ach single interrupt re$uires additional port manipulation to be enabled% 'f the interrupting condition occurs# e% g% a change on the port bit# the processor pushes the actual program counter to the stac, @+hich must be enabled first? 7ee initiation of the stac,pointer in the 7tac, section of the 72A0 descriptionA% &ithout that# the processor +ouldn/t be able to return bac, to the location# +here the interrupt occurred @+hich could be any time and any+here +ithin program e5ecutionA% After that# processing >umps to the predefined location# the interrupt vector# and e5ecutes the instructions there% =sually the instruction there is a J=0< instruction to the interrupt service routine# located some+here in the code% )he interrupt vector is a processor3specific location and depending from the hard+are component and the condition that leads to the interrupt% )he more hard+are components and the more conditions# the more vectors% )he different vectors for some older A12 types are listed in the follo+ing table% @)he first vector isn/t an interrupt but the reset vector# performing no stac, operation?A Name 2-7-) '6)0 '6)1 )'0-21CA<) )'0-21C 0<A )'0-21 C 0<8 )'0-21 C 0<1 )'0-21 1F )'0-20 1F 7<' 7)C =A2) )O =A2) =!2=A2) )O A6ATC 0< Interrupt Vector !!ress "#$# 0000 0001 0002 000" 3 3 000H 000E 0006 3 000F 0008 0009 3 "#"# 0000 0001 3 3 3 3 3 3 0002 3 3 3 3 3 %&$& 0000 0001 0002 000" 000H 000E 3 0006 000F 0008 0009 000A 0008 000C ;ard+are 2eset# <o+er3 n32eset# &atchdog 2eset :evel change on the e5ternal '6)0 pin :evel change on the e5ternal '6)1 pin Capture event on )imerLCounter 1 )imerLCounter 1 G Compare value A )imerLCounter 1 G Compare value 8 )imerLCounter 1 G Compare value 1 )imerLCounter 1 verflo+ )imerLCounter 0 verflo+ 7erial )ransmit Complete =A2) char in receive buffer available =A2) transmitter ran empty =A2) All 7ent Analog Comparator 'riggere! ()
6ote that the capability to react to events is very different for the different types% )he addresses are se$uential# but not identical for different types% Consult the data sheet for each A12 type% )he higher a vector in the list the higher is its priority% 'f t+o or more components have an interrupt condition pending at the same time# the up most vector +ith the lo+er vector address +ins% )he lo+er int has to +ait until the upper int +as served% )o disable lo+er ints from interrupting during the e5ecution of its service routine the first e5ecuted int disables the processor/s '3flag% )he service routine must re3enable this flag after it is done +ith its >ob% For re3setting the ' status bit there are t+o +ays% )he service routine can end +ith the instruction*
RE>I
Avr-Asm-Tutorial
38
http://www.avr-asm-tutorial.net
)his return from the int routine restores the '3bit after the return address has been loaded to the program counter% )he second +ay is to enable the '3bit by the instruction
*EI ' *et Interr:Et En%)-ed RE> ' Ret:rn
)his is not the same as the 2-)'# because subse$uent interrupts are already enabled before the program counter is re3 loaded +ith the return address% 'f another int is pending# its e5ecution is already starting before the return address is popped from the stac,% )+o or more nested addresses remain on the stac,% 6o bug is to be e5pected# but it is an unnecessary ris, doing that% 7o >ust use the 2-)' instruction to avoid this unnecessary flo+ to the stac,% An 'nt3vector can only hold a relative >ump instruction to the service routine% 'f a certain interrupt is not used or undefined +e can >ust put a 2-)' instruction there# in case an erroneously enabled int happens before +e +rote an interrupt service routine% 'n a fe+ cases it is absolutely necessary to react to these false ints% )hat is the case if the e5ecution of the respective service routine does not automatically reset the interrupt condition flag of the peripheral% 'n that case a simple 2-)' +ould reset the other+ise never3ending interrupts% )his is the case +ith some of the =A2) interrupts% 6ote that larger devices have a t+o3+ord organi4ation of the vector table% 'n this case the J0< instruction has to be used instead of 2J0<% And 2-)' instructions must be follo+ed by an 6 < to point to the ne5t vector table address% As# after an interrupt is under service# further e5ecution of lo+er3priority interrupts are bloc,ed# all int service routines should be as short as possible% 'f you need to have a longer routine to serve the int# use one of the t+o follo+ing methods% )he first is to allo+ ints by 7-' +ithin the service routine# +henever you/re done +ith the most urgent tas,s% )his is not very clever% 0ore convenient is to perform the urgent tas,s# setting a flag some+here in a register for the slo+er reaction portions and return from the int immediately% A very serious rule for int service routines is* The first instr$ction is always to sa(e the processor stat$s fla's in a re'ister or on the stack. !o this before you use instructions that might change flags in the status flag register% )he reason is that the interrupted main program might >ust be in a state using the flag for a branch decision# and the int +ould >ust change that flag to another state% Funny things +ould happen from time to time% )he last instruction before the 2-)' therefore is to copy the saved flags from the register bac, to status port or to pop the status register content from the stac, and restore its original content% )he follo+ing sho+s e5amples ho+ to do that* 7aving in a register*
Isr@ I& R15,*RE0 ' s%Ce f-%gs A... <ore instr:,tions...B O$> *RE0,R15 ' restore f-%gs RE>I ' ret:rn fro< interr:Et Isr@ P$*/ R15 ' s%Ce register on st%,L I& R15, *RE0 A...<ore instr:,tions...B O$> *RE0,R15 ' restore f-%gs POP R15 RE>I ' ret:rn fro< interr:Et
)he method on the right is slo+er# the method on the left re$uires a register e5clusively for that purpose% Jenerally* All used registers in a service routine should either be e5clusively reserved for that purpose or saved on stac, and restored at the end of the service routine% 6ever change the content of a register +ithin an int service routine that is used some+here else in the normal program +ithout restoring it% 8ecause of these basic re$uirements a more sophisticated e5ample for an interrupt service routine here%
."*E0 ' "ode(*eg<ent st%rts here .OR0 0000 ' Address is Dero ROMP *t%rt ' >he reset(Ce,tor on Address 0000 ROMP I*erCi,e ' 0001@ first Int( e,tor, I&>0 serCi,e ro:tine A...B here other Ce,tors *t%rt@ ' /ere the <%in Erogr%< st%rts A...B here is eno:gh sE%,e for defining the st%,L %nd other things I*erCi,e@ ' /ere ;e st%rt ;ith the Interr:Et(*erCi,e(Ro:tine P$*/ R16 ' s%Ce % register to st%,L I& R16,*RE0 ' re%d st%t:s register P$*/ R16 ' %nd E:t on st%,L A...B /ere the Int(*erCi,e(Ro:tine does so<ething %nd :ses R16 POP R16 ' get EreCio:s f-%g register fro< st%,L O$> *RE0,R16 ' restore o-d st%t:s POP R16 ' get EreCio:s ,ontent of R16 fro< the st%,L RE>I ' %nd ret:rn fro< int
:oo,s a little bit complicated# but is a prere$uisite for using ints +ithout producing serious bugs% 7,ip <=7; 216 and < < 216 if you can afford reserving the register for e5clusive use +ithin the service routine% As an interrupt service routine cannot be interrupted @unless you allo+ interrupts +ithin the routineA# all different int service routines can use the same register% .ou understand no+# +hy allo+ing interrupts +ithin an interrupt service routine# and not at its end +ith 2-)'# is not a good idea( )hat/s it for the beginner% )here are some other things +ith ints# but this is enough to start +ith# and not to confuse you%
Avr-Asm-Tutorial
39
http://www.avr-asm-tutorial.net
* Calculations
;ere +e discuss all necessary instructions for calculating in A12 assembler language% )his includes number systems# setting and clearing bits# shift and rotate# and addingLsubtractingLcomparing and the format conversion of numbers%
<ositive +hole numbers @8ytes# &ords# :ong+ords# etc%A# 7igned +hole numbers @7hort'nts# 'ntegers# :ong'nts# etc%A# 8inary Coded !igits @8C!A# <ac,ed 8C!s# A7C''3formatted numbers%
'f you come from a high3level language* forget pre3defined number formats% Assembler doesn/t have that concept nor its @sometimes frustatingA limitations% &hat you earn is* you are the master of your o+n format?
2egisters d+0 to d+" are in a ro+# but don/t need to be% 'f +e need to initiate this double +ord at the beginning of an application @e% g% to H#000#000A# this should loo, li,e this*
.E#$ d;i = 7000000 ' define the ,onst%nt LDI d;0,LO41d;i2 ' >he -o;est 9 )its to R16 LDI d;1,3.>E!1d;i2 ' )its 9 .. 15 to R18 LDI d;!,3.>E61d;i2 ' )its 16 .. !6 to R19 LDI d;6,3.>E71d;i2 ' )its !7 .. 61 to R19
7o +e have splitted this decimal number# called d+i# to its binary portions 8.)-H to 8.)-1 and pac,ed them into the four byte pac,ages% 6o+ you can calculate +ith this double +ord%
Avr-Asm-Tutorial
40
http://www.avr-asm-tutorial.net
$"% 0 0 0
+, 0 0 0
#" 0 0 0
$+ 0 0 0
% 0 0 0
, 0 1 0
" 1 0 0
$ 0 1 0
.ou can calculate +ith these numbers# but this is a bit more complicated in assembler than calculating +ith binary values% )he advantage of this format is that you can handle as long numbers as you li,e# as long as you have enough storage space% )he calculations are as precise as you li,e @if you program A12s for ban,ing applicationsA# and you can convert them very easily to character strings%
*( (. 'ac@ed BC1s
'f you pac, t+o decimal digits into one byte you don/t loose that much storage space% )his method is called pac,ed binary coded digits% )he t+o parts of a byte are called upper and lo+er nibble% )he upper nibble usually holds the more significant digit# +hich has advantages in calculations @special instructions in A12 assembler languageA% )he decimal number 2E0 +ould loo, li,e this +hen formatted as a pac,ed 8C!* B)te 2 1 -igits H\" 2\1 Value 02 E0 % 0 0 , 0 1 " 0 0 $ 0 1 % 0 0 , 0 0 " 1 0 $ 0 0
' Instr:,tions for setting@ LDI R18,0?0! ' $EEer )yte LDI R16,0?50 ' Lo;er )yte
)o set this correct you can use the binary notation @0b%%%A or the he5adecimal notation @05%%%A to set the proper bits to their correct nibble position% Calculating +ith pac,ed 8C!s is a little more complicated compared to the binary form% Format changes to character strings are nearly as easy as +ith 8C!s% :ength of numbers and precision of calculations is only limited by the storage space%
*( (0 6umbers in A,CII-format
1ery similar to the unpac,ed 8C! format is to store numbers in A7C'' format% )he digits 0 to 9 are stored using their A7C'' @A7C'' G American 7tandard Code for 'nformation 'nterchangeA representation% A7C'' is a very old format# developed and optimi4ed for teletype +riters# unnecessarily very complicated for computer use @do you ,no+ +hat a char named -nd f )ransmission - ) meant +hen it +as invented(A# very limited in range for other than =7 languages @only F bits per characterA# still used in communications today due to the limited efforts of some operating system programmers to s+itch to more effective character systems% )his ancient system is only topped by the -uropean E3bit long teletype character set called 8audot set or the 0orse code# still used by some finger3nervous people% &ithin the A7C'' code system the decimal digit 0 is represented by the number H8 @he5 05"0# binary 0b0011%0000A# digit 9 is EF decimal @he5 05"9# binary 0b0011%1001A% A7C'' +asn/t designed to have these numbers on the beginning of the code set as there are already instruction chars li,e the above mentioned - ) for the teletype% 7o +e still have to add H8 to a 8C! @or set bit H and E to 1A to convert a 8C! to A7C''% A7C'' formatted numbers need the same storage space li,e 8C!s% :oading 2E0 to a register set representing that number +ould loo, li,e this*
LDI R19,R!R LDI R18,R5R LDI R16,R0R
'f +e have a register that is already set to he5 05"0 +e can use the 2 +ith this register to convert the 8C!*
OR R1,R!
Avr-Asm-Tutorial
41
http://www.avr-asm-tutorial.net
isolates the lo+er four bits @G the lo+er nibbleA% 6ote that 2' and A6!' are only possible +ith registers above 21E% 'f you need to do this# use one of the registers 216 to 2"1? 'f the he5 value 050F is already in register 22# you can A6! the A7C'' character +ith this register*
A&D R1,R!
)he other instructions for manipulating bits in a register are also limited for registers above 21E% )hey +ould be formulated li,e this*
*3R R16,0)00110000 ' *et )its 7 %nd 5 to one "3R R16,0)00110000 ' "-e%r )its 7 %nd 5 to Dero
'f one or more bits of a byte have to be inverted you can use the follo+ing instruction @+hich is not possible for use +ith a constantA*
LDI R16,0)10101010 ' InCert %-- :neCen )its EOR R1,R16 ' in register R1 %nd store res:-t in R1
inverts the content in register 21 and replaces 4eros by one and vice versa% !ifferent from that is the )+o/s complement# +hich converts a positive signed number to its negative complement @subtracting from 4eroA% )his is done +ith the instruction
&E0 R1
7o K1 @decimal* 1A yields 31 @binary 1%1111111A# K2 yields 32 @binary 1%1111110A# and so on% 8esides the manipulation of the bits in a register# copying a single bit is possible using the so3called )3bit of the status register% &ith
3*> R1,0
the )3bit is loaded +ith a copy of bit 0 in register 21% )he )3bit can be set or cleared# and its content can be copied to any bit in any register*
"L> ' ,-e%r >()it, or *E> ' set >()it, or 3LD R!,! ' ,oEy >()it to register R!, )it !
)he inverse division by 2 is the instruction called logical shift right# :72%
L*R R1
)he former bit F# no+ shifted to bit 6# is filled +ith a 0# +hile the former bit 0 is shifted into the carry bit of the status register% )his carry bit could be used to round up and do+n @if set# add one to the resultA% -5ample# division by four +ith rounding*
L*R R1 ' diCision )y ! 3R"" DiC! ' O:<E if no ro:nd :E I&" R1 ' ro:nd :E DiC!@ L*R R1 ' On,e %g%in diCision )y ! 3R"" DiCE ' O:<E if no ro:nd :E I&" R1 ' Ro:nd $E DiCE@
7o# dividing is easy +ith binaries as long as you divide by multiples of 2% 'f signed integers are used the logical shift right +ould over+rite the sign3bit in bit F% )he instruction Barithmetic shift rightC A72 leaves bit F untouched and shifts the F lo+er bits# inserting a 4ero into bit location 6%
A*R R1
:i,e +ith logical shifting the former bit 0 goes to the carry bit in the status register% &hat about multiplying a 163bit +ord by 2( )he most significant bit of the lo+er byte has to be shifted to yield the lo+est bit of the upper byte% 'n that step a shift +ould set the lo+est bit to 4ero# but +e need to shift the carry bit from the previous shift of the lo+er byte into bit 0 of the upper byte% )his is called a rotate% !uring rotation the carry bit in the status register is shifted to bit 0# the former bit F is shifted to the carry during rotation%
Avr-Asm-Tutorial L*L R1 ' Logi,%- *hift Left of the -o;er )yte ROL R! ' ROt%te Left of the :EEer )yte
42
http://www.avr-asm-tutorial.net
)he logical shift left in the first instruction shifts bit F to carry# the 2 : instruction rolls it to bit 0 of the upper byte% Follo+ing the second instruction the carry bit has the former bit F of the upper byte% )he carry bit can be used to either indicate an overflo+ @if 163bit3calculation is performedA or to roll it into more upper bytes @if more than 16 bit calculation is doneA% 2olling to the right is also possible# dividing by 2 and shifting carry to bit F of the result*
L*R R! ' Logi,%- *hift Right, )it 0 to ,%rry ROR R1 ' ROt%te Right %nd shift ,%rry in )it 8
't/s easy dividing +ith big numbers% .ou see that learning assembler is not );A) complicated% )he last instruction that shifts four bits in one step is very often used +ith pac,ed 8C!s% )his instruction shifts a +hole nibble from the upper to the lo+er position and vice versa% 'n our e5ample +e need to shift the upper nibble to the lo+er nibble position% 'nstead of using
ROR R1 ROR R1 ROR R1 ROR R1
)his instruction e5changes the upper and lo+er nibble% 6ote that the content of the upper nibble +ill be different after applying these t+o methods%
'nstead of a second A!! +e use A!C in the second instruction% )hat means add +ith carry# +hich is set or cleared during the first instruction# depending from the result% Already scared enough by that complicated math( 'f not* ta,e this? &e subtract 2"*2H from 21*22%
*$3 R!,R7 ' first the -o;()yte *3" R1,R6 ' then the high()yte
Again the same tric,* during the second instruction +e subtract another 1 from the result if the result of the first instruction had an overflo+% 7till breathing( 'f yes# handle the follo+ing?
'f the carry flag is set no+# 21*22 is smaller than 2"*2H%
'f the Sero3bit in the status register is set after that# +e ,no+ that 216 is e$ual to 05AA% 'f the carry3bit is set# +e ,no+# it is smaller% 'f Carry is not set and the Sero3bit is not set either# +e ,no+ it is larger% And no+ the most complicated test% &e evaluate +hether 21 is 4ero or negative*
>*> R1
'f the S3bit is set# the register 21 is 4ero and +e can follo+ +ith the instructions 82-P# 826-# 820'# 82<:# 82: # 827;# 82J-# 82:)# 821C or 8217 to branch around a little bit%
Avr-Asm-Tutorial
43
http://www.avr-asm-tutorial.net
Puestion to thin, about* &hy is that e$ually correct# half as long and less complicated and +here is the tric,(
Avr-Asm-Tutorial
44
http://www.avr-asm-tutorial.net
7&A<ping and get the lo+er 8C!% A little bit more complicated is the conversion of 8C! digits to a binary% !epending on the numbers to be handled +e first clear the necessary bytes that +ill hold the result of the conversion% &e then start +ith the highest 8C! digit% 8efore adding this to the result +e multiply the result +ith 10% @6ote that in the first step this is not necessary# because the result is 4ero eitherA% 'n order to do the multiplication by 10# +e copy the result to some+here else% )hen +e multiply the result by four @t+o left shifts resp% rollsA% Adding the previously copied number to this yields a multiplication +ith E% 6o+ a multiplication +ith 2 @left shiftLrollA yields the 103fold of the result% Finally +e add the 8C! and repeat that algorithm until all decimal digits are converted% 'f# during one of these operations# there occurs a carry of the result# the 8C! is too large to be converted% )his algorithm handles numbers of any length# as long as the result registers are prepared%
and can be read +ord3+ise +ith the :<0 instruction from the table% An alternative is a table that holds the decimal value of each bit in the 163bit3binary# e% g%
.D3 0,6,!,8,6,9 .D3 0,1,6,6,9,7 .D3 0,0,9,1,9,! .D3 0,0,7,0,9,6 .D3 0,0,!,0,7,9 ' %nd so on :nti.D3 0,0,0,0,0,1
)hen you shift the single bits of the binary left out of the registers to the carry% 'f it is a one# you add the number in the table to the result by reading the numbers from the table using :<0% )his is more complicated to program and a little bit slo+er than the above method% A third method is to calculate the table value# starting +ith 000001# by adding this 8C! +ith itself# each time after you have shifted a bit from the binary to the right# and added to the 8C! result% 0any methods# much to optimi4e here%
9.+ 6$ltiplication
0ultiplication of binary numbers is e5plained here%
1234 * 500 =
699678
========================
&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%
Avr-Asm-Tutorial
45
http://www.avr-asm-tutorial.net
Avr-Asm-Tutorial
46
http://www.avr-asm-tutorial.net
)he ob>ect3code has been opened# the cursor is placed on the first e5ecutable instruction% F11 does single steps%
)he registers 20 and 22 are set to 05AA and 05EE# our test binaries# to be multiplied%
Avr-Asm-Tutorial
47
http://www.avr-asm-tutorial.net
22 is rotated to the right# to roll the least significant bit into the carry bit% 05EE @0101%0101A yielded 052A @0010%1010A%
8ecause the carry bit had a one# the content of the registers 21*20 is added to the @emptyA register pair 2H*2"# resulting in 0500AA there%
6o+ the register pair 21*20 is rotated one position left to multiply this binary by 2% From 0500AA# multiplication by 2 yields 0501EH% )he +hole multipli] cation loop is repeated as long there is at least one binary 1 in register 22% )hese follo+ing loops are not sho+n here%
Avr-Asm-Tutorial
48
http://www.avr-asm-tutorial.net
=sing ,ey FE of the studio +e multi3 stepped over these loops to a brea,point at the end of the multiplication routine% )he result register pair 2H*2" has the result of the multiplication of 05AA by 05EE* 05"8F2%
)his +asn/t that complicated# >ust remind yourself on the similar decimal operations% 8inary multiplication is much easier than decimal%
As the result of these t+o 83bit binaries might be up t+o 16 bits long# the result +ill be in the registers 21 @most significant byteA and 20 @least significant byteA% )hat/s all about it%
)he program demonstrates the simulation in the 7tudio% 't multiplies decimal 2E0 @he5 FAA by decimal 100 @he5 6HA# in the registers 216 and 21F%
Avr-Asm-Tutorial
49
http://www.avr-asm-tutorial.net
After e5ecution# the registers 20 @:78A and 21 @078A hold the result he5 61A8 or decimal 2E#000% And* yes# that re$uires only t+o cycles# or 2 microseconds +ith a 1 0csLs cloc,%
7o +e >ust need to do t+o multiplications and to add both results% 7orry# if you see three asteris,s in the formula* the multiplication +ith 2E6 in the binary +orld doesn/t re$uire any hard+are at all# because it is a simple move to the ne5t higher byte% Just li,e the multiplication by 10 in the decimal +orld is simply moving the number one left and +rite a 4ero to the least significant digit% 7o let/s go to a practical e5ample% First +e need some registers to
load the numbers m1 and m2# provide space for the result# +hich might have 2H bits length%
' ' >est h%rd;%re <:-tiE-i,%tion 16()y(9()it ' ' Register definitions@ ' .def Res1 = R! .def Res! = R6 .def Res6 = R7 .def <1L = R16 .def <1M = R18 .def <! = R19
)he t+o numbers are loaded into 21F*216 @dec 10000 G he5 2F10A and 218 @dec 2E0 G he5 FAA% )hen +e multiply the :78 first*
Avr-Asm-Tutorial ' ' M:-tiE-y ' <:- <1L,<! ' M:-tiE-y L*3 <oC Res1,R0 ' ,oEy res:-t to res:-t register <oC Res!,R1
50
http://www.avr-asm-tutorial.net
)he :78 multiplication of he5 2F by he5 FA yields he5 0F0A# +ritten to the registers 200 @:78# he5 A0A and 201 @078# he5 0FA% )he result is copied to the lo+er t+o bytes of the result register# 2"*22%
)he multiplication of the 078 of m1# he5 10# +ith m2# he5 FA# yields he5 2616 in 21*20%
6o+ t+o steps are performed at once* multiplication by 2E6 and adding the result to the previous result% )his is done by adding 21*20 to 2es"*2es2 instead of 2es2*2es1% 21 can >ust be copied to 2es"% 20 is added to 2es2 then% 'f the carry is set after adding# the ne5t higher byte 2es" is increased by one%
<oC Res6,R1 ' ,oEy M*3 res:-t to res:-t )yte 6 %dd Res!,R0 ' %dd L*3 res:-t to res:-t )yte ! )r,, &oIn, ' if not ,%rry, P:<E in, Res6 &oIn,@
)he result in 2H*2"*22 is he5 262EA0# +hich is decimal 2E00000 @as everybody ,no+sA# and is obviously correct%
)he cycle counter of the multiplication points to 10# at 1 0;4 cloc, a total of 10 microseconds% 1ery much faster than soft+are multiplication?
Avr-Asm-Tutorial
51
http://www.avr-asm-tutorial.net
bviously four multiplications no+% &e start +ith the first and the last as the t+o easiest ones* their results are simply copied to the correct result register positions% )he results of the t+o multiplications in the middle of the formula have to be added to the middle of our result registers# +ith possible carry overflo+s to the most significant byte of the result% )o do that# you +ill see a simple tric, that is easy to understand% )he soft+are*
' ' >est /%rd;%re M:-tiE-i,%tion 16 )y 16 ' ' Define Registers ' .def Res1 = R! .def Res! = R6 .def Res6 = R7 .def Res7 = R5 .def <1L = R16 .def <1M = R18 .def <!L = R19 .def <!M = R19 .def t<E = R!0 ' ' Lo%d inE:t C%-:es ' .eM: <1 = 10000 .eM: <! = !5000 ' -di <1M,/I0/1<12 -di <1L,LO41<12 -di <!M,/I0/1<!2 -di <!L,LO41<!2 ' ' M:-tiE-y ' ,-r R!0 ' ,-e%r for ,%rry oEer%tions <:- <1M,<!M ' M:-tiE-y M*3s <oC Res6,R0 ' ,oEy to M*4 Res:-t <oC Res7,R1 <:- <1L,<!L ' M:-tiE-y L*3s <oC Res1,R0 ' ,oEy to L*4 Res:-t <oC Res!,R1 <:- <1M,<!L ' M:-tiE-y 1M ;ith !L %dd Res!,R0 ' Add to Res:-t %d, Res6,R1 %d, Res7,t<E ' %dd ,%rry <:- <1L,<!M ' M:-tiE-y 1L ;ith !M %dd Res!,R0 ' Add to Res:-t %d, Res6,R1 %d, Res7,t<E ' ' M:-tiE-i,%tion done '
:oading the t+o constants 10000 @he5 2F10A and 2E000 @he5 61A8A to the registers in the upper register space %%% 0ultiplying the t+o 078s @he5 2F and 61A and copying the result in 21*20 to the t+o most upper result registers 2E*2H %%%
Avr-Asm-Tutorial
52
http://www.avr-asm-tutorial.net
0ultiplying the t+o :78s @he5 10 and A8A and copying the result in 21*20 to the t+o lo+er result registers 2"*22 %%%
0ultiplying the 078 of m1 +ith the :78 of m2 and adding the result in 21*20 to the result register/s t+o middle bytes# no carry occurred %%%
0ultiplying the :78 of m1 +ith the 078 of m2 and adding the result in 21*20 to the result register/s t+o middle bytes# no carry occurred% )he result is he5 0--68280# +hich is 2E0000000 and obviously correct %%%
0ultiplication needed 19 cloc, cycles# +hich is very much faster than +ith soft+are multiplication% Another advantage here* the re$uired time is A:&A.7 e5actly 19 cycles# and it doesn/t depend on the input numbers @li,e is the case +ith soft+are multiplication and on overflo+ occurrences @than,s to our small tric, of adding 4ero +ith carryA% 7o you can rely on this %%%
' /%rd;%re M:-tiE-i,%tion 16 )y !7 )it .in,-:de =<9def.in,= ' ' Register definitions .def %1 = R! ' define 16()it register .def %! = R6
Avr-Asm-Tutorial .def )1 = R7 ' define !7()it register .def )! = R5 .def )6 = R6 .def e1 = R8 ' define 70()it res:-t register .def e! = R9 .def e6 = R9 .def e7 = R10 .def e5 = R11 .def ,0 = R1! ' he-E register for %dding .def r- = R16 ' -o%d register ' ' Lo%d ,onst%nts .eM: % = 10000 ' <:-tiE-i,%tor %, he? !810 .eM: ) = 1000000 ' <:-tiE-i,%tor ), he? 0F7!70 -di r-,3.>E11%2 ' -o%d % <oC %1,r-di r-,3.>E!1%2 <oC %!,r-di r-,3.>E11)2 ' -o%d ) <oC )1,r-di r-,3.>E!1)2 <oC )!,r-di r-,3.>E61)2 <oC )6,r' ' "-e%r registers ,-r e1 ' ,-e%r res:-t registers ,-r e! ,-r e6 ,-r e7 ,-r e5 ,-r ,0 ' ,-e%r he-E register ' ' M:-tiE-y <:- %!,)6 ' ter< 1 %dd e7,R0 ' %dd to res:-t %d, e5,R1 <:- %!,)! ' ter< ! %dd e6,R0 %d, e7,R1 %d, e5,,0 ' 1%dd Eossi)-e ,%rry2 <:- %!,)1 ' ter< 6 %dd e!,R0 %d, e6,R1 %d, e7,,0 %d, e5,,0 <:- %1,)6 ' ter< 7 %dd e6,R0 %d, e7,R1 %d, e5,,0 <:- %1,)! ' ter< 5 %dd e!,R0 %d, e6,R1 %d, e7,,0 %d, e5,,0 <:- %1,)1 ' ter< 6 %dd e1,R0 %d, e!,R1 %d, e6,,0 %d, e7,,0 %d, e5,,0 ' ' done. noE ' Res:-t sho:-d )e he? 0!5703E700
53
http://www.avr-asm-tutorial.net
10 cloc, cycles for loading the constants# 6 cloc, cycles for clearing registers# and "" cloc, cycles for multiplication%
9.- &i(ision
6o# unfortunately there is no hard+are division% .ou need to do this in soft+are?
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 ===================================
!efinition and preset of the registers +ith the test binaries# presetting the interim register and the result register pair @the result registers are presetted to 050001? After 16 rotations the rolling out of the one stops further division steps%A#
Avr-Asm-Tutorial
55
http://www.avr-asm-tutorial.net
the 163bit3binary in rd1h*rd1l is rotated bit+ise to the interim register rd1u @multiplication by 2A# if a 1 is rotated out of rd1u# the program branches to the subtraction step in step H immediately# the content of the interim register is compared +ith the 83bit binary in rd2# if rd2 is smaller it is subtracted from the interim register and the carry3bit is set to one# if rd2 is greater the subtraction is s,ipped and a 4ero is set to the carry flag# the content of the carry flag is rotated into the result register reh*rel from the right# if a 4ero rotated out of the result register# +e have to repeat the division loop# if it +as a one the division is completed%
'f you don/t understand rotation yet you/ll find this operation discussed in the multiplication section%
)he test binaries 05AAAA and 05EE# to be divided# have been +ritten to the registers 21*20 and 2"%
)he interim register 22 and the result register pair are set to their predefined values%
Avr-Asm-Tutorial
56
http://www.avr-asm-tutorial.net
21*20 +as rotated left to 22# from 05AAAA the doubled value of 0501EEEH +as yielded%
6o overflo+ from rotation into carry has occurred and 0501 in 22 +as smaller than 05EE in 2"# so subtraction +as s,ipped% A 4ero in the carry is rotated into the result register 2E*2H% )he former content of the result register# a single 13bit in position 0 has rotated to position 1 @content no+* 050002A% As a 4ero +as rotated out of the result register pair# the ne5t step to be e5ecuted is a branch to the beginning of the division loop start and the loop is repeated% After e5ecuting the loop 16 times +e have reached the brea,point set at the end of the division routine% )he result register in 2E*2H holds 050202# the result of the division% )he registers 22*21*20 are empty# so +e do not have a remainder left% 'f a remainder +ould have been resulted +e can use it to decide +hether an incrementation of the result should ta,e place# rounding of the result up% )his step is not coded here%
)he +hole division needs 60 micro3seconds processor time @open a processor vie+ in the studio menuA% A rather long time for a division%
Avr-Asm-Tutorial
57
http://www.avr-asm-tutorial.net
*( +( Linear conBersions
As an e5ample the follo+ing tas,* an 838it3A!3Converter measures an input signal in the range from 0%00 to 2%EE 1olt# and returns as the result a binary in the range from Z00 and ZFF% )he result# a voltage# is to be displayed on a :C! display% 7illy e5ample# as it is so easy* )he binary is converted to a decimal A7C'' string bet+een 000 and 2EE# and >ust behind the first digit the decimal point has to be inserted% !one? )he electronics +orld sometimes is more complicated% -% g%# the A!3Converter returns an 838it3;e5 for input voltages bet+een 0%00 and E%00 1olt% 6o+ +e/re tric,ed and do not ,no+ ho+ to proceed% )o display the correct result on the :C! +e +ould have to multiply the binary by E00L2EE# +hich is 1%9608% )his is a silly number# as it is almost 2# but only almost% And +e don/t +ant that ,ind of inaccuracy of 29# +hile +e have an A!3converter +ith around 0%2E9 accuracy% )o cope +ith this# +e multiply the input by E00L2EED2E6 or E01%96 and divide the result by 2E6% &hy first multiply by 2E6 and then divide by 2E6( 't/s >ust for enhanced accuracy% 'f +e multiply the input by E02 instead of E01%96# the error is >ust in the order of 0%0089% )hat is good enough for our A!3converter# +e can live +ith that% And dividing by 2E6 is an easy tas,# because it is a +ell3,no+n po+er of 2% 8y dividing +ith numbers that are a po+er of 2# the A12 feels very comfortable and performs very fast% 8y dividing +ith 2E6# the A12 is even faster# because +e >ust have to s,ip the last byte of the binary number% 6ot even shift and rotate? )he multiplication of an 83bit3binary +ith the 93bit3binary E02 @he5 1F6A can have a result larger than 16 bits% 7o +e have to reserve 2H bits or " registers for the result% !uring multiplication# the constant E02 has to be shifted left @multiplication by 2A to add these numbers to the result each time a one rolls out of the shifted input number% As this might need eight shifts left# +e need further three bytes for this constant% 7o +e chose the follo+ing combination of registers for the multiplication*
Register 21 2H * 2" * 22 2F * 26 * 2E
After filling the value E02 @00%01%F6A to 2H * 2" * 22 and clearing the result registers 2F * 26 * 2E# the multiplication goes li,e this*
1% )est# if the input number is already 4ero% 'f yes# +e/re done% 2% 'f no# one bit of the input number is shifted out of the register to the right# into the carry# +hile a 4ero is stuffed into bit F% )his instruction is named :ogical37hift32ight or :72% "% 'f the bit in carry is a one# +e add the multiplicand @during step 1 the value E02# in step 2 it/s 100H# a% s% o%A to the result% !uring adding# +e care for any carry @adding 22 to 2E by A!!# adding 2" to 26 and 2H to 2F +ith the A!C instruction?A% 'f the bit in the carry +as a 4ero# +e >ust don/t add the multiplicand to the result and >ump to the ne5t step% H% 6o+ the multiplicand is multiplied by 2# because the ne5t bit shifted out of the input number is +orth double as much% 7o +e shift 22 to the left @by inserting a 4ero in bit 0A using :7:% 8it F is shifted to the carry% )hen +e rotate this carry into 2"# rotating its content left one bit# and bit F to the carry% )he same +ith 2H% E% 6o+ +e/re done +ith one digit of the input number# and +e proceed +ith step 1 again%
)he result of the multiplication by E02 no+ is in the result registers 2F * 26 * 2E% 'f +e >ust ignore register 2E @division by 2E6A# +e have our desired result% )o enhance accuracy# +e can use bit F in 2E to round the result% 6o+ +e >ust have to convert the result from its binary form to decimal A7C'' @see Conversion bin to decimal3A7C'' on the +ebsiteA% 'f +e >ust add a decimal point in the right place in the A7C'' string# our voltage string is ready for the display% )he +hole program# from the input number to the resulting A7C'' string# re$uires bet+een F9 and 228 cloc, cycles# depending from the input number% )hose +ho +ant to beat this +ith the floating point routine of a more sophisticated language than assembler# feel free to mail me your conversion time @and program flash and memory usageA%
Avr-Asm-Tutorial
58
http://www.avr-asm-tutorial.net
Avr-Asm-Tutorial
59
http://www.avr-asm-tutorial.net
-s- R5 ' rot%te )it 8 to ,%rry %d, R6,r<E ' %dd L*3 ;ith ,%rry %d, R8,r<E ' %dd M*3 ;ith ,%rry <oC R!,R8 ' ,oEy the C%-:e to R!@R1 1diCide )y !562 <oC R1,R6 ret ' "onCert the ;ord in R!@R1 to %n A*"II string in R5@R6@R8@R9 fE,onC9%@ ,-r R7 ' *et the de,i<%- diCider C%-:e to 100 -di r<E,100 <oC R6,r<E r,%-- fE,onC9d ' get A*"II digit )y reEe%ted s:)tr%,tion <oC R5,r<E ' set h:ndreds string ,h%r -di r<E,10 ' *et the de,i<%- diCider C%-:e to 10 <oC R6,r<E r,%-- fE,onC9d ' get the ne?t A*"II digit <oC R8,r<E ' set tens string ,h%r -di r<E,R0R ' ,onCert the rest to %n A*"II ,h%r %dd r<E,R1 <oC R9,r<E ' set ones string ,h%r ret ' "onCert )in%ry ;ord in R!@R1 to % de,i<%- digit )y s:)str%,ting the de,i<%- diCider C%-:e in R7@R6 1100, 102 fE,onC9d@ -di r<E,R0R ' st%rt ;ith de,i<%- C%-:e 0 fE,onC9d1@ ,E R1,R6 ' "o<E%re ;ord ;ith de,i<%- diCider C%-:e ,E, R!,R7 )r,, fE,onC9d! ' "%rry ,-e%r, s:)tr%,t diCider C%-:e ret ' done s:)tr%,tion fE,onC9d!@ s:) R1,R6 ' s:)tr%,t diCider C%-:e s), R!,R7 in, r<E ' :E one digit rP<E fE,onC9d1 ' on,e %g%in ' End of ,onCersion test ro:tine
Avr-Asm-Tutorial
60
http://www.avr-asm-tutorial.net
+ 'roFect planning
1=.1 How to plan an *12 pro>ect in assembler
;ere are the basics on ho+ to plan a simple pro>ect# to be programmed in assembler% 8ecause the hard+are components determine a lot# the hard+are considerations are discussed first% )hen a chapter on interrupt follo+s and after that timing issues are discussed%
;o+ many timers are needed and +hich resolution should these provide( &hich valuesLinformations should be preserved +hen the operating voltage is shut do+n( @--<2 0 capacityA ;o+ much storage space is re$uired( @72A0 capacityA 7pace re$uirements on your <C8# ho+ much space for the processor fits best# +hich pac,age types are available( perating voltages and po+er re$uirements% 'f the operating voltage comes from a battery or an accumulator# the po+er characteristics play an important role% <rice for the device( nly relevant for production in larger series% 6ot at all depending from the processor/s internals# and a matter of unpredictable mar,et conditions% Availability( 'f one starts a pro>ect +ith the A)9071200# probably from a rummage table# can ma,e it cheap% 7uch a decision is not very sustainable% <orting such a pro>ect to a tiny3 or mega3device mostly ends up in a complete redesign of the soft+are# that also loo,s and feels much better# +or,s better and re$uires only a fraction of code lines%
Avr-Asm-Tutorial
61
http://www.avr-asm-tutorial.net
-nabling interrupts* 'nterrupts re$uire the stac, hard+are% 7o set 7<: @and in larger devices 7<;A at the beginning to 2A0-6!# and reserve the upper part of the 72A0 for that purpose @e% g% the last 8 to 5 bytesA% -ach internal component and each condition that should be able to trigger an interrupt has to be enabled to do that# by setting the respective interrupt enable flag bit% 7+itching those bits on and off is a ris,y thing# so better design your soft+are +ithout s+itching% )he ' flag in the status register 72-J has to be set at the begin and remains set during operation% 'f it is necessary to clear the ' flag during an operation outside an interrupt service routine# add the set3'3flag instruction +ithin a fe+ instruction +ords% 'nterrupt vector table* -ach internal component and each enabled interrupt condition corresponds to a specific interrupt vector# placed in a certain address in the flash program storage% )he instruction at this address is a single3 +ord 2J0< instruction# in large A)mega processors a t+o3+ord J0< instruction# to the respective interrupt service routine% )he vector addresses are type3specific% &hen porting the soft+are to a different type# those re$uire ad>ustment% -ach vector address in the table# that is currently not used# is given a 2-)' instruction @in large A)mega types a 2-)'# follo+ed by an 6 <A% )hat prevents erroneous ghost interrupts to be running into false code% )he use of the % 2J directive for ad>usting vector addresses does not provide safety against those events% 'f an interrupt condition occurs# the respective flag in the control register of the internal component is set% )his is automatically cleared# if the interrupt is e5ecuted% 'n some rare cases @e% g% in case of a )O buffer empty interrupt condition of an =A2)# if no further character is to be sentA# the interrupt enable flag of the component has to be cleared first and the interrupt condition flag at last% 'f the interrupt condition gets true for more than one component at a time# the interrupt +ith a lo+er address +ins the race% 'nterrupt service routines* -ach service routine starts +ith saving the status register 72-J in a register e5clusively reserved for that purpose# and ends +ith restoring that status register% 8ecause interrupts can occur every time# also in times +hile the processor is performing instructions in the main program loop# any disturbance of that status register can cause unpredictable malfunctions% 8efore >umping to the service routine# the processor pushes the current instruction counter to the stac,% )he interrupt and the >ump to the respective service routine disables further interrupts by temporarily clearing the ' flag in the status register 72-J% -ach service routine ends +ith the instruction 2-)'# that pops the instruction pointer from the stac, and sets the ' flag on again% 8ecause the e5ecution of an interrupt service routine bloc,s any further interrupt re$uests from being served# even those of a higher priority# each service routine has to be as short as possible and performs only the time critical portions of the tas,% :engthy response operations have to be performed outside the interrupt service routine% 8ecause interrupting an interrupt service routine does not happen# all interrupt service routines can use the same temporary register% 'nterfacing interrupt service routine and main program loop* )he communication bet+een the interrupt serve routine and the main program loop is performed via single flags# that are set +ithin the service routine and cleared in the main program loop% )he clearing of flags is either performed in single +ord instructions or interrupts are temporarily disabled during that step to bloc, erroneous over+riting of other flags that +ere possibly changed in bet+een the three steps read3modify3+rite% 1alues that the interrupt service routines provides are handed over in dedicated registers or in specific 72A0 locations% -ach change of those values# that are used later on outside the service routine# have to be chec,ed for possible corruption# if another interrupt can occur in bet+een% 7ingle byte handling is easy# but handing over t+o or more bytes re$uires a hand3over protocol @interrupt disable during hand3 over# flag setting to prevent over+rite# etc%A% As an e5ample# the handover of a 163bit timer value re$uires disabling of interrupts first% ther+ise the first byte read does not necessarily correspond to the second byte read# if another interrupt happened in bet+een% 0ain program loop* &ithin the main program loop the processor is sent to sleep# +ith the sleep mode IidleI selected% -ach interrupt +a,es up the processor# >umps to the respective interrupt service routine and# after its return from interrupt# continues its operation in the main program loop% 't ma,es sense to chec, for any flags that +ere set +ithin the service routine% 'f that is the case# the treatment of the flag can be performed% After all things +ere finali4ed# another chec, for the flag settings can be made @in case of long routinesA and the processor can be sent bac, to sleep%
Avr-Asm-Tutorial
62
http://www.avr-asm-tutorial.net
.BHA!rsre'!E!315! !savin'!the!status!(urin'!interrupts .BHA!rmp!E!316! !Temporar,!re'ister!outsi(e!interrupts .BHA!rimp!E!317! !Temporar,!re'ister!insi(e!interrupts .BHA!r)l'!E!318! !Fla'!re'ister!)or!#ommuni#ation .BHA!+int0!E!0! !Fla'!+it!)or!si'nalin'!2>T0-.ervi#e .BHA!+t#0!E!1! !Fla'!+it!)or!si'nalin'!T"0-?ver)low !... !2.3-Ta+le .".B.?3-!I0000 !!!!!!!!r8mp!main! !3eset!ve#tor%!e<e#ute(!at!start-up !!!!!!!!r8mp!isrNint0! !2>T0-ve#tor%!e<e#ute(!on!level!#han'es!on!the!2>T0!input!line! !!!!!!!!reti! !unuse(!interrupt !!!!!!!!reti! !unuse(!interrupt !!!!!!!!r8mp!isrNt#0N?ver)low! !T"0-?ver)low-ve#tor%!e<e#ute(!in!#ase!o)!a!T"0!over)low !!!!!!!!reti! !unuse(!interrupt !!!!!!!!reti! !unuse(!interrupt !!!!!!!! !...!other!int!ve#tors !2nterrupt!servi#e!routines isrNint0:! !2>T0-.ervi#e!3outine !!!!!!!!in!rsre'%.3B-! !sa)e!status !!!!!!!!in!rimp%&2>J! !rea(!port!J!to!temp!re'ister !!!!!!!!out!&?3T"%rimp! !write!temp!re'ister!to!port!"! !!!!!!!! !...!(o!other!thin's !!!!!!!!s+r!r)l'%1LL+int0! !si'nalin'!2>T0!to!outsi(e out!.3B-%rsre'! !restore!status reti! !return!+a#$!an(!ena+le!interrupts isrNt#0N?ver)low:! !T"0!?ver)low!.ervi#e!3outine in!rsre'%.3B-! !sa)e!status in!rimp%&2>J! !rea(!port!J!in!temp!re'ister out!&?3T"%rimp! !write!temp!re'ister!to!port!"! !...!(o!other!thin's s+r!r)l'%1LL+t#0! !set!T"0-)la' out!.3B-%rsre'! !restore!status reti! !return!+a#$!an(!ena+le!interrupts !Gain!pro'ram!start main: l(i!rmp%/2-/:3AGB>0;! !set!sta#$!re'ister out!.&/%rmp l(i!rmp%@?*:3AGB>0; out!.&@%rmp !...!other!thin's!to!(o !2>T!Bna+le!)or!T"0!over)lows l(i!rmp%1LLT?2B0! !?ver)low!2nterrupt!Bna+le!Timer!0 out!T2G.O%rmp! !set!interrupt-mas$!o)!the!timer!! l(i!rmp%:1LL".00;M:1LL".02;! !pres#aler!+,!1024 out!T""30%rmp! !start!timer !2>T!Bna+le!o)!the!2>T0!input l(i!rmp%:1LL.B;M:1LL2."00;! !.@BB&-Bna+le!an(!2>T0!int!on!all!level!#han'es out!G"A"3%rmp! !to!the!#ontrol!re'ister l(i!rmp%1LL2>T0! !ena+le!2>T0!interrupts out!-2"3%rmp! !to!the!interrupt!#ontrol!re'ister !set!interrupt!status!)la' sei! !set!interrupt!)la'
!Gain!pro'ram!loop loop: sleep! !pro#essor!to!sleep nop! !(umm,!)or!wa$e-up s+r#!r)l'%+int0! !2>T0!)la'!not!set r#all!ma#heNint0! !han(le!2>T0!event s+r#!r)l'%+t#0! !T"0-?ver)low!)la'!not!set r#all!ma#heNt#0! !han(le!T"0!over)low r8mp!loop! !'o!+a#$!to!sleep
!/an(le!event!results ma#heNint0:! !han(le!2>T0!result #+r!r)l'%1LL+int0! !#lear!2>T0!)la' !...!(o!other!thin's ret! !rea(,%!+a#$!to!loop ma#heNt#0:! !han(le!T"0!over)low
Avr-Asm-Tutorial
63
http://www.avr-asm-tutorial.net
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%
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 2egister set 0 2EE Constant 2egister GV 2egister 72A0 GV 2egister# direct 72A0 GV 2egister 72A0 GV 2egister and '6C !-C# 72A0 GV 2egister 72A0# displaced GV 2egister <ort GV 2egister Copy 7tac, GV 2egister <rogram storage S GV 20 2egister GV 72A0# direct 2egister GV 72A0 2egister GV 72A0 and '6C !-C# 2egister GV 72A0 2egister GV 72A0# displaced 2egister GV <ort 2egister GV 7tac, 8 8it# K1 Add 8 8it 8 8it K Carry 16 8it# constant 8 8it# 31 8 8it 7ubtract 8 8it# constant 8 8it 3 Carry 8 8it 3 Carry# constant 16 8it logic# left logic# right 7hift 2otate# left over Carry 2otate# right over Carry Arithmetic# right 6ibble e5change And And# constant r 8inary r# constant -5clusive3 r nes3complement )+os3complement Su( function instruction C:2 r1 7-2 rh :!' rh#c2EE 0 1 r1#r2 :!7 r1#c6EE"E :! r1#rp :! r1#rpK :! r1#3rp :!! r1#ryK,6" '6 r1#p1 < < r1 :<0 7)7 c6EE"E#r1 7) rp#r1 7) rpK#r1 7) 3rp#r1 7)! ryK,6"#r1 =) p1#r1 <=7; r1 '6C r1 A!! r1#r2 A!C r1#r2 A!'& rd#,6" !-C r1 7=8 r1#r2 7=8' rh#c2EE 78C r1#r2 78C' rh#c2EE 78'& rd#,6" :7: r1 :72 r1 2 : r1 2 2 r1 A72 r1 7&A< r1 A6! r1#r2 A6!' rh#c2EE 2 r1#r2 2' rh#c2EE - 2 r1#r2 C 0 r1 6-J r1 S61 S61 S61 S61 S61 SC61 SC61; S61 SC61; SC61; SC617 S61 SC61; SC61; SC61; SC61; SC617 SC61 SC61 SC61 SC61 SC61 0lags S61 1 1 1 1 2 2 2 2 2 1 2 " 2 2 2 2 2 1 2 1 1 1 2 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 Cl1
Avr-Asm-Tutorial
65
http://www.avr-asm-tutorial.net
Su( function
instruction 782 rh#c2EE C82 rh#2EE 87) r1#bF 8:! r1#bF 78' pl#bF C8' pl#bF 7-S 7-C 7-6 7-1 7-; 7-7 7-) 7-' C:S C:C C:6 C:1 C:; C:7 C:) C:' C< r1#r2 C<C r1#r2 C<' rh#c2EE )7) r1 2J0< cH096 'J0< 2CA:: cH096 'CA:: 2-) 2-)' ' S C 6 1 ; 7 ) ' S C 6 1 ; 7 ) '
Cl1
2egister# copy to )3Flag 2egister# copy from )3Flag <ort# set <ort# clear Sero3Flag Carry Flag 6egative Flag )+os complement carry Flag ;alf carry Flag 7igned Flag )ransfer Flag 'nterrupt -nable Flag Sero3Flag Carry Flag 6egative Flag )+os complement carry Flag ;alf carry Flag 7igned Flag )ransfer Flag 'nterrupt -nable Flag 2egister# 2egister 2egister# 2egister K Carry 2egister# constant 2egister# ^0 2elative 'ndirect# Address in S 7ubroutine# relative 7ubroutine# Address in S 2eturn from 7ubroutine 2eturn from 'nterrupt
Compare
'mmediate Jump
Avr-Asm-Tutorial
66
http://www.avr-asm-tutorial.net
Su( function
instruction 8287 bF#c12F 828C bF#c12F 82-P c12F 826- c12F 82C7 c12F 82CC c12F 827; c12F 82: c12F 820' c12F 82<: c12F 82J- c12F 82:) c12F 82;7 c12F 82;C c12F 82)7 c12F 82)C c12F 8217 c12F 821C c12F 82'- c12F 82'! c12F 782C r1#bF 7827 r1#bF 78'C pl#bF 78'7 pl#bF C<7- r1#r2 6 < 7:--< &!2
0lags
Cl1 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2 1L2L" 1L2L" 1L2L" 1L2L" 1L2L" 1 1 1
Jump if not e$ual Jump if carry set Jump if carry clear Jump if e$ual or greater Jump if lo+er Jump if negative Conditional Jump Jump if positive Jump if greater or e$ual @7ignedA Jump if lo+er than 4ero @7ignedA Jump on half carry set Jump if half carry clear Jump if )3Flag set Jump if )3Flag clear Jump if )+os complement carry set Jump if )+os complement carry clear Jump if 'nterrupts enabled Jump if 'nterrupts disabled 2egister bitG0 Conditioned Jumps 2egister bitG1 <ort bitG0 <ort bitG1 Compare# >ump if e$ual 6o peration thers 7leep &atchdog 2eset
Avr-Asm-Tutorial
67
http://www.avr-asm-tutorial.net
LD r1,1rE,rEI,(rE2 Lo%d the register r1 ;ith the ,ontent %t the -o,%tion th%t register E%ir rE 1K, . or 52 Eoints to 1rEI in,re<ents the register E%ir %fter -o%ding, (rE de,re<ents the register E%ir Erior to -o%ding2 LDD r1,ryIL66 LDI rh,,!55 LD* r1,,65565 Lo%d the register r1 ;ith the ,ontent %t the -o,%tion th%t register E%ir ry 1. or 52, disE-%,ed )y the ,onst%nt L66, Eoints to Lo%d the :EEer register rh ;ith the ,onst%nt ,!55 Lo%d register r1 ;ith the ,ontent %t -o,%tion ,65565
Avr-Asm-Tutorial LPM LPM r1 LPM r1,5I LPM r1,(5 L*L r1 L*R r1 MO r1,r! &E0 r1 &OP OR r1,r! ORI rh,,!55 O$> E1,r1 POP r1 P$*/ r1 R"ALL ,7096 RE> RE>I ROMP ,7096 ROL r1 ROR r1 *3" r1,r! *3"I rh,,!55 *3I E-,)8 *3I" E-,)8 *3I* E-,)8 *3I4 rd,L66 *3R rh,,!55 *3R" r1,)8 *3R* r1,)8 *E" *E/ *EI *E& *ER rh *E* *E> *E *E5 *LEEP
68
http://www.avr-asm-tutorial.net
Lo%d register R0 ;ith the ,ontent of the f-%sh <e<ory %t the -o,%tion th%t register E%ir 5 15/@5L, R61@R602, diCided )y !, Eoints to, )it 0 in 5 Eoints to -o;er 102 or :EEer 112 )yte in f-%sh 1Lo%d register r1, 5I in,re<ent 5 %fter -o%ding, (5 de,re<ent 5 Erior to -o%ding2 Logi,%- shift -eft register r1 Logi,%- shift right register r1 MoCe register r! to register r1 *:)tr%,t register r1 fro< 5ero &o oEer%tion 3it ;ise or register r1 ;ith register r! %nd store res:-t in register r1 3it ;ise or the :EEer register r1 ;ith the ,onst%nt ,!55 "oEy register r1 to IQO Eort E1 In,re%se the st%,L Eointer %nd EoE the -%st )yte on st%,L to register r1 P:sh register r1 to the st%,L %nd de,re%se the st%,L Eointer P:sh Erogr%< ,o:nter on st%,L %nd %dd signed ,onst%nt ,7096 to the Erogr%< ,o:nter 1re-%tiCe ,%--2 PoE Erogr%< ,o:nter fro< st%,L 1ret:rn to ,%-- %ddress2 En%)-e interr:Ets %nd EoE Erogr%< ,o:nter fro< st%,L 1ret:rn fro< interr:Et2 Re-%tiCe P:<E, %dd signed ,onst%nt ,7096 to Erogr%< %ddress Rot%te register r1 -eft, ,oEy ,%rry f-%g to )it 0 Rot%te register r1 right, ,oEy ,%rry f-%g to )it 8 *:)tr%,t r! %nd the ,%rry f-%g fro< register r1 %nd ;rite res:-t to r1 *:)tr%,t ,onst%nt ,!55 %nd ,%rry f-%g fro< the :EEer register rh %nd ;rite res:-t to rh *et )it )8 in the -o;er Eort EIf )it )8 in the -o;er Eort E- is ,-e%r, P:<E oCer the ne?t instr:,tion If )it )8 in the -o;er Eort E- is set, P:<E oCer the ne?t instr:,tion *:)tr%,t the ,onst%nt L66 fro< the register E%ir rd 1rdI1@rd, rd = R!7, R!6, R!9, R602 *et the )its in the :EEer register rh, th%t %re one in ,onst%nt ,!55 If )it )8 in register r1 is ,-e%r, P:<E oCer ne?t instr:,tion If )it )8 in register r1 is set, P:<E oCer ne?t instr:,tion *et ,%rry f-%g in st%t:s register *et h%-f ,%rry f-%g in st%t:s register *et interr:Et f-%g in st%t:s register, en%)-e interr:Et e?e,:tion *et neg%tiCe f-%g in st%t:s register *et %-- )its in the :EEer register rh *et sign f-%g in st%t:s register *et tr%nsfer f-%g in st%t:s register *et oCerf-o; f-%g in st%t:s register *et Dero f-%g in st%t:s register P:t ,ontro--er to the se-e,ted s-eeE <ode
*> 1rEQrEIQ(rE2,r1 *tore ,ontent in register r1 to the <e<ory -o,%tion in register E%ir rE 1rE = K, ., 5' rEI@ in,re<ent register E%ir %fter store' (rE@ de,re<ent register E%ir Erior to store2 *>D ryIL66,r1 *>* ,65565,r1 *$3 r1,r! *$3I rh,,!55 *4AP r1 >*> r1 4DR *tore the ,ontent of register r1 %t the -o,%tion th%t register E%ir ry 1. or 52, disE-%,ed )y the ,onst%nt L66, Eoints to *tore the ,ontent of register r1 %t the -o,%tion ,65565 *:)tr%,t register r! fro< register r1 %nd ;rite res:-t to r1 *:)tr%,t the ,onst%nt ,!55 fro< the :EEer register rh E?,h%nge :EEer %nd -o;er ni))-e in register r1 "o<E%re register r1 ;ith 5ero 4%t,hdog reset
Avr-Asm-Tutorial
69
http://www.avr-asm-tutorial.net
($(# ,tac@pointer
Port 7<:L7<; Name 7<: 7<; 0unction 7tac,pointer 2eaning :o+38yte of 7tac, pointer ;igh38yte of 7tac, pointer From A)9072"1" up+ards# not in 1200 From A)9078E1E up+ards# only in devices +ith V2E6 bytes internal 72A0 Port- !!ress 00"!L05"R 2- !!ress 05E!L05E*aila(ilit)
Avr-Asm-Tutorial
70
http://www.avr-asm-tutorial.net
Bit E H " 2 1 0
Opportunities 0G'gnore 7:--< instructions 1G7:--< on instruction 0G'dle 0ode @;alf sleepA 1G<o+er !o+n 0ode @Full sleepA 00* :o+3level initiates 'nterrupt 01* =ndefined 10* Falling edge triggers interrupt 11* 2ising edge triggers interrupt 00* :o+3level initiates interrupt 01* =ndefined 10* Falling edge triggers interrupt 11* 2ising edge triggers interrupt
'nterrupt by e5ternal pin '6)1 occurred 'nterrupt by e5ternal pin '6)0 occurred
Avr-Asm-Tutorial
71
http://www.avr-asm-tutorial.net
Bit F 6 E H " 2 1 0
2eaning )imerLCounter 1 verflo+3'nterrupt )imerLCounter 1 Compare A 'nterrupt )imerLCounter 1 Compare 8 'nterrupt @6ot usedA
Opportunities 0* 6o 'nt at overflo+ 1* 'nt at overflo+ 0* 6o 'nt at e$ual A 1* 'nt at e$ual A 0* 6o 'nt at 8 1* 'nt at e$ual 8 0* 6o 'nt at Capture 1* 'nt at Capture 0* 6o 'nt at overflo+ 1* 'nt at overflo+
)'C'-1
) '-0
Opportunities 'nterrupt30ode* Automatic Clear by e5ecution of the 'nt32outine 2 <olling30ode* Clear by instruction
)imerLCounter 1 verflo+ reached )imerLCounter 1 Compare A reached )imerLCounter 1 Compare 8 reached @6ot usedA )imerLCounter 1 Capture3-vent occurred @not usedA )imerLCounter 0 verflo+ occurred @not usedA
($(2 Timer-Counter +
Port )CC20 3 3 Bit Name 0unction )imerLCounter 0 Control 2egister + 3 & 3 2eaning 000* 7top )imer 001* Cloc, G Chip cloc, 010* Cloc, G Chip cloc, L 8 2%%0 C702%%C700 )imer Cloc, 011* Cloc, G Chip cloc, L 6H 100* Cloc, G Chip cloc, L 2E6 101* Cloc, G Chip cloc, L 102H 110* Cloc, G falling edge of e5ternal <in )0 111* Cloc, G rising edge of e5ternal <in )0 "%%F @not usedA , 3 Port- !!ress 05"" # 3 " C702 R 2- !!ress 05E" $ C701 4 C700
Opportunities
Avr-Asm-Tutorial
72
http://www.avr-asm-tutorial.net
Port )C6)0
R 2- !!ress 05E2
($(5 Timer-Counter
Port )CC21A 0unction )imerLCounter 1 Control 2egister A Port- !!ress 052F R 2- !!ress 05HF
+ C 01A0
, C 0180
# 3
" 3
$ <&011
4 <&010
Opportunities 00* 01* 10* 11* C1AL8 not connected C1AL8 changes polarity C1AL8 to 4ero C1AL8 to one
00* <&0 off 01* 838it <&0 10* 938it <&0 11* 1038it <&0
0unction )imerLCounter 1 Control 2egister 8 + 'C-71 Name & 3 2eaning 6oise Canceler on 'C<3<in -dge selection on Capture , 3
'C6C1 'C-71
0* disabled# first edge starts sampling 1* enabled# min four cloc, cycles 0* falling edge triggers Capture 1* rising edge triggers Capture
E%%H @not usedA " C)C1 Clear at Compare 0atch A 1* Counter set to 4ero if e$ual 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
2%%0 C712%%C710
Cloc, select
Port )C6)1:L;
R 2- !!ress 05HCL05H!
Avr-Asm-Tutorial
73
http://www.avr-asm-tutorial.net
Port C21A:L;
Port C218:L;
R 2- !!ress 05H8L05H9
Port 'C21:L;
R 2- !!ress 05HHL05HE
($(9 !atchdog-Timer
Port &!)C2 3 3 Bit F%%E H " &!) &!Name 0unction &atchdog )imer Control 2egister + 3 & 3 , &!) 2eaning @not usedA &atchdog )urnoff -nable &atchdog -nable <revious set to disabling of &!- re$uired 1* &atchdog active 000* 1E ms 001* "0 ms 010* 60 ms 011* 120 ms 100* 2H0 ms 101* H90 ms 110* 9F0 ms 111* 1#9 s Port- !!ress 0521 # &!" &!<2 R 2- !!ress 05H1 $ &!<1 4 &!<0
2%%0 &!<2%%&!<0
($(* EE'R4M
Port --A2:L; 0unction --<2 0 Address 2egister Port- !!ress 051-L051F R 2- !!ress 05"-L05"F
--A2; only in types +ith more than 2E6 8ytes --<2 0 @from A)9078E1E up+ardsA
Port --!2
R 2- !!ress 05"!
Port --C2 3 3
Avr-Asm-Tutorial
74
http://www.avr-asm-tutorial.net
Bit F%%" 2 1 0
Name --0&--&--2-
2eaning @not usedA --<2 0 0aster &rite -nable --<2 0 &rite -nable --<2 0 2ead -nable
0unction <revious set enables +rite cycle 7et to initiate +rite 7et initiates read
0unction 7<' 7tatus 2egister + &C : & 3 2eaning 7<' 'nterrupt Flag &rite Collision Flag
@not usedA
Port 7<!2
R 2- !!ress 052F
Avr-Asm-Tutorial
75
http://www.avr-asm-tutorial.net
($(
Port =!2
7ART
0unction =A2) 'L !ata 2egister Port- !!ress 050C R 2- !!ress 052C
Port =72 3 2OC Bit F 6 E H " 2%%0 Name 2OC )OC =!2F2
=A2) 2eceive Complete =A2) )ransmit Complete =A2) !ata 2egister -mpty Framing -rror verrun
1* Char received 1* 7hift register empty 1* )ransmit register available 1* 'llegal 7top38it 1* :ost char @not usedA
Port =C2 3 2OC'Bit F 6 E H " 2 1 0 Name 2OC')OC'=!2'2O-6 )O-6 C;29 2O88 )O88
R 2- !!ress 052A # )O-6 " C;29 $ 2O88 0unction 1* 'nterrupt on received char 1* 'nterrupt at transmit complete 1* 'nterrupt on transmit buffer empty 1* 2eceiver enabled 1* )ransmitter enabled 1* Char length 9 8it @holds 9th data bit on receiveA @+rite 9th data bit for transmit hereA 4 )O88
2eaning 2O Complete 'nterrupt -nable )O Complete 'nterrupt -nable !ata 2egister -mpty 'nterrupt -nable 2eceiver -nable )ransmitter -nable 93bit Characters 2eceive !ata 8it 8 )ransmit !ata 8it 8
Port =822
R 2- !!ress 0529
Avr-Asm-Tutorial
76
http://www.avr-asm-tutorial.net
Bit " 2 1 0
0unction 1* 'nterrupts enabled 1* Connect to )imer 1 Capture 00* 'nterrupt on edge change 01* @not usedA 10* 'nterrupt on falling edge 11* 'nterrupt on rising edge
Avr-Asm-Tutorial
77
http://www.avr-asm-tutorial.net