HCS12 Microcontroller and Embedded Systems: Using Assembly and C with CodeWarrior 9780136072294


380 113 147MB

English Pages 752 Year 2009

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

HCS12 Microcontroller and Embedded Systems: Using Assembly and C with CodeWarrior
 9780136072294

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

3DUDHQFRQWUDUODSiJLQDFRUUHFWDUHVSHFWRDODUFKLYR3')VXPDUDOD SiJLQDLQGLFDGDHQHOOLEUR(MHPSOR/DSiJLQDGHOOLEURHVODSiJLQD GHO3')$MXVWDUHO]RRPDSDUDYLVXDOL]DFLyQySWLPD   &217(1,'2 

&RS\ULJKWLL 3UHIDFH[ $ERXWWKH$XWKRUV[LY &DStWXOR,QWURGXFWLRQWR&RPSXWLQJ 6HFFLyQ1XPEHULQJDQG&RGLQJ6\VWHPV 6HFFLyQ'LJLWDO3ULPHU 6HFFLyQ6HPLFRQGXFWRU0HPRU\ 6HFFLyQ+DUYDUGDQG9RQ1HXPDQQ&38$UFKLWHFWXUHV 6HFFLyQ5,6&$UFKLWHFWXUH &DStWXOR7KH+&660LFURFRQWUROOHU+LVWRU\DQG)HDWXUHV 6HFFLyQ0LFURFRQWURODGRUHVDQG(PEHGGHG3URFHVVRUV 6HFFLyQ2YHUYLHZRIWKH&38DQG&38 &DStWXOR+&6$UFKLWHFWXUHDQG$VVHPEO\/DQJXDJH3URJUDPPLQJ 6HFFLyQ,QVLGHWKH+&6 6HFFLyQ7KH+&60HPRU\0DS 6HFFLyQ7KH+&6$GGUHVVLQJ0RGHV 6HFFLyQ+&6&RQGLWLRQ&RGH5HJLVWHU 6HFFLyQ+&6'DWD)RUPDWDQG'LUHFWLYHV 6HFFLyQ,QWURGXFWLRQWR+&6$VVHPEO\/DQJXDJH 6HFFLyQ$VVHPEOLQJDQG/LQNLQJDQ+&63URJUDP 6HFFLyQ6WDFNDQG'DWD7UDQVIHU,QVWUXFWLRQV &DStWXOR%UDQFK&DOODQG7LPH'HOD\/RRS 6HFFLyQ%UDQFK,QVWUXFWLRQVDQG/RRSLQJ

6HFFLyQ-65DQG&DOO,QVWUXFWLRQV 6HFFLyQ3URJUDPV8VLQJ,QGH[HG$GGUHVVLQJ0RGH  &DStWXOR+&66,23RUW3URJUDPPLQJ 6HFFLyQ,23RUW3URJUDPPLQJLQ+&6 6HFFLyQ,2%LW0DQLSXODWLRQ3URJUDPPLQJ &DStWXOR$ULWKPHWLF/RJLF,QVWUXFWLRQVDQG3URJUDPV 6HFFLyQ$ULWKPHWLF,QVWUXFWLRQVDQG3URJUDPV 6HFFLyQ/RJLF,QVWUXFWLRQVDQG3URJUDPV 6HFFLyQ&RPSDUH,QVWUXFWLRQDQG3URJUDPV 6HFFLyQ5RWDWH6KLIW,QVWUXFWLRQVDQG'DWD6HULDOL]DWLRQ 6HFFLyQ%&'DQG$6&,,&RQYHUVLRQ 6HFFLyQ6LJQHG1XPEHU&RQFHSWVDQG$ULWKPHWLF2SHUDWLRQV &DStWXOR$GYDQFHG$GGUHVVLQJ0RGHV/RRN8S7DEOH0DFURVDQG0RGXOHV 6HFFLyQ$GYDQFHG,QGH[HG$GGUHVVLQJ0RGH 6HFFLyQ$FFHVVLQJ/RRN8S7DEOHLQ)ODVK 6HFFLyQ&KHFNVXPDQG$6&,,6XEURXWLQHV 6HFFLyQ0DFURVDQG0RGXOHV &DStWXOR+&63URJUDPPLQJLQ& 6HFFLyQ'DWD7\SHVDQG7LPH'HOD\VLQ& 6HFFLyQ/RJLF2SHUDWLRQVLQ& 6HFFLyQ'DWD&RQYHUVLRQ3URJUDPVLQ& 6HFFLyQ,2%LW0DQLSXODWLRQDQG'DWD6HULDOL]DWLRQLQ& 6HFFLyQ3URJUDP520$OORFDWLRQLQ& &DStWXOR+&6+DUGZDUH&RQQHFWLRQ%'0DQG6+H[)LOH 6HFFLyQ+&63LQ&RQQHFWLRQDQG%'0 6HFFLyQ6HWWLQJWKH3//)UHTXHQF\LQWKH+&6 6HFFLyQ([SODLQLQJWKH6)LOHIRUWKH+&6 &DStWXOR+&67LPHU3URJUDPPLQJLQ$VVHPEO\DQG& 6HFFLyQ)UHH5XQQLQJ7LPHUDQG2XWSXW&RPSDUH)XQFWLRQ

6HFFLyQ,QSXW&DSWXUH3URJUDPPLQJ 6HFFLyQ3XOVH$FFXPXODWRUDQG(YHQW&RXQWHU3URJUDPPLQJ 6HFFLyQ+&67LPHU3URJUDPPLQJLQ& &DStWXOR+&66HULDO3RUW3URJUDPPLQJLQ$VVHPEO\DQG& 6HFFLyQ%DVLFVRI6HULDO&RPPXQLFDWLRQ 6HFFLyQ+&6&RQQHFWLRQWR56 6HFFLyQ+&66HULDO3RUW3URJUDPPLQJLQ$VVHPEO\ 6HFFLyQ+&66HULDO3RUW3URJUDPPLQJLQ& &DStWXOR,QWHUUXSW3URJUDPPLQJLQ$VVHPEO\DQG& 6HFFLyQ+&6,QWHUUXSWV 6HFFLyQ3URJUDPPLQJ7LPHU,QWHUUXSWV 6HFFLyQ3URJUDPPLQJ([WHUQDO+DUGZDUH,QWHUUXSWV 6HFFLyQ3URJUDPPLQJWKH6HULDO&RPPXQLFDWLRQ,QWHUUXSW 6HFFLyQ,QWHUUXSW3ULRULW\LQWKH+&6 6HFFLyQ,QWHUUXSW3URJUDPPLQJLQ& 6HFFLyQ3URJUDPPLQJWKH5HDOWLPH,QWHUUXSW &DStWXOR/&'DQG.H\ERDUG,QWHUIDFLQJ 6HFFLyQ/&',QWHUIDFLQJ 6HFFLyQ.H\ERDUG,QWHUIDFLQJ &DStWXOR$'&'$&DQG6HQVRU,QWHUIDFLQJ 6HFFLyQ$'&&KDUDFWHULVWLFV 6HFFLyQ$7'3URJUDPPLQJLQWKH+&6 6HFFLyQ6HQVRU,QWHUIDFLQJDQG6LJQDO&RQGLWLRQLQJ 6HFFLyQ'$&,QWHUIDFLQJ &DStWXOR$FFHVVLQJ)ODVKDQG(HSURPDQG3DJH6ZLWFKLQJ 6HFFLyQ3DJH6ZLWFKLQJRI)ODVK0HPRU\LQ+&6 6HFFLyQ(UDVLQJDQG:ULWLQJWR)ODVK 6HFFLyQ:ULWLQJWR(HSURPLQWKH+&6 6HFFLyQ&ORFN6SHHGIRU)ODVKDQG(HSURP

&DStWXOR5HOD\2SWRLVRODWRUDQG6WHSSHU0RWRU,QWHUIDFLQJZLWK+&6 6HFFLyQ5HOD\VDQG2SWRLVRODWRUV 6HFFLyQ6WHSSHU0RWRU,QWHUIDFLQJ  &DStWXOR63,3URWRFRODQG57&,QWHUIDFLQJZLWK+&6 6HFFLyQ63,%XV3URWRFRO 6HFFLyQ63,0RGXOHVLQWKH+&6 6HFFLyQ'657&,QWHUIDFLQJZLWK+&6 6HFFLyQ'657&3URJUDPPLQJLQ& 6HFFLyQ$ODUPDQG,QWHUUXSW)HDWXUHVRIWKH'6 &DStWXOR3:0DQG'&0RWRU&RQWURO 6HFFLyQ'&0RWRU,QWHUIDFLQJDQG3:0 6HFFLyQ3URJUDPPLQJ3:0LQ+&6   $SpQGLFH$+&6,QVWUXFWLRQV([SODLQHG $SpQGLFH%$VP,'(,PDJH&UDIW&&RPSLOHUDQG'%XJ $SpQGLFH&,&,QWHUIDFLQJ6\VWHP'HVLJQ,VVXHVDQG:LUH:UDSSLQJ $SpQGLFH')ORZFKDUWVDQG3VHXGRFRGH $SpQGLFH(+&63ULPHUIRU[3URJUDPPHUV $SpQGLFH)$6&,,&RGHV $SpQGLFH*$VVHPEOHUV'HYHORSPHQW5HVRXUFHVDQG6XSSOLHUV $SpQGLFH+'DWD6KHHWV  ËQGLFH

 Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

  

LiiJrllr), of cッョャZNLセ@

www.fut ureerc.com

CIIIIII"I:lol: in PulJlil'>lliuol 011111

Malidi. Muhammad Ali. lies 12 m icnxontroller and embedded .yst."TIS' u.ing A.nnelly & Sons Company. The co'''' Center.

WlL'S

printed by Dellland Production

Copyright Cl 2009 b )' I'oanon Ed uo ation, In c.• Upj>tr Sadd le Hi,'er, Now Je r .. )· 074S!1. Pearson Prentice Hall All rights TCSCrvOO. Prillloo in the United States of America. This publication is proエセ エ ・、@ by O;'pyri ght and P"'"mission shou ld b( ッ「エ。 ゥョセ 、@ frun 1M publiJlle' prio r to any prohibitw reproduction , セ エ HャQ ァ・@ in a retrieval system, or ll11nsmission in any form or by any meillts , electronic, 。ョゥセ 。ャL@ pbotoo;OJlyinW. n:Wnlinll. or ャゥォ セキ ゥ NZ@ For ioformation reJlllniing pY)llrm to the lUlLS'l! rl{ uniflC(J/;Qn of Our pk",et.

- Muhammad All MazM!

I dedicme my pan 10 my fam ily

for the patience and ,llIpporlllrey provided dwing the prodllCtion

HjャィゥNセ@

book.

Their love he/ped me 10 see this book tlrrough.

- Donny Cow:ey

I,

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

PREFACE Products using m icropr(lcessors genera lly fall into two calC gories. The first category uses hi sh-perfonna nce m icroprocessors such as the Pent ium in applica-

tions where s),stem perfonuance is critical. We ha ve rul entire book ded ic ated to Ihis topic. Ihe 8Ox86 IBM PC wId Compatible CQmpulen, VOlumes J alld II. from

Prentice l-la[ L In the second category of applications. perfonnanc.: is second ary; issues o f cost, space. power. and rapid development are more critic al than raw pro -

cessing power. The mic roproxcssor for Ihis category is often called a microcontroller. T his book is for the second calegoryof app li cations. The HCS I 2 is a wide ly used m icrocontroller. There arc many reasons for thi s. including the legacy o f once popular chip ca lled 68l1 C 11. This book is intended for usc in coll cgo:-lcvd courses leaching microcomT(l llers and em lxddw systems. II not onl y establishe; a foundation o f As>embly language programming. bm also provi des a セ ッューイ」ィョᆳ sivc 「B 」。 エ ュセョエ@ of ]-](5 12 intcrfacin g for engineering student s. Fro m this bad:ground , the des ign and iDlcrfhc ing o f m icrocontrollcr-based cmbooded systems can 「セ@ セ クー ャ ッイ」、 N@ This boot can also be used by practic ing technicians, hardwafC engin eers, com plllc r scienti st s, 3ntl hobbyists. It is a n ideal sou rcc for those wanting to movc away from 68 HC II to a more powerfu l chip. Prerequisites Readers should ha ve had nn in tmductnry d igital course. Know looge o f Assembly language would be hel pfu l bm is nOl necessary. A lt hough thi s book is wri nen for those with 110 background in Assembly ャ。 ョ ァャセ・@ programmin g, Sllldents with prior Assembly lon guage expe rience will be oble to gain a mastery of HCS 12 architectu re very rapid ly and stan on their projects ri ght away. For the HCS 12 C programming sect ion s of the book, a basic knowledge of C programmin g is requ ired. We use the CodeWurrior compilcr IDE from Freescu1c throughout the book. Th e CodeWamOl compiler is available for free from the Frcesca le website (www.freesca le.com). We enco umge you to use the CodeWumor or some other IDE to simulute and run the progrums in this book.

Overview A sysk'ffiJtic, step-by-step approach is used to cove r various aspects of HCS 12 C and A ssemb ly ャ。ョ ァオ。セ@ progmnuning and interfa cing. Many exam pl es lmd sample progmms ure given to clari fy the concepts and provi de ウエ オ、ャGQエ セ@ wi th an opportunity 10 leam by doing. Rev iew questions are provided at the end o f each section to rein force the main points of the set:tion. Chupk,- 0 COveTli n wnbcr sySll'lIl8 (binary, d ecimal ,:md hex). and provilks an introduction to basic logic gates and com pu ter memory. This chapter is designed espec ially for student s, such as mechani ca l engineering studelll s, who have not takell a di gilal logic cou rse or tliose who need to fefresh tlieir memory on (hese: copies. Cliapler I di scu.sses the hisiory o f the HCSI2r9S 12 and features of (lie origina l fami ly members such as the 68 HC I I . It al so prov ides a list of various me mbers of the HCS 12 fam ily.



www.fut ureerc.com

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www. freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Chapter 2 di\lCUSSCS tho: in terna l archilo;cturc oflho: HCSI2 and c the

CodeWumOJ compilCJ from Frceswle for Ihis and other C progrums of the HeS 12 fami ly th roughout the book. The Code Wurrior is avai labl e for free from the www.frccscalc .comwcbsitc. the h:mlware connect ion o f the HCS I 2 chi p . In Chapter 8 we 、ゥ sャ[ オFセ@ Chupier 9 describel; the HCS 12 timl-"TS und how to use them as event counChapter 10 is dedicated to seriu l (\;11:1 commun ication ofl he HCS I 2 (lnd ils interfacing to the RS232. 11 also shows HCSI2 communiC3lion wilh COM pons of the x86I BM PC and compal ible computers. Chapter I I provides a detui led d ist"llssion of HCS 12 interrupts wil h many examples on how 10 write inlerrupt hand ler pro grams. Cha.pter 12 >bows HCS I2 interfacing with real -world 、・カゥ」 セ@ such as LC Ds and keyboards . Chapter 13 shows HCS12 imerfacin g with rea l-world devices such as OAC chips. AIX' c hips. and >t: fl';OfS. In Chapter 14 we cover how 10 u se HCS 12 Flash ami EEPROM memories for da ta slOrage and explains ho w 10 do page switching in Flash mem o!),. Chapter 15 co vetS the bask interfacing of the HCS I1 chip !O r elays. oplo iso lalors. and stepper motors. Chapter 16 shows how \(l COIUleAddition of binary and hex numbers Tho add ition o f bi nary numbers is a very strai ghtforward process. Tab le 0-3 shows

D

tho addilion (lft wn bilS. The di scu!:5ion of sub· エイオセQ ゥ ッョ@ ofbi nury numbers is bypasscU si nce all oom p .ucrs usc (he ad dition process 10 im ple-

men t subl mclion. Aithough com puters have adder ci rcui lry. ャ ィ 」 イ セ@ is no St:purnte circuit ry rur subtractcrs. Instead, adder s arc uscd in ron · junt1 ion with 211 complement c ircuitry to pcr· rOffil subtmcl ion. In mher words, to implement "x - y" , the computer tak es the 2's complement or y and adds it to x . Th e concept o r 2's com· p[t'rrwnt is reviewed next Exrunple 0-8 shows the addition or Tabll' 0. 3: Din an- Addition binary numbers. A+ B Ca rry Sum 0+0 0 0 0+1 0 1 1+ 0 0 1 1+ 1 1 0 Example O·H Add the fo llowin g binary numbers. Check against their dec imal equivalents. Solu tion: 1Jedmul IJjnuf")' 11 0 1 13

+

lJlOl 10 11 0

--" 22

2'5 complement To get the 2's complem enl or a binary number, in vert al l the b it s amI then

6

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

add I to the r(sult Invcning the bit s is simp ly a mauer o f changin g aU Os to I s and Is 10 Os_ This is ca lico the ャセ@ complemenf. $cc Example 0-9_

Enlllpl e 0-9

Take the 2 's complement of 100 1110 1. Solu tion : 10011101

binary number

OI IOOOIU

l 's セッュー

OIIOOOIJ

2's セッ

j・ュ@

+ ューj・@

Addition and subtraction of hex numbers In studying issues rdated 10 software and hanfw are of computers. it is often necessary 10 add or subtract hex nWlIbers. Mastery or these tedUl iques is ':SSClltiaL Hex addi tion and subtraction arc discu ssed separately bo:lo w.

Addition of hex numbers Thi s scctioo rlcscnbcs the process of adding hex numbers. Slanin g wit h the

kast significant digits, the di gits are added together. If the resul! is less than 16, wri te that cction gi vcs an ovCfview of d igital logic an d design. First, we cover

binary logic operaTions, then we ウィッ|セQ@ gales that perform these functions. n」セエN@ logic gules are put oogclhcTw form simple digitul drcuits. Firmlly, we rover S()mc logic devices commo nly found in microcontro l1cr interfacing.

,-----=-----,-----,

,

Binary logic As ment ion oo earlier. computers use the binary nwnber system because (he two voltage lev els can be representoo as the ( \\"0 digits 0 and I. Signals in d igi tal electronics have t\\"o d istinct voll age levels.. For ex ample. a system may define 0 V as logic 0 and +5 V as logic I. Figure 0-2 sho\\·s (hi s system with the bu ilt-in tolerances for variati oru; in the voltage. A valid d igital signa l in ulis examp le should be w ithin either of the two shaded areas.

L;clusivc-OR produces u 1

output i f one (but on ly one) input is I. If both opernnds are 0, the o Ulput is O. Likewise. if both opernmls ure 1, the ou tput is "Iso O. Not ice from the XOR truth tab le , Ihal whenever the two inputs are the same. the output is O. This function can be used to 」 ッイョー。 セ@ Iwo bils to sec if Iht:y urc the tmmc. NAND and WOR gates

The N AND gule ヲ オ ョセQ ゥッョウ@ like un AND gale with an invcncr on the OUTput 11 produces u 0 OUlp .1I when all inputs ure 1; olh(:rwi se, il produces u 10utput. The NOR gale function s li ke un OR galew ilh an inveTlc r on the outpu t. II produ ces 11 1 if all inp uts ure 0; 04hl'Jwisc, it produces a O. NA ND and NOR gates are used extensively in digital design because thl-y ure ・オLセケ@ un d ineXp(.'l1 sive to rabri cate. An y circu it that cun be d t."l;;gned with AND. OR, XOR. und INV ERTER gates can be irnpk mented using only NAND and NOR gales. A s imple e.'(am pl e of this is given below. NOliee in NAND, thaI if any input is 0, Ihe outpul is I. Notice in NOR, that if any input is I, the OUlput b O.



Next we will show a simple logic design to add IWO binary digits. If we add IWO bi nary digi ts iィ・セ@ are four poss ible outcomes:

 0+00 +1 1+ 0 1+1 -

  



10

O UIP UI

NOTX

1 0

LogiG design using gates



Inplll

U





l ll'..;icaJ LII Hrtu

CDI'I)'

Sum

0 0

0

0

1 0

x ----{>o- NOT X Logical XOR Funct io n In l!UTS

O UII! UT

XY 00 U1 1U 11

XXOR Y 0

0

IAlglcal NA ND F u n c llo n IUl!u lS

O u tl! UI

XV

X NA NDY

00 0 1 10 11

1 1 1 0

Logical NOR Funct io n

I nlJU b

O utl)U t

XY 00 0 1 10 11

XNOR Y 1 0 0 0

www.fut ureerc.com

Page: 1

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Notice !hat when we :ldd 1 + 1 we get 0 wit h a cart)' 10 Ih e next higher p13ce. We will need to delCfll1ine the sum ond the cany fOf Ihis design. Notice Ihm the sum column above matches the output for the XOR function, and that the carry column matche s the output for the AND func tion. Figure 0- 3(u) shows II simp le adder illlp lem cnled to identify a prc.:klCllllincd binary address.

SECTION 0.3: SEMICONOUCTOR MEMORY In this >('Chcn we discuss various types Df scm icon ctuclOr memori es llnd

their characteristics such as caracily, organi zat ion. and access li me. We will a lso

show hoI'.' the memory is connected 10 th e CPU. Before we em ba rk on the subjcct of m emory, it will be helpful to give an OVCfVicw of oomplllCf c rgani7.atioo and イ」セ[キ@

some Icrminology Thai is wirlcly uscd in computeTli tCTallrro.

Some important terminology

Bit

o

0000 Byte 00 00 0 000 Word 0000 000 0 00 00 0000 Ni bble

Rlocall from the 、 ゥ セャ[ オ ウ ゥ ッョ@ above that U bit is u binary d igil lhu l can have the vnluc 0 or I. A byte is defined as 8 bils. A nibble is half a byte. or 4 bils. A word is 11'.'O by l':&, or 16 bits. The display is illlcnded 10 sIlo w the reial ive size of these units. O f course. th ey coul d all b.: composed of any co mbina tion o f reros and ones. A kilobyte is 210 bytes. whi ch is 1.02 4 bytes. The abbreviation K is often used 10 Tepl"csenl kilobytes. A megabyte , or meg ャiNセ@ some call iI, is 220 by le:bows a block: diagram of the internal (lrganizalioll of a computer. The functioll of the CPU is to exe.::U!e (proca; s) informat ion stored in memory. The function of 1/0 devices such as the keyboard and video monitor is to provide a means of co nullunicaling with the CPU. The CPU is C01Ulel;kd to memory and Ito

through a group of wires calkd a bU!>. The bus inside a computer allows signals to carry in fomtation from place to pia.:.: just as a street allows cars to carry people address bus, from place to pl ace. In ev ery computer there are thrtt types of 「オセウZ@ data bus. and control bus. For a device (memory or 110) to be recog ni zed by the CP U. it must be assigned an address. The address assigned to a given devie.: must be unique; no two devices arc allowed to have the same address. tィセ@ CPU puts the address (in 」ゥイセオエケ@ finds the device. binary, of course) on the address bus, and the 、」セッゥョァ@ Then the CPU uses the data bus either to get data from that device or to send data to it , Contml bu ses arc u!iCd to provide read or |セtゥ エ 」@ signals to the rlcvicc to ind icate if the CPU is asking for information or send ing information. Of the three buses, the add ress bus and the data bus determine the capability of a given CPU.

More about the data bus Because dum buses lITe used w セョイケ@ in formation in and out of u CPU, the more OOIU buses uvui lub1e, the better th e CPU. If one thinks of duta buses lIS highwny lanes, ir i3 clenr thn! more Inn es provide a better pathwny between the CPU und it s ex temul devices (such a s prin ters, RA M, ROM, etc.; sec Figure 0-9). By the sume token. Ihnl ゥ ョ」 イ ・Qlセ@ in the number o f lanes ;nt-Teases Ihe cost of COI1Slructioo. More OOtu buses menn u more ・セーエN Biャウゥ カ・@ CPU nn ll compult-,-. The averngc size o f llu!u 「 オセ@ in CPUs vunes bctwoc"ll 8 and 64 bi ts. Enrly pt,-wrml compu ters such as App le 2 used an 8-bit data bus, while supL,-compul ers such as Crn)' used a M-bit data bus. Data bu ses ure bi llireClional. bec:Juse the CP U must use them eilhl,- to i'lXeive or to send ruIn. The proocssing po\\'erofu computer is reluted to the size of its buses, bt--.::ausc an 8-bil bus call sell ll out I byte a lime, bu t a I ii-bit bus can seOO out 2 bytes ut a time, which is twice us fust.

More about the address bus Because the aWircss bus is used 10 i!lcllli f)' the devices and memory COIl 14

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x. com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

ncrted to the CPU, the more address bits ava ilable, the larger the number of devices that can be セイャ、 イ」ウ 、⦅@ In other word s, the nllmber of nddress bits for a CPU dctcrmincs the number of locations with which it can communicate. The number of loc ations is ul wuys eqwl to 2-", where x is the nU mbL"f of address lines.

regnrd less of the size of 100 、セュ@ 「オセN@

For exu mpJc, 11 CPU with 16 a!ld rl'Ss lines

call provide a lolal of 65.53(; (2 16) or 64K o f addressable memory. Eru,:h [Qemjon all general-purpose m icrocall have II ma.'{imwn o f I byte of data. This is 「セ。オウ・@ processor ( PUs are what is called b)'1e addn!S$abll;!. As another example. the IBM PC AT uses II CPU with 24 address line s and 16 data lincs. Thus , tho: tolal a ccessible memory is 16 tl1('gabytcs (2 24 - 16 mcgabyl CS), In this ex amp le there wcu ld be 224 10000tions. and because each location is one byte, thed to

activate the CS pin of the memory chip. 11 is the CS pin thaI , along with RDfWR, allows the l1 0w of daL1 in or QUI of the ITICmory chip. No data can be wrincn inlO or read from the memory ch ip unk ss CS is activated. As can be seen from the Jutu sheets of SRA M and RO M, the CS input of a memory chip is nonnal1y act ive LO W ami is activated by the output o f lOO memory decoder. Nom1311y mem ories ure di vided iolO blocks, an d the outpu t of the deroder ウ・ ャ ・」ャセ@ a givcn memory block . Thl..-e ure three ways to generute a memory block selecto r: (a) us ing simple logic gates, (b) using the 74LS 138, or (e) using programmable log ic such as u CPLD or FPGA. Each meth od is dcS register A. After completin g on e instmetioo, the program counter points 10 the oorlress of the next instruction to be executed, which in th is case is 1402H. Addre ss 1402 is sent out 011 the address bus to fetch lhe next instruction. 4. From memory location 1402H the C PU fetches cod e 04H. After decoding, the CPU knows lhul it musl lldd the byte siui ng ut the next address (1403) 10 the A. aヲエセ NL@ the CPU bri ngs the value (in th is case, 42H) in to con tents ッイ・ァゥウエセNL@ rcgistcr A. il provides the contents of register A along with this value to the C II Arn: R U: IJ'l:T ROJ) UCT10 J'I: TO COMPUT ING

31

Page: 31

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

A LU to pcrform the addition. It then tal:cs the result of the add ition from the A LU', outpu t セ ョ、@ puIS il in register A, Meanwhi le the program cou nter becomes 1404, the addrcss of lhe next in struction. 5. Address 140411 is put on the address bus and the rode is fetched into the CPU,

decoded, aM

セ」オエ

、 N@

This coOc llgnin is nM ing II \'llJUC 10 regiStCf A. The

program counter is updated to 1406H. 6. f ゥョ セQ Q ケL@ the contents of add ress 1406 (HALT code) arc fClChcrl in and executed. Th e HA LT in SiruClioo tel ls the C PU to SlOp incrementi ng the program

COUn1Cf and 。Nセ ォゥョ

ァ@

for the next instruction. Wi thou t the HALT, the CPU would

conti nue updat ing the program coun ter and fetching instroctions. Now suppose that address 1403 H coo tuinoo the vulue 04 in stead of 42 H. HoI\.' wou ld the CPU rl iSiingui sh between data 0 4 to be ndded and code 041 Rl'fTlemberlhat code 04 for this C PU mean s "move the next vul ue inl o rcgiSll."T ,\ " . Therefore. lhe C PU wi ll nm lry 10 det:ode lhe nexl vul ue. 11 simp ly moves lhe con 10015 of lhe followi ng mem ory localion in lo rcgislCT A, regard less o f i1S value.

Harvard and von Neumann architectures E\'ery lllicropmcessor mUSl have me mory space to sl ore program (corle) and data. While cooe provid es instruclions to the CPU. the data prov ides Ihe information 10 be processed. The CPU uses buses (wire Iraces ) Ie acc ess the code ROM and rlata RAM m emory spaces... The early computers used the sam e bus for access ing both the code and data. Such an arch.i tcclure is com monly re ferred 10 as loon NeumiUm (Princelon) architecture. ThaI mea ns for von NeumalUl computers. the process of accessing cooe or data cou ld cause: each 10 get in th e other's way and slowdollTI the processing speed ofthe C l'U. because each harllO wait for the other to fi nish fetching. To spero up the process of program execution. SOllie CP Us use what is called Harvard (U"Chilecrure. The H arvard architecture has scpamle bu>es for the corle and rlata memory. See Figure 0- 20. That means thaI we need four sets of bu scs : {I} a set of rlata buses forcarry ingda la illlo anrl out oftheC l' U. (2 ) a set of add ress buses for accessing the rlala . (3) a set o f dala hu>es for carrying corle into lhe C PU. anrl (4) an arldress bus for accessing !.he code. See f igure 0 -20. This is casy to implement inside an IC chip such as a m icroeontroller wherc both ROM rorle and data RAM arc internal (on-chip) and distances arc on the mic ron and mi llinder on Harvard architect ure is no t implcmcnlcd in the worlrl of PCs anti work stHtion s_Th is is also the reason that m icrocomrollers such セウ@ PIC |jL セ」@ Harvard architecture in tern all y, but th ey still usc \"on Nellmann architC ,..

6-1liI

Lセ@

MEMORY セ@

,

セ@

セ@

,

, ,
ded. because Flash is an EEPROM (e h:l."u icaJl)' イョ

セ k@

I : TIlt: II CSIZ I '-'SIZI\1ICKOCONTKOLU:R

Page: 53

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

erasable p r oセ i I N@ Depending on the way the Flash memory is designed. you mus t cra >e the en li re oon1cn1, of a block of ROM in order 10 program i1 aga in. This erasing o ( Flash is done by the ROM programmer il>o:lf, so a separate c raseI' is n01

ne;Ih a . More 「\ゥョセN@ abul low(t" セ o Nエ@ ['" that product. importacnly. "",up:>

»

» » »

» »

» » »

» >:> »

List the n . g lslcrs tlf the II CS 12 mkrOl:on lroDcr M anipul a te tla ta us in!; the re!;isters a nd load li nd :nl d in struct io ns Code §im pl e II CSI1 Assembly la n guage in struc tio ns Assembl e and r un an IICS I2 p rog ra m Describe th e !>equence of c\'cn ls tha t occur u pon II CS I 2 power-u p Exa mine p rograms in ROM cOOt' of I he I ICS I2 Ex plai n the ROM lIIl'III Or)' llIap uf lhe II CS12 Deta il the execu ti on of II CS I2 Assl'lIIb l)' lan lluage iu§t r udi ons Describe II CSIl a d dress in c mod es Describe II CSIl di recth'c! for Assl' lIIb l)' la ng uagc prog ra mming Explai n the purpose of the eCR (conditio n code fCgislr r) register Di K UU nK'mory space a ll ocathm i n the II C812 Di agra m the use of th e stack in th e II CS I 2

59

Page: 59

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

SECTION 2_1: INSIDE THE HCS12 In Ih is SCC(ion we exam ine the major rcg; Slcrsof thc HCS 12 and show their

usc wilh the simple inslruclions dealing wi th load and add. Registers In the C PU, [egislers arc used 10 store informat ion tempomril)'. ThaI in formation cou ld be H by te of data to be processed, or an ud{]rcss pointing 10 the dutu to be fetchetl. The HCS 12 registers are either 8-bj! OJ 16-bi t Th e 8 bit!; of 3 イ セァゥウ ᆳ (cr arc shown ill Figure 2-\ from the MSB (mos t s ignificant bi l) D7 \0 (he LSB (least ,igni rICilll1 bit) 00. Since thefe are 3 la rge number ofreg islL'Js in dH; HCS I2,

we will con ccm rale ィ ・ イ セ@ on some orlbe widely used general-purpose reg isters and cover special regislers in fut ure chapters.

Xセ

ゥ ャ@

reg ister:

i dG ャ ッ ャ セ i セ ャ ッ ャ セ ャ イョ ャ ッ ャ@

160M regiMe!':

101510141°1310121011101°109 108 107 100 I Dsl04 1 I 02 1 I DOI OJ

I Fll:urr 2-1. BIt



セ ウjャZBエu

B@

D 16-bit register

01

I

A

B

8-bi1 reg ister

8-bit register

tIL S- lind l6-b,t Rt, glucrs

Th e most w ioel y used reg iscCTS of the HCS 12 are A, Il , X, Y, SP (stack poinler), CCR (oondicion eode register), and PC (program eOUnler). All o f the above registers are 16-bits, exc ept A, Il , and CC R . $o:c Figurc 2-2. The A and B registCTS arc refcrrco lo as accumulacors and arc widel y used by the a rilhm cc ie and logic instruclions. Comb ini ng registcrsA and B will give us a 16-b il rcgiSlcreallcd D, wh ich is used for the l 6-hit arithmClie and log ie operalions. To un 65535 deci (FFFFH ) 5. A value to be loadoo into a register mus t be preceded with a pound sign (II). Otherwise the comma nd will load from a m emory locati on. For example " LDAA $17" means 10 movc into register A the bytc held in memory location 17H, whk h cou ld have any value. In o rder to load the valuc 17H into the (!CW mum tor we mUSl wtite "1DM ' $17"' with the It- preced ing the nwnber. 62

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Notice that the absence of the pound sign will not cause an e rror by the assemb ler since it is セ@ valid instruction_ HOII'ever, the result would not be what the programmer int ended. This is a common error for t>cginnin g programmers in

the lIeS ' 2.

ADDA and ADDB instructions Th e AD DA and ADDB instruction s huve the fol lowing format ADDA s ource ; ADD s o urce opecand to the ace u A ADDB s ource ; ADD sou rce operand to the accu B

The ADDA im lructioo tells the CPU to udd the source byte 10 H.'g i Sll..- A and p llt the result in the dest ination register A. To add two numbers suc h as 25 H and 34H, each call be moved \0 a reg ister and then added together:

;load 25H i nto A ;load 34H i nto B

LDAA .$2 5 LDAB .$34

ABA

;add B to accumulator A (A - A + B)

Executing the pHlgranl above rewlts in A - 5911 (251-! + ) 411 - 59H ) and il - 341-1. Notice that the content of B docs not change. The re arc al ways many

ways to wrile the sanle program. One qu estioll tha t m ight cOlne to mind a fter looking at the program above. is Whether it is neccssary to move both data items into registers before adding th.;m together. The answer is no. it is not neecssary. Sec Figu re 2-3 . Look m the foll owin g vari ation of the same program:

LOAA '$25 ADDA '$34

; load one operand into A (Az2 5H) ; a dd t he second operand 34H to A

Annthcr vari ati on

LOllB '$25 ADDS ' $34

ゥウセ@

;l oad one operand into B (S=25H) ; a dd t he second operand 34H to S

In the above cases, whil e one rcg isteJ contained one value, the SCi:ond value followed the instruction as an operand. This is called an imm('di01e operand. See t' igure 2-3 . The exanlp lcs sho wn so far for th e ADD instructi on indi cate Ihat the source operand can be either a relli ster or immed iate data. but the destina tion must always be register A Of B (the accwnuJakm;). In othe r words, an ins truction such 3.'; "ADD 1$25, '$34" is inV'.llid since an accumulator. register A or B. must be in volved in any 8-bil arithmetk operat ion. There are several 16-bit registers in the HCS Q R セ@ PC (program counter). D. X. y , and SP (stack pointer). The impOl"lance and usc of the program counteJ are covered in Sec tion 2.2. The X and Y registers are used in ac cessing data using index add ress ing mode, which is discussed in Scrtion 2.3. Th e use of the stack poinleJ is discussed in Section 2.8.

Review Questions t. Wri te the instructions to m ove value 34H into register A and value 3FH into register Il. then add them together.

CHAPTER Rセ@

IICS I2A RCnITECflJRE&A.W...\ffiLYI.ANCUACE PROCIU..\IMIN(;

63

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

2. Write the inslruclions to add toc values 16H and CDH. r lacc the re sult in reg ister A. ウ@ A and B. 3. Troc or false. No value can be moved dirced y int o イ」ァ ゥセエ」イ 4 . What is the largest hex value that can be moved into an 8-bil register? What is

the 、」ゥュ

セャ@

C 65535 (FFFFH )

In the fi rst two add ress ing modes. the operand s arc eit he r in side one of the CH .... PT E R 2: IICS I2ARCnITECflJRE&A.W...\ffiLY IANCUACE PROCIU.\IMIN(;

71

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

registers or tagged along with tho: instruction itoclf. In most programs, tho: data to be proccssoo is often in SOIT\(' memory location of RAM. There arc many ways to access this data. Next we describe these diffe rent methods.

Extended address ing mode In extended address ing mode, the dala is in a RAM mem ory loca tion whose address is know n, an d th is address is given as u par1 o f the inslrlK.1ion. Con trust this w ith immediate addressing mode, in wh ich the openm{] ゥエセ」 ャ ヲ@ is provided with the instruction. The "if' sign distinguishes between the IWO modes. See the ・セオューャウ@ belo w,;tOO note the オ「ウセBiャ」・@ of the " II " sign.

; load A teom RAM location eOOH ;load B from RAM l ocation 80 lH

LDM $800 1DAB S801

The above examples should «,inforce the importance of the "If' sign in HCS 12 ;ru;lruct iolls. See the following code.

LOAA 1 $25 ; load f25 into A (A- 25H) LOM $SOl ; load RAM location SOlH ; J.nto A

(A - 99)

/\ ddress

Dilm

"Xl

STAA Instruction The STAA instroetion tell s the CPU to move (in reality, copy) the source, register A, to a destination in the RAM . Aftcr this instruelion is exccmcrl, Ihe localion poinling 10 Ihe regisler or RAM will have the same value as register A. The STAA stores the contents of A into any location in the RAM region using cxtendcrl 。、イ・ウNセ ゥョ ァ@ ll"IOde. The followin g progmm will put 99H into locu tions 800--804 of the RAM region:

LOAA 1$99 ;A = 99H STAA $600 [ ウエッセ・@ (copy) A contents to location SOOh STAA $601 ; stor e (copy) A contents to location SOlh STAA S 802 STAA $603 STAA $604 The foll owing program ""i ll a) first put value 33 1-1 into RAM location s 1200. 1201. and 1202. b) then add them to accumulator A. and c) storr the result in RMI location 1204:

LOM S TAA STAA STAA

Address 12UO 120 1 1202 1203 12lJ.1

Data

33 JJ JJ

"99

'$33 ; A - 33H $1200;move(copy) A contents to location 1200H $120l ; move(copy) A contents to location 1201H $1202;move(copy) A contents to location 1202H ;clear イ・ァゥウエセ@ A (A- DO) eLRA

12

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

33H) ADoA $12 0 0;add A and ICC 1200H, result in A (A ADOI;. S12 01 ;add A and ICC 1201H, result in A (A 66H) ADOA $12 0 2;add A and ICC 1202H, result in A (A 99H) S'rAA $12 04 ; store A into RAM location 1204H E:a:ample 2-3

State the COlllenlS o f RAM locations after the folJ(lWing program : tS9 9 セ@ c

STAll. cセ@ Lセ@

S812 H8 S

; l oad ; 10 .. d

セXQS@ cセ@

tS3F Lセ@

5814

tS63 STAll. $815 cセa@ ts 12 S T All. 5816 c

セ@

; l oad

,

with va l ue

• wi th • wi t h

valu: m.mber for ASCII ' 9 ' LOM . ' 1 ' ;1>. - 3 1H. 31 h ex is f or ASC II ' I ' LOAB . · Z · ; B - SAH, whic h is hex m.llTl)er for letter Z To define ASCII slri ngs (more than onc character), \\"e use the OC (define runs tant) di rective. We wi ll look at DC usage in fu mre ehaplcrs.

Assem bler directives While instructions tell the CPU what to do, directives (also calico P.leuJ{J· irrstrucliorrs) give directions to the 。 セウ」ュ「 ャ ・イN@ For example, the L DAA llnd ADDA instruction s arc comma nd s to the C PU , but EQU, ORG, and H.'D are direCd by th e fo llow ing diltttives: (a) ASC _DATA EQU ' 4 ' (b) HY_DATA BQU '1;0001 1111 4. Give the value ill register A for the following: MYO)UNT

EQU

15

LOAA fM YCOtrNT

5. Gi ve the value in RAM location 22011 for Ihe fo ll owing: MYOOUNT EQD $ 95

MYREG LDAA

EQD $220 *MYCOUNT

STM

MYREG

SECTION 2.6: INTRODUCTION TO HCS12 ASSEMBLY LANGUAGE In Ihis seclioo we discuss Assembly language fOO11at 3nu define some widely u SC(! tcnninology 。 セ^ッ」ゥZャA、@ with Assem bl y I:mguagc programmi ng. While tho cru can work ooly in binary, it can do so at a very high speed. II is quite tedi ou s ami s low for humuns, however. 10 de ul wilh Os ami Is in order 10 program the computcr. A program that con sists of Os and Is is ca ll cd machine language, In the earl y day s of the computer, progrumm(:rs coded programs ill mac hine language. Although the hexadecima l system was used セウ 。@ more e fficien t way to represent b iru ry numbers, the process of world ng in Jf\:Jchine code was Sl ill cumbersome for humans. evセ Biャエオケ L@ Assembly lunguuges were 、・カ」ャッ jャMBサセ@ which provided ュョセGiャッ ゥ 」ウ@ for the machine oodI: instructions, plus other frutures that made program ming faster and less pron e 10 error. The teon mnemonic is frequently used NGHZイゥ ョァ@ liH:ratu re 10 re fl'- to codes amI abbrev iation s in computer science und 」ョァゥセ that are rdati ve ly cas)' to rem em be r. Assembly la nguage pmgram5 must be translated into machine code by a prog rnm called an UliSemblcr. Assembl y language is referred to as a iOI'l'-lcl'ellangooge because il deals direc tly with the internal structure o f Ihe CPU. To progrnm in Assl:lIlbly language, the pm grnnuner must know all the rClolistclb of the CPU and the size of each. as well as other detai ls. Today, one C:Ul use many di fTl,-e m pmgranulling languuges , such as BASIC, C. C++. Java. and numerous others. These l:Ulguages are ca lled high -/ew l QPイァ オ。 ァセ@ because the programmer does not have 10 be conc erned lI'ilh the internal details o f lbe CP U. Whereas an assembler is used to tnulslate an Assembly lan guage prognlm into machine code (so metimes al so called Obj/XI code or opcode for operation code). hi gh-level languages are trans lated into machi ne code by a program called a compiler. For instance. 10 write a pmgram in C, one must use a C com piler to translate the program imo machine language. Next we look at J-ICS 12 Assemb ly lan guage fOllna!.

Structure of Assembly language An Asse mbly language program consists of, among other things, a series

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

of lincs of Assembly Janguago: mbly language ins truction ッョ セ ゥ sャウ@ of a mnemoni c, ッーエ ゥョセ ャQ ケ@ fo11o\\'oo by onc or IWO operands.. The operands arc the data items being man ipu l3lcd, and the mnemonics arc the commands to rhe CPU, tc ll in g it wha t to do with those item s.

An Assembly lnnguagc pmgmm (sec Figure 2· SI) is Hscries o(StatemenTS, or lin es, which arc either Asoc mbly language instru ctions such as ADDA and lDAA, or stmemcnts cnllcrl directives. \Vh ilc instmction. te ll the CPU wha t 10 o cali ed

ーNセ・

B ッNゥョウイ

イッ

」ャッョDI@

give

、 ゥイ」エ

ゥッョ

セ@

to the assem bler. F()f

example. in Figure 2·9 while the LDAA and ADDA instructions arc commands to the CPU, ORG ami END arc direc tives 10 [he assemb ler. The O RG d irective tel ls the a ssembler 10 place the opcodc at memory location 0 whi le END indicates the end orllle f;(JU Tce code to the 1ls,'ICJ11blcT. In other worlis , ooe (]irec live is for Ihe Sian of the program ami the OIher for tho en d of rn e program.

ORG $ 800 0 LDAA f$25 ADDA 1 $12

; start (or i gin) at loca t i on 8000H ; load 25H into A (A:25H) ; add to A va l ue lZH ; now A _ A + 12H - 2 5H+12H- J / H) ADOA II< to _ A va l ue 1< ; add A A • 1< ; now )7H+OEH-45H ) AOOA HOOlOIOOO ; add to A va lue 28H (IOIOOO b in ) ;now A '" A + 26H s 45H+28H-6DH) HERE JMP eE'" ; stay io t his l oop END ; end of as m s ou rce f ile

-

I'Igu re 2-9.

sセ

ュャ^ゥ・@

uf MO Assr m bl y l

。 ャ ァ オ。

セ・@

Pr"l:fllm

An Assem bly language instruclion consisls offour field s:

( label]

mnemon i c

[ opecands]

( ; comment]

Brackets ind ic ate Ihat a field is opti ena l and not all lines have [hem. I1rackelS shoul d nol be typed in. Regarding Ihe abo ve form at . the followin g [loinls should be nOled: I. T he label field allows the progra m to n.fn to a li"e of セッ、・@ by name. n'e lalxl fi eld cannot exceed a emain number o f ehar1l(tcrs. Check your assembler for th e rule. 2. The Aswmb ly language mnemonic (instruction) and op::rand(s) fields together perform the re al work o f the program and accomplis h the tasks for which the program was wrillCn. In Assembly langu age statem ents such as LDAA ts55 ADDA ts61

A DDA and LD AA arc the mne monics that produce opcodcs; the ''$55'' and "Sf; T arc the operands. Inste ad of a "mem o" i, and an operand. tllese two fiel ds could contain assemb ler p>eooo- in slruetiolls. or 、ゥセ」エ ゥ カ・ウN@ Reme mber

CH .... PTER 2: IICS I2A RCnITECflJRE & A.W ...'ffiLY IANCUAC E PROCIU..\lMIN(;

If7

Page: xiv



__

----------------------------------------------------------------_. . -----------------------------------------------------------------_._-_. Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

                         

that directi ves do nO( generate any machine co de (opcooe) and arc u sed only by the assemb ler. as oppo >ed to instruction s thm are tran sl81cd inlo machine code (opcode) for the CPU to execute. In Fi gure 2-9 tho: ORG (origin) and END (Xlmmands arc examples o f directives. More of lhcsc pscudo-inSlroctions arc discu s >ed in future chaptCTS.

3. The comment (k id begins with a semico lon comment indicator ";", Commnll s may be at the end () f a lin e or on a li ne by themse lves_ Th e セ AiscャQ「 ャ 」 イ@ ign ores ッ ュャtHGョエ セ@ hu l they arc indi sf'C11sab1c 10 prog rammers_ A llhough oom mcn lS arc opti onal, they SIHlUld be used lo dcscribc the program in a way that makes il e as ier for somoone 01>(' to read and understand. 4 . NOlicc the laocl " HeRB" in the label lido in Fig ure 2-9. In the 1MP the HCS I 2 is loki to Sl:J y in this loop indefi nitely. I f you r sysk'm has a monitor program you do nOl need Ih is lin e and il should be de leted from your program . In s・セ Q ゥoャ@ 2. 7 we wi ll St:e ho w 10 (.Teule u read y-Io-nlll program.

Review Questions I. What is the purpose of pse udo- instruc(ions"i 2. ]Z[Mセ ]ZNセ エ イョNs ャ 。H・、@ by the assemble r into mach ille code. whereas are no l. 3. True or false. Asse mbly language is a high-le l'e llanguage. 4. Which of the following ゥ ョ ウエ イオ 」 ャゥ ッョセ@ produces opcode'! Lil;t a ll that do. (a)LDAA #$25 (b)ADDA #12 (c) ORG $2000 (d) JM P HERE 5. Pseudo- instructions are .11 00 called .. 6. True or false. Assemb ler directives are 110\ used by (he CPU itself. They are simp ly a guide 10 the aS5embk r. 7. In Question 4. which ins h.lcl ion is an asse mbler direc ti ve'!



--:=-=:-:::::::,

SECTION 2.7: ASSEMBLING AND LINKING AN HCS12 PROGRAM Now that the basic form o f an Assembly h nguage p rogram has been gi\'cn , Ihc nex t qu cs.rion ゥ ウ セ@ How il is crealoo, assemb loo, and made read y 10 run? The steps 10 e reate an exeClIL1b1c As.'lCmhly language program (sec Fi gure 2- 10) arc 。 セ@ follows: I. First we u se II エ」セャ@ edilor to t,'Jle in a progmm simil ar 10 Figure 2- 11. In the ca I is fed to converts the inst ructions into machine the HCSI2 assem bler. The 。Nセウ・ュ「ャイ@ code. The assembk r will produce nIl objt:(;t file. Th e l'X lemion for Ihe object

file is "0" . The exlcnsion for lhe list file, which contains nny syn tax errors and their lin e numbers. is "1st" . The lSi fi le cun be viewed " 'il h uny text cdilor.

3. ASSl:mblers n:q uire a lhird SICP t:llh:d linting. The link progmm lakes OIlCor lllore object file s and produces a hex file and map. The hex file has thc exlcnsimi "s I9". Aner a successful li nk, the hex file is ready 10 be bumc-u im o Ihe HCS1:t 5 progrum ROM or downlouded miD !he HC 51:! t イオゥョセᄋュ N@ See C hupl c..g for more details.

Many of lhe Windows-based ID E as>e mblers combine steps 2 rul d 3 into one step after the program has been typed.

More about asm and object files The asm fi l.: is also called the .soun::e fi le and must have tilt "asm" extension. As mentionoo earlier, thi s file can be e1"C3ted II'ith a text editor sudl as Windows Notepad. Many assemb k rs 」ッュセ@ with a エ セクエ@ editor. Th c assembler converts the asm file 's Assembly language instruction s into machine language and provides the 0 (object) file. The HCS12 as>o:mblcr produces the objcct and 1st filcs. Thc object file. as mentioned earlier, has an "0" as its eX lCnsion. In modular proCllAPTER 2: IICS12ARCIIITECTURE&AS%!\ffiLYLANGUAGEPROGRA..\L\1ING

H9

Page: 89

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

;HCS I 2 aセX

later"

Lセ@

'"'

Lセ@

セ m「

ャ ケ@ l

;. Lセ@

5210

'"'

,-

Lセ@

no t '00011100

'oc

0

;A

210H

Lセ@

''"

0

A

0

; salle the SIJ!i in ,"0 21 011 l atay here forever ; end ot " ",. Bッオイ」 f ile セ@

Lセ@

""

'"

Da t a .

" """''"' '" 'e, ,., " = • •• '" '"

t 511

セm@

セL@

,,_

address aoooll - 25" (A- 59") ;"dcu ss how 10 perfo rm 3 loop ing oclion in HCS I 2

and then cNplai n the bronch Uump) inSlructioos. bOlh conditional and unoondi lionセl@

Loo ping in HCS12 Repeating a sequence of instruction s or an opl--ru tion II. ct-rulin number of limes is called a loop . Th e loop is one of mos! widely used programmi ng techniques. In lhe H CS I 2. there are seve!".!.i ways 10 [c peat an opcmt ion JIlUll Y tim es.

One way is to Icpcal the operation ove r ami ovcr Wlti J it is finished. as shO WIl below:

,, , ; acto. value , value , "

c eM .oM AOM AOM wセ@

Co A Co A lA Co A lA A lA co A lA

i Ml loop l i[.5op. 11 SOl'S on li1oP >oP >oP >oP

mp OOP

mp >oP >oP >oP

mp

OOP "'C

'"

MYREG

AGAI N

Suln tion : The CPU (ins truction) cycle lime - 112 r.Ul z - 0.5 1'5. The lime delay inside Ihe AGAIN

loop is (200 " 19) x 0.5 lis - 1.900 lIS. The a bove delay was ve rified using bo th CodeWarrior and o>cilloS(ope.

SECTION 3.3: PROGRAMS USING INDEXED ADDRESSING MODE In thi s section we prov ide some

・ セ オ ューャ

」ウ@

of using

ゥ ョ、

」セ・、@

address ing

moUe .

Clearing RAM buffer The fo llowing shows how to cl ear RAM Jo,;;atiOllS using indexed addressing mode: LOX IS80 0

;I oa d SOO K in to X

eLRA

;A -

,ru 0.' 0.'

; clear RAM loc 800+0

Lセ@

Lセ@

Lセ@

'"' ,ru

O. ,

STAA O,X

'"

O

;i ncr!)l'tlen t

X

(X=801)

;cllOar RAM 10; HI'1'

セL@

G^i

..

.0;;"'" " IOCi>fl'l • IOClr1'l 1

lIAWRlt,PI\5 lAWRIU'Ilt セ B セ w

|iocゥtnヲエ a orN

iI

ip





HLI@

ji@ i セ@

mGpVセ@

'!I{lII1.(l. " "P61

'llCIII1L ","V.. l セi[jrwャNGpVS@

1IOOftMMro1

tャuZA

IGH

i@

t セ@

G aセ@

N Mセ@



"" ,., "" "

IOCI>I'IG

iLヲ

U llII; AMll

::J '>OI/1""' 1 Zj

GセajエI\@



IttliPT2 locBpGセ@

セG a iQ

Bt ::J • N^ャIoiZッュe ::J "'Di ll""'.

IlAWInl Fr'L'Cscal r)

CHAPTER 4: IICS12f9S12 110 PORT PROG R "lMMING

I3S

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x. com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

MOSl WWM Qi セャGエ_ip|@

PA[Hl7IANOlIE TRIG(I

mwiIGセfヲoOイオ@

セ@

l セ@

OCOlPTO

PAOWAN05 PAOO4JANOI PAoo:.JJANOl

J.'K11P1l IJCO'P12 OCllPlJ

MC9S12D-Famil)' IXWU C 11

80 ()FI'

IX6IPT6

1J

"00' MIIfIOOO 1MY1TAI'

H

/I'OIX;iiAGiiiHKGU

IS

paAャioセQw

taQT@ paUiセoャjILN

a@t

ADORMlI'.TAOIPIiO

16

AOORl,w.,rAl lP81 AIlQIl?!lu,rMfI'8l IlQRMII.,T7I IIPBJ lIOOR4JtIfIT

cセ@

'$55

; Ilake por t ;1>. -

ヲゥセG@

;put



セ@

U

oセ@

Lセ@

:1>. '"

OCU,

'" "AA "AA '" CM'

E'ORTB

;A _

""

'" '"

=

B

an output

",tt

port B pins

AA' :put M' on port B pins

r

セオL@

'M

U

It must be noted Ih:.l1 un less we ucl ivuh: the DDR bit (set i, to I), the data will not go from Ihe port register to the pins o f the HCSI2. This means that if we remove name i I the fi n;t two lin es oftbe above code. the 55 H and AAH Upon reset configured as i values wi lloo t show up on the pi ns. The), will he s itting in the SFR of Port B inside the CPU. Another VCJsioll of the previous program using the MOVB instruction is as fol lows: 'SFF,DORB IS55, P()RTB セカ・@ セカL@

U

'" セカL@

'" 'M

;_k,. Port B an outpu t por t ; put 55H on port B ーゥョセ@

OCU,

'SM, P()RTB ocu,

: put MH on port B pins

U

It must be noted that 55H (010 10 101) whl'fl complemcoted Ix.'colIlt.'s AAH (1 0 10 1010). Appendix C !ilIOW S c urrent drivi ng capability for I/O pin logic levels. NOle!hat upon reset, all ports have value 001-1 in their DDRx reg islers. This means all ports arc con figured as input s. See uampJe 4- J.

DDR register role in inputting data To make a port an inpul port. we must first put Os into the DDRx register for that port. and then bring in (read) the data pre>ent at the pi ns. The code in part (b) of Exarnpk 4-1 will get data present at the pins of port H and send it to pun B indefin itely. after add ing the value 5 to il:

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Eump le 4 - 1

Write and l(l st 3 program 10 3} toggle al i lh" bi ts of PORTA and PORTE and b} get a b)1e of data from PHI and send it to PORTIl. SoIUllon:

'1

""

eo" eo"

c"'

$ 1101

S1108

,ssn

Lセ@

"IT

Lセ@

oセ@

cセ@

C,

; set

OOAA

cセL@

ts55

STAll S TAll

イッセL@

,,-;' =

st .. ck pointer

;>:Jake ; >:Ja k e

;,

;pu t

PORTS OCU,

'" oセ@

FF

port port 55h

",

, ,

."."

output ".,,, out put ".,,,

on port

A

pins

; COOlple"u;mt rElq A U

'M

;-----------DELAy D8LAY PSHA

1200 」セL@ Lセ@

" "

セ@ c

Lセ@

00 ' 00' 00'

"t25 0 "

,,'C " '"' ,,'C t"l

'"' PULA "

""

b)

'''" cセL@

U llllllll

S TAA

oセ@

」セL@

nOOOO OOOO Lセ@

oセ@ cセ@

m A DDA

S'I'AA

'M

" イッセL@

U

;/\ - lll lllli (bin a ry) ;Port B an output port (1 for Ou t) ;A _ 00000000 (I.>''''''y) ;Port H iOn inpu t port ( 0 for input ) ; J:l()V& da ta fro'" PTH pins to ceq A

; add some lIalue to it [ セョ\ャ@

i t to Port B ;continue foreve r

Anomer versio n o f the progl1.l.l11 is as follow s:

,... outpu t , - . input port

OOV, OOV>

HIT, OURS tOO, DDRH

;1Mke Port ;_ke Port



m

;IIOV," d .. t .. fro m PTH p in ... Co ;add " .. 1 \.1 .. Co : send CO セイエ@ ; continue forever

C,

セ@

ADDA Lセ@ Lセ@

"

l'ORTB U

'0_

"

".,,, r .. g

A

,"

CHAPT ER 4: HCS12t9S12 ItO PORT PROGR"lMMING

139

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Again, it must be nDled that WlIerial communiculion. We will show how to use these ahemuh.. fu nctions in fu 1ure clmp-

,=

Analog-to-digital converter pins HCSI2 ch ips can huve one or tWO ァM」 ィ セ ョ ・ ャ@ AOC mod ules. In the SO-pin (QFP) HCS 12 chip. we have one module. and the 8 Ch;UUleiS are designated:l.'; the PADOO- I'AD07 pins. The I 22-pin LQF P chip has two modu les of ADCs and the pins arc des igllllwd as PADOO-PAD07 and f'AD IO-I'AD 17. SL'e Fif,'IIres 4- 1 and 42. We wi ll study ADC in Chapler 13. NOle that we can usc: the ADC pills for 1/0 OIXIU by the AOC. The only diflercnce is that they do 1I0t have DDK rctistl:Js.

Review Questions I. True or false. All of the lieS] 2 pons have 8 pins.



2. Which pad:agc type gives us more IXlns1 J . tョNエ セ@ or false. I'ORTK docs exist in the SO-pin HCSI 2 ch ip.



4 . Code a セ ゥューォ@ progmm 10 send 9911 to 1'0.1 A. 5. To make Port Il an output port, we must place _ _ _ in registcr _ _セ@

 

SECTION 4,2: 1/0 BIT MANIPULATION PROGRAMMING



In th is >OCtion we ヲオ ョ ィ・イセ。ュ ゥョ」@ the HCS 12 1/0 in stmctions. We pay specia l atten tion to 1/0 bit manipulat ion because it is a powerful and widel y used fea· ture of tile HCS I2 fami ly.



110 ports and bit-addressability



So met imes we necU 10 acce ss only I or 2 bits of the pon illslead of the en tire 8 bits. A powerful fc:J ture of HCS l2 110 ー ッ イエセ@ is their cupabili ty 10 ucceS/; individ ua l bits of the pon WitllOut altering the resl of the bits in that port. For all

  

142

www.fut ureerc.com

Page: 1

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

HCS I2 pons, 11.'0 can 。」ウMセ@

www.fut ureerc.com

either .111 & bi ts or any group of bits Wi lh olH altering

the rest. Tnble 4-51i5ts The bit-oriented inSl rucrions (on he HCS12. Although the inslruClioos in Table 4-5 can be used for any RAM localion, I/O port opcrati oos use them most oOen. We wi ll see the use o f these insrruclions through ou t fut ure clmptclb. Tahl e 4-5: Bl r-OrlenlM In st ructi ons for lies 12

Next we describe all these instructions and exam in e the ir usage.

BSET (bit set) To sct HIGH C(TtaUt bits of a g iven locat ion, we use .he syntax "BSET mas k-byte " where mcm_101' is any loemion in the RA M (or register) and mask_ by!C has the desired bi t number as 1. A Ithough the bh -oricntcd

mem_lcc,

in stru Cl ions c:m be used for m:mipulation of bits DO--D7 of any RA M loc ation .

they arc mOsl ly used for I/O pClli s in Clllbt:ddcd systems. For exam ple, "BSE'! toRTB, %00 100000" sets HIG H bit 5 of Port B. We can use Ihis instruction 10 set HIG H more th an on e bi!. For example, ''ESET PORTS, %00000 01 1" !ids HIGH bils DO and 0 1 o f Port 13 See Example 4-2 EUllIp le 4-2 An LED is eonncetcd t(l cach pin of P(lrt B. Write a pr(lgram t(l turn (In each LED fr(lm

pin DO to pin 0 7. Ca ll a delay m(ldu le be fore ruming on the next LED. Solu tion : L DAA

tS IT

;A

S TAA

DORB

; .,.. l. count .. r [セGャ@

t S840

EB

C5 58

Address

2)

=

"''" 7D

840 841 842 843

H_ Byte

H_ Byte

ADDA

セ オョッ@

of

Address

:branch I f C " 0 : lnere ..",nt (now H_ Byte " 0) IA 1D + Ell セ@ 688 and C - 1

ADDA

ADDA

RAM location 60"' to L_byt "

.... r

=

A (A

0)

; " _ Byt " " 0 [セ ・エ@ th e point e r ; "dd byte ; bypa ss if C- O ; .. dd on .. ' 0< Coury i t .... ; OOC =unter

; "," x t

;do '0< ; store

,n

",

the bytes result

CIV\P'I'ER 5: ARIT IIMET IC, LOG IC INSTRUCTIONS, AND I'ROGRAMS

153

Page: 153

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

For exampl.:. [001; at the addition of SJCE7 + $3138D. as shol\"n next.

,

3C £ 7



"----'D JB 74

When Ihe first byte is added. there is a carry (E7 + 8D - 74, CY - I). The caft)' is propagmcd 10 the higbcr byH\ which results in 3C +) D + I - 78 (a ll in ィセIN@ Exa mple 5-3 shows the above steps in a HCS12 program. We can also usc HCSI2 suppons the 16-bit the 16-bit add instruction 10 do the sarno: th ing ウゥョセ@ arithmetic opermions e セ ャi イョ

ャG{c@

5-)

Write a prognun to add IWO 16-bi t numbers. The nwnbers are S3CE7 and $3 138D. Assume lilat RAM [ocalion 807 - (80) and local ion 806 - (3D). I'lace [he sum in RAM locations SOli a nd 809; loo; ation 809 should have die [ower byte.

D","

3CE7 + 3138D

c---

7fH4

""

Solu tion : Lセ@

'00' '"AA

..,m,,, Lセ@

セャッ。、@

'$.&7 $601 $609

the low byte nOW'

,i'! -

E1

• 80 -

ML セ@ セ

me

;load the high by t e

$8 06 $808

;A

=

ョ、@

Ii'! CY -

$E7)

IA -

1

SJC)

A • RAM_ I oe ... ,,;oI: CY,

.. dd1n9 th .. UppIS

ISS

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

the upper d igi t (OOl1 + 60 H - 139 H) 10 ensure thaI the res-ul! is BCD (52 + 87 -

139). This prob lem is so pervasive that most mi croprocessors such

。セ@

the HCS I2

have an in struction 10 deal with it The II CS I2 instruc tion ··DAA'· is designed to oorrccl lhc DCD addition problem. This is di>cus..:d next

DAA ins tr uc tio n The DAA (dcciJl1:J I adjuSt uccu mu l:llor) instruction in the HCS 12 is provided 10 COITt(.1 the ufOTl:mcnl ionoo problem Ilssocimed with BCD lIddition. The mnemonic " DM" works only with an operand in the A register. The DAA inSlructioo will add 6 to the 10\\, Value D > Value

c-,

www.fut ureerc.com

Z - l

A< B A < Value B < ValklC D < Value

A-B A B D

Value Valu e Va lue

Exampl e 5. 20 Wri lc code 10 dClC1ll1inc i f data on PORTE contains the value 99H_ If SO, write len er -Y' 10 PORTA; olhCtWisc, make PORTA - "N'. SoIU llon:

Lセ@

DDRB,Ul 1l111 1 ; PO RTH = input DDRA,Ul llll ll ; l'ORTA '" output t ' N' : A = ' N' IASCII) ; roRTfI - • N' E'ORTPl

BC LR BS E T セ@ c

BAC K

」セL@

1$99

;/\ -

0> Va l ue )

(lV!'.:R

Using BHI and BlO instructions for unsigned numbers All hough BCS (tw.l.Ilc h if carry set) and BCC (branch if c any clear) chtx:k the ca rry flag and can be usa! after a co mp are instruc tion. it is rtx:o lluuendal thal I1IU (branch if higher) and OLO (branch if lower) be used for two reasons. One reason is that many assemb lers will assemble BCC as 111-11. and OCS as OLO. which may be confusing to beginning programmers. Another reason is th at "branch if higher"" and "branch if IO Il'er" are easier to understand IInll) "branch if immed iately apparaH that carry is set"" and "branch if carry clear. " since it is ュ ッセ@ one number is larger than another. than whether a carry would be generated if the two numbers were subtracted. The OLO an d 111-11 instlUct ions are lI'ide ly used in comparison of unsigne d numbers. See Examp le 5·22. CHAPTER 5: ARITHMETI C, LOGIC lNSTRUCTIONS, AND PROGRA:'>I S

169

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Enm pl e 5-12

Assume 1hul 1'011 B is an input pOl1 con ncl-1ed 10 u pressure Sl.'I1SOJ. Wri te a progrum to read the sensor value and h:sl it for the value 75. ,\ccording 10 the lest results, place the vlllue into the locations illdicmed by IIl e fo llowing.

then A = 75

If P =75 If f» 75 If 1' < 75

then GREG

=P

then LREG = P

Solu tioll;

c."

"'" =, ""

OR"

$ 92 0

$92 1 ; PORTB _

DDRB, '\. 111111 11

m

Lセ@

;A

oPA

PORTB

: comp ar e

"ro

EXI T

;branch ;not セ GQオ。

'W ,m

LOWER



セGョ@

セ@



U,"

.., .

;sav e セL@

m,

GBセ@

" ""

...

; S ,"V"

inpu t

dci_l

" ",equal '" " , (C -

PORTB with

",

B・@

EXI T

'M LOWE R

; セB

=

l it must

セ@

10",,, r

g can the b its in a byte. eZャij

ーャ セ@

5-27

Write a program to bring in a b ),1C of data seria lly (on e bit at a time) via pin PB7 and save it in RAM location $82 1. The byte comes in with the LSD first. Solution: counter R(:OtJIfT 'W $820

,,' ,,'

Lセ@

I1YREG

$821

D008, \ 10000000 =, ""

,m .

; RlI..."I

AGAIN

ROOUNT

PORTB,\ l OOOOOOO,N EXT

Gセ@

, ., , '"

: branch H

; rotate dqht .,1 th carry to NLセ@

'AA

OVER

,'" ,,,

.. c a rry [ッエセイキゥウ@

・ッセ@

OVU

..

l-alI S

179

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

SECTION 5.5: BCD AND ASCII CONVERSION In Ihis section we provide some rcaJ-worlrl examples of how 10 usc arith-

metic and logic instrucTions. We wil l covcr their applications in real-world devices in future ChuptCfS. For exumpie. muny neWL,. mii..'TOCOnIWlicTs have ureal-lime clock (RTC), where the li me and dme arc kepi even when the power is off. These microcootrollers provide the time und date in BCD. To displuy them. however, we must convt.'I1 BCD volues 10 ASCII. Next , we show the upplicu tion of logic nnll

roln te instructions in the convCfsion of BCD and ASCII.

ASCII numbers On ASC II keyboards, when the key "0" is activated. "011 0000" (30H) is provided to the comp uter. Sim ilarly, 31 H (0 11 000 1) is prov ided for key " I ", and so on, as shown in Ta ble 5-8. It m ust be noted thaI BCD numbers are uni versal although ASC II is slan dard in Ihe Unit ed States (and many othe r ,ountries). Because the keyboard, printers, and monito rs aJl use ASC II, how is data converted from ASCII to BCD, and vi,e カセイウ。_@ Tht!se are the subje"s coverc'd next.

Tabk 5-8: ASC II セョ

、@

BC I) Codes ror Digits 0- 9

Pac ked BCD to ASCII convers io n In many systems we have whu t is culled a real-lime clock (RTC). The RTC provides the lim e of day (hour, minute, second) セ ョ 、@ the date (year, month, 、セケI@ conti nuously, regardless o f whether the power is 011 or off (see Chapter 16). Thi s data, oo,,'ever. is PJovided in packed BCD. For this datu to be displa yed on n device such as lin LCD, or to be prinh:d by the printer, it muSl be in ASC ll fOO11 at. To convert IXlcked BCD to ASCII, you muSl first convert it to unlXlcked BCD. Then the unpllCked BCD is tugged with 0 11 0000 (30H). The foll ow ing demonstrates conw ni ng packed BCD 10 ASCII. SL"t: also Example 5-30.

'"

JI...k .. d SCD

t1np" .. k .. d IlCD

ASCII

29H 0010 100 1

$02 ,509 0000 0010 0000 1001

$32 $39 00 11 0010 00 11 100 1

$32 $39

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Eumpl e 5-30 aウNセ オュ \Z@ that register A has pocked BCD. Write a program to COIl"c n packed BCD to two ASC II numbe rs and place Them in RAM ャ ッ」。エゥ BL セ@ SM6 and SIW7.

SoI Ullon: BCD_VAL HJ'SC

' _Me Lセ@

c" no

"" ""

I set aside I set aside

$806 S807

"-

t OCD VAL

tsor

AI-lDA

[エョ。セォ@

L _ASo:clion.

concept of signed numbers in computers 」 クセューャ

In eVI.-ryd:J y life, num bers オイ セ@ used [hut could be puo;ili ve or negllti ve. For a tempera ture of 5 IS

INS

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

From the above examp les. we conclude that in any signed number addition, V indi cates whether the fC8Ult is va lid or nOl . If V - " th e resu lt iSCrroneollS: if V - O. the result is valid. We can Siale emphatically lhal in unsigned mun bcr add ition, we must monitor the SlalU S of C (carry fl ag), and in signed munbcr addition,

the V (overflow) fla g mu.! Ix: monitorcrl. In the HCS12, instructions such as Bee

and Res allo\\' the program to branch right after the addition of unsi gned numbers, セウ@ we ,.1 W in Section 5. 1. The re セイ」@ also the Bve (branch if V is clear) an d the BVS (branch i f V i s SCI)

'l"a ble 5-9: II CS I2 Br .. nch Instr ucti ons Use d for Sig ned N umbers

two bnmch instrudions for the

ゥ BAGゥ G セ N セ Gゥ ャ ゥB セB [ェャセ 8VS

Bra nch if V set

Branch if V

aゥBセ B セ ゥB ェャセ@

1

N fl ag (ncgutive), BM I (brunch

BVC

Brunch if V clear

Branch if V

0

al low us 10 correct the signed numDcr error. instructions for We th e Valse flagImvc thai

8MI BrL

Branch if min ns Branch if plus

Branch if N - I Branch if N - 0

if mi nus) and BPL (branch if plus). See Table 5-9.

Word -si zed (1 6·blt j signed numbers In HCS I 2 a word is 16 bits ill length. Settillg aside theh' S I3 (D IS) for the sign. leaves a tolal of 15 bits (D I4-DO) for the magnitude. Sec Figure 54. Thisgives amllge of - 32,768 to +32,767. If a number is larger than tIti s. it lIUJSt be treat ed as a mui tiworu operand HnU be p rocessed chunk by chlmk the same way as unsignoo numbers.

ID"ID"ID"ID" ID" ID"I '" ID6 I D' I D6 I D' I '" I D3 1D' ID' I DO I $ign

--

mognltude

-

range of sijPloo word ッー セ イ。ョNャウ N@ To セッョカ ・イャ@ a ョ セ ャiB エゥ B@ 10 The followinl,t shows エィセ@ its word operaoo repre.entation, the three sto:ps discussoo in negative byte operands an:

,.d Deci mal

Bi na ry

- 32,768

1000 0000 000 0 0 000 1000 0000 000 0 0001 1000 0000 000 0 001 0

8000 8001 6002

1111 1111 0000 0000 0000

1111 1111 1 110 1111 1111 1111

!Tn:

00 00 000 0 0 000 0000 000 0 000 1 0000 000 0 00 10

0000 0001 0002

0 111 1111 1111 1110 0 111 1111 1111 1111

'm

- )2,767

- 32 , 766

-, -,, H

"

+32,766 +32,761

セ@

ITIT

"IT

Ov erfl ow flag i n 16-b it operat ions

In

II

16-b it opCaJUu:u from DO to D7. Give III I.' result for 68H.

Z? Writ e a progra m thai finu s (he position of the T he data is

>C'J.lUleU

ヲゥ セH@

high in an S-bj! data item.

fmm D7 10 DO. Give tile re,ult for 68H.

SECTION 5.5: I3CD AN D ASCII CONVERSION 28. Write a program l(l convert Ihe following packed BCD nwn be r !oASCII. Place we ASCII codes in data RAM locations starting at 5840. MYocn ROIl

D Bェセ@

29. Writ e a program to convert the fo llowin g ASCII Ilwubers 10 a packed BCD. MYASC_l MYASC 2

EQU EOU

'S ' '1 '

SEC TION 5.6: SIGNED t.'1.Th.IBER CONCEPTS AND ARITIlMETIC OPERATIONS

30. Show holl' The following arc rcpresenlCrl by TOO 。セ^」ュ「ャイ@ (a)_23 (b) +12 (e) _28 (d)+6F in oox (c} - 121': (I) +127 3 1. The memory atklrcsscs in eom pUlcrs are (signcrl , unsigned) num bers. 32. Writc a program for cach of thc following and ind icatc thc status ofthc V fl ag

CHAPTER 5: ARITHMET IC, LOGIC lNSTRUCTIONS, AND PROGRA:'>IS

191

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

      

fer each: (b) (- 123 ) + (_127) (8)(+1 5) + (_12) (d) (_127 ) + {+I 27) (e) (+25H) + (+ 34H) ョ@ the C and V flags and where each one is used. 33. Ex plain the diffe rence 「」Aキセ 34. When is t he V flag misro1 Explain. 35. Which reg ister bolds Ihe V flag? 36. How do you detect Ihe V flag in th e HCS 12'> How do YC ll detect lhe C fi ag? 37. In an S-b i! operand , b il _ _ is usOO for 1he sign bit, whereas in a 16-b it

operand, bit _ _ is used for the sign bit.

ANSWERS TO REVIEW QUESTIONS SECTION 5.1: AR1TH!l.IETlC INSTRUCTION S AND PROORAMS



1. 2.

A. B



J. 4. 5. 6.

No. The oc:conciQPCllOlld ihould Ix in "'gi>lt bltentimlaify lifl blank

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

CHAPTER 6 ADVANCED ADDRESSING MODES, LOOK-UP TABLE, MACROS, AND MODULES OBJECTIVES VIJon com pl etion of this cha ple r, ),ou will he lillie 10;

» » >:>

» » >::.. » »

C od e IICS I2 aウNセ」 ュィャ I G@ lan guage prO);rams using advanced ind cnd 。、イ 」ウNセ ャョァ@ mod es Code IICS I2 illslru ct ions to IUlIllipulllte II look-u p ta bl e ACl'CSS fhed dahl rcshlln g In '.he prog ram RO ;\l space Dist' uss how to \' r CIlil" nlllUOS and lII odul l'S Code IICS I2 programs for ASCII and BCD data cOJ\\-crsion Code HCS I2 PfOI,:ntUl S tu crcalC and Gセsi@ the checksum b)-Il' List the IIlh-alltll l:cs of IIlll cros and modul l'!i in prugra lluuing Understand the conce pts of GLOBAL and EX1'EKNAL in modular

prO!;ralllwiu;

195

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

SECTION 6.1: ADVANCED INDEXED ADDRESSING MODE In previous chaplIn we , howesl-i nc ) Alk,- clearing loe. po inlccl to by X, the X is jl1(;rcmen led by I . CL R 1,+X (pre in c) The X is increml.'Ilh:d by I . then loc. po inted to by X is cleured. CLR 1,X- (poSl-dec) Alk,- cleuring loc. po intoo to by X, the X is dccn:ml'l11t:d b y I. CLR I ,- X H ーイ セM、」I@ ll1c X is dec remenled by I, Ihl:n he. pointoo to by X is cleared. NOll;: This lublc shows Ihe syntax fo r tile X registcr. It also works for dIe Y and SP regエゥ 、」ャッBtiNョQセ GiQ Q@ values CUrl iSlers, but PC u mnOl be used wit h the 1)'

""

,

"'"

"" "'"'

SECTION 6.3: CHECKSUM AND ASCII SUBROUTINES In this seclion we loo k at some wi del y used subrmu in cs such as checksum byte. BC D, an d ASCII conversion.

Checks um byte in ROM To ensure the in1egri1y o f RO M c PQエZャセL@ every ウケsAセ GヲャQ@ muS! perfonn u che.: ksum cakulatiolL The checks wn wi ll delect any corruption of the COIll cnlS of ROM. One cause o f ROM corrup tion is curren t su rge , either wtK.'Il the system is turned 00, or during operatiolL To ensure data inlegrity in ROM, the chcckswn process uses w ha t is called a checksum b)'t"d

1,X+

HNE

Lセ@

,

;A- O

"" m, "' " 'W 'M' " "AA '" t ' G' ' -' L

,

:addi ng bytes in c l uding Ch ec It: livc allows a programmer 10 w rite macr06 and save the lll in a file. ami ャ 。エセイ@ brin!; them imo any program file. For exam ple, as,ume that the macro, from Program 64 were written and tllen ウ。セA@ under the filename GセyjッNacroャ@

,Jo'.AC ".

As,wn ing that Ihese maCfOS are saved on a disk under the filena me ''MYJo'.ACR01,Jo'.AC'', Ihe INC LUDE 、ゥセエカ・@ call be u>ed to bring this file int(l any ".asm" file ruld then Ihe program Crul calJ upml rulY (If the macros as many t imes as needed. When a file indudes all mocr(l S, the ma,;;ros are lista! al the bcgirming (If the ", [sl" file and. as they are expanded, will become part o f the prOgmllL To understand Ihis. sec Pr(lgram 6-5. I Proqram 6-5 : eoq"li"" por t B usi"!1 macros ゥョ」ャオ、

セ@

' MtJo'JlCROl , MlIC '

I'J H

ュ。」イッ

; ---- - -------- -- ------- -- ----p eoge...

BSET

DDRB,Ull ll111

セ@ セエN@

f rol'! ,.acro

ヲゥQ セ@

et s

;Port

B .. " .. n output

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

"'H "'H ,

OVER

DELIIY oセL@

'M

-

www.fut ureerc.com

$55. !'ORTB 20 0 , $10 $AA, l'ORTB 200 ,S10 ()VER

.:tiD

;--------------------end

Of

tile

MLiST directive When view ing the .lSI file with macros. we sec Ih em fully 、 ゥsヲ^j。セ、⦅@ The expansion is SCI by default, and it shows the macro at every locm ion it is 」。 ャQ セ ャN@ Th is is fin e for 1""0 or three itemJion s, bu t wht,, , Ihere arc more, il can beoome cumbersome, Using the Mt. IST OFf' d irective , we can tu m off the display of

mac ros in the list file. Using MLtS T ON wi111um

・セーオョウゥッ@

back on. Com pn c

Figm es 6-1 and 6-2 10 see the diflhl'l1 CC 1x1ween these directi ves. ・ セ」 。 ャB@ He mセ・ BL 「ャ・イ@ (e) Copy"ig ht F CI1olhc fo ll owi ng A SCII c haracters 10 PO RTA, basco on the status oflhc switches :

0000 0001 0010

00 11 OJ 00

'0'I' "'J '4 -

0101 0 110

'j"

0 111

'T

11100 1001 10 10 l Oll

"" " -

'6'

11 00

'8' 'C'

1101

'D'

1110

'ET

I I 11

SECTION 6.3: CHECKSUfl.l AND ASCII SUBROUTI NES 23. Fi nd th e checksu m by te for the fo llowing ASCII message: " Hello" 24. True OJ fa lse. If we add all b)'les. includ ing the cha:k slllll byte. and the result i!; OOH, there is no error in th e data. 25. Wrile a program 10 (a) b'Cllhe dma " Hello , my fel low world c it izen s" from progra m ROM. (b) C'J.lcuJale lhe checbl.llll byte. a nd (e) tes t the checksum b)'1e for any data e rror. (binary, BCD. 26. To di splay dma on LCD or PC monj lOIl>. it mu st be in

ASCII ). 27. Assu me that the lower 4 bits of Pon E are colllccll:d \0 switches. Write a pro gram \0 send the following ASC II ,hara,lers 10 Port A ba!iCd on the status of tile s\\"itches: 0000 0001 0010

00 11 OJOO 0101 Ol IO Ol JJ 1000 1001

'"

'0' 'I'

'"

'J'

>4'

.,'6' 'T

''""

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

28. WrilC a program 1(l oonvcrt a >c ries ofpad:: lo:>

»

セ ィZャ

ーエ・

イ N@

you will be ab .... to:

EnmilK' C d ata typn for the I ICS l 2 C ode C program Ii for lim t' d elay find I/O operati ons C ode C program Ii for 1/0 bit m anipu la tio n C od e C program Ii for lo gic a nd 。 イ ゥ エ ィ ュ・ ャセ@ op erat ion s C ode C program Ii for ASC lI and OC D da ta con n' rsion C od e C program s for bi nary (h ex) 10 Ikcim al convers ion C ode C program Ii for d ata serializa ti on Und er!ilOnd C cllmplle r RAM and RO :'ll all oco lio n

125

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Why program the HCS12 in C? Compilers produce hex files that we download into the ROM orthe m icro controller. T he $ize of the hex fi le produced by the compiler ゥセ@ one of tlle main concerns of m i\:rocollIroUer prQsrammers for two reasons: I . Microo:oll tro ll ers have limit(d on-chi p RO M. 2. T he code space for the HeS 12 is limited Ie S i l K. How do cs the choice of programming language affcet th e compiled pro gram size? Whi le Asse mbl y language produces a hex fi le Ihal is much small er than C. programming in Assembly language is often tedi ous and time consuming. On the other hand, C p rogramming is less time consuming and much easier to write. but the hex file size produced is much larger than if II"C used Assembly language. The fo llowing arc some of the major reasons for I>.TIling pro grams in C in stead of Assembly: I. 2. 3. 4.

II is easier and less lime consuming to write in C than in Assembly. C is easier to modi fy an vo i d "'. $lIel"y(uns i gn e d int I; void "'.... in (void) OORB

DORA

= =

OXFF;

Ilmaite Ports A and B ou tpu t

OXFF:

PQRTB-O > vold .... inl l/o id) ! DD RB -

I/male p ins are used 10 pro vi de supp ly voltagc 10 the I'LL and osc il1alo EXTERNAL par1 of the chip. Th e PLL ulkJws lIS to OSCILLATOR EXTAl havc another source of working frequen- SIGNAL t:)' independent of the t..-ySlul ooc illll lo freq ufl'l • IOClr1'l 1

lIAWR1' J>1I.S lAOORIU'Ilt セBipj@ セw

|iocゥtnヲエ a orN

iI



HLI@

i セ@

mGpVセ@

'!I{lII1.(l. " "P61

'llCIII1L ","V.. l セi[jrwャNGpVS@

1IOOftMMro1

G aセ@

N Mセ@



"" ,., "" "

IOCI>I'IG

IGH

t セ@

U llII; AMll

::J '>OI /1""'1 Zj

GセajエI\@

Gセanョ@

IttliPT2 locBpGセ@

セG aiQLヲtャuZA@

Bt ::J • N^ャIoiZッュe ::J "'Dill""'.

IlAWITl1.lf'S"n'l

0

Fig urt' 8-5. Syslem Clock Gt-lM'nitor in II CS12 (from Freesule)

'"

• •

,

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

BKGD pin and SOM (Background Debugger Mode) In recent years the l'rec!;lCale has equipped the ir CP Us w ith a powerful feature called I3DM (Background IXbugger Mode). I be HDM is a combinatjon of hardware ruld software Iha! allows us to trace a prosrrun onc instruelion at a ti me. Using the 13 DM lI"e can trace a given program and examine the COlllell!S o f the C P U registers and memory after Ihe execution of each iru;aroet ion. Tlti s feature is called backgro",rd debugger mode because it tries 10 use IIl e id le (ulH.Lsed) C P U 'YcJeS a sing le pin called BKGD to cOllullunicale externally with a hOSI system such as an x86 PC. T he ID E so flw arcs such as CodeWarrior

send and m:civc infonnation 10 Ihe HCSI2-based system via this pin seri ally. Many recent gene rations o f tminn boards come: with the: 130M and Loade:r combined ready to bo: conne0 we h.we to buy a separale USB type BOM-PO D (or serial COM pon BOM-POD) to eonncel thc se trainers 10 th e host PC. Prior to Ihe advent ofB DM (or for Ihe proccs>ors lhal 1ackcrl the BOM feature) we had 10 spen d hundreds of do ll ars for :m IC D (in-ci reu it debugger) or an IC E (in...:ireu il cmulmorj lO be llblc to trace thc program 10 fi nd the bug. The BDM is so important in the f イ セウ」。ャ・@ prodUC1s lhm all lheir processors come already BOM enubled for the single-ehip mode. In other modes such as expanded mode we must enab le the BOM oplion.

Downloading the program into HCS12 Gt"ll t,-ul ly there ure thrcc wuys 10 down loud the program in to 11 ch ip. u セゥ ョァ@ a devil;e progl1l111lller (or KO M burner). In this case you must remove Ihe chip from the tarb'Ct syste m and place it in the dcv ice programmer. A Zl F (zero inSt.'I1ion force) socket on both the device programmer and targct system makes thc removal of the chip quicker and less damagin g than with a stan dard sockcL When イ・ュッカゥョセ@ and reinscrtinl,\. wc mu st observc E5D (electrostatic discha rye) procedures. The fo llowin g arc somc of the features of a dcv ice programmer from hltps: llwww.EEtools.com: I) Auto !;Carch devke: >elect funct ion supports eHスp r oセ ャ ウ@ and mkrocon trollers. 2) Device in>ert iou tc.t id elllifle. improperly iD!;erted device before programmmg. 3} Checks for incorrecl device iru;enioll, backward. incorrect position. and JXlor pin contact. 4) Device: Opc:ra tions: Re ad. l3Iank check. Program, Vnify. Checksum. Data. compare, Sccuriry, Auto (blanl: cbcck-program-vcrify), Option Bit program. 5) Displays prognunming paranleters and optional bit infonnalion on the

a)

screelL

CHA PT ER 8: HCS I 2 HARDWA RE CONNECTI ON, 80:'11, AND 5 19 HEX FIL E 263

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

6) $cts dcviceJbuffcr address ranges before p rogramm ing dcvk.

Program counter value upon reset Aelivmin g the Reset pin will eau se all va lues in th e registC1"S to be losl. Table 1ecs 1's comple menl 10 cuku late the checksum byte mtlla" Ihan l's co mplement, which was wvered in Chapters 6 and 1. Also notice that the checksum byle at the end of each line represents the 」ィセォウオュ@ byte for everyth ing in thaI line and not just for tile data portion.

S. CC is u single byte. This lus t byte

Figure 8- 10 shows the source file for toggling PORTA. Now, compare the Mta ponion of the 5 19 fik in Figure 8-12 wi th the information under the OIlJ field of the lSI file in Figure 8- 11. Notice thatthcy arc identical, as lhey should be. Thecxtra Lセ@

"

Lセ@

an output

;Make port A

"" " - ""

'" "M 'M' "M "M .= " H55

CO""

, 'l'fI

"

COM

; pu t

P()R T1I

"",",

por t 11 pi n5 セ@

PORTA

'"'

FIg ure 8-10. Sou n e FIl e for Tngg llng PORTA

I セZ@ 12826 12821 12828 12829 1283 0 12831 12832 12U"

'0' セZ@

"" """ "'" D

000000 00 00 02 0000 04 000006 000008

セAM@ ⦅[ッセ」@

⦅セ@ __セ

8 6E'F 510.02 8 655 5AOO

ョ⦅セ@

WM

1$ E'E'

: A " ITH

"M

OOAA

;fOake Port

L2 WIV\

1$55

OOOOOA 5AOO

'TAA

00000ltentimlaify lifl blank

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

CHAPTER 9 HCS12 TIMER PROGRAMMING IN ASSEMBLY AND C OBJECTIVES VIJon com pl etion of this cha ple r, ),ou will he able 10;

» >:>

» >:>

» » >::.. »

Usl Ihe time rs or lhl' li es 12 lind Ih rir associated rcglslcrs Describe Ih e frc ..-- runnlng fClllurc ofl he Il CS12 limt:r Dcscribt, Ih e output-compan.· feature uflhe II CS12 timer Program Ihe ou tput-com pare feat ure in Assemhly lind C Dcscrihe Ih e input-ca pt u re fell'ure oflhl' IICS12 limcr PrOl:ram the inpu t-cllp l ure fcature in Asscmbl)" and C I'rlll:ram the II CS I2 timers in asセjiャ「ケ@ anll C 10 I:cllHatc time dela ys Program the II CS I2 counler.; in Assembly and C as cHn l cou nt ers

m

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Every timer needs a clock. pu lse to tick. In the microccntrollcr, the clock source elm be internal or ex ternal. If we usc Ih e inlC'lll al cl ock source, then the frequency of lhe cry stal oscillator on the XTA L and EX TAL pin s is fcd into the timer. TI!crcforc, it is used e ither lIS a timer 10 mcmrufc lln d generate a time rlc by or as a munlcr to rolln! events happen ing Olllsi(lc the micro-

oontrol1cr.

SECTION 9.1: FREE-RUNNING TIMER AND OUTPUT COM· PARE FUNCTION In Ihis ウセエゥ ッ ャ@ we diswss the lies 12 time r and Ou tput Com pare func tion ami sho w how 10 pmgl1.l.l11 it in Assemb ly language.

The free-running timer In HCS12 The HCS ll has a singk l 6-bit timer (counter) ca l[ed fiee-nu",ing lime,-. Se---®



TOF " 0

TOF "' O

Tor .. o

TOF - O

TOF - l

     

cun IIlso usc l he TOF to cause un Inlemlpl. Churter 11 shows huw to use TOF to cause an inIL"Ilupt. Noltl , we dest.Tibc !he presclli er option of lhe free-runn ing lill1\,'J.

The system control registers (TSCR1 and TSCR2) T he ヲイ セB・Mイ オョ ョゥァ@ limer has lwo control registers called TSC RI (limer syslem セッュ イ ッ ャ@ reg I) and TSR2 (Ii mer system セッョ エ イッ j@ reg 2 ). T he TSCRI and TSC R2 are S-bil registers. The bits for TSC RI and TSCR2 are shown in Figures 9-3 and 9 4. respeclively. See Examples 9-2 and 9-3. These registers are w idely used for progranmti ng the lICS I2 limer.

          

TEN

n :i\"

D7

I TSWAI I TSFRZ I TF FCA I

o

0

o

Timer enable o · Disable timt:r. Used for re..h., in); the power cons umption I - Enable timer. It

L[GI|B

エセ@

ul' with eao;;h pu,"e.

in WAIT Timt:r stops セゥャ・@ 0 - Timer 」 GN ュ エ ゥョオ・ セ@ couming up during エセ@ WAlT mo:;ode . I • Timt:r stops oountiD!: up durin); the WAIT ュッNiセ@ TS fll.Z D5 Timt:r stops < 32.768 illS) = 1 / 65.536 ms "" 15.25 Hz. cセG@

t SBO TSCR l Lセ@



セ@

TS CR2

BSI:T

S"A ...

TlOS, セoャ@ tsO I TCTLI

Coo セ



Lセ@

LセN@

Lセ@

; ..n .. bl ..

ti_r

tsoo セ@

'655 35

'"Gセ@

"f1"W l, "T FLGl_ C 4F. 'I'fLGl, '00010000



BSET

'M

GBセ@

; toqgle pin upon "'''teh ; r .... d cunen t TCNT カセ@ lu e セッ、@ 65 535 puis ...

Gイ@

ADDD

, ,,'

, no in te rrupt, no prescalar ; selec t ou t put COllpare

L@

,-

'"

; 100 tHCE need 50 pulses he") since ,"'II PACID 2 ; in i t i!lliu: PACII - -50 [port bNセ@ PORTB , \00010000 BRCLR PAFLG,I1PAFLG_ PIIOVF, liERE ;st"y セイ\N@ until PACA ov,"cflows BSET PAFLG, I1P AFLG _ PN:)VF; cl aac CO, flag for the ne"t round ;PORTB.4 BSET PORTE , \000 10000 (lVER "M

"""' ,m

'l1li

"-

'" -"

.,

"

www.fut ureerc.com

Page: 1

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Exampl e 9-25

Assume thaI a I Hz pul..: is C(l111l(Xlcd to inpu t for PACA (pin PT 7). The pulses represent the Illlmbcr of bOllles bein g packllgcd together. Wri te II program to rum on PORm.4 every lime 12 hon les go hy. The progmm , hou ld display the bin ary coun! on

PORTA. Solu tion ; We &1.1 th e initial event co wller value 10 - 12 (FFF4 in hex ), then the unt il it reaches F1'fE Upon Ol'crflO \\", \I"e turn on Ihe PORTI3.4 pin. Counter

""

エセョ

STAA BeLR

DORA OORT, tIlooooooo Coun t e r

; roRTA ... セ@

Gouiャセ@

up

G@

; .. n"bl", 16-bit event count"'T

outpu t Lセ@

a " input

Lセ@

nO l010000

S TAA

PAC'l'L

'"" '"

t SFTF 4 PACN32

BeLR

E'ORTB, I 00010000

b}

PAFLG, OIPAFLG_ PA()VF . HERE '.6 tay her e ""til PACA ッ|ャ・ セ\Zlr@

B SE T

BS]';"

"OC L

ョャlGj@

OS.S 1

L UAA

'" Lセ@

セッオ

セ@

"AA

; no i nterrupt, rising e dge ;0 _ -12 (FFN in h e x) .sinc e we need 12 puls e s ; ini t i"llz e PACA=-12

; l'ORTB.4

=

0

Iturn off) イヲャッセ

Gs@

E'ORTB,IOOOIOOOO , turn on i>ORTB.4 for ・セイゥG@ 12 pulses PAn ,G,IlPAF!.G_ PA(JV!';clear ttte flag' tor ette ne>ome exam ples In Ihis !>Celion we sholl' C programming f(lf the I-IC S12 QUII'lII Compare. Input C apture, and f'ul sc Accum uial(lf features. As IO'C sa w in the examp les in Chapler 7, the gencral·purposc rcgiSICfs and memory of the 12 arc under the control of ttle C compiler and!lfe nO( accessed directly by C statements. All of lhe special functien イセ ァゥ sャ」 イ ウ@ for pcnphera ls. ィッ キセカ イ L@ arc accessible d ircclly using C siセエ ・ ᄋ@ monts_ As an ・ ャ セ ュ ー ャ ・@ e f ッ」ウセゥョァ@ Ihose special イ ・ァゥセエイウ@ dircclly, we saw hew te access ports PORTa-PORTE in Chapter 7. Nelli, we discuss how to access the HCS 12 limen d irectly using Ihe C co mpiler.

lies

Accessing timer registers in C In C we can access limer registers Sllch as TCNT. TSCR I, and so on, dircelly using Ihe approprime header file_ NOle when programmi ng in Cede Warri or オセゥョァ@ C Ihallhe bit nam ing conventio n is d iffcrcnl from Ihm used in a ウMセ 」ュ「 ャ ケ ⦅@ We must make sure 10 オウセ@ the bil mask: version ef the reg iSlCTS for C synlnx. Exu mples 9-28 Ih rough 9-46 repeul the pn.'Vious exump les in C. See Tub le 9-1. "l'able 11-1: Co mp aring Ui l Na llling COll \'entioll! in CodeWarrior

, IKU" 'dcd with thC5C tool •.

Calculating delay length using timers As we have seen in previous sed ions, the deluy lenglh dl.'pend s on Ihree fuelors: (a) the crystul frequency, (b) the p rescuk,- fucl or, and (c ) the C compiler (because variou s C compi lers genemle d ifferent hex code sizes). Study the ex amples in Ihi s sect ion and verify エ ィセGヲャQ N@

'l»

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Eump le 9 -28 (C wn ion of Eum plf'$ 9-3 an d 9-6)

Write a C program l(l coonl エャh セ@ number of lime s the fr« -numing timer overflows ( TOf is ra ised). D isp lay the binary number OIl PORm . Show how oftclllhe number chaalges. Ass ume XTAL - 4 MHz. Usc a) no prcsca[er and. b) a prcscal" rutch

,

whil elll Tcount _ TClfT;

'recu nt = Teou nt + 6250 0 ; Tel = 'reount; whil e THGI

(t (TFLGI

=

TFLG!

" TFLG1_C7F _MASK1) , llwde for chan 7 match Ile lear CIF

I TE"LGl _ C7F_ Ml'.SK;

Another way to verify the llbovo values is as follows:

112 )( 4 MHz - 2 MHz and III IS)( 2 MHz - 125,000 Hz due 10 rhe prcsca1cr and T 1/125 ,000 Hz = 8 " s for TeNT. Now, 0.5 s 18 " s = 62,500.

'"

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x. com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Eump le 9 -32 (C wn ion of Eum ple 9-11 )

Asswuin g XTAL

4 MHz., write a progrnm to b>eneratc a square wave o f 50 Hz fre-

quency on pin PT6. Use ch:mnel 6 lIlld II preSUlJer of 128 fOT the TCNT. Thi s is the C

vCl!iion of Example 9-11. Solu tion:

Look at the following , tcp s: (a) Ill>: 4MHz=2 MH zand 111 28:< 2MHz= 15.625 Hz ami T"" 11 15.625 liz = 64

"'

(b) T - 1 / 50 Hz - 20 ms. the period of the square wave. (c) 112 of it for the high and low portions of lhe pulse = 10 illS (d) 10 ms ' (,4IlS - 156 lincl ude \LBYセQRーUNィ^@ IHnd "f 'l'FLGl C6F M!\SK

' defin e TF LGI C6F セa

sk@

Ox4 0

unsig"",d int TCOlln t!

voi d maIn (VOid ) {

TseRl - 0>::10 ;

PA PB

an output an outpu t

/I " n"bl" t.i"",r Iino int e rrupt, no prescaler MoL セ o[@ !I"el e c t ch ... n 6 for Input Cspt ure

/ / :;;el ect cllalUle l 6 for captu r e on r is in g e;J.:ju

TFLGI - T!"LGI I Tl'LG l _C6!"_MI\SI\; Ilclear C6F while (!I'I'!'LGI 'n"LGl _C6 !"_ t'.ASr; )) ; I/Chan 6 Hrst da1n" edge Tl - 'reG ; flgH. the 'I'C6 v " lu e

TrW l -

Tf'LGl

I 'ITLGI_C6F_MASK;

lIelMr C6F

while (!(TFLGl & TFLGl_C6 F_ I'.ASK));llc".m 6 2nd rising e dge T2 = TC6 ; / (g .. t th .. TCNT v;o.lu .. Tcount = T2-Tl; PORTB = Tcoun t ' 0 1OOO FF: Ildisp lay the l ow byte PORTA - ((Tcount セ@ 0 101'1'00) :>:> 8) : Iidiaplay the upper byte r or(; ; ) ;

HCS l l

{'ORCA=] ==

( 2 MH z - 15,625 Hz due 10 the prcscnlcr and T - 1/15,625 H z 64 セウ@ for TCl\' T. That means we gel the value of 208 (110 1 0000 binary) for the period since 13.3 ュセ@ I 64 l.1 s = 208. Now the pul se width can be unywhCJc from 1 10 207 clock ャゥ」ォNセ N@ lincl ud e ャゥヲョ、セ@ rFLGl_C6F_MAS K G セヲゥLオ@ TFLGl _C6F_"'.A5K 0>: 40

lendif un3i'1ned int 'I'count , void BL セゥョ@ lvoid)

n,

TZI

DDRB = Ox IT; II_ ke PB OT is oonne;>8) セ@ /I display the high byte

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

IEu mpl e 9 -42 (C wn ion of Eu mple 9-23 ) Asswlling that d ock pulses are fed into pin PT7 for PACA an d a buzze r is connected \0 pin PORTS.! , ",'Ti te u progmm w sound the buzzer HOer 1,000 pulses. Thi s is thee version o f Example 9-23.

Solu tion: To sound the buzzer evel)' 1,000 pu lses, we sel lhe initial event coo mer va lue 10 - 1,000 (FC18 in hex), then the counter counts up until it reac hes SF FF F. Upon overflo w. we ca n sound the bu zzer by 10000gling the PORTB.l pin. linclude unsigned int )1ycoun t; vdd _in lvoid) {

0",02, I hna.l< & PORTE.1 an output -Ox80, /IJrlake ('1'1 an input

DDRB '" oORB I DDRT - DDRT セ@

PACTL - Ox 50 ; PACNJ2 - OxFC1S; セ@

wh.i le I! iPAFLG whi1 .. (1)

lienable 1 6-bit PACA event counter, fino interrupt , count ーオl セ・ウ@ on dsin9 f/!5et PACA 16-bi t e is セッj u| ・i[エ、@ es represent tbe JUu nber of boUles bein g packaged IOgctltcr. Write a pmg!1.lm to !Urn 011 PO KIUA every time 12 boules go by. The program should display IIl e binary cow!t on PO RTA. This is the C version of Exam ple 9- 25.



$o IU lioll : We sel Ihe initial event 'QUilter value to - 12 (FFF4 in hex). thell the eountercounlS up lttlti l it イ」。セ ャエ 」ウ@ FFF F. Upon overflow, we turn on the PORTBA pin.



_include inc MyCounc, voia lMin Ivoid)



オョセゥAQB、@

,

DDRA _ Ox FF; PACTL = 0 >l.' a presc aler o f 64. 25. PrognlJll channel 2 for Outp ut Com pare to gener.J.te a square wave of 1 kHz wilh 50% dUl)' cyc le. Assume that XTAL = 4 MHz. CHAPTER 9: IICS12 TrMER PRO GRAMM IN G IN ASSEMRLVANIl C

323

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

25. Program channel 4 for Output Compare to generate a ;;quare wave of] kHz with 50% duty cycle. Assume Ihm XT AL - 4 MH z. Usc the largest prcscalcr possible. 27. Assuming that TCNT - FFF I 11, indicate which stat es TeNT goes through

until the overflow flag is raised. How many stales is that? 2S. Assuming that XTAL - 8 MH z, find the period o f d od: pulse fcd to the TCN T fer 100 following prcsca1crs: 128 (a) 2 (b) (c) S (d) 16 (0) 32 (I) 64

SErrlON 9.2: INPtrT CAPTURE PROGRAMMING

21). Explain the role of the TlOS register for the Inpul Cupture funclioo. 30. True or fulse. Th e In pul C upl ure fund ion can 、セQ 」ャ@ only the f311 iog ed ge. 31. How many Input Captu re chmmcls do we have in HCSI2? Give the name of the Te" イ・ァゥウャセ GM for each H[ ィ セ ョ ョ・ ャ@ and the input pin US,-;ociulcd with il.

32. Explai n the ro le of TCTL3 and TCLT4 in Input Cupture mi ng o

ヲ オョ

セQ ゥ ッョ@

progmm-

33. Explai n the ro le of the TCx register in the InputCupture functi on and how the CxF flag is raised. 34. True or false. We can use a given TCx chann el for both Ihe Output Compare an d ,he Input Cupture function at the sume time. 35. True or false. Each Inp ut Capture ChalUlci ha.-; its own al ge detect flag. 36. The se]e(:tion of Output Com ]Xire/lnpu t Capture fund iOiI is dOile by Illallipulating the bi ts of the _ _ _ register. Show how we select the Input CaptW'C function for chann el 3. SECfION 9.3: P ULSE ACCUMULATOR AND EV ENT COUNTER PROGRAMM ING 37. How mallY8-bit PubeAocwnulator chalmeb do we have in the HCS 12'! Give their naJlles and Ihe input pi ns assoo;:iate\i with them. 3S. Explain the role of the PACTL in Pulse A,cWTIulator fWlction progranuning. 311. Explain the role ofllle lCPAR register in Pu lse Acc um ulato r progr311unin!>. 40. True or false. We ,an use a given PACx dmzmei for both rhe !l-bit and 16-bit pulse a"U llmialion at the same time. 41 . True or false. Each Pulse Accumulator channe l has its 0\\11 edge detcet flag. 42. The select ion of 16-bit and S-bit Pu lse AccwllulalOr fu n"iOlI is done by manipulating the bits o f the _ _ _ rcg iSlcr. ShOll' how we selcc I the 16-bit I'ul se Accum ulator A. 43. How mallY 16-bit Pulse ACCWll U!atOrs can \\'e have in HeS 127 44. Explain how the PACA is formed. 4 5. For the PACA countcr, which pin is used for the inp!.1t pulse? 4 6. For the PAC! COlotcr, which pin is used for the input pulse? 4 7. Troc or false. Th e Pulse Accumulator can dctcct on ly thc falling edge. 4 S. Program PACA to be an evcnt counter Use 16-bit mooc, :md display the hina-

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

ry rount on PORTD and PORTA com inuously. Set the initial セッオョエ@ 10 20,000. 49. Program the r AQ rounlor to be an even l counter. Di splay the binary COlin! on

PORro continuously. Sci the initial セッオョエ@ to 20. 50. Explain the role of the PAOVF bit in the PAFLG register for the Pulse Accumulmor function. SEC TION 9.4: HCS12 TI MER PROG RAMMING IN C

51. Wri te the C version of Problem 25. 52. Wri te the eversi on c f Prob lem 26, 53. Write the C versi on of Prob lem 48. 54. Wri te the C version of Prob k'fll 49.

ANSWERS TO REVIEW QUESTIONS SECTION 9 1: FREE_RUNNING TIMER ANIJ OUTI'UT C(),I.' PARE r UNCfION

1. 2 3. 4. 5. 6.

, 7.

9.

Fal.. Fal.. True 10,000,000 indicate. nmer cnabl:: , ti mOTcontmuu counring dumg ,t.o WA IT, and free..:

.

$FFFF.OOOO SFFFF,OOOO 100 11' I 0.5

セ@

セ@

200; therefore Te O

セ@

TCNT + 200.

SECTION !U: lNl'tJT CAI"ItJRE PROGRAMMING l. _ S

2

,-

Tru, Tru,

,TlOS ; Fa! ..

SECTION 9.3 : rULSE ACCUMULA1'ORAND EVENT COtiNTER PI«)(iRMIM1NG 1.

2. 1. 4. 50

PH The clock oourw for the timer com", from pin P'fO. Ye, We mu, t configuf'< the I'm a. input !o al lo"" te.: d ock, tocome in finm a n extC'TIal ."mce. Ye.

CHAPT ER 9: IICS12 TrM E R PROG RAMMIN G IN ASSE MRLVAN Il C

325

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

This page ;>ltentimlaify lifl blank

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

CHAPTER 10 HCS12 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C OBJECTIVES V,Jon comp leTion orthls chapler, ),ou will he lillie 10;

» >:>

» >:>

» » >::.. » »

» » » » »

Conlruslllnd COIl1IN""c scrlu l ,'crsus parallel communication U SI Ihe IIth'unlages of se rial comJllunklltlun o\'t:r parlilld Explain serial COJlIlIIUniclitio ll prolOl'oI CunlrllSl synchronous "ersus IIsYJlchronuus curnnlunlclltlon ContrllSl h alf- .'... nus full-duplcx transmissio n Explai n the pron'Ss of da ta fralllin !: Oeseri"e data tran sfer ralc IIml bps rate Define Ih e RS232 st alltlard Expla in the use uflhe MAX232 anu I\1AX233 chips ャオ」イ。セ@ tbe IIC512 1\-ilb au RS23Z セHIョ」Gエイ@ DiSl.' uSS the baud rale of the IIC512 Oeserihe Ih e セイゥ。 ャ@ cOllllllunication !calures of Ih e IICS I1 De$crilw th e main fl'Gistcrs used for serial communicali on on the II CSIZ Prog ram the II CS12 H'rial port in asャゥセュ「ィ G@ alld C

m

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Computers transfer data in two ways: parallel and seriaL In parallc l data transfers, often eight or more li nes (wire conduc Hlrs) arc used 10 trans fer 、ュセ@ to a away, [Xvicc. that u>o: paral],:l transfers include device thaI is on ly a few ヲセQ@ printcrs and hard dish; each uscs cabl0 means thm at the receiving end there mus t be a !>Cria l-in-parn llcl-out shift register to receive the scrial data b it s an d pack them into a byte. Of C(lUI'SC, if data is to be transferred on the teleph on e line, it m ust be convened from Os an d Is to aud io wnes, whic h arc s inu soidal signal s. Th is convcrs ion

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

is performed by a peripheral device called a mQdem, which stands for " modlilaエッイ

O 、」ュッオ

ャセエHIj ⦅@ .. When the distan ce is short, In.: digital signal can be transfcrreCoos ou t signa l CTS to the DTE (PC) 10 indi cu\e that i1 can rt't'Cive gro Uld the data now. Thi s input s ignal to the DTE is used by the DTE to sturt f iセオョ@ 10,,(;, n オャ ャ| ャオ、セュ@ C"nnl..:!!"n tTunsm issioo. 5 . oeD (dolO eurrier detcet). Th e modem n.'Io3cns aignul DeD 10 in form the DIE (PC) lhu t 11 va lid carri l-"f ィ 。セ@ been detCded and that COIital:t between il an d the 01111.,- mock-m is eShlblished. tィ セ LM ・ヲッイL@ OCD is un ou tpu t from Ihe modt:m and ltll input to the PC (DTE). 6. RI (ring ind icator). An output from the mor.k:m (OCE) and an input to u PC (DTE) that indicates that the telephone is ringing . RI goes on and off in synchronization with th e ringing sound. O f tile six handshake signab. tllis is the lea st orten used bcclluse modem; take care of Wlswering the phone . If in u g iven syste m the PC is in cha.rge of answe ring the phone. however, this signa.l can be used. From the above description, PC and mode m communi cation can be SUIllmarized as follows: Whi le signals DTR and DS R are used by the PC and modem. respe..:t ively, to indicate lhatthey are alive a nd well, Ins and ers are the signa ls

"'0

X

CHA PTER 10; HCSI2 SERIAL PORT PROGRAMMING IN ASSEM BLY AND C

333

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x. com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

that actually control the flow of data. When the PC wants to send data it as.'lCl1S RTS, and in response, the modem. i fi ! is reMy (has room) to llCCCf't the d.%1, ウ」ョ、セ@ bad: CTS. If, for lad: of room, the Il10dcm docs not activate C 1'$. the PC will desert DTR and try again. RTS and arc al so referred 10 as }"lrffimrc flew COn-

ers

tml.ligna/s_ This concludes the description of the most important pins of the RS232 signnls plus Tx D, RxD, and ground. Ground is also r('fCITed 10 as SG (signa l grou nd). ィ。ョ、^

ィ セォ」@

IBM PC/compatible COM ports IBM PC /compat ible computers based on x86 (8086, 286, 386, 486, and all Pentium) mil,roprocessors uscd 10 have two COM ports. BOlh CO M pon s were RS232-type con nectors. Muny pes usell one cueh of the D8-25 und D8-9 RS232 connCi:tors. 111c COM POri S were designated as COM 1 ami COM 2. In recent years, one o f these hus been Tcpla,,;OO with the US B p:>rt, and COM 1 is lhe on ly f;Crial p:>rt avai lable, if any. We can conned !he HCSI2 f;Cria l p:>rtlo Ihe COM I port o f a PC for seria l communiealion experiments. In the abscnee of a COM port. we can use a COM-to -USB convertl'J module. With thbc background in serial conullwlicalion. キセ@ arc ready 10 look at 1l1e HCS 12. In 1l1e Il cxt section we discuss the physic al connection of the HCS 12 and RS232 connector, ruld in Section 10.3 we ;;ox how to progra m the HCSI2 >.:rial COllullwl icalion port.

Review Questions I. The transfcr o f data using para ll el lines is (faSlcr. slower) but ;0::::-::-,;:;::-;;:::::;'_(more expensive, less expensive). 2. Troc or ヲ 。ャセ N@ Sending data to a primer is duplex. 3. Troc or ヲ。ャセN@ In fu ll duplex we must havc two data lincs, onc for transfer and one for receive (sync hronous, as)llehro4 . Thc start and SlOP bits arc used in Ihe nous) method. 5. Assuming tha i we arc transmini ng Ihe ASC lllc ner "E" (0100 01 0 1 in bi nary) with no parity bit and one stop bit, show the sequence of bits transferred serially. 6. In Question 5, fin d the ovcmcad dnc 10 frami ng. 7. Calculate the time it lakes to trans fer 10.000 ehar:\Cters as in QueS lion 5 if we usc 9.600 bp s. Whal percentage of time is wasted dnc 10 o\'cmcad" 8. Troe or falsc. RS232 is not TTL oompatible. 9. What v(lltage level s arc U$Cd f(lr binary 0 in RS2327 10. Troe or falsc. Th e HCS I 2 has a bu ill·in UART. II . On the boek ッヲセXV@ PCs. we nommlly Mve _ _ COM pon oonnecoors. and 12. The PC COM p:>r1s ure desigrlUled by OOS and Wi ndows as

JJ4

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

SECTION 10.2: HCS12 CONNECTION TO RS232 In Ihis SlXlion, the deL1;l s of the physical connecti on s of the HCS I2 to RS232 conneclOrs arc gi ven. As stated in Section 10.1. lhe RS232 standard is not TTL compatible; therefore. n line driver such as the MAX232 chip is requi roo !O OOlWcn RS232 \'oll agc levels Hl TTL level s. an d vice versa. The interfacing of the HCS 12 with RS232 COn nCl-10r S via the "-1/\X232 chip is the mai n topic Of lhis sectIOn .

RXD and TXD pins in the HCS12 The HCS12 has 111'0 SCI (serial colnnl wl ical ion interface ) ports and they designated as SCIO and SCII . Each {lfthe SCI pon s has 111'0 pins that are used specifica lly for Irnnsfcrri ng and rece iving data serially. These two pins are ca lled TX D and RXD and are part o f the pon S group (PSO-PSJ) of the Q I'P package. For SCIO \\'e have pins 63 (PSOfRXDO) ;uld 64 (l>S IrrXDO). In the case oflbe second seria l port of SCll . pin 65 (pS2IRXDl ) is assigned to RXDl and pi n (>6 (1'S3fTX D I) is des ignated as TXD I. These four pins are not l T L セッュ ー。 エ ゥ「ャ・[@ there fore . they require a lille drive r 10 make Ihem RS232 w m patible. One such li ne d river is the MAX232 セィゥー⦅@ This is discussed nal 。イセ@

MAX232 Becaus0 widely u:;ed to communicate with II CS I 2-bascd systems, we w il l emphasi ze >eri al conununications of the IICS[2 with the COM pon of tile PC. Some of the baud rates supported by PC HypcrTcrm.inal arc li sted in Table 10-3. You can ex amine theI'C baud rates by going to the Microsoft Windows HypcrTcrm.inal program and Tah [e 10-3: S om e clicking on the Comm lmicat ion Sen ings option . Th e II CS [2 PC Bau d RaH-s In transfers and receives data serially at many different baud I l\'perTer mlna l done with th e help of two 8-hit reg iSiers ca lled SCIB DH (SCI baud rate h igh) and SC IBDL (SCI baud rate low). For セ@ given crysta l frequency, the \'alue lonrlcil into the SClBDH :SClBDL registers dec ides the hau d rme. The relation between the value loaded into SCIBD H:SClBDL and Fosc (frequency of tbc erystal oonnectcrl to the XTAL and E XTA L pins) is dietateil by the fol lowing fOmlu ャ 。セ@

Desired Baud Rate -

1,200

2,400 4,800 9,600 19,200

38,400 57,600 115,200

Fo>d2(16)( X)

where X is the va lue we loa d into the sc ibdh セscibdl@ registers. The two registers of SC IBDH and SClBDL give us 16 b ilS, bu t on ly 13 bils are used. ThO! means they cun toke vu lucs from I 108 191 (0 to SI FFF). Assumi ng Ihul Fosc= 8 MHz (ECL K = 4 MH z), we rove the ヲッ ャ オキ ゥ ョァセ@

Dt:sired BlJJd Rale = 8 MH z/2( 16)( X) = 250 kH21X To get the X value for differenl baud r;lteS we can so lve the cquation us follows:

x = 25 0 kHzlDesin:d Baud Race Tuble 1()'4 sh ows Ihe X vulues for the di flen:nt ooud rulCS if ECLK = 4 MHz

C" .... PT E R 10: HCS I 2 SE RI AL PO RT PROG RAM;\U NG IN ASSEM 8 LY AND C

337

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

I SB R7 I S 8 M I SB RS SBR7- SBRO

,

ャ セ Z@

I SB R) I SIlRl I SBR! I SBRO

The;e are the JowerS hilS ,,[the 13 used for seuing!he hlud rate.

,

o

SIlIt12- S BII.II These are Nオ

SIlR4

セ@

I SB RtZ I SBR J I I SB R IO I SB R9 I SBRtI I

upper 5 b its o f !l,e 13 u$COd for 1

R0I:I",..,. L"... (SC ID RL)

CHAJ>'I'ER IU: UCS I2 SE RIAL l'O lfl" I'ROGRAMM ING IN ASSEM ULY AND C

J J9

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca



SCI Control Registers 1 and 2

     

We have two SCI COnlm] Registers: SCie R I and SO eR2. They セァ

the framing of data by specifying the number of bits per character. In th is textbook we use the no parityoptioll with a d ata size of8 bils. T he SeleR2 register is オNセ・、@ 10 enable the seria l por t to send and receive data. a mong other things. Figure 1012 describes various bils of Ihe SClC R2 register. Several of the SClCR2 register

bils arc widel y used by the UART. The TE (transmit enable) and RE (m:dvc enab le) are th e most important bils in this register. T he rest orlhe bits are used for interropt-drivcn seria l communication. In Chapter I I we will sec ho w Ihesr

o - No ovemln J - Ovemm "lTor D1

Noise Flag elfor bit 0 - No noise

FE

Dt

I - Noise error F rJminl! Error bit 0 - No (milling error

1 - Framing error OQ

Parity flag error bit 0 - No parity aroT I = Parity error

T he i"'l'.. イ ャ セャ」 」@ of th e TUK1:. To tnllI< mil a byte of d ata seria Uy via tho: TXD p in. we is an internal regist must write it into the sa Data Register. The tm ... mit shift セァゥウエ・イ@

whose job is to gel lhe data from the SCI Data Re1;islt:r, frame il with the start ano.l Slop bits. and send it (lut (lne bi l at a ti me via tile TXD pin. NQlice !bat tbe tmtUmit shi ft セァ⦅@ ister is a parallel-in- serial-out shifter and is 1101 access ible to the programmer. We can only write ..., the SCI Data Register. Whenever the shifter is empty, it gets its new data from the SCI Dnta Registcr IItld cie:crs tile SCI Dat.1 RelliSfcr immediate ly, so it docs not send t!be same data twice. When the shifter ヲ\Zャセィ・ウA@ data from the SCI セオ@ Register. i lears the TORE flag to ind icate it is ernpy and the SCI Data Regi.cer i. ready fo r the ""xt ch",,,,,,,,r. 1,I,'e mU"t cb""L the TDRF 11:1); boofuru we writu an"\lQ r"tljl

: W9 .. ust wdte to hlCJh by te reg even i f zero : set the baud r a te to 9600 Bセ@ Lセ@ ;w rite to l ow byte ;B-bit data, no parity "nd no interrupt Bセ@ SCll)CRl ;w rite to control reg 1 Gセa@ ; ..",,1>1 .. both tu.nsmit ilnd r .. cdv .. HOC B セ@ SCIOeR2 ; wri te to control fljlg 2 t 'G ' I I letter ' G' to bIJ t ransfIJrred ;ASC Bセ@ SCIOSR l , IaSCIOSR1 _ TIJRE , HERE [ 」ィ・セ@ ro r Data rentroI ItCII"tcr, 8 SCI Cuntrol RGli,tcr True It i, mised whon 1110 byto in the SCI Data Register i, lTansferrOO 10 the tmn"", il セィ It i.ciClrod w hen ".-e wrire a byte 10 SCIDR 10 be nmsmiuod, ゥヲエ@

セァゥウエ・イL@

I(), 2

SECTION )() 4; HCS12 SE RIAL PORT PROGRAMMING IN C l.

2 3.

True

n",

4.

True SC IBD

5.

SCI

sセオN@

ォAi

BセGM

1t I"" u. mow Ihll! セ@

b \,te hal b!:m

="eo,l and we nrnllo I'IC); il '4'

from the SCI Data Register.

CHAPTER 10: HCS I 2 SE RIAL PORT PROG RAM;\UNG IN ASS EM8LY AND C

] 57

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

This page ;>ltentimlaify lifl blank

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

CHAPTER 11 INTERRUPT PROGRAMMING IN ASSEMBLY AND C

OBJECTIVES VIJon com pl etion of this cha ple r, ),ou will he lillie 10;

» >:>

» >:>

» » >::.. » »

» »

C o ntruslllnd COIl1IN""c In lcrru pls B」イセ オ ウ@ polling eクーャセゥョ@ the ーャイッウセ G@ of the IS R (I nt erru pt St,r"kc rou tl m:) List the ュ セェッイ@ in terrupts oftlw II CS12 F.x pillin the pur pose of the Inte rru pt ,'ccto r lable Enable or di sabl e II CS I2 intHru pts PrOl: ra m the II CS I2 timers usin g interrupts Oeseri"" Ih e H lernal hard ware interrup ts of thl' II CS I2 Prog ra m the II CS I2 for int H fupl -lllucd seria l cOllimunicalion Define th e in terru pl priorit y o f the II CS I2 pイqャセQu@ IICSI2 inlerrupts in C I' rlll: ra m II C812 RTI in lcrru pt ill Aliscmbly an d C

'59

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

 

In th is c ha plcr we explore the concept of the intcrropt. The HCS I2 interru pt program ming in Assembl y an d C arc also discus,oo ,



SECTION 11.1 : HCS12 INTERRUPTS



In Ihis section, fi rst we cxaminc the d ifference beTween rolling and interrupts "nd then describe ャ ィセ@ various inte rrupt s or the HCS 12.

                     

Interrupts vs. polling A single microconlrolJer can serve several d ev ices. Thefe are two " 'a)'s to do lilal: interrupts or po llin g. In the interrupt method, whenever Wly dcviu: IlI.'Cds service. the device no tifies the microconlIollcr by scnding it rul interrupt sigua l. Upon セ ゥ|G ャ ァ@ an interru pt signa l. the microcommllcr ェョエ・ イオ ーセ@ wh atever it is doing and serves the device. The program as;;ocialed with the il11errupl is called the illlerrupr service routine (ISK) or interrupl hood!'!r. In polling , the microcon troller continuousl), monitors the status of a given dev ice; when the status ootld i· lion is met, it perfomls the oerl.'ke. After titat, it moves on I() moniter the next device lUlti] each one is servicro. Althout;h pollin g can moni tor the slatu6 of several devices and setve ea,h of them as ,e rtain condition s arc me l. it is not an efficient use of the microcoll troll er. The adVrultage of interrupls is Ihat the microeontroller Crul serve many de vkes (not all at me same time. of ,ourse); each device can gel the al1emion o f the mkrocolllro ller based on the priority assigned to it. The polling rn e tlu.x j UIIInot assign priority since it ( hecks all devices in a roundrobi n fashion . Mo re imp:1l1rullly. in the illlerropt method the microcomroller can also ignore (ma sJ;:) a device request for service. Th is is again not poss ible with tite polli ng memod. The most imponant reason that the intemIpt method is preferable is that the polling method wastes mu,h of th, microrontroller's time by polling dcvkes that do not need ser vice. So in order to avoid lying down the microcontroller, intctn.lpls arc used. For example, in discuss ing timers in Chapter 9 we used the instroelion -- BRCLR TFLG2, TOF , target ", an d wa ited until the timer rolled over, and whik II'e were wait ing we cou ld not do an)1hing else. That is a waste of the mieroconlrollc r's time Ih at eould have ken used 10 perform some uscfu l task s. Tn the case o f the limer. if we usc the inlClTIl pl method , Ihe mierocontroller can go about doing other lasks, and whe n the TOF fl ag is raised the timcr wil l in tcnupt the mi crocont ro l1cr in whHl CVcr it is doing.

Interrupt service routine For every int eJl\lpt, there must be ;m interrupt service rou tine (ISR j. or interrupt h:.md 1.: Acc1.umdat ors Aand 13. !\.lemory locations for lhese interrupts are shown in Fi gu«, I I- I . ) . Two interru pts are set asid e for external hardware interrupts. Pin nwn be rs 5(i (PEO) ruld 55 (PE l ) in port E are for Ihe external hardware interrupt s XIRQ and IRQ. respa.:t ivel y. Memory locati(lns SFFF 2 and SF FF4 in the interrupt vector table are assigned to XI RQ and IRQ, res:po:clivc1y. 4. Serial C()Inmunication #0 (500) has a singk imerrupl Ihat belongs to both receive and transmit. 5. Two in tcrrupl s arc SCI aside for lhe Analog-to-Digit al Conveners ATOO and A1D l. SeeTable ll-l.

3{,2

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Ta bk> H-I : Parti al List ing of Lnt errupt VeClorTa bk> for th e IIC 512 lョエ

セ イオーャ@

ROM Location (Hex)

Globa l e ャ。「 セ@ (eC R Mask)

LOl'al Enable

1 II i,

"it

"

"il

-il

"

, ,1 , -I , ,1 , -I

r ORTr For the oomp lCf(l liSl

S('(l

FFSE- FF8F th e HCS I2 mamm l.

I bit PIEP (PIEPO- 7)

From t セ 「 Q」@ 11 -1 , not ice that onl y two bytes of ROM space arc assigncrl to the resct r in. They lIro ROM address lo cations $FFFE :md $FF FF. Also nOl icc in Tab le 11-1 th llt 2 bytes nfaddrcss loca tion arc SCI aside for eac h internlp!' Becau sc these auurel;s locutions belong w the FhL'ih ROM in the HCS 12, we hu\-c two t:oo ices: u) place the 2-byle mkJress o r lhe ISR in the vector table to p:>in t 10 the

address of a RAM 10 redirect the processor IIlI'ay ISR itself, or b) place the RM「セB」@ fmm the inlCffi1pl veCtor table in Flush 10 some user-uccessible RAM locutions. Th e HCS12 tminers emp lo y the second method 10 allow uccess to the HCS I2 interrupt vear e ; toggle PTI pin upon !Utch ゥ ョ エ・ セオ ーエ セ@ in CCIl

」セL@ tS80 S TAt. TI E ; .. n ;ob l .. in ", .. cc upt f oc Clwonn .. l 7 OVER BRA OVER ; k ....p 「オセケ@ .. nd .... it foc int .. cc up t ;-ISR t o c Output COt:lpa c e Ch a n n" l 7 :it Caine here because ot Outpu t COlr.pare channell Match. TCi ISR LDD TeNT ; read current TeNT value

-

AODO

S TD BSET

t 6 2 5 00 TC7

;we ne ed. 6 2500 ーオャ セ m@ ; 1 0000d t h e TCI ITime r Cornp"' re 7 )

TrLG1, \ I OO OOO OO

; c l ea r Cha nnel 7 セ BG」 ィ@ ; r .. tucn fc Olll int .. rrupt

f l ag

:Interrupt VeIT

Coun t .. r En t ry

,

I RAMEnd+l

; ini t L.lh .. t h .. s t" d , poin t .. セ@

Lセ@

OOAA

BSE T BCLR

DDRB ,\OOOI OOOO

OORT, \ 10 00 000 0

, f'ORTA .a s output LヲGor tb Nセ@ o utput セ L@ ; "", ,,i n put

Coun t er nOl0 l 00 l 0 PACTL

, ..n"bl .. 16-b i t IOv ..nt count .. r , with int IO rrupt PAOVI, rising

Lセ@

m Lセ@

Lセ@

..

0"

ce"

"" , BCLR

tstTF4

; 0--12

"

PACN32 f'ORTB, '000 1 00 00

'AA

;--------------------PACA_ ISR BSl':T BSl':T Lセ@ L

セ@

STAA

ce" om

BCLR

,n

-

"'

..

I'n·4 erial interrupt is useel Invalid lnslroclioll Or:ode Trap S W[ X IRQ IRQ . .

.

.

.

the X IRQ is responded to are shown in Table 11 -4. We Call raise the priority by first. On ly after XIRQ セ@ ィッN loadi ng a v alue inte the HPRJO n:sister. been sCJviced is the IRQ sc.-viced since it has the lower priori ty. Indeed. ul1 inlerrupls ussociuted wilh the I bit ィオセG・@ lower priority thun XIRQ . See Fi gure J 1-17 an d Tuble J J-4. In reu li l)" the priori ty Z[」ィセ Gヲャ ・@ in the table is nothing bu t an intem a l poll ing sc アuセG i c@ in which lhe HCS I2 pol ls the interrupts in the seqUl'llCC liSlOO in Tab le 11 -4 . an d responds lICCOJd ing ly.

Setting int errupt pri ori ty with th e HPR IO reg ister We

CalUlOt

a lter the priority ass ign ed 10 the first six in terru pts shown in

C HAPTER 11: INTERRU f>T P ROGRAMM IN G IN ASS El\ffi l.Y AND C

, 1 HPRIO V31ue (CCR Mask) 10 Ele\'ale (lin)

, , , , , , ,

, , -, , ,

-,

,

-,

SPI SCIO (Seriul COM iI 0 )

sell (Seriu1 COM il l ) ATDO (A rul og-To- Digi tul 110 ) ATDI (A nal og -Ta-Digi tal Il l ) PORTJ

FFD8- FFD9 FFD6 FFD7 FFD4- FF D5 FFD2- FFD3 FFOO-FF D I

I bi t

D8

I bi t

D6

D4 D2

PORTH

FFCC- FFCD

I bi t I bi t I bi t I bi t I bi t

PORTI'

FFl!E- FF8F

I bi t

FFCE- FFCf

See the HCS12 manual for the complete li sL

DO

CE CC

"

Fast context saving in task switching エゥュ Hャ@ operaTing systems In many appl icati ons, stich 。セ@ mu ltitas king イ」。ャセ (RTOS). Ihe CPU bri ngs in ッョ セ@ lask (job or process) HI a lim e :md CXOCU les il

ClIi\P"I'ER 1.1: INTERRlJPT PROGRAMMING IN ASSEMBLY AND C

385

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Enmple 11-14

vu lue i f we want \0 assign the highest priori!)' 10 SC10 (a) Show Ihe HPRlO イ セ ァゥウエ・イ@ (SeJiul Com 0). Then (b) discuss what happens if SCW, IRQ , and Timer Channel 7 are actiV3U:U at the same time. Solu tion: (a) Accord ing \0 Tab le 11-4 we must have HPRI O '" $D6 (b) Step (a) assigned a highe r priority to SCIO than the Dlhen;; there fore , when the SCIO, IRQ, and TirnerChanncl 7 inlerrnpls are activated at the same lime, the HCS12 services SC IO firs! , then it !;efv ices IRQ. then Timer Channc l 7. This is due 10 the fact Ihal SCIO has a hi gher priority than the olher two because o f Step (a). As a resull, Ihe sequence in Table 11 -4 is fo llowed. whkh gives a high er priority to IRQ over Timer Channel 1. lC1 0JC It moves to Inc ョ ・ セ エ@ one. m execulmg eaen laS , " 'D ICn ャsoQセ Giャ@ orgunlzeu :m un interrupt st'JVice ro utin e, lICceSS 10 all the resources uf lhe CP U is cri liUlI in performing the lask in a rimely m:lnner. II is the job of lhe progmmm ers 10 make sure the enlire conlenl s or the CPU urc SIlved 00 the stud before exa;u ti on of the セGiQ i s@ be fore switchi ng 10 u new lusk is called new エ。セ ォN@ Th is セ ャv ゥ ョァ@ of the CPU 」ッョャ comexr saI'ing (or comal swirclring). The use of the stack as a plllCe 10 save the CPU's contcnlS is tedious. lime consumi ng, and slow. Fur thi s reusen some CPUs such as x86 mi croprocessors have instructions such as PUSHA (Push All) and POP" (Pop Al l), which will push un d pop ull the main regislers 011(0 the stack with a sing le in struction_ In the HCS 12, each task gL"I1 l,.ally nLuis Ihe key rcgiSll"JS o f A. B. X. Y, CCR. and so OIL For Ihm イ セ。ウッョ@ the HCS 12 aUlOm acicall)' saves these rcgislen; un stack when un in terrupt is オセQ ゥ カ オエZ、 L@ This wuy, these key rcgisl c.-s of the main lask arc saved intemally_ To restore the orillina l cOllt ems o f these key reg islers, \I'e use Ihe instruclion " RTI " instead o f " RET' at the end of Ihe ISR.

Interrupt latency The time from the moment an interrupt is activated 10 the moment the CPU starts 10 execute the ISR code is ca lled the inlerrupllalency_ Tlu s I:l!en Hnclude :2 101

II

1011 +12

OFF"

11 x2 " 12x2 13

12 >< 214

14 x2 1S

15x2 13

IS ;.;2 14

15 x21S

14 x2 16 15 ;.;2 16

16>< 215

16 >< 216

0111 +81 1000(+9

OFF· OFF"

11 00(+13

OFF*

12 >( 0.25 lOS - 0.256 ms. ThaI means RTI can pcrfOffil its action at mte of every 0.256 ms. b) If RTlCTL=< 0 1111111, we sel 16x 2 16 x 0.25 1'5 = 220 " 0.251'5 セッ ュゥ@ That JIlcallS RTI call perfOlm its acliOIl a\ the rate of every 0.2621 44 second s.

= 1.048.576 x 0.251'5 = 0.262144

I I-I I XTAL

RTlCTL

Rll causei an interrupt at thSR '"'

COUNT COUNT

wセ@

cセa@



'" "

OVER Lセ@

wセ@

  oセr@



ORG

 



"HI

; inc r ('IDnn1: thn CO UNT ;A _ COUNT lis it 2 s7 (6 x 0 . 262144 sl l i t not clear RTIF and return ;get the last value ; toggl e bit 4 ; sto r e the new value ;displtly on FQRTB

1'11000100 00 TE}of'p STAA roRTB OCR COUNT BSET CRGFLG.'U OOOOOOO ;clear RTI F ." ; return from interrupt EORA Lセ@



; load RTICTL r C9istcr

; cle a r the TEMP r eg i ster ;clear COUNT BS ET DDRB,%OOOlOOOO ;rnal< p.... " i, 270 1.11"

3.

a「ャNM

jWセ

セBエャ

セ@

[ G@

00_ Ui RAM

ACC

rogram 12-4. Program 12-4C ShOll'S keypad programming in ll CS I 2 C.

CH .... PTER 12: I"C IlAND KEYROA RlllNTERFA crNC

423

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

GrOl6ld all rows

Read ti ll columns

Read all (Xllulm$ 00

".

00

L __(!: II ke)'$

row?

,..

o pen?

,..

Find which key is pressed Read a ll columns

Getswn code from table

,.. '---_ _ ,(

Wail for dabounce

Read all oolumns

""

L _ _セ

Fit,: Iln \2-7. FID ... 」ィセイ

GB@

ャ@

"' rur

p イ オセャQiN

ュ@

12-4

Return )

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

12 - 4 :

[ pセアイ。ュ@

keypad programming using pol l i ng

T セ T@

;1 5106 de l ay h i gh b y te of val ue

D1 5mH EQU 17

Dl SmL EQU 2SO ; l ow byte o f value COLS EOU PORTB; keypad columns ROWS ROWO ROW' ROW' ROW)

EQU PORTA; k eypad rOlol8

EOU EQU EOU EOU EOU

COW

fo, r owO fo, r ow l f o, row2 fo, r ow3 %OOOO l l l l ; col umn mask

%1111 1 11 0 ; mas k %1111 1101 ; mas k %11111 01 1 ; mask %1111 0111 ; mas k

,, ,

KeQDED

;reg i sters fo< ISms delay OS . S OS . S OS . S DC. S ' 123A' i ROW 0

DR15mB DR1 5m1

PDELAY KeODE l

oc .s

KCODE2

DC . S ' 78 9C I ; ROW 2

KeODE3

OC . 9

, code

• 456B ' h

; ROW 1

0' 0 ' ; ROW

)

section ORG

ROMS ta rt

Entry ;

LOS

t RAMEnd+l

; in i tia l ize the stack poi nt e r

LDM '$H S'rAA OORA STAA DORT

; PORTA Output ; PORTT-output

LDAA '$00 STAA DORB

Kl :

eLR ROWS

; PORTB I nput I q round all [0101$ at once

LOAA COLS ; read all col. ensure keys are open ANOA ' CO LM ; mas k unus e d b it s CMPA 'COLM K?,

BNE Kl

; wa i t

CLR ROWS JSR DELAY

Z\j

LDAA COLS ANDA tCOLM CMPA tCOLM BNE OVER BRA K2 OVER : JSR DELAY LDAA COLS ANOA tCOLM CMPA tCO LM BNE OVERI BRA K2

until key releas e ",11 ro",s /'It 0"CI1SOf S. In Ihi s c ha pler, we will explain how the ADC sect ion of the 12 works. We will also show the interfaci ng of >CI1sors and diocuss the issue of signal oonditioning.

lies

SECTION 13.1 : ADe CHARACTERISTICS セ M エッ M 、 ゥ ァ ゥャZj@ COTIThis sec lion will e.'\p lore the A DC dmraclCrisl ics of uャオッ chips. Fi r.>l, we desc ribe some gencm! オNセ ー・」 エ s@ o r lhe ADC itse lf, then examin e the serinl ;md parullc1 ADC chips. カ・イQ

セNLM

ACe devices AImIn g-to-digita l conven ers are among the most widel y used device:> for data acquisition. Digital computers uoe binary (discrete) vulues. but in the physi cal " 'orJd C'Verything is analog (cont inu\lUS). Tempera ture, ーセウ ウオイ ・@ (wind or liquid). hum idit y_ ami velocity are a few examp le!; o f p hysical quanlities that we deal wilh every day. A physical quanlilY is converted 10 electrk al (\'olla ge. currenl) signals us ing a deY ice ca lled a transducer. Transducers are also referred 10 as $/t!rsion time is defined as tbe time it lakes tho: AOC to conll(Tt the ana log inpul to 8 rl igita l (binary) number. The convCfsinn time is di cla l oo by the clock source connC\:tcd t(l the AD( as well as the method used for data convCfsion and tuhnol ogy usco in the fabrication of the A DC c hip such as "'l OS or TTL trehn(llog)'_ vセL@

V,cf is an input voltage オNセ・、@

for the referen ce voltuge. Th e voltage con-

nec ted to thi s pi n, a long wi th the resol ution of the AOC chip, dictate the step size. For un 8-bi t AOC, the s.t ep size is V,cF'256 becau se it is un 8-b it AOC, tuul 2 to the po wer o f 8 gives u:; 25 6 steps. See Table 13- 1. For exumple . ifthc lIIl:Ilog input runge needs to be 0 \() 4 voh s., V ref is connected to 4 vo lt s. Th at givt:S 4 V! 256 = 15.62 mV for the ウNエ セ Bp@ size oftm 8-bit A OC. l n 。ョッエ ィ セ NLM case. if we need 3 st ep size of 10 m V for an 8-bit AOC. tJu:n Vrcf= 2.56 V, bL'Gluse 2.56 V!256 = 10 lilY. For me 10-bit A DC, if Vr l = 5 V, then the

ウ エ セ Bp@

size is 4.88 mV as show n in Tabl e 13-

Table 13-1: V"" Relation to VI. Ran ge lo ran K-biIADC Y in Range (V)

\' r ef (V) P

セU@

5.00 4.0

sエセー@

Sin (IIIV)

Pセ

5/256 T@

41256 31251.

19.53 15.62 II .? 1

3.0 oセS@

2.56 2.0 1.28

o \() 2.56 o \() 1.28

2.56/256 (0 21256 ?8 1 128/256-5

1



1/256



セ セ

R@ ャ@

C H .... PTER 13: .... DC, DA C , AND SE: NSO R INTE:RFAClNG

3.90

435

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Table IJ-J: V...,/ Relati on 10 VI"

r 。ョセ@

f or an lO-bit ADC

\' I'd (V )

Vln Ran ge (V)

Step Size (mV)

4_"

5.00

U 10 5

5/ 1.024

4.096

oh.J4.096

4.0%/1 ,024 - 4

3_0 2.56

o to 3 o to 2.56

2.048

0102.048

3/ 1.024 - 2.93 2.56/I,U24 - 2.5 2.04S11.0:24 - 2 1/ 1,024 - 1.25

128

0 10 1.28 1.024

o l(l

1.024

1.024{1.024 - J

I. Tab les 13-2 und 13-3 show the relationship bclwccn V",rand step size (onlle 8ood IO-bit AOCs . resplll\tivcly. In some inpu t uppl icati ons. we need the differential reference voltage where vGセヲ]@ V",( (+) - V",r (- ). Often tile V",d- ) pin is COIl ョセGゥZ

ャ ・、@

to ground and the Vref (+) p in is used as the Vref.

Digital data output

In an S-bil AOC we have an S-bi! digital 、NセエZャ@

olllflU! of 00- 0 7 while in the

H)-bit ADC the data OlJlput is 00-09. To calculate the output vo ltage. we usc the foll owing fonnulu'

v. step s;:e

where Dro , = di gita l dutu output (in da.i mul ), Vin = unulog inpm vollage, und Slep size (resolution) is the smolleSl change, which is V,..tl256 for on 8-bh ADC. See Exumple 13-1, Thi s mI la is brough l oul of lhe AOC ch ip eilher one bil ul u lime (st.-rially), or in one chunk , using a purul1cl line of ッオQー オエセ N@ This is d iscussed nex t Ellllllpic 13-1 For an S-bil AlX. we have Vref - 2.56 V. Calc ulate the DO- I)7 outpul if the analog input is: (n) 1.7 Y, and (b)2.! V. So lu tiou : Bcl:ause the step size is 2.561256 - JO mY, we have Ihe following: (a) D"", - 1.7 V! lO mV - 170 in rlccim al. whi ch gives us 1010 10 11 in binary fo r

07- 00.

(b) Do... == 2.1 Vll0 mV == 210 in deeimnl , which gives us 110100 10 in binary for 07- 00. ParaHeI versus serial ADC Th e ADC chips are cil her parallel or serial. In a rmrallcl ADCs, we have 8 or more pins deMA3

"'

C", AGND

CHO

CS

""""" Dl!MAl D2IMA2

AOC 0848

"'-

www.fut ureerc.com

D' 1N'"

WR CS AD

SCLK

VDO

MAXI112

C",

REF IN REFOIJT Din S'R"5N SSTRB

DOVT f---

Figu re

iセN@

MAX l lll Sn-iaiAUC mock Llias:ra m

leI·in-serial-out slJiIl register responsible for sending OUI tlle binary data one bit at H time. Th e 00- 07 data p ins or lhe 8-bil/\ OC provide un 8-bi! paral lel dmn path between the AOC chip and the CPU. In the ca f;C o r lbe 16-bi l pam lle1 AOC t:hip. we need 16 ーゥャl セ@ for the data path. In order to SIIve pins. many 12- and l6- bi t AOCs 1J!;e イゥョ セ@ 00- 07 to sen/I 0111 the uflpo....- IInrllower ィ ケ イ・セ@ /l f the hi nnry dlll,,_ In recent )'ears, for lllany appl icat ion s where space is a critica l issue, using such II large nu mber o f pins for data is not feasible. For Ih is rcason , serial devices such as the serial AOC 。セ@ ba.:omi ng \\'iddy used. Wh ile the serial AOCs US( fewer pins and their smaller packages take much Jess space on the prin ted circu it board. more CPU lime is lll:\.'ded 10 get the con vened dua fmm the AIX' because thcCP LJ mUSI ge( data Olle bit a( a time. in stead of in o ne single read operali. (a)ADC0848 (b)MAX 111 2 5. Fi nd the slep size for an 8-bit AOC, if V!d - 1.28 V 6. For question 5, ca[cuJm e the DO-D7 OUlput iflhe anal og input is: (a) 0 .7 V. and (b) I V.

43'

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x. com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

DAC

V,,"

(Digital-to-Analog

oon ...erter)

Analog Input Vol tage

- [>

Control

r-

Successive Approximation Register

11111111 Binary Ou tput Voltage Figurt'

Q SMセN@

Succcss!veAp pr oxlmatl"n AOC

SECTION 13.2: ATD PROGRAMMING IN THE HCS12 B«auoe th e AIX: is widely used in data acquisition, in re.:ent years an increasing Ilwn ber of micrQwntmllers have an on-c hip ADC pcriphcrnl. jusl li ke ti mers and UARTs. An on-chip ADC el iminates the nero for an externa l ADC COII-

IItt lioll. which leaves more pins for Olhe r 110 acti vities. The majority o f the

J-Ies 12 chips come with 8 channels of A DC , and some !-Ies 125 have as Dlally as 16 channels of AIX. The Freesea!.: HeS 12 li te rature uses the ATD (analog-lo-l.1 AT D Power down in Wail mode N@ I = Hall convef1lion a.... p'Pt.":; o f sensors such lIS ligh t and pressu re sエN BiQウッ イ セN@

Temperature sensors Transducers eonvcn physkal data such a s temperature, light intensity, flow, and spred to ekclli cal signa ls. DCf'Cnding on the Iransrluccr, the output pro、 オセ」 、@ is in the (onn of voltage. current. resist ance , or capacitance. For ex ample. temperat ure is C(lnvCi1ed to electrical s ignals usi ng a tron>duccr called a IhennUlor. A IhcmliSlOr responds to ICm perature change by changing its rcsiSl nncc, hut its response is not li near, as seen in Table 13-6. Th e comp lex iry associated with | セ tゥ ャ ゥョ ァ@ so fl w:l1"e for SI tch nonlinear devices ィセ セ@ led man y manu facturers to market a linoar temperature sensor. Sim ple and widely usccod data 10 Ihe DAC 10 gent:rnte u ウャ オゥ イ

M ウ ャセGp@

rump.

So lu tion : I $ FF , DDRB IO , PORTB moセ@

moセ@

AGAIN

m

,'-' '64

Ic ount from 0 to FF H, se nd it t o DAC

m CA 'TAA

; roRTB II" ou tput ; c le a r PORTE

イッセL@

DELAY AGAI N

; le t

DAC r e cover

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Tab le B-IO: Angle nUll s Voltage Magnitud e fo r Sine Wav e

a

Ang ll' (degrees)

V ou t (Vo ltage Uagnilude)

SinO

v。ャオ・セ@

Se nt to DA C (d I'C imal) (Voltage Ma g. )( 25. 6)

5V + (5\'1< sinO)

integer val ues represent ing the voltage magnirude f(lf each angle (with )O-degl"«' Increments). To generate Table 13- 10, \\'C ass umed a fu ll- scale voltage of 10 V for DAC output (as designed in Figure 13-23 ). I'ull-scale output of the DAC is achieved whcn all the data inputs ofthe DAC arc HI GH. Therdore, 10 ac hieve the full- sca le 10 V output II'C us'I'ER 14: ACCE SS ING FLAS II AND EEI'ROM. AND I'AGE SWI'I'C HLNC 475

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

; copying data from code RO M to data RAM locations ORG PAGE_ 20S tart COPY _ DATA

LOX

1$8500

; load p ointer . X ·

$8500 , ROM address

; load pointer . y . $860 , RAM address LDY '$860 LOAA f CN'rVAL STM COUNTREG B5 LOM 1 , X+ ;get the byte f rom Flash , incr. pointer STAA 1 , Y+ ; save it in RAM and increment pointer DEC COUNTREG

BNE

B5

;keep looping ; return ; calculating checksum byte RTC

ORG PAGE _21Start CAL CHKSUM

toM fCNTVAL

STAA COUNTREG; load the counter LOX 1$860 ; load poin ter. X - $860 , RAM address e LRA [ aセo@ B2 ADDA 1,X+ ; add and increment pointer DEC COUNTREG:decrement the counter SNE B2 ; loop unti l counter =c zero

NEGA STAA Q,X

; 2' s camp of sum ; save the checksum as the l ast byte RTC ; return ; testi ng chec ksum byte ORG PAGE_22Start TES T _ CHKSUM

SSE! DDRB,%11111111 1DM tCNTVA1+ I; add i ng 5 bytes a nd checksum byte STAA COUNTRE G; load the counter 10X ' $860 ,l oad poi nter . X '" $860 . RAH addr ess CLRA

B3 ADDA 1 .X+ DEC ountreg B3 BNE CMPA to BEQ G_l LOM t ' B ' STAA PORTB

; 1>..-0

; add and increment poi nter [ 、Y」イセョエ@ th9 count9 r ;l oop until counter· l Ooul pr O!:rllUl HBイ ィ セI@ I セイャエGゥ・@ i ィセ@ fi セ U「@ untU ..-c " ril e 10 Ih b H-gbler. T he FDt VLU lei. u. l", uw if l hh r "l:;"ler 11 3' エN」セ ッ@ Bイゥ H セ ッ@ lu. 2) For th e p urpose of on -chlp f ャ セウ ィ@ l iming, t lK' h us doc k ca nn OI he less th .o 1 MHz 3110.1 (be セ M i セ Lil@ doc k mu, 1 be in III " イ セョ」@ of 150 kHz- 21JO kHz. O l lLtr"-;"". too prog ra m H キイゥ ャセI@ l e raseof Flash " -i ii rw>t wo rk セ ョ 、@ il c. o セ|B・ ョ@ d amage th e N ᄋ i セ Lィ

N@

A conlbina tioo of I' Rut 10'8 a nd F UI カセ@ bi t, a,.., u..,d 10 ott l be tim ing of i セ ウャ {proZGエ ャ@ tu Ihe nnge ur 150 kHz- 201l kHz.

S セ@



セ ャァ

オイ

・@

14-7. FC L KDl V (Flas h Clock

d ィ ゥ 、 セI@

Register

Usin g FCMD we can perfnrm Inc fo l1nwing actioo s 00 the

fャ

。 セィ

セ@

a) Emsn Verify. Thi s ensures tha llhcre is nn data io a given FL1Sh lncalion before we wri le new d.11a_

CHAPT ER 14: ACC ESS ING FLAS" AND [E P ROM, AND PAGE SW ITC IHNG

479

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

  

C MOS CMDB bils are usod \0 perform the fol lowing IlClions:



vセ

イゥヲ

ケ@

$05

Erase

$20

Word Program (\\'rilCS 2 bytes ro an even address lOi.'ation.j Sector e イセBL@ H s・ セlqイ@ セ ゥコ ・@ vari e. frum drip !oJ dtip.)

S40 $41

Mass Erase (Block ErRSC. Block size varies from cllip 10 chip.)



;\'o(e:



In HCS 12Dx256 the セ ゥコ・@ o f a block is 64 KB and It.: s.:ctr size is 512 B. In lies 120.:5 12 the 5;"" of a bl ock is 128 KB and !he seclOr 5i." i. 1,024 Il.



Figu re 14-8. FCII1D (Fl ash Co mmand) Regi ster

  

b) To write (prQgram) 2 「ケ ャ セ@ of da ta to a given address location , The address location must bo: an even address. This is the option lIsed to program (write) new data to Flash after it has been erased. Notice, we can wrile only 2 b)1CS at a tim e. c) Erase a SC{:tor of Flash. The sector size varies among family members,

is shown in Table 14-4. For example, in the fltC9S12Dx5 12 the sector is 1,024 b)1CS.

     

d) Erase a block of F1ash. In the II CS I 2, several pages gfOl.lpcd together arc rcfCtTOO 10 as a Nnd. For examp le. in th e MC9S12Dx5 12. a bloek is cqlmlto S pageso f 16KB, which gives us a block ウゥセ@ of 128 KD. Sec Figure 14-9. That means. in the M C9S I Dx5 12. there are fou r blocks. They 。 セ@ numbered as bloc ks 0 , 1, 2, and 3_ To crase セ@ block of Flash memory, we need to know the b lock number. The FCJ\TfG (Flash Configuration) registCT is used 10 identify th e block number we want to crase_ For details of the FNCFG register see the MC9S12Dx5 12 manuaL Block stora ge devices li ke erasing is ideal lOr using Flash in arrlicarion s such as ュ 。ウMセ@ memory Slick dri ves or MP 3 players_ The only problem with too HCS 12 Flash is the ""

Fl gun' 14-9. MC 9S 12DxS12 Bl oc k SI2t' p ·l odlfil'd for C ianI )' )

I CBEIF I CelF

POVL I Aa::ERR

I

0

IBLANK I

0

o

C 8 1':1F Command Buffer Empty l nlcnupf F lag J - CQIl1IDand 「オヲセウ@ are ready to ao::cpt a new commarKl

0 = Command buffers are full ce ll' Command Completion

nag

I .. All oomma!ld;; art colt\flleted o - Command ;s in pmg"'ss I'O\,L Protect;"n Violation 1 .. Pro(ooion viollllion has occurred.

0 = NQ protection violation has oo;curred ACC1: I{K Fl.."h A0: 1 of rlala to the Fl ash memo ry (1) r..lakc sure that the FDIVLD bit of the FDlVCL K reg ister is sct to high

(FDIVLD = 1). The HCSI2 tw iners nOO11ally do tha1.lI !so muke sure CBEIF= I. Th e CHEIFi s rOrl of the FSTAT rcgissc r. (2) Write a word (2 byt es) of duJu and its f ャ。セ ィ@ memO!)' address location. ュオセ@ be un even address. The datu is kept in un inlCmal butTe!" until

The mWrcss

you follow the TlC xt two steps. (3) Write the vulue $20 (0 the reMD regislCr. Th e value $20 is the program

option in Figure 14-8. (4) Wrik: the value S!lO to the FSTAT reg ister. Thi s will lrunsfer (wri le) Ihe dulu from Ihc in leffil l 「オャヲセ イ@ 10 Ihe Flash lIll less Ihere is u prob k-m. Problems can oc;(;ur a) jf ll" e try to write 10 a sec ure area of Fi3sh (indicated by the PV IO L flug ) or b) Fl ash is nol accessible (indicat noI pmu:cted a", e"",bled for prQKram or era'"e. 0 - The whQle E EPRO M arn.y is pro!ected.

:\'V I6:41 Non_Volatile flag bits These throe bits are avai lable 10 the IIscr as nonvolatile flags.

[PotS EEPROM Pr01«tion address mllge Disable I ., PMection disabled 0 - Protection enabled .: 1, 2 :01 E EPRO M Protection addres- 5;7.e The EP[2:0] biLS 、N・イュゥョセ@ the size o f

000

SFCO-SFFF

エィ

セ@

001

$F8o-SFFF

IUbyres

010 011 100

SF4Q.-SFFF SFOO-SFFF SECQ.-SFFF

192 byte. 256 bytes 320 byte. )84 byteJ 448 byte s 511 bylCJ

101

SE8Q.-St;FF

110

SE40-SF1'F

IJ 1

SEOI)-SH'F

protected seo: of die FCLKDlV register is optio na l. 4 . Troc or fal>e . In sening the dock for EEPROM, thc use o f the ECL KDIV reg ister is op tional. 5. Troc or fal>e. Upon rcsy-!I preS\: ak,". The bus clod< i. divilkd by S lxforc it is divided ilj:ain by the FDIVK biLS. Q = 1'111' l>us clock is divided by tho: FDIVx bits. See l>\:\Qw. FD VIS-- F D]\'0 Fisoh clock divider bilS

BUYS FVl V4 FU1 V3 '-':)1\'1 fut V] f l)lW 0 0 0

0 0 0

0 0 0

0 0 0

0 0

,

,

0

0

clivid\: by 1 (FDIVx + 1) divide by 2 divide by 3

divide by 32 (FDlYx + 1) :\OICS: I) キ セ@ l.,.,,,,,,t 11' 0\:'''''' ("rit e) I er'" t til " rl a,1I u n til ..ᄋ セ@ .. rit e II) (h i!. rl'l:;, je r. The FD V I. D Itt. liS k rm ... i flh i. ' egiol .... ha5 h ""n •.-rittrn 10. 2) Fur th e p urp usc of "n -chip FWsll 11m In\:. t he b us d oc k cannot ill' 10'" lha,. I M liz and the セ G iオ ィ@ doc k must be in tbt イ 。ョセ」@ of 150 k1IL-200 kilL.. o ャ ィッイキ[Lセ L@ ,"" ーイ ッセ イ。 ュ@ (.n ile) i セ イNウ」@ uf FI. slt "lli lUI' wurk lI od II ea,' セョ Gッ@ d.mHI:C Ih!'

•·.... h.

3) i\ ro mh lna rl oo of PRO IV8 a nd FOI VJ hi lS are !!sed 10 set , lie l im in g of Flash 10 I "" イkャQセc@ of 150 ォ h セ@ - 200 ォh セ N@ fャ

ァ オイ

セ@

14-17. FC LKDlV (Fla sh Clock Divid e)

r ャGァ

ゥ ウ エ セイ@

Eumpl e 14- 1 For an HCSI2 -ba!iCrl system, we ha ve Fo,.; - 4 MHz and I'bus - 2 MHz. Fi nd the val ues for the FCL KDIV register if we wall! the I'CLK to be in the 150 kHz- 200 kHz range. Solu tion : From Figure 14-IS. we have the follo wing: I) Fbus - 2 MHz. whi(h is greater than I MHz. In other words Thus - 112 MHz - 0.5 セ オN@ which is less than II'S. 2) Fo>c - 4 MHz. It is less th an 12.S MHz , therefore we make PRDI VS - O. Thai means PR DCL K - 4 "1Hz. J) PRIX'LK)( [5 + 0.5 I's1 - 4 MHz)( 5.5 セ オ@ - 22 is an integer. Therefore FDIV5-FDIVO values are set al 4 MHz)( (5 + 0.5 IJs) - I - 21 or 0 10 10 I in binary. 5) FCLK - 4 "1Hz I (2 1 + I) - 4 MHz 122 - l SI kHz 6) FCL K - I S I kH z is > 150 kHz. Also 1/(1 8 1 kHz) + 0.5 IJS - 5.5 IJS + O.5 IJ S - 01'", which is gtealer than 51Js. Therefore we set the FC LKDIV register to 00010 10 1 in binary or 15 in hex. CHAPTER 14 : ACC ESS ING I'LASII AND EEPRO;"l1, AND PAG E SWITC IlL''' G

499

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca



)

"'"



00



Thus セ@

Qセ



(

D_@

Program I Erase Impossible

yoo PRDIV8 - 0 (resel)

 

00

OIicilator dock > 12.8 MHz?

 

yo.



I I PRDCLK = oscillator clock I

PRDIV8 - 1 PRDCLK = oscillator clodl l8

I



).



PRDCLK[MHz] セ@ HUK t an irteger?



「 セ

00

L }I@

yo;



FD IV[5:01- INT(PRDCLK(MHz) •



FD IV[5:0] = PRDCLK(MHz]

x HUKt「オウ

ャ セウャ

I@

HUK

t 「セウ

- ,

 

I

TI'y to Oea-&*e Th.J$

FCLK - (PROa..K) I (1 + FDIV[5:0])

 

1 1 FO-K]MHz] +

t「オウイセャN_@

5

y"

ood



Feu< Z!. O.I5MHz

?



( pイッ

セ。ュャe

イ。ウ・@

-

Impossible

h-- ,: uIY 14-111. P RUI V8 a llli FDl V Bll s





FDIV[5:1lJ2:. 4? 00





0"

".





)

SlKJ

d・エセ

ョャ

。 ィ

) HI Q@

iG イッ」 セ、 オ イ・@

'''''

ィjウャ

I@

www.fut ureerc.com

Page: 1

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Exampl e 14-2 For an HCS12-based syste m, we l13ve Fose - 16 MHz and Fbus - 20 MHz using PLL. find Ihe va[kleS for Ihe FCL KDlV register ifw.: want FCLK I(l be in che 150 kHz- loo kHz

range. Solullon: From Figure 14-1 S, we ィ。セ G」@ the fol lowi ng: I ) Fbus = 20 MH z, which is greater (han 1 MHz. In OIher words Thus = 1120 MHz == 0.05 liS. whi ch is less than I ,",5. 2) Fose = 20 MHz. It is more than 12.8 MHz, therefore we make PRDIV8 = I and PRDeLK = 20 MHz18 = 2.5 MHz. 3) PROCLK x [5 + 0.05I1sl - 2.5 MHz x 5.05 liS - 12.r;25 is 1101 an integer. t ィ・イヲッセ@ f DI V5-FDI VO va[kleS セ@ set at 12 dttimal 01"00 1100 ill binary. 5) FCLK - 2.5 MHz I ( 12 + I) - 2 MHz 11) - 192 kHz 6) FC LK- 192 kHz is > 150 kH z. Also 11(192 kHz) + 0.05 flS - 52 IlS + 0.05 flS 5.25 flS, w hich is greater 111.111 5 fU_

Therefore we

SCI

(he FCLKDlV registCf to 01001100 in binar)' or 4C in ィ」セN@

IEDlVlD I PRorvs l EDlVS I EDIV4 I EDTV3 I EDTV21 EOrvl I EDTVO I EOIVLD EEPROM lock diviok, lca 150 kH z. Also 1/ 192 kHz + 0.05 fl S - 5.2 fl S + 0.05 fl O5.25 fl 8. which is greater thun 5 fl 8.

Therefore we

SL1

th e EC LKDIV register \0 01 001 100 in binary or 4C in hex.

CHAPTER 14: ACCESSING FLASII AND EEPROM. AND PAGE SWITC IIL"G S03

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

PROBLEMS SECTION 14.1: PAGE SWITCHING O F FLASH MEMOR Y IN HCS ll I. What is the di fference betwccn lhe 64 KI3 memory space and 512 KB of Flash memory in the I'I1C9S11Dx5 12 chip'! 2. Troe or false. In Ihe I-lCSI2, any melllory spac e beyond t;4 KD is olT-chip. 3. Troe or faloe. To access the memory beyond 64 KI1. we must use page switching. 4 . Troc or false. !'PAGE is an 8-bit regis ter. S. True or falsO use relays nnd OpfoisolalOl'S. This c ha ptCf d iscusses motor control and shows

HCSI2 inlcnacing with rclays. o plOiSOlalOrs, and ' lgJpo:r motors. We use both Assembly and C in our program ming cxampleL1tor ィ。 セ@ an LED (li ght-em iui ng diodc) lransminer and a pholO sensor receiver, separated from each other by u gup . When (."UrfL"Il1 fl ows through the di ode, it tmnsmi ts;1 light signa l :lc ross the gap lind lhe rece iver prod uces the !;;Ime signu l "'ilh the !;;Ime phase but n differenl currenl und nmp lilude . Sec Figure 1j- j. Oploiso lmoTS UTe nlso w idely used in com municuti on eq uipment such us mode ms. Th is device al lows a compu ter 10 be conneclL"d 10 a telephone li ne without risk of da ma.ge from power surges. lllc gap between the tmnsm iucr lind receiver o f oploiso lal ors prevents the elelo1ricuI curre m surge from reaching the Systlo"Ill.

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

ilWセ@

flgu re

ャ セN@

ャ lPWセ@

ILD 74

OPTOISO LATOR

OPT()SOLATOR

Op to lsolalOr

p。セ

ォ 。セ・@

www.fut ureerc.com

OPTOI$OLATOR

Eum pl es

Interfacing an optoisolator The optoisolator comes ill a smail IC package with four or mort' pins. l 11ere are 31>0 packages thai contain more than olle optoisolator. When placing an opto iso lator between Iwo circuits. we must use !II'O !;t"parate voltage sources. one for c och side, as shown in Figure 15-6. Unl ike relays. 00 drive rs need to be placed Ixtw«n rhe mic rocontroller/digital output and the oploisolmors.

ILD74

OPTOISOlATOR

HCS12

-"

, ,

PIlO

±, '"



,

,

7_( セ@

,

セM "in an



• ,

,

'5V

I,; ure 15-6. Con t rol'i n a Lan1

+1 2V

r'-



10;';0191 r

C IV\PTER 15 ; REL W, OPTOISOLAI'OK.AND S rEI'PER MOTOR

セ@

lamp@

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Review Questions I. 2. 3. 4. 5. 6.

Gi ve one application where would you use a re lay. Why dQ we place a driver bc'\ween the microc olltrolJ er and the relay? What is an NC relay? Why are relays that u.o;e coils called electromechallical fela)'s'! What is the advalHage of a solid-state fda y over an EMR'! What is the advalHage of an optoiso lator ol'er an EMR ?

SECTION 15.2: STEPPER MOTOR INTERFACING This scelion beg ins with an OVClVicw o f the basic opcrmi on of >leppcr mOlO I'S. Then we describe , _ _ _ _ _ _ _ _---,_ _ _ _ _ _ _ _----,

how 10 interface a SICPf'Cr motor 10 the HC S12. Finall y, we usc Assemb ly lan guage programs 10 dcmonslratc con-

A

1m! of lite anglo and direction o fslep\x-'J mOlor rolal;on.

Steppe r motors A STepper motor is u widely used device 1hm (runs-lales electrical ー オ ャ ウ」セ@ into mechani cal moveme nt. In app lica tions s uc h 。 セ@ disk drives, dol matrix printers, and robot ics, the stepper motor is used for position control. Stepper motors CO lll-

B

lIIonly have a permanent magnet rowr (also CllJled the shafl) surroundeon thai using the ULN2003 is p11'femb1c to the usc of tmn siSIOTS as drivers is thut the ULN2003 has un ゥ ョ ャセGQ Q@ diode 10 hIke cure o f bud EM F, DS .B

BGセ@

,

.,

tSn", DORB

;loc 620H '0< ; pOr"t R out put

'$66

; load IItep IIcqucnce

FGRTB

; 1$3UO :lcqm:mC(l to motor ; rot a te ..-ight cloc kwise

"

cec WM

"AA CSAA

BACK

Bee OYER

'$80 cセ@

OVER

DE:LAY

"'

OS,

DELAY

;wai t

RM

MeK

;keep going

R2 , SFF

BGセ@

,;0,

""

"" "" "" "" "" "

ENEQ D1

'"

Change the value ofD ElA Y to sct the speed of ro tation . 5 16

"'"

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

., ._7k

HCS12

.,--

.-

www.fut ureerc.com

T03teppermotor

._7< ._7
d _ k l ' lI\8 ""512

., Fi gun- 15-9. II CSl2 Con ""N ion to Stepp er l\I"IO r

Steps per second and rpm relation セョ、@

The relation bclw(Xn rpm (rel'o lutions per minUle), steps per rel'o lution, SlepS pc r second is as fo llows.

SliPj per second -

rpm" Steps per rew/u/il,)tl

'--''''--''''''ii--''-''''-'-'60

The 4-step sequence and number of teeth on rotor The switchi ng sequence shown earlier in Tab le 15-3 is ca lled the 4-$lep swieching sequence because aller four sl eps the same Iwo windin gs will be "ON" .

How muc h mo\'ctllcnl is associated with these four steps? Aftcr completing every four steps. the rotor moves on ly one IOOUI p i!\:h. Therefore. in a stepper mOlor with 200 sleps per rel'o h.ll ion, the rolor ha s 50 teeth becau se 4 x.so - 20U steps are needed 10 complelC one rt'volmion. This k ad s to the conclusion that the minimu m step aIlg l.., ゥセ@ 。 ャB G。ケセ@ a function of Lィセ@ number of '",, ' h on the rotor. In OI h..,r words. ,h.., sma ller the step angle. the more teeth the rotor passes. See Example 1.5-2. eNセ。ューォ@

15-2 G ive the numbcrof times the four-step sequence in Tab le 1.5-3 mus t be applied to a stepper mo tor to make an !(O-degroo move if the motor has a 2-dcgrcc Slep an gle. SoIU l ion: A motor lI'ilh a 2-dcgrcc Slep angle has the following characteri sti cs: Step angle : 2 degrees Steps per revolution: 180 Number of rotor teeth: 4.5 Movement per 4-Slep sequence: 8 degrees To move t he roltl!" 80 degrees. I'.'e need to >cnd 10 oooseeutive 4-stcp sequences. bccausc 10" 4 steps x 2 degrees - 80 degrees.

C IV\P'J"ER 15: RELW, OPTOlSOL.AI"OK.AND S , TEPPER MOTOR

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Looking at Example 15-2, one might wonder what happ::ns i f we want 10 move 45 degrecs, because the steps arc 2 degrees each. To .111010' for finer resolutions, all stepper mo tors allow what is called an 8·step switching sequenc e. The 8-

step sequence is also calkd ha/f-$teppl"g, b::.. » »

UndersTa nd t.he Serial Peripheral 'n terfuci ng (S ri) protocol eクーャセゥB@ how' Ih e SPI read li nd wr lle ッー セイ 。Gゥオョウ@ work Examine the S I'I pins SlIO, SI)I, CE, and SCLK C od e progra ms in Asscmhly and C for SP I Explain how th e rea l-tilll e dock (RTC) chip works Explain the f unction of Ih e DSI306 UTe pills Explain the f uncti on of Ih e DS I3tt6 RTC rl1,:istcrs Understand the inll'f"facin g of th e USI3 I16 UTe to the HCS I2 C ode prtlgram s to di sp la y tim e and date in Assembly alll.l C

»

Explore and prol:r am lbe alarm and intfrr upt Ifat ures of the RT e

>:>

» >:>

www.fut ureerc.com

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Th is ch apler discus>cs the $P I bus and shows the interfacing and programmin g o f the D$13 06 Trn l-timc c lock (RTel, Il11 S P I chip. We w ill descri be the DSJ) 06 RTC's pi" functions and sho w its in terfacing an d prog ramming wi th the

HCS I2. Will usc both Assembl y and C for programs.

SECTION 16.1: SPI BUS PROTOCOL Th e SP I (Sl.'li ll i pl.-ri pherul in terfuce)

ゥセ@

1I bu s im erfucc conn ection incorpo -

mled into man y devices suc h as ADC, DAC, and EEPROM. In this section we exumine the pins o f the SPI bus lind show how the r c:.u1 lin d "'file opl:l"3l ions in the S PI work. SPlbu5

The SPI bus was origin ally , carted by Motorola Corp. (now Frc escale), but in TCCelll yeu rs has become u wide ly used standard mlaph:d by mun y sem iconduc tor chip compan ies. SPI devices USt: on l)' 2 pins fur data lramfer. ca lled SDI (Di n) ami S DO (Dou l) . instead of th e 8 OJ more pillS USL-U in trnd ilio[]3 j buses. T his reduction o f data pins reduces the paekage size an d powe r con sump tion drasl ically. m ak ing them id eal for m allY app lications in wh ich space is a major concern. T he SP I bus has the SC LK (shift clock) pin to synchronize the data tran sfer betw«n two chip s. The last p in o f the sri bus is CE (chip enable). \\'hich is used to initiate and term inate th e data tran sfer. T hese four pins . SD I, SDO. SC LK. and C Eo make the S PI a 4-wire inter face. See Figure 16- 1. T here b abo a widely used standard call ed a 3-wire illlt:rjalX bus. In a J -wire im erface bus. we have SCLK and CE, and only a single p in for data transfer. T he SPI 4 -wire bus c an hecome a 3-wire interface when the S DI and SDO data pi ns are lieTEI' - 1 is ・ ヲt・ 」エゥ B・j セ@ iWno.aI. 1 - SPI Dam Register empty 0 - SP[ Data Register IIOt empty Mode Fault tlag is used for mode selection error. Soo the HCS 12 manuaL M O O F D4 1 - Mode fault bas OCCUlTed. 0 - Mode fallil has not occurred . fャァ

オイ

セ@

16-10, SPISR SPI

s i セャ

キ G@ rセ

ャZ「

ャ セイ@

CH .... PTER 16: s ri PROTO COL AND RT C INTERFA C ING W ITIIII CS I2

533

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Steps in programming SPI In progranuning Ihe 5 1'[ of the HCSI2 10 (raJl$fer character bytes. the foJIOIl" inS steps must be taken: I . The SI'II3 R セァゥウエ・イ@ is loaded lI"jlh a value to SCI the baud rate. 2. The $PiCR I register is loaded wilh the value $5 4. indicat ing srI options. 3. The $PiCR2 register is loaded wilh the value SOO. This step is optional since the default value is 00. A lso send the value 00 10 the WOMS register 10 enable pull-up resistors on the PTP pon . 4. Monitor the $PTEF bi t or th.: s r i SIaI US Register (SPISR) to make sure s r i is

ready for a byte before writing another byte to S PIDR. If SI'TEF - I. then Ihe 5.

6.

7_ 8.

SP! Data Register is e mpty and can go \0 Ih e next slep. The charneler b)1c 10 be lransmin(d is written into the $P! Data Register (SPIDR). Monitor Ihe $PIF bit of lbc sri Sta tus Register (S PISR) to make sure the transfer is complete. Read the SPIDR ID clear the $P IF flag fDr the nex l roun d. To transfcr the next charoctc r, go to Stcp 4. E.'(ampl e 16-3 shows the program to tnms fer data via the SPI pin.

ElI:ampl e 16-3

Wrile a program for the HCSI2 to transfer the leiter "G· via the s r I pin at 100 kHz baud rate, oontimN.lusly. Usn $PJO and 3.% ume XTA L - 4 MH z, BusFrcq - 2 MH z, and CE is oonneded 10 ground. So lu llon:

Hl

OVER H2

Ln.o.A 1 $20 [セBGエ@ til.", baud r at'" STAA SPIOBR LllIU\ 1 554 ;no i nt errupt, S PI v. uter, active-H I GH $TAA $PIOCR I ; Loll ing edge SCI : Sil va CO, ;get CO, セL@ ; .'Iil Ve CO" dil t e ;get CO, mont h ; .'I /1V", th'" mont h ; g et CO, y ear Lセ@ ; s a ve CO" ye a r BCLR PORTB , mFORTB_ BIT1;ma ka CI;-O (e nd mul t i b y t a read) convert p a c k e d BCD t o AS CII a n d d isp l a y LDX t RAMSt il rt ; a ddre.'ls o f r e g is t e r s f o r t ime/ da te

""'" "" "M "" "AA '" " S>

'" "' '" '" '" "'" "AA '"M'

"" "M "" "M ""

54'

'" '" "" '" =

'"

d., "'y """

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

"

WM

.1

sm

CNT

; 6 bytes of data to display ;set up the counter ; get the BCD from RAM イ@ nibble ; mao k th e ャセ」 ; セィゥヲエ@ right to get uppe .. nibble

LDA ... O,X

tSFO

MOA

oセ@

"''' "" "" "" "" WM AND ... oセ@

1$30

OS,

TRANS

WM

t' : '

OS,

TRANS

'" '" LDA ...

Lセ@

OS, m

;m ilke i t an ASCII ; displ1l y the data

TRANS

1, X+ tSO F tS30

www.fut ureerc.com

;ge t BC D data once mo re , increment pointer ; m5sk the upper ni bble

;make i t an Asell, ;display the d has a lola l o f _ _ bytes ッヲャセ。エゥョウN@ G ive the 。、 、イ・ウセ@ for セ。 、@ and write opemlioru;. 30. Whal are Ih econtenls o flhe OSI3 06 lime and date registers if power to the Vee pin is lost?

31. Whal are th e contents of the gen era j·pu rpo>o: RA M ェ ッセ。エゥ

ッ ャ ウ@

if powe r 10 the

Veel is losf!

32. When does Ihe OS 1) 06 switch to a baU ery energy source'! セ。ャ ᄋ エ ゥュ ・@ dock (ti me) セァ ゥ ウエ・イ _@ 34. Whal are the addres>o:s assigned 10 the calen dar? 35. Which rcgistCf is used 10 SCt thc M IIPM mode? G i\'c the bit localion of that regis ter. 35. Which イ セァゥウエ・イ@ is used to Sltentimlaify lifl blank

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

CHAPTER 17 PWM AND DC MOTOR CONTROL

OBJECTIVES Upon co mpl et ion ofl h is chaptl" T. ),ou willlw abEl' to:

» >:. >:> »

>:> »

Oeserihe th e bas ic op eration ofa DC mot or C od e IIC5 12 prognlms 10 con tro l a nd opt'nlt e:ll DC m otor Ilescrib ... how P\VM iii usffi. lo control motor speffi C od e P\VM progr nm!i 10 control ond Ilperafe a DC m Olor Ilescribe th e PWM fea tureli of fh l' I1 CS I2 C od e HCS I 2 A!ise mhly and C pmg r:ams 10 creO le rwl'I1 flulse s

555

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

This chaplcr d i>cU 5SCS the topic of rWM (pu lse width modlilalion) and shews HCS 12 i nterfacing with DC mOiors. The ch aracteristics of DC mOIDn arc dist:hanica l movement. In the DC JIlOior we ha ve only + and leads. Cmllie.: ting them to a DC volt age source moves the motor in one d irtt liOIL l1y reversing the polarity. the OC motor will move in rhe opposi!e direction. One can eas ily experi mem with the OC motor. For example. Slllall fan... キ[セ^、@ in many motherboards!o cool the CPU are run by DC motor s. By ・ッョセAゥァ@ their leads CO !he + ruld - vo ltage sou rce. the DC motor lIloves. Whi le a stepper motor moves in steps of I 10 IS degrees. the DC mocor moves eom inuously. l n a stepper mOlor. if we know the s!arting posit ion we can easily eOUllt the nwn ber of seeps the motor has moved ruld calculate the futal JX1sitiotl o f th e motor. Th is is not possible in a OC motor. The maximum speed of a OC motor is indicated in rp m ruld is given in the data she.:t. The DC motor has 1\\'0 types of RPM : no- load and loaded. The manu facturer 's data sheet gives the no-load rpm. The no-load rpm can bo: from a few thousand to tens ofloousands. The rpm is reduced when moving a load an d it decreases as the load is increased. For examp le, a drill turning a sereII' has a mueh lower rpm speed than when it is in the no-load silual ion. DC motors also ha ve voltセァ・@ and eurrenl ralin gs. Th e nom ina l vo ha ge is the カッ ィ セァ・@ for IMI mot or lmrler normal conditions, and can be from I to ISO Y, depending on the motor. As we inerease the voh age. the rpm goes up. The currenl rating is the current consumption when the no mina l voltage is app lied wi th no load. and can be from 25 rn A to a few amps. As the load increases. the rpm is decreased, unless the current or voltage pmvirled to the mOIO!" is increased. which in tum increases the torqlle With a fixcrl voltage. as the load increases, the current (rower) oonsumplion of a DC mOIO!" is increased. If we over load the motor it wi ll stall , and that can damage the mOIO!" due 10 the heal gcncralcd by high eUlTcn! co nsum ption .

Unidirectional control f ゥ ァutセ@

(CCW) イッエ。ゥilセN@

17- 1 shows the OC motor 」ャッ・ ォ キゥセ@ (CW) and ooun terc lockw;sc See Table 17- 1 for sele.::ted OC motors.

Bidirectional control With the help o frelaysor ウッュセ@ specially design ed chips we can change the direction of the OC motor rotat ion. FigllJes 17-2 through 17-4 show the hasic oon556

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Ta bl e 17- 1: Selil'cted DC M ot or Cha ra cll'risli ts of I I-Bridge control of De motors. Figure 17-2 shows the セッ ョ ・|Zャ ゥ ッョ@ of an I-I-Bridge using simple sw itc hes. CHAPTER 17 : PWM AND DC MOmR COi\""ffiOL

557

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

.y

j

G

,

Lセ@

,

SWITCH

M r

li

swセc

セ@

}II' h@

セ@ セ -i ァオイ・@

17-3. II-Dndge Molor c

,

SWITCH

I

-

ャ ッ」ォ|オセ・@

,

SWITC H

CLOC KWISE DIRECTION

Cu nfigurallOll .y

j

sセイch@

;:J

)

,

SWiTOl

セB@

,

SWl TCH

,

SWITCH

I セNZ@

COUNTER _ a.O O0\

Iiturn on

J onto the stack. and the slack poinlt."f (51') is d«remented by 2. Then the prcgram counter is loaded with Ihe lIew address and comrol is 1r3ns fc ITL>tl \0 lhe su broutin e. At the end of the procedure, when RTS (rd urn from subroUline) is executed. PC is pulled off the stack. which セエ オイョ ウ@ COIItrol to tbe ill$lruclion after the J5R. Notice that JSR is a J-byte instruction, in which one byte is the opeode. aneth.: ol heJ !II'o bytes are the 16-bit addre,s oflhe target subromi ne. Aloo notice that we must uS( RIS (return from subroutine) at the ゥッョ N@ end of the subroutine if we use die JSR ゥョウャイオセエ BSR (bran,h to subrou tine) is a. 2-b)1e ゥョウャイオセエ ゥ ッ ョ B@ in "'hioh one byte is used for the opcode and the s«ond byte is uoed for the target subroutine reJati\'e address. An 8-bit relative address limits it 10 エィ セ@ カ。 ャ オセウ@ in the rang' of _128 to +127 bytes away from tile pcosram セッオャQ・イN@ Nolke that we must usc RTS at the end with the BSR. target address located in th, expanded (memory space beyond To reach エィセ@ 64 KB) pages of the HCSJ2, we must オセ・@ CALL CAL L uses rhe PPAGE register to access the pages of ex panded memory beyond the 64K 「ケエセウ@ space. If calli ng a subroutine wi th CALL, the PC reg iSlC r is pushed onto the stack, and the stack pointer (SP) is dccrcmcntC M C 0, Z 0 M are not changed. t ィセ@

CO:\1

(II mp lem en T memo",'

Flugs: N, Z,C=l, V =O This co lllplemems the contents of a memo!), loca liOiL The result is the l's complement oflhe memory. That is: Os bet:ome Is and Is beco me Os. The fo llowing addressing mod es are supported for Ihis instruction: 1. Extended: COM 1 6- bit memor y add r ess Examp le: COM S155 0 ! complement data in RAM l oc o $15 50 2. Indexed: COM O,X ; comp l. da ta in RAM poin te d to by X CO:\IA

Co mpll-m ent A

Flugs: N, Z,C=l, V =O This comple ments the COiik'flIS o f re gi stt.'r A. thc a(;cwnulator. Thc result is dIe I 's comp le ment o f tb e accumu lator. That is: O!; become Is and Is become Os. Exam ple: LDM ' $55 ; 11."'010101 01 A AGAIN: COMA ; compl ement STM roRTB ; togg l e b i ts o f PORTS ; continuously BRA AGAIN

..,-

CO:\IB

Co mpll'ml' nt B

N.Z,C=J,VeoO Fla gs: Thi s complement s the contl"l1t s of accumulator B. The resu ll is the I's wmplem:n t of lICcumul:! tor S . Th at is: Os become 1s amI Is become Os. Example: ; 8=0 1010101 LDAB '$55 AGAIN: COMB ; cou'I,-'l""Ll",nL セ BGy N@ B STAB roRTB ; toggle a ll bits o f PORTB BRA AGAIN ; continuously C PD

Co mp a re D with mem o r\·

ヲャセ セ]

r@

Th e magn it udes Flug: N. V, l, Cof the 0 regisk,- (Double accumulator A:S) and a 16-bit word dam are co mpured und con di tion nags are set accord ing ly. The L _ _ _ _ _'----_'---_---" 16-bit word data (W) CIIll be IIll immediate value or 2 bytes of data located in me mor y locations M and M + I . This instruction is really 0 - W und the fla!;' are set Zセ セ@ shown ill the !lIb1e. Th e conten ts or o and th e contents of memory loolti ons M and M + I UTe not cha ngl'd. APP ENDIX A: II CS I2 I NSTR UC TI ONS EXPLAI NED

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca



C PS

             

Compare Sla ck Pointer with m emorv

Flag: N, V. Z, C The magnitudes of the SP (Stack Po inler) register and a 16-bi t word data arc compared and cond ition fl ags are set accordingly. The 16-bil word data (W)

am be all innnl"tiiale value or 2 bytes of data joca!oo in memory locations M and M + 1. Thi!; in structioll is real ly SP - W and the flags are sci accordingly. The ,oDlenrs of SP and the contents o f memory locations hI and M + I are nol ,hanged.

C PX

Compare X with memo",

Flag: N, V, Z, C The lu agn il uues or llie X regi sler and a 16-bi t word data (W) are compared ami condition flags arc sel accordi ng ly. The 16-bil word data (W) can be an inmle diatc value OJ 2 bytes of data located in memory locations M セe ami M + I. This in struction is really X _ Wand the flags arc X Va lli c

c ry

Sセ

C - I , セ@ C- 0 Z- 1 CZ- 0

o.

Compare Y willi memor,·

Fl ag: N. V, Z, C The ュ。ァ ョゥャ オ、・セ@ of lhe Y rcgislL'J lUld a 16-bil word dala (W) are compared ami con di(ion flags are sct accord ingly. The 16-bi e word ClUJ be lUl immediate value OJ 2 bytes of data IOCUlcd in ml.'Il1OJ)' loculiorlS M lind M + 1. This in &lruc (ion is really Y - W and the nags are sct a s shown in the table. t ィセ@ contents o f D and the contents o f memory loea- A ケセ \ セ | ァ B セQ B セ G ZS (iolls M and M + 1 are not 」ィ。ョァセGサ{N@ Y - Value DAA

y^v。

Dccimal Ad ju§tA

ャ オセ@

」セ セQ M

C-

o.M コセ Zセッ -M

 

Eumpk LDM #$47 ADDA #$38



DM

;A-OI OO 0 11 1 ;A=$4 7+ $38 =$ 7 f, invalid BCD ; A- I OOO 0 1 0 1- $8 5 , va l i d BCD

 

(inva l id BC D) (a f ter

    

DA A)

(valid BC D) In the above exam ple. since the klWe r nibble was greater thrul 9. DAA added 6 loA. If the lower ni bble b Jcss than 9 bu e H = 1. it al so adds 6 10 the lowe r 600

セ@

1

C - O.Z - O

Fl ag s: C, N, Z Th is in struction is used uflC r add ition o f BCD nwnbem 10 convert the resu ll bat:k to BCD. Th e duta is udj usted in the fo ll owi ng two possible cases . I. It adds 610 Ille lower 4 bi ts o f A if it is grea ter tlmn 9 or if f! = 1. 2. It also add s 6 to the upper 4 bits o f A if it is greater than 9 or if C '" 1.



www.fut ureerc.com

Page: 1

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

nibble_ See the fo llowing

」 クセュイャ

www.fut ureerc.com

」⦅@

Example: LOM H29 hODA IS18 OM

;A""0 010 100 1 ;A;0 100 000 1 INCORRECT ,A-OI OO 0 111 • $47 VALID BCD

$29

+ $18 $41



incorrect res ul t in BCD

6 $47

correct res u lt i n BCQ

The sumo thing cun happen for till: upper nibble. See the following 」セオュー

ャ 」N@

Example:

LOM 1 $52 ADOA ' $91 DAA

; A'"'0 10 1 00 1 0 ;1\- 1110 0011 i nvalid BCD ;A-OI 00 0011 and Cal

$52

!....ill. $E3

'-----.J!

(inva lid BCD) (after OM, addin9 to upper nibbl e)

$1 4 ) valid BCD Sim ilar!)'. if the upper ni bble is less than 9 ami C = 1, &c the following example. Example: LOAA 1$94 ADDA 1 $91 OM

jt

must be correctL>U.

;A=100 1 01 00

;.11.-0010 0101 incorrect ;.11."1000 0 1 01 ,

va l id BCD

;for 85,C-1

It is poss ible ilial 6 is added to both the high and low nibbles. See the follo\\';ng exam ple. Example :

LOAA ' $5 4

ADOA ' $87 DAA

DREQ

;A_ OI01 0100 ;A- 110 1 1011 in v a l id BCD ;A-OIOO 0001 , C- l (BCD 141 )

Derre men l and Branch If [guallo z

セ イAャ@

Flags: None In this instruction a register is decremented, ami if the resu ll is zero it wi ll branch (0 the target 。、セ ウ N@ The register ,an be A. 13. O. X. Y. or SP. EXample:

DBEQ II

;decrement II and branch i f A=O

A ppt: N nlX A: 11 CS 12I J'Io:STRUC TIOJ'Io:S t:X pLAINt:1)

601

Page: 601

---------------------------------- ------------------------------Fam ilia Freescale 9S12

-------------------------

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

OBEQ

e

; decrement B "d branch i f B- O ; decrement 0 , od branch i f 0-0 ; decrement x ,oct branch i f x- O ; decrement Y , od branch i f

OBEQ 0 DBEQ x

' -0

DBEQ Y

Nolice tliat th.: target address 127 bylC s fo rward.

セ。ョ@

be no mo«, Ih:ul 12S bytes bacl..-ward or

Dl'1:reme nr a nd Rran ch If No! Equal I" Ze ro

IlRNE Fl ags: In tlus w ill branch to Example: DBNE peNS DBNE: peNS

None

illSlruct ioll a register is 、セイエGャi・ョ 、L@ and if the result is not zero it the target address. The regis ter can Ix A. 13. 0, X. Y. or S I'. A B

0

x

DBNE ¥

; dec lC ement A , oct branch if A i , My 0 ; decrement B o be used after s.ubfraCI instroclions such as

SUll A, suno, and so 011 . Notice IMI in th is insb1Jclion the target addrcss cannot be fun her than - 32,76& 10 +32,767 bytes from the progra m oountcr. L o ns Branch if Minus (if N - I)

LUMI

fャ オァセZ@ None Th is in slruc tion exumi ne s the N fl ug and jum ps i f it is I (N = I ). NOlice thm in Ihis instruction the t3q:Ct address c anoot be {an her 1han - 32,768 10 +32,767 bytes fr(lm the program counter.

LONE

Lo ng Branch IfN ol Equ a l 10 7.A'ro (If Z - 0)

Flags:

None

This instruc tion exam ines the Z fl ag and jum ps i f il is 0 (Z - 0). Notice that in Ihis instruct ion the target address cannot be (anller than _32,768 to +32.767

bytes from the program counter. LBPL

Long Brunch ir Plu s (if N = 0)

Flags: None Thi s in struction cx ami nes the N flag and jum ps if it is 0 (N - 0). Notice mmin this inSlruetion the turget ad dress cun no t be flll1 her th:.m - 32,768 to +32,767 bytes from The program coun Ter. LURA

LOllg Ur.tneh Alw3\'s

Flags: None Thi s is a 4-byte inSlroclion . The 2 byt es arc the opcede and lhe sccond 2 bytes arc Ihe signed nllm ber displaccmenl. which is added 10 Ihe PC H ーイッ ァイ セュ@ counler) of Ihe inMruCli on foll owing Ihe LBR A 10 gel the cargel 。、 イ ・ウNセ@ Th crcfore, in Ihis jump Ihe i セ イ ァ・エ@ address must be within _32,768 to +32,767 !lyles of the PC (program eoomcr) of the in Slmet ion セヲイ 」イ@ me LBRA since 2 byccs of add ress ca n cake values o f - 32,768 to +3 2, 767 bytes. This atldress is oflC n re ferred to as a rellllil'e add,.e.fs since the lurgt.1 uddress is - 32.76810 +32,767 byles r elati\'e 10 Ihe program counler (PC). LDVC

LOllI: Uranell if

o|GH

セイ ャッキ@

Cleared (V - 0)

Flags: Non e Thi s insblJClion ex am in es The V n ag, and if it ise lcarcd it lI'ili jump 10 me lセイァ」エ@ address. Noticc thnt in Ihi s in stru ction thc I3rgCI address cannot be fnn her than _32.768 10 +32,767 hyt es from .he ーイッ ァイ セュ@ counlcr,

A l-'pt: Nn l X ,\: II CS 12 I J'Io:STRUCT I OJ'Io:S t:X I-'LAINt:1)

611

Page: 611

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

L ong Bran ch if o.."t"rnow St-t (V . I )

LDVS

Flags: NOlle Th is inslfuclioll examines the V flag. and if il is set it wi ll jum p to the larget address. Nolice thai in Ihis instruction th e target addm; s cannot be fa rthe r than - 32.768 10 +32,767 bytes from IIle program counter.

LORN

Long Oraneh Ne\'er

Flags:

None

This is i ll イ セ。ャゥ エケ@ a 4-bytc NOP thai is executed ill three cycl es. It is the COmp k'fllCnl o f the LBR A instrud ion. The following three instruction s perforlll the sa me action:

LBRN HERE LBRA HERE

LBRA $

LOAA

Loa d Acc.umulato r A

Flags: N. V, Z Th is louds a byte into reg ister A. T he value can be an immediate value or

in some ml'fTlory \oem;on. The followi ng ure some examples of how it is used for variou s addressing modes: LOAA LOAA 10M LOM LOAA LOAA

WAU

J $5F

. 99

; A'- $SF ; A'"'9 9

; load i nto A f rom PORTE MRTB $1500 ; load into A from locat io n $1 5 00

;load i nto A f rom location po int co by X 0_ Y ; load into A from l ocation po i nt t o by Y

0_"

Load Acc umulator U

Flags: N, V, Z Th is loods a 「ケ エ セ@ into register B. Thc カ 。 ャ オセ@ セ。ョ@ bt: an imrm:tiiatc カ。 ャオ セ@ or ill SO lllC mcm ory Iocatioll. The follo wing are some examplL"S of how it is used: LOAS LOAS LOAB LOAS LOM LOAA

LOD

J $5F

. 99

; B-$5F ; B-9 9

; load into B f.= PORTE ; load i nto B f rom locat i on $1 5 00 D,X ; load into A f rom location point co by O_Y ; load i nto A from location po i nt Co by

FORTE $150 0

X

y

Loa d Double Accu mula tor D Flags: N, V, Z T his loads 3 Hi-bit word in to register D. The va lue can be an immediatc

6\l

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

value or in some memo ry location. The fo llowing arc some examples o f how it is オウ」、セ@

LOO LOO

'$5F77 .9920

LOD

S15 00 : load in to D from l oc S15 00 and S15 01

LOO LOO

; lo ad into 0 tr om location X and X+ l D, Y ; lo ad into 0 f rom location Y and Y+ 1

a,x lッセ、@

LOS

; D-SS f 7 7 ; 0-9920

Suck Poinler

Flags: N, V, Z This loads a 16-hi l word into the sr regi stcr. The val ue c an be an immediate value or in some memory location. The following arc some examples o f hollo' it is used: ; SpcS5F17 LOS f$5F17 ; SP-9920 LOS .9920 LDS S15 QO;load into SP f rom lac $15 00 a nd $1501 LOS a ,X ; lo ad into SP from locat io n X and X+l

LOS

D, Y ;load into SP from l ocation Y and Y+l l ッセ

LIlX

、@

Index rtJ;;isicr X

Flags: N , V, Z This load s a l 6-hil word inlO regi stcr X. The value can bo: an immediate or in some memory location. Th e fo llowing arc some ex am ples o f how it is カセャオ」@

used:

LOX LOX LOX LDX

LOY

f$5F77 :X"'S5F77 t 9 9 20 : x-992 0 S15 0 0 : load into X f rom loe S1500 and S15 01 O, Y : load into X f rom location Y and Y+ 1

Loud Index rt-gisler Y

Flags: N, V, Z This k>ads a 16-bit word into reg ister Y. The value can be an immediate value or in some memo ry location. Th e fo llowing arc some ex amples o f how it is used : LOY t$5F77 : Y-S5 F7 7 LOY t9 9 20 : Y-992 0 LOY S15 0 0 : loa d in to Y from l oe S1500 and $15 01 LOY O,X : lo ad into Y f rom location X and X+1

LE,\S

t oud S(a(k Poinl(r I-li lh EfTl"t:tiW t\d dros

Flags: None This loods. an d fo:x:tive address into the $ 1' register. The eff(Xtive address is formoo by oo mb ini ng the base index registers of X, Y, SP, or PC and an offsct value, which can be an inuncdiate value or the content of a register such as A . !l. and :;0 on.

APP ENDIX A: II CS12 I NST RUC TI ONS EXPLA I NE D

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

L EA.,\:

L oa d X wilh EfTl'tl h 'e Ad d rt'!lli

Flags:

NOlle

Th is loads an effective address in to register X. The effect ive address is formed by combining the base index イ 」ァゥ ウエ」セ@ of X, Y, SP. o r PC and all offset value . which can be an immediate va lu e or the content of a register such as A. B.

and

>0 011 .

LEAY

L oa d Y wil h Effl'flive Addr elis

Flags:

Nonc

Thi s loads an effC(;live address into register Y. Th e e ffect ive address is formed by com bining Ihe base index rcgistcn; of X Y, SP. or PC and an offset value . which can be an immediate va llle or the content of a regisll:r such as A. B. and 00 on. L og ical S hift Left Memon>

LS L

Flags:

N, Z, V, c

This shi.'Is all bilS of u memory loca-

I C

tioo one hi t position left. Bi t 0 is loaded "'ilb :10. The C bit is louded from the MSB of thc L _ _ _ _ _ _ _ _ _ _ _ _ _ _ _--'

memory locatio n. Example:

LOM '$9 9

iAo;$99

STAA $ 15 00

; $1 500-(1 00 11001) ; No w S1 500; (0011001 0 ) .nd C;1 ; Now S1500=(0110 01 00) .nd C=O

LSL S1500 LSL S1500 LSLA

Log ical Shift Left A

I

Flags: N, Z, V, c Th is ウィ ゥ ヲエ セ@ all bits of A one bit posiC tioo left Bit 0 is loaded ,,·ith a O. The C bit ISloaded from (he M SB of A. L_ _ _ _ _ _ _ _ _ _ _ _ _ _--' Example: LDM '$99 iNu .. A-00 1 1 0010 ClW.l C-1 ;No w A- 011 001 00 and C-O LSLA

L'''''

LSLB

Log ical Shift Ldt B

This sh i Ih all bits of B one bit posi(ioll le ft. Bi t 0 is loaded wah a O. Th e C blt

is loaded from (he M SB of B. Examp le : LOAB '$99

LSRB LSRB 614

C

IMSS _ lSSI _ o

L _____________----' ; B=$99 ; No w B=11 001100 and C=l ; Now B"1 11 001 10 and e - o

www.fut ureerc.com

Page: ix

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x. com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

LSLD

www.fut ureerc.com

Logical Sh ift Lt'fl D

Flags: N, Z , V, C This shills all bits o f D one bit position left. Bit 0 is loaded with a O. The Cbit is loaded fm m tIle MSB of D. Example:

LDO

; Now 0 - $3 332 and e e l ; Now 0- $666 4 and C"O

C

LSR

;0-$99 99

' $9 999

LSLD LSLD



d G ⦅ U@

dX セhl

dW@

__

_ _D ____'+- O

IAl glco l Sh ift RighI i\1emoT\'

Flags: This セ ィゥヲャウ@

N, Z, V. c all bi ls of memory

I

location one bit position righL Bit1

O_

IMSB _

I

LSB _

C

is loaded with O. The C bi l is IQaded, _ _ _ _ _ _ _ _ _ _ _ _ _ _--' with the LSB of m emory. u aillple: ; ;0.- $ 99 LDAA ' $99 STAA $ 1 500 ;$ 1 500"( 1 001100 1) LSR $ 15 00 ;NOw $1500- (0100 11 00 ) and Ca l LSR S1500 ;Now SI5 00;(00100110) and C"'D

I O- IMSB _

LSRA

I.ogleo l Shlfl RighI A

Flags: N. Z, V. c This sb iftsall bit s of A one b it position ri ght. Bit 7 is loaded with U.

.

LSBI -c .

111t C bit is loaded from the LSI3 OIL_ _ _ _ _ _ _ _ _ _ _ _----' rcgislI:r A.

EXample:

L5RB

LDAA ' $ 9 9

; A- $ 99

L5RA LSRA

; Now A_OIOOI I OO and Cal ;Now A=OOl OO l lO and C=O

I"ogleo l Shlfl RighI B

Flags: N. Z, V. C イMセ[Z]@ This >hifts all bits o f 13 on e bi!'1 positionri ghl. Bi! 7 is IOalkd with O. llle C bit is loaded from til\: LSB 01 D.

セァゥウエ・イ@

セ@

O- I MSB _

LSBI -c

_ _ _ _ _ _ _ _ _ _ _ _..J

uamplc: LDA8 . $99 LSRB LSRB

; 8 - $ 99

; Now B-OI100 1 100 and C-l ;Now B=001 100 110 a nd C=O

A PP ENDIX A: II CS 12 I NSTRUC TI ONS EXPLA I NED

6"

Page: x

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Logical Shift Right D

LS RD

Flags: N, Z, V. C This shi ns all bits of DOlle bit position right. Bit 15 is loaded with a O. llJe C bj! is loaded frum the LSB of D. Example:

LDO l$9999 ;D-$9999 ;0-$6666 and cセャ@ LSRD ;No'"" 0-$3)3) and C-O LSRD

H"'

o -IL D'_' _ _D...J '

DO

r-

c

Place Larger (i\lodmum) of IWO va lues In A

MAXA

Flags: N, V. Z, C

The magnitudt.'S of lheA regism and a byte of data in memory are compared and the Jarger one is placed in A. The S-bil d3l3 is loo:,:a{(d in memory loo;alion M. It is assumed thal the data ill both A and the memory location are wlsigned. MAX'"

1'101'1' Larg er (i\lorlmum) of IWO \'oIUl's In i\1emllr\'

Flags: N, V, Z, C The magnitudes of the A register ami a byte of data are compared and the

larger one is placed in memory. The byte data is located in memory location M. It is assumed that the data ill both A and Ihe me mory loc3I ion are unSignL-d. ;\I £M

Determine grade of Members hip

See the HCS 12 munun!. !'IINA

I'la ce Sma ller (Minimum) of t wo ulUigned

カ。

ャ オ・セ@

in A

Fl ags: N, V, Z, C Th e m Hgnitudes of the A register and a byte of dam arc compared and the smal ler one is p laecrl in A. The bylC of data is loealCd in memory loc ati on M. It is ll,';sumcd Ihut the duJu in bo th A Ulld Ihe meTl1 0JY locarion ure un signed. pャS

MINM

cセ@

S m3 lll'r (Minim uml uftwu unsi!lm, d Va lUl"!i in M

Fl ags: N, V, Z, C The m agnitudes of Ihe A registCT and a byte of data arc compared and the ウュセャ ャ 」イ@ one is p lnccrl in memory. The bytc of daTa is locatcd in memory loenli on M . II is assumed that the data in both A an d Ih c memory locati on arc unsigned.

MOV8

Move II 8 vtc Ordala from source t o destination

Fl ags: None Th is copi es a bylC from the source loc ati(l1l to tho: deslinm iolL Scr thc foJ6 16

www.fut ureerc.com

Page: xi

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

lowing examples:

M:lVB '$99 , S1500 ; ioad $99 into location S1500 MOva O,X,C,Y ; move from location X to location Y

MOVW

Mo.'!.' 1I Word of da ta from soun'!.' to de!illnll lion

Flags:

None

This copies a l6-b il word from the source locations to the destinations. Sec the following examples:

MOVW f$9972 , $1500

M:)VW O,X, O,Y

; load 59972 into locations ; $1500 and 1501 ; 51500"( $99 ) and 1501" (572)

; move word fr om locatio ns X and X+l I tO locations Y and Y+l

Muhiplv II vte "I' 「IGエ

MlJL

Flags:

セ@ ( V -

A x 8 UJlSib\ IICtl)

C

This m ultiplies an unsigned byte value in register A by an unsigned byte value in register 13. The 16-bil result is placed in 0 (A and Il) where D has the lower 8 bits and A has the higher S b il s. Example:

LOAA '5 LODB f7 MUL Ex ample'

; D-7xS-3S"$23. A-O , 8-$23

no

LDM LDAS Us

MUL

;O=lOx15= lSO= S96 , A=O, B= S96

Example' L DM

'S25

LOAB 'S78 ;0;S1158 A;$ll. B=S58 MUL ; (S25 x $78 = S1158) Ex omple: LDM

no D

LDAB '200 ;O=$4E20, A=$4E, B=$20 MUL ; (100 x 200 .. 20 , 000 .. $4820) NEG

NeGa le memorv

Flngs:

N, Z, C, V

Thi s rcrlaccs Ihe cements of a memory localion wilh ils 2's complement Th e re sult is Ihe 2's oomplemcn! of !he memory.

APPENDIX A: II CS 12 I NSTRUCTIONS EXPLA I NE:D

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Example' ; A=O l OlOOQO

LOM 1$58 STM S15 00 NEG

; $ 1 500 ($58) ; $ 1 500 ($SO)

$1 500

1- b lended: NEG 16-bit memory a ddress NEG $1550 ; 2 ' s camp o f data in RAM loco $ 155 0 e クセューャ」@ 2_ Indexed: NEG O, X ; 2 ' 8 comp data in RAM pointed by X NEGA

Fl ag,: N, Z, C, V Thi s ta kes the 2's com pl ement of the oonlcnts of rcgi SlCf A, 1he accum ulator. The r('su l! is the 2's oomp lement of lhe occumu lator silti ng in A.

Exump ie:

LDM '$58

; A-OIOIOOOO

NEGA

; A=1011 0 0 QO

l'\: [GH

Flags: N, Z, C, V This ta kes the 2's complement of the oonCerns ofregislCf B, The accumula· tor, The result is the 2's oomp lcmcnl of the accumu lator sitting in B.

Example'

; B- OI110100 ; B=100011 00

LDAB ' $74 NEGB

NO t'

No Oper3 1ion

Flags:

None

Th is pcrfonns no opcrati(l11 and execution continuos with the next in stnKlion . It is somcli mcs u,oo for lim in g dela ys to waste clock cyc les. Thi s in struction HIャ@ following only updates the PC (program counter) to point to the next ゥ ョウエイオセゥ NOP.

ORAA

Lug Il'll lOR A

Fl ags: N.Z. V - O Th i. penonn. B j ッXゥセ。j@ O R on th e ope rand •. bi t by bil. SlOring the result in register A. Noti cc that both the source ami destination values arc byte-size only.

A 0

0 1 1



AORB

0 1

0

0 1 1

1

1

Examp le : L OM .S30 ORM .S09

$39 $0 2 $39

'"

; A=$30 ; A-$30 OR with 09 ("",S39)

00 11 0000

ilOilO ] Oil ] 00 11 1001

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Exam ple'

; A=$32

LOAA '$32 ORAA 'S50

; 7\.=$72

$32

0011 00 10

SSQ

0 1 01

DODO

$72 01 11 00 10 The fo llowin g addressing JOOdcs UTe s upported fu r ,he DRAA inSlrul-1iOl1 : ORM 'data Example: ORAA 1$30 I. Immediate: 2. Dire; i セqュPQ@

0101 l J Ql 0010 l i v",,)

Assume 0=$345 and M=($349) S345 0011 01 00 010 1 0011 01 00 0101 0011 01 00 10 01 2' s corop +1011 1011 01 1 1 - $349 - $004 1 11 11 1111 1100 C=l (step 3 , negat i ve) SWI

Software Interrupt

Flags: I bi t - 1 Th is is u so rt wure interru pt It cuuscs un in terlup t without using an ・セ エセLM 11.11 hard ware pi n. Upon execution o f the SWI, registers SP, CCR , A, B, X, and Y arc pushed onto the stack and SP is dec remented ac cordingly. A"".: NIJ IX ,\ ; 11CS 12 I NSTRUCT IONS EXPLAINEU

629

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

            

II also makes I bit - I, therefore preventin g another interrupt The cx " prompt ind icating thaI DBUG I 2 is conununicating with your Pc. dッセGャ

{ ッ。、@

the 519 file into your trai ner

after typ ing the load command in the Tenninal and pressing tile IXlIm load kon. "nli s is shown in fゥ ァ オイ セ@ 8 -4.

, ,.. セBL

G uャ@

セQ^i⦅ャ|エ@

イB

-,

セ@

セ@

セ@

e

I f"'·""'1

ᄋ セ N BL@

,



• セ@

• •

"-

,

A セ G GB@

" ,, , "'.0100. -"°0'·" no , , 000

·

0-

........ "" /112 »,.. •• "" I " ..". 1'0""'"'0

, ,

-

,

I- rD j'X j

.. "

セ@

[ i.

,, Hill'

セ@ セ@

...

>

""""" '--.0 1 &"" , is '"" 0.,,,,,",,,,, "",_ J Bqlinlcominuc: ・クセオエゥッョ@ of u,;cor MDIII 11 00 ll20

1100 1110

5555 5555 5555 5555

5555 5555 5555 5555

5555 5555 55S5 5555

5555 5555 5555 5555

1I11UUll •• • IJIJUUU.

The breakpoint セッュ。 ョ、@ ru ns. a program 10 a spccifi.:: addr.::ss, allowing you to exrunine the results . The " I3R" rommand (breakpo int) wiJl display the current breakpo ints:

>M Br .. " leV712\b . n\ .....,... _.

! JC1 _ 5 . _ k

iec ! Zw -0 - lC , \ l oc:v'1 'Z\ 1"" locle

... ..

LO O U

www.fut ureerc.com

maln( \loid)

/ , p u t your DDRB DDRA DDRH DDRJ

code here , / f jlflake POrt B an outpu t

Olill

Ox!'"!'" ; OxFF; OXOO ; OxFF;

A iBLセ ヲ Oセ

ォ NL@ 。 セ@

Po rtA an outpu t

.. PTH a n in p ut

PTJ - 0;

OOUNT

TSCRI

0;

=

l/ initializlO thunt

Qx BO ; / lenab llO thlO エゥセ・イ@

TSCR2 = Qx B2 ; / I.m;.b llO i n t 12 $ PII

642

$3 EOO $3 E02 $3 E(W $3 E06 $3 E08 $3 EOA $3 EOC $3 EOE $3 E1 0 $3 E1 2 $3 E 14 $3 E1 6 $3 E 18 $3 E IA $3 E IC $3 E IE $3 E20 $3 E22 $3 E24 $3 E26 $3 E28 $3 E2A $3 E..."C $3 E2E $3 E)O $3 E32 $3 E34 $3 E36 $3 E38 $3 E3A S3 EJe $3 E3E

II C Bus

VecTllr Addr('SS

$3E40 SJE42 SJE44 e RG Lock S3E46 Pulse AccumulatOf B OvcrOow S3E48 Mod D own Cou nTer Underflow $3E4A Pon H InTerru pl $3E4C Pon J Intl-'Trupt $3E4 E Am , $3E50 AmO $3E52 SCII $3E54 SCIO $3E56 $3E58 SPIO I\! lse ACl--umulatOf A Input Edge $3E5A I\!l se ACf.-umulatOf A Ove rllow $3E5C $3E5 E Ti Jl)(,,- O verllo "' Ti lllL'J C hanne l 7 $3E60 Timer C hanne l 6 S3E62 Ti ITK.,- C hunne l 5 S3EM Tin",,- C hanne l 4 S3E66 Timer C hannel 3 S3E68 Ti mer C hanne l 2 S3E6A TImer C hanne l l S3E6C TImer C hanne l 0 S3E6E Real Tillie Interrup! S3E7 0 S3E72 IRQ XI RQ $3E74 SWI S3E76 Uni mp lemellled Instruction Tra p S3E78 NIA S3E7A NIA 53E7C NIA S3E7E

DLC SCME

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

APPENDIX C IC INTERFACING, SYSTEM DESIGN ISSUES, AND WIRE WRAPPING OVERVIEW This appendix provid es an ovcrvh:w of Ie In terfacing and IICS I2 inlcrflll!ing. In addition, we look al the mlcrulvntrollcr-baSt--d sys tem liS II whole II nd cxami ne some grncr ll llSl;ucS in system d cslj:n. First. in St",Iion C. I. W(' provid e an oWn 'i t, " , of I e In terfacing. Th e n. in SI't'.li on C.2, the fatHlllt of li eS 12 110 porls lind intcrfllcinl; 11ft> discu sSt.'d . 51"'!\o" C.3 examines sys tem d esign Issul'!;. Seedon C.4 shows wire "'Tappin!;_

643

Page: iv

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

SECTION C.1: OVERVIEW OF Ie TECHNOLOGY In Ihis Sl'CIion we exami ne

Ie Icchnniogy a nd d i>Cl] ss some major C a 0.1 !-I F monolith ic capacitor forcach IC Placc the 0.1 !-IF mon()lithic capaci t()r betwcen Ve e ami ground ofcach IC Milk e sure the leads ure us short lIS possible.

IC" I IIC", I I IC#) I i ic セ@ Fi gu n- C _14. [) a i.y C hain Cono ",,!i,", (not r.,.,., mm eo dtd fo r power lineo)

APPE NDIX C: Ie

i nterfacセ@

SYST EM DES IGN ISSUES

6"

Page: xiv



------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

                         

This page ;>lte.ntimlaify lifl blank

www.fut ureerc.com

Page: 1

Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

------------------------------------------------------------------------------------------------------------------------------------------Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com ww w.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

APPENDIXD FLOWCHARTS AND PSEUDOCODE



OVERV I EW

ィ ゥ セ@ a pp"ndil: pro\"id es a n in trod udi on fa writi ng n owcha rt s :lin d pseu docod e.

661

Page: 661

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www. freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

Flowcharts If you h:wc taken fin y

ー イ セカ

(Terminal)

ゥ ッオウ@

programming cuurses, you are probubly fumiiiur with fl owchU11ing. Flowcrorts usc gruphic symbols 10 represent d ifler-

ent typeS of progmm operations. These symbols ure corme..; I,:d tog1.1 hcr into (l Ilowchurt 10 show the flow of 」セ・オャ ゥ ッョ@ of a program. Figure 0 -\ shows soille of the more com monly used symbo ls, Flowchart lcmplmes are available to help you draw the sy mbols quickl y an d neady.

Pseudocode fQP|Gセィ。イエ

practice

ェョァ@ 1Il

has been standard

industry

fo r decades.

However, SOIl"M: find li mitations in using flowchart s. such as tile fact that you can', wrile much in the lin le boxes. and it is hard to gel me "bi g picture" of what the program does without gen ing bogged down in the detai ls. An al1crnativc l(l using flowchans is pscudOl:odc, which involves writing brief descriptions of the flow of the code. Figures D-2 through 0-6 show flowchan s 3ntl pscudooodc for oommon ly used control Slructurcs..

7

IL-_=_, Connector

o

Stnlcturcrl programming uscs Fig ure 0 ·1. Com monly Used Fl owch:lr l Sy mbo ls of progm1l1 control three basic i セGpcs@

I Statement 1 Statement 1 Statement 2

1

I

セ Z NGB@

Figure D-2. SEQUENCE Pst'ud ocooe ven us Flo wch a rt

6{,2

I

www.fut ureerc.com

Page: iii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

Sirocrurcs: sequence, control, and ite ration. SCcurl()CO(lc!l11d llowchnns. NolC in Figures D-2 through D-6 that "statement'" can ind icate one Sialement or a group o f S!Htemcnts. Figures D-5 and D-6 show two iteration control SlroC!urcs: REPE AT UNTIL and \VHILE 00. Both SlmclUrcs execute a statement or group of SUItemcnlS rcpc.1tcd ly. The difference be twee n them is thaI th e REPEAT UJ'I,'TI L struclUre always executes the sW.tcmcnl(S) at least once, and checks the con di ti on after each ゥャセLMオエッョN@ whereas the WHILE DO Jl1:Jy 004 exet;u te tilt: S!:Itemenl(s) at ull because the cond irion is checked at the beginn ing of each iteration

I F (cond i t ion) THEN Statement 1 ELSE

S'ta'temen't 2

Statement 1

セ@

I

Statement 2

I , O-J. IF THEN ELSE Pscudol't..dc vers us Floluhart Figure

H' (con0

f$1400

CC AA MM

;COUN'l'

CO tJrfTREG

0,:(+ COUIfTREG

" '" ,,= "'""

)

,

"

"'Co

APPEl\"1)IX D; FLOWCHARTS AND PS EUDOCODE

count "'.. ,,, ,0>

"ddr""" 、Bエセ@

".,

;decre!l:ent counter ;loop unt il counte r la tore >h.

'""

,,
ltentimlalfy /('/1 blank

www.fut ureerc.com

Page: xi

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

APPENDIXE HCS12 PRIMER FOR x86 PROGRAMMERS !i-bjt registers:

, 116 At. AH. HL, BH. CL. eH. DL. 01-[

II CS I2 A. B and up to several ki lobytes of RAM kx:a tiOJl s

x_ y

16-bit (data poillle r ): I3X. 51. Dl IP ( 16-bit)

PC (l 6-bit)

!'rogram Counter: Inpu t:

MOV IN

OX, p or t AL, ox

MOV

DX, port addr

OUT

DX, AL

a ddr

LDAA PORT'" ; x - A, e , 8, H,

Output: STM

PORTx ; x - A, B, E,H, ...

Loop:

DEC CC JNZ TARGET

Slack Poinler:

51' (I G-hi!)

DEC BNE

MyReg TARGET

SP (I &-bil)

As \\'e PUS H data onlO the stac k, il decrements th e SP.

The same

AS \\'0 POP data from (he ,tacl: , il increment s (he S P.

Th e same

Data movement: From the rode scgmCll t: M)V AL , es : [ SI]

LDAA 0,

x

M)V AL, [ S I I

LDAA 0,

x

M)V AL , [ S I I (Use 51. DT. or BX only.)

LDAA Q,X

MJV [ S I ] , AL

S1'AA 0 , x

f rom the data segment:

From RAM:

To RAM:

A PPENDIX E: lI eS I2 PRIMER FO R Jt:86 PR OG RA MMERS

667

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

www.fut ureerc.com

APPENDIX F ASCII CODES

1:0 .. 1

-,

-,-, -, -, -,-, -,-, -,-,-, -, -, -, -,-, -,-0 セ@

-, セ@ セ@

-0

-,

-, セ@

-,

-, "

----

{,,"

h
O,...... II

.. BGセL

セ@

F^[N@

on"",,, 3;>a.

S



セ⦅@

01. Iod:>;,. bft 10 l.. .tI1Id...!

セ@

"" _ i't:JgIoA-4on_:l67 IO'"d r ..,10 1,·1 on _ , :.;,

C .... ' . _•• M....... , ..... 4.0

'"

APPE NDIX II : II CS 12 INSTR UCT ION R EFER ENC E

671

Page: xii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

..."""".- .

,

... セ

Nd\i

Bi@

Ea:CW1 (,] . and

0)!)I'l"0rQ

IIQua!;

(>IQ

CPU C'l1IQ.

• lb-:#: OpGra:lon ar>(l

u pャQセDq@

"'...,,,,,"'". 6-D.l CPhKl« lo>:h (..... ,.. .... Qゥァョッ、NセoB@

rMdI

, _ 0-'" ""''"'"'''' -" lot r. . . ""'" 'l' セ@



ャN

ᄋ w⦅セLNiBGィ\|ッI@

_ O-t:IOcon_ lli _torl:wO I "'" Nイ

NGセ@

C;Oo . . .........10 0 .. -0. t.n l. "'" _...,.". __... セ@ til ""1 boc""JQ0

698

1\'



.--•

Mセ@

セ@



;

.,

,

." ... ." ...



••

"• "



"

• • •



...... """lJ
"";WIIOCAN.r.VRJ

セoャゥヲ@

- CNllIJIoI'I' Nセ@

.0...::· NセL@





QIエaNセ

CMI"::",' canB

セ vセ

B@

CN/11;WR7

N@

セLM

Goセ@

.0"" . """'T!RIo:::.. ,'"-

G Mセ@ -.""

Lセ

L@

- .a. ._. ,..- . .. --••. . ••• ••• _. .. .. ....... , ... -G セ^\xiG@

セ@

Nセ@

Lセ@

1>IdOQVI Nセ@

セ ャriイッN@

セN@

セ@

ャ セ





BSNQ@

'M""

セ@

セ@



"

Gセ

Bセ@

'.""

Nセ@

, lid

••

hlW

ON

セ@

L Mセ@

N セN@

"W

Nセ@

-"'I'll

,OJ"""

セ、@

..."Ii. ,.."" .. "

Lセ@

セ@

セ@

セN@

N セN@

....... ',:.oW

LセN@

.... ;W

.... N

"

;l.UOS - o,ros

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C wit h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icr ocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

""'....

N....

Nセo@



"""-,

Nセ@

L@

""

Nセ@

セB

f@

""

.Nセ

eN,.C'\,'

N@

,m

c.... QT>I:\,>10_ Tloo BGセ⦅@ 01 セ@ PLl .1-. P"< 1180' 2 ッMfBG[ セ ᄋ@ ••• 、BセLN@ .. .02

www.fut ureerc.com

Page: xiii

------------------------------------------------------------------------------------------------------------------------------------------Fam ilia Freescale 9S12

Libro: HCS12 Microcont roller and Em bedded Syst em s: Using Assem bly and C w it h CodeWarrior

Los siguient es sit ios son fuent es de inform ación para los m icrocont roladores de la fam ilia 9s12: www.freescale.com www.s12x.com www.pem icro.com www.9s12.com www.em beddedrelat ed.com www.t echnologicalart s.com www.t echnologicalart s.ca

fセ・

N」。

ャ・@

Sel'llieonduclor,

www.fut ureerc.com

lit(:.

Ii

.5

.:

(; ,•

.. • l• C

u

セ@



i

.,J1 ••

p' ...... セBG@ _ NO .. .... "'" ."," '" rw..",_ Of NO - 100 io ,r.. セ GB@ c.aOOble OJ . ., • •