MICROCNTROLLRS MECH ENGR
MICROCNTROLLRS MECH ENGR EMCH 367
Popular in Course
Popular in Mechanical Engineering
This 133 page Class Notes was uploaded by Garry Goyette on Monday October 26, 2015. The Class Notes belongs to EMCH 367 at University of South Carolina - Columbia taught by V. Giurgiutiu in Fall. Since its upload, it has received 96 views. For similar materials see /class/229633/emch-367-university-of-south-carolina-columbia in Mechanical Engineering at University of South Carolina - Columbia.
Reviews for MICROCNTROLLRS MECH ENGR
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/26/15
EMCH 367 Fundamentals of Microcontrollers Exercise BUTTONS BOX EXERCISE BUTTONS BOX GOALS AND OBJECTIVES The goal of this exercise is to review the use of the parallel ports as an inputoutput lO device Registers that control the parallel ports will be explored A 4button 4LED box will be used as a communications link This exercise has the following objectives 0 Review the use of parallel ports 0 Illustrate the use of Port C for input and output 0 Introduce the concept of shifting register and memory content 0 Practice the use of the THRSim11 IO box for input and output BASIC CONCEPTS a Define in your own words quotPARALLEL COMMUNICATIONquot b For the two parallel ports PORT B and PORT C what is the difference between them c What are the memory locations that are used by each of them PORTB PORTC d What is DDRC Explain how it works e If you place f0 in DDRC at address 1007 and then load aa into PORTC at address 1003 what will the output of parallel Port C be Fill the results into the table Dr Victor Giurgiutiu Page 1 7112010 EMCH 367 Fundamentals of Microcontrollers Exercise BUTTONS BOX PROGRAM BUTTONSBX This program demonstrates the use of Port B for output and of Port C for both input and output Port C is configured to have the pins PC1 PC3 PC5 PC7 for output This is achieved using the Data Direction Register for port C DDRC Since the default setting for Port C is input the pins that have to be set to output have their image set to 1 in DDRC In our case the bits and of DDRC are set to 1 Thus the Port C pins PC1 PC3 PC5 PC7 become output while pins PCO PC2 PC4 PC6 remain input Dr Victor Giurgiutiu Page 2 7112010 EMCH 367 Fundamentals of Microcontrollers Exercise BUTTONS BOX The program loops continuously reading data from the some Port C pins and sending data back to the other Port C pins Simultaneously the data is also sent to Port B Instructions Flowchart w a Load REGBAS in reg X b Clear port B by storing zero in it Select Port C pins for output c Load in accB d Store accB to DDRC Main loop e Load Port C to accB f Shi accB to the left g Store accB to Port C h Store accB to Port B i Branch back to v j SWI FLOWCHART Draw a flowchart for the program in the space provided above CODING Use the flowchart to code your program in the simulator Write or paste your coded program in the space provided Code the program in to the personalized file LASTNAMEFirstnameButtonsbxasm using the standard template EXECUTION Open THRSim11 Close the Commands window Open port registers and THRSim11 IO box Open your program Before assembling your program disactivate the Store accB to Port Cquot instruction by putting at its beginning see the code in Example Button Box Set breakpoint and reset registers Set standard labels LabelSet Standard Labels Set display of accB to binary Set display of PORTB and PORTC to binary Tile windows Arrange windows for maximum benefit Paste your screen below a Before you run the program verify the Port C pins functionality In the THRSim11 IO box toggle up the switch PC2 You will see that the corres onding bit in Port C register bit becomes 1 immediately Paste your screen below i b Toggle down the switch PC2 in the IO box Run the program The program will loop continuously between label 0 v and opcode Dr Victor Giurgiutiu Page 3 7112010 EMCH 367 Fundamentals of Microcontrollers Exercise BUTTONS BOX d With the program running toggle up the switch PC2 in the IO box Immediately bit I in PORTC will switch to one Simultaneously pin in PORTB will become 1 and the light PB in the IO box will lit Press the stop button and capture the screen Paste your screen below e Try to toggle other PC switches in the IO box You will notice that now only the even switches PCO PC2 PC4 PC6 are producing the setting of the corresponding bits in PORTC register The odd switches PC PC PC PC can be toggled but with no effect on the PORTC register This illustrates how DDRC controls PORTC register f Restart the program by pressing the Run button With the program running try to toggle the other switches You will notice that the toggling of the even switches PC PC PC PC has the effect of switching on the odd Port B lights PB PB PB PB This is the result of the data from the odd Port C pins is loaded in accB left shifted and sent backto Port B g Finally reactivate the line store accB to Port Cquot by removing the This makes your program ready to be used in Lab2 WHAT YOU HAVE LEARNED In this exercise you have learned 0 The use of PORTC for input and output 0 The concept of shifting a register 0 The use of the THRSim11 IO box for both input and output 0 New words and expressions toggle switch shift a register shift data Dr Victor Giurgiutiu Page 4 7112010 EMCH 357 Funoamentats otMtorooontrouers Examp e 5 EXAMPLE5 OBJECTIVE Tms stmpte exampte nas tne foHthng obtectwes Revtew 2rdtgtt oeotmat anthmettc thn carry to prepare tne ground for 2rdtgtt hex artthmettc thn carry PROGRAM asm program ts stmttarto ex3 asm but uses numoers outstde tne o e 9 range tt performs tne anthmettc operatton 9 8 17 To achteve WS tne program does tne foHthng toao9mto aooA usmg LDAA te 9 gtA Load8tnto aooB usmg LDAB te 8 gtB AddaccAte 9thhaccBte 8 AB gtA A17 EXECUHON HRSth Maxtmtze THRSth thdow ctose tne Commands thdow Open nte Ex5 asm Assemote we Ttte thdows Set break potnt at tne hne oontammg svvt Set tne otsptay ofA B regtsters to Deotmat Reset regtsters D x v Yourscreen snouto tookhke tn Rb mt mm Vow ame aha mawmm mw Wm w nw rasm x tart nf main program nun Pnnnnam 9 Define program variables non para o P Sunnn oeoin typing ynur cone 9 Start nf main program Sr n1 oo oo tooo oo mu Pnnnmm c hum Senna ch m1 LINE m1 mm P Scans x Hegin typing your cane Loan no x End nf maim iroiram mu SFFFE r SH E M FDR mm s x End nf main program m mu SFFFE reset vector Foo tant set to start Dr VtmqutuvgtuHu Paget mmmu EMCH 367 Fundamentals of Microcontrollers Example 5 Dr ctor Giurgiutiu Page 2 7142010 EMCH 357 Fuhgamehtats utMtomouhtmuers Examp e 5 Use the Step button to step through the program Press the step outtoh ohoe The regtsters do hot ohahge Press agam urh ergtsToaoeothto act A ressagam Nurhoer8tsToaoeothto aooB Press 0 are ao ed toge her The resuTt 17 appears H V 500A The number 8 ts stm preserved H V AccB Your soreeh shouTo took We thts he at mm Vew Emmm twa mawmm mmd whw w 3 a E 33157 gt H I m a a Start as main prggrap um um Pnnmmn n Scan n1 mm r n r sunnn a Hegin typing gggr cane x tart nf main prngram Loan uy nun Pnnnnan c x1111nnnn Sc a c6 nu Loan as E use x Hegin typing ynur can Loan uy Loan as x End nf main Erniram mu SFFFE n Sfffe D an FDR SI RT g x End nf main prngram w mu SFFFE reset uectnr run Tant set tn start Duhhg the aoottoh 9 8 17 dectmatanthmettc wth carry has been performed The numbers HH Ve aho etght w o gwe the number Seve tee Whtch ts greaterthah Hme shoe the greatest hurhoerthat can be represented wth Just one oeotrhaT otgtt ts hthe a carry to the next Tevet ens had to be enacted Th woros hthe pTus etght makes Sever carry ohe h symbots 9 8 17 I m 2 m a a m WHAT YOU HAVE LEARNED Th thts strhpTe exerotse ou have rewewthg oeotrhaT ahthrhetto wtth carry to prepare the ground for uhoerstahothg hex ahthrhettowtth carry The ththgs that you have reweweo are The greatest hurhoerthat can be represented wtth a sthgTe oeotrhaT otgtt ts Hme Numbers greater than Hme are represented wth two or more otgtts For exarhpTe hurhoer Seve tee ts represented as 17 t e wtth two otgtts Wheh the resuTt Ofaddmg two oeotrhaT hurhoers ts greaterthah hthe a carrytakes pTaoe New Words and notattons addmon thh carry Dr VtmqutuvgtuHu Page 3 mmmu EMCH 367 Fundamentals of Microcontrollers Example 5 Dr ctor Giurgiutiu Page 1 7142010 EMCH 367 Fundamentals of Microcontrollers Example SCI RECEPTION EXAMPLE SCI RECEPTION OBJECTIVE This example has the following objectives 0 Review the use of serial communication interface SCI for reception 0 Illustrate the receiving of a character through SCI PROGRAM SCIRECEPT This program is an example of SCI reception The character T is being sent to SCDR when TDRE is set Instructions Flowchart Code START LDX REGBAS a Load REGBAS in reg X LDAA 00110000 b Initialize BAUD9600 STAA c Initialize 8bit word Initialize REGBAS In reg X LDAA 00000000 d initialize TE and RE Initialize SCI STAA BAUD 9500 LDAA 00001100 Wait for the reception of a keystroke 8bit Word STAA 39f RDRF is set by TE1 RE1 LABELO NOP loading SCSR into accA and AND with mask for RDR N00 eration LABEL1 LDAA SCSRX 00100000 ANDA 00100000 BEQ You are here when reception data reg is full Load SCDR into accB g Store accB through Port B h Branch back to e LDAB SCDR X STAB PORTBX BRA LABELO Check if RDRF is set Load SCSR into accA AND with mask 00100000 Loop if zero Load accB from SCDR Store actho Port B i SWI FLOWCHART AND CODE The program flowchart is show to the right of the program instructions Note the initialization block which contains reg X initialization and SCI initialization After initialization the status of RDRF reception data register full flag is checked in a loop When RDRF is set the loop is exited and the content of SCDR serial communication data register is loaded in accB This operation automatically resets RDRF Now the program loops backto the beginning and waits for another transmission The essential code for the program is shown to the right of the program flowchart This essential code was incorporated into the standard asm template to generate the file SCIreceptasm EXECUTION Open THRSim11 Close the Commands window View ports registers and serial registers View serial transmitter Open and assemble SCIreceptasm Set breakpoint at LDAB SCDRX and at SWI Reset registers Set standard labels LabelSet Standard Labels Set display of BAUD SCCR1 SCCR2 SCSR to binary Set display of accA to binary Arrange windows for maximum benefit Reset A B X PORTB Press the RESET button Your screen should look like this Dr Victor Giurgiutiu Page 17212010 EMCH 3B7 Fundamentals of Micrucuntrullers Example SCl RECEPTlON initialize aaungann initialize Eshit warn initialize TE and n tanttn a wait reeeptinn Lanttl check it nnnr is set nun with nask rnr nnnr 95m Nane man a natal slap SFFFE reset uectnr slant set tn start at prngran a Press the RUN button The program should loop on LABEL1 and exit the loop when the condition RDRF1 is satisfy This condition is checked with the mask 00100000 The mask is applied on the value found in SCSR When bit 5 in SCSR is set the mask senses it and the condition for exiting the loop is satis ed b Type the character T in the serial transmitter window and press end The character is sent to the MCU The MCU takes a few laps to sense it When the MCU senses it the RDRF gets set 39 d and the check RDRF loop is ex te c When the check RDRF loop is exited the program gets to the line LDAB DRX This line is a breakpoint At this moment the screen looks like this Dr Victur Glurglullu Page Z7ZlZEI1EI EM cH 3B7 Fundamentals of Microcontrollers Example SCl RECEP HON initialize naunwann initialize usnit nnrn initialize IE and n reeeptinn L BEL check if nnnr is set an nitn mask Fur nnnr Ssun None l Slavl a Dalal Slap SFFFE reset uectnr Slant set tn start nr prngran Note that that SCSR is 11100000 ie the RDRF ag bit 5 of SCSR is set This indicates that the character was received The TDRE and TE gs ie bits 6 and 7 are also set but this is due to the reset Note also that the ASCII code for the character T 54 appears in SCDR serial communication data register From SCDR it will be loaded into accB d Step manually to the next line which loads the data from SCDR into accB This load operation automatically resets RDRF The screen looks like this I alenl n n in w a gag 3315 gtHm 39 l LDX quotREGIME p e nl REl H Uictnr xrxn c a Eb um um nnnn initialize anununn min 1 51m snn c S a7 mumx mun n S1n2h xnnnnnnn c 7 as unnnnnnnn initialize usnit nnrn 3m 1 51M Hun xccnz n 1n2n xnnnnnnn initialize IE and n SEER n sinze xnnnnnnn nzr 55h SI SEDR I1 51 mm W a wait rnr a keypress receptinn nnainansnnle um EH1 ab 22 L HEU LDM KEELX check if RDRF is set I cmz in H mum mmnnnn am with nask m m maul 1 e Vnu are nere nnen tne rece SFFFE reset uectnr on an run will set tn start nr prngran gt I n s v lvsnnaealine ungaozm Wen agar nan Elpcktycles sear Note that SCSR is 11000000 This proves that RDRF bit 5 has been reset by the loading 39om SCDR but TDRE and TC remained set since they are not affected by reception operations Dr Victurcvlurgullu Page 3721znm EMCH 3B7 Fundamentals at Micrucuntrullers Example SCI RECEPTION e Step again The content of accB is stored in PORTB Your screen looks like this initialize naunyann initialize Erhit warn initialize TE and n reeeptinn Laaztl check it nnnr is set nun with nask Fur nnnr EllSUD None 1 SiavlBDalal Sm sme reset neeth F slant set tn start nf veteran Note that the ASCII code for T ie 54 appears in PORTB f Switch again to auto run The program loops now again on LABEL1 Press again the send button in the serial transmitter The characterT is sent again and alter a few laps the program exits the loop and gets to the LDAB SCDRX breakpoint g Run again automatically Change the character in the serial transmitter to A You will notice that the corresponding ASCII code 41 appear in SCDR and then after manual steps gets loaded in accB and stored in PORTB WHAT YOU HAVE LEARNED In this example you have learned 0 The use ofserial communication interface SCI for reception 0 The reception of a character through SCI 0 New words and notations RDRF ASCII code Dr Vlct r Glurglullu Pag347ZlZU1U EMCH 367 Fundamentals of Microcontrollers 795sz68j9doc Dr Victor Giurgiutiu Page 1 7212010 EMCH 367 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION EXAMPLE OUTPUT COMPARE TIMER FUNCTION OBJECTIVE This example has the following objectives Review the use of MCU Timer function as an Output Compare OC device Review the setting of OMx and OLx bits to select a desired OC event in this example we set OM3O OL31 to generate a toggle on the 0C3 pin Review the detection of the TOCx match with TNCT and the corresponding OC action Present the correlation between delay DT with actual frequency of the square wave Explore the accuracy with which frequency can be adjusted Explore the determination of low and high bounds on the frequencies that can be generated with the MCU V Logical 1 5 V L H L H Logical o o I At At At At Figure 1 Square wave schematics showing the halfwave duration At and the low L and high H states PROGRAM EXOC This program is an example of timer output compare The program runs freely and generates repeated toggles of the output compare pin 0C3 PA5 at equal intervals that are determined using the delay variable DT Thus a square wave is generated The program instructions are given in the first column below FLOWCHART AND CODE The program flowchart is show to the right of the program instructions Note the variable definition block in which DT is defined Next the initialization block contains reg X initialization and timer OC initialization The program stores the current time TCNT plus the delay DT in the 0C3 timer TOC3 A loop is entered in which the 0C3 flag OC3F is checked When OC3F is set the loop is exited The OC3F is reset and the value of TOC3 is updated with the current time plus the delay Then the program loops back The program loops back to the beginning and waits for a new keystroke to restart the process The essential code for the program is shown to the right of the program flowchart This essential code was incorporated into the standard asm template to generate the file ExOCasm Dr Victor Giurgiutiu Page 17132010 EMCH 367 Instructions i Define variable 0 Half wave duration DT 2 bytes ii Initialize o Initialize index X to REGBAS o Initialize timer 003 function set to toggle OM30 OL3 I Store initial time DT in T003 Wait and loop until OCSF is set when OCSF set proceed Reset OC3F Update TOCS add DT to current time and store in T003 vii Branch back iv 539 Slt Dr Victor Giurgiutiu Fundamentals of Microcontrollers Flowchart Define variables 0 Half wave duration DT 2 bytes 0 Initialize index Xto REGBAS o Initialize timerOC3 function set to toggle OM30 OL Store TCNTDT in TOC3 Check if OC3F is set Reset OC3F Store TCNTDT in TOC3 Page 27132010 DT START LABEL1 Example OUTPUT COMPARE TIMER FUNCTION Code ORG DATA RMB 2 ORG PROGRAM LDX LDAA 00010000 STAA CTL LDD T ADDD TCNTX TD TOC3X LDAA LG1 x AN DA 00100000 BEQ LDAA 00100000 STAA LDD ADDD TCNTX STD TOC3X BRA LABEL1 EMCH 367 EXECUWON Fundamentals of Mlcrocontrollers Example OUTPUT COMPARE TlMER FUNCTlON Open THRSim11 Close the Commands window Aew CPU registers timer registers port A pins memory list Open and assemble ExOCasm Set breakpoints at 0013 and and memory Set standard labels Set display of TCTL1 TFLG1 to binary Arrange windows for maximum bene t Press the RESET button Your screen should look like this gum at SWI Reset registers mm s Elle Edit Egrmecl mew elv 1 Emh yew E cme L a meWmm a3 3 BI gala gt H gt I mask Fur nnan L31 set nca tn tuggle stare rcuronr in Inca and or tn IENI Scnw ea ENLX Scn1n en 1a 10 rncax stnre new time in Inca Scum 2n 22 mm L BEH hack tn the tn nun REXEI reset nectar srrre en n run stunt set tn start nf prngram lAsm lasw Inns SH EFnRE I1 Swan Sun mm M Sun1 1n 1nnc Sun 1n2n xnnnnnnnn 1 n21 Sun m M 5 Int 1 n IEILZ n mxm I1 Sun In N S1n23 mxkz I1 S1n2h IFLGZ I1 S1n25 Sun Sun xnnnnnnnn Sun Sun lxsmnn livszeaa ramquot pcsenn u lElackEycles 2 a Put 0020 in DT When doing this note that DT takes two memory locations 00000001 b Step through your program Notice how the bit 4 is initialized in TCTL1 this sets 0C3 to toggle Dr Victor Gmrgmuu Page 37132010 EMCH 367 Fundamentals of Mlcrocontrollers Example OUTPUT COMPARE TlMER FUNCTlON c Step further Note that the value in TCNT is added with DT and stored in TOC3 At this point your screen looks like this 5e gm amh yew newe Lwd gawmm nmm wmmw aw 5 5 FH mgnl II J39BXEMEthQt BE 0 m LST 14 s 3 V Plum alEl 1n nn rnnr LDX a xnnnnnnnn a 1n Lon l a mask Fur nnan L31 2n I set nca tn tuggle nn LDD stnre rcuronr in Inca ne noun a 1a In mask lnnp nemmymt gang Run an In N Sunnn Sun 1 gm Fur ncar hack 0 Sun HJEIE Sun Sun and or tn IENI Sunnn Una Sunnn stnre new tame n Inca c1 sffff hack tn the tn Inez sffff Inca Snnaz Inch SH nun nzxzr reset uectnr Inns SH Sffte E M FDR mm set tn start nf prngram mm 1 Sum 5quot mm M Sun1 Sun e21quot n S1nnc Sun IEIU 391 1M xnnmnnnn IEILZ n 1n21 Sun Insk1 n 1n22 Sun IFLIH I1 1 23 X Inskz n S1n2u Sun IFan 1 S1n25 s lASm las lxnnm lvshm iwsmn fwme l mkwda m d Step further The program goes through the loop on LABEL1 As long as TCNT is less than TOC3 the bit OC3F in TFLG1 bit 5 remains zero and the program loops e When the value of TCNT exceeds TOC3 the bit OC3F gets set Simultaneously the output compare function is activated Recall that our program was set to toggle the value in pin 003 when output compare condition is met Look in the Port A pins window Notice that the pin OC3 PAS is set Your screen looks like this Dr Victor Gurglullu Page 47132010 EMCH 367 Fundamentais of Microcontroiiers Exampie OUTPUT COMPARE TiMER FUNCTiON E Lsr 1n nn mn LDX imam 1n um unnmnnnn mask Fur nman L31 2n 1 munx set nca tn tuggle Scum m an um or stare mumquot in Inca Sunny 23 n2 noon mum n 1a 0 rncax k maim lnn Sc f m H mum mnmnnnnn mask car near Maman Scn11 27 F3 aEn Lkast1 lnnp hack nkm okra or m sunnn sun m nnn1 2 mun reset mm m 5m Sfffe on an m mm set tn start nf prngram m 1 51m 5 mm m Swan sun 1 was Sun m 1 an xnnm nnnn n21 nn S s1n2 sun N 1 23 X 1 4 Sun Sun 1 magma uuuuuhsec iAsnn imz ixsmun ivs2c3a isPsmrr iiPEscnUd ii iack ycie 53 f At this point the condition for exiting the loop is met and when stepping further the loop is exited Your program gets to 0013 The mask for OC3F is stored in TFLG1 and OC3F gets reset Your screen is unznnk uxnnn1nnnn mask Fur nman L31 rcrL1x set nca tn tuggle or stare IENIoDI in Inca runnx rncax x maim lnnp in mnm xn 23 Lkazn Ll ck nca 2n an an rnn1x r nk unmannnn Emmava HIE am mam p mm okra or m sunnn sun A 11 Snnm 2 v mmem ut t c mar n Ev HE I ESX St YE new time in I ES sum 2n H mm hack n m n ma reset nectar m5 Sm Sfffe an an mm m n start nf mmquot 1 51m 5 Sun1 sm 1 nnc Sun Sun xnnmnnnn n21 Sun n22 Sun Sun xnnnnnnnn 1 nzu Sun Dr Victor Gmrgmuu Page 57132010 EMCH 367 Fundamentals of Mlcrocontrollers Example OUTPUT COMPARE TlMER FUNCTlON g Step further The time increment DT is added to the current time TCNT and stored in TOC3 as the new time Your screen is mt nn ST RT n LDX unznna LIN unnmnnnn mask Fur N3 L31 gran IEIL1X set nca tn tangle LDD or stare Icuront in Inca anon mm D Inc3x e Main lnnp n n Sc n 35 23 mm mm mum check ncar Sc f m H M mnmnnnnn mask m ncar ohm 5E Sun 27 En mm lnnp hack am am or n sum sun a sum 2 v when nut t cn I 1 1121 Snunn or z and or tn wequot E2 Sana 39 NVX Ilca Snunn Incax stare new tlme 1quot Tuna asset reset nectar Sfffe on an Fun Stunt set tn start nf prngram T ES rrr anRc I1 Swan Sun mm M Sun1 Sun n21quot n S1nnc Sun TETU 391 1M xnnmnnnn rcrtz n 1n21 Sun Insk1 n 1n22 Sun TFLIH I1 1 23 X Inxkz n S1n2u Sun FLGZ n S1n25 Sun v lAsnn lassh lxxinnn imeae lsPsnm Wseme lElackEycles 83 h Step again through your program Observe that the whole procedure is repeated only that this tIme the toggle was from 1 to 0 This shows that effec ively a square wave of half wave duration DT is being generated at pin OC3 PA5 Next we will verify the length of the half wave in time units and determine the effective frequency Press the Reset button Press the RUN button The program should again loop on LABEL1 for a while and then exit the loop and stop at c013 At this point your screen looks like this Dr Victor Gmrgmuu Page 67132010 EMCH 367 Fundamentals of Mlcrocontrollers Example OUTPUT COMPARE TlMER FUNCTlON L E c2 1 En SIN LDX REGIME X Sc a n 1 Loan unnmnnnn mask Fur l13 L I MIE2 X Sc S a7 2 ma TETL1X set HES tn tuggle P 21E1 X Sun an H LDI I stare TENT DT in Intel PailHES X Sun 23 2 Dim TENTX PainHEM X n I T E3X Pasn23 X1 Pan EZ X at Main lnnp 39 P 7 E1 X Senna an 23 LanEn Loan TFLG1X check near Scnnf an H mum mnmnnnnn mask Fnr near Ewenannex BE Scan 27 F3 BEn mm lnnp hack mm om In M sum sun t 1 sum 2 v e we are were when nutiut Daniel2 naiiens 39 Sums 37 23 3mg In nx 2 233 Sum m an um m m m tn mu m2 Sm 5cm ea ne mm mm m3 Sunnn Scmh en 13 m rncax stnre new time in Inca mm SH Scum 2n ee mm mm hack tn the tn m2 Sm m was Snnaz Inch SFFFF mu nun reset nectar s rm an Fm39 quot 5 5quot 39 39 E1l I1 51quot Sun I 1 1 c 5quot ET I1 1 2 X 1 I1 1 21 SE n r S1n25 nn lSimulaledlime unuuualsec lAsZn lasaz lxtmnn lvsznan lsPsmrr liPcscma lElnckEycles 52 1 Note that the clock cycles are 62 and the simulation time is 31 us These values are entered in Table 1 j Run again through the program At the next breakpoint your screen looks like this IlIIHilIEilIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIEII ee 1n nn mm LDX nntum A 5 1n LDM Mnnmnn mask fnr nnan nL31 rurt1 gmgm xnm s Scunn Senna Scans a7 Scum Sunny 2n mn x set nca tn tnggle 2nnn an an Lon m stnre mum in ma ea ne mm mm Sunnh en 1a 10 Inc3x e Main lnnp Senna an 23 L HEU Lona IFLG1X check ncaF scnnr nu 2n mum unmnnnnn mask rnr near quotWm H Scan 27 F3 BEn mm lnnp hack nm m n sum sun n1 2 v e we are here when nutiut Daniel2 haiiens mnenegime Sun Sums a7 23 Ema TFLGLX 5 Sum an an LDI In and In tn mm 5 scn1n ea ne anon rcNIx Sana Scmn en 13 m rncax stnre new time in Inca SH Scum H 22 mm L HEU hack tn the tn SH Sunnn SFFFF nnn RESET reset uectnr Inns Srrrr crunc n 1nnn Sun nc1n n 1nnn Sun nc n S1nnc Sun Sun xnnmnnnn n21 Sun Sure E M FDR 3mm set tn start nf Erninm 1 n22 Sun Sun umnnnnn 4 s1n2n Sun zazazze 55r 3333 S1 n25 Sun l V swulale lwe unnunaseee lAsZn inset lxsiuun lvs2c3n lsPsmrr liPcscma ElaDKEycle n3 Note that the clock cycles are 113 and the simulation time is 565 us These values are entered again in Table 1 Dr Victor Gmrgmnu Page 77132010 EMCH 367 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION k Run further through your program and after each breakpoint stop record the clock cycles and the simulated time in Table 1 Do this until you have completed 6 LH groups These correspond to 6 square waves 5 Calculate the halfwave time At and the equivalent frequency f12At When doing this omit the first row in your readings Note that the time interval oscillates between 25 and 26 us while the frequency oscillates between 200 and 192 kHz ie 199t02 kHz or 199t1 kHz These oscillations are an indication of the repeatability of your process and are due to the displayed simulation time being limited to 1 us while one MCU cycle takes 05 us m Calculate the raw frequency corresponding to the delay 0020 using the formula fmw Hz Notice that the raw frequency is 3125 kHz while the obtained 2DT 05us frequency is 20 kHz The difference is a programming overhead due to the extra cycles that are consumed in the program between two OC events We expect that this overhead will become less and less significant as the delay increases ie at lower frequencies n Put the value 0200 in DT Repeat the procedure above and enter the clock cycles and simulate time values in Table 1 Note that the effective frequency oscillated between 1859 and 1866 kHz ie 18625t00035 kHz or 18625t02 The repeatability of our simulation has greatly improved Calculate the raw frequency corresponding to the delay 0200 using the formula fmw Hz Notice that the raw frequency is 20 kHz while the effective frequency 2DT 05us is 18625 kHz The difference has reduced considerably 69 error This confirms the hypothesis that the programming overhead due to the extra cycles that are consumed in the program between two OC events is less significant at higher DT values ie at lower frequencies 0 Repeat for DT2000 For this long delay the frequency scale is switched from kHz to just Hz In just a couple of cycles you note stable behavior and perfect frequency accuracy This is due to the desired frequency 122 Hz being much lower than the MCU clock frequency 2 MHz For more details of how these errors are generated in the MCU please see Appendix 4 Dr Victor Giurgiutiu Page 87132010 EMCH 367 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION Table 1 Dr Victor Giurgiutiu Page 97132010 EMCH 367 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION GENERATING A DESIRED FREQUENCY We will now practice to obtain a desired frequency Table 2 We will start with a low frequency eg 100 Hz since we have noticed that our square wave generation behaves much better at low frequencies Then we will increase the desired frequency until a practical limit is obtained a Examine the row 100 Hz in Table 2 Notice that the corresponding halfperiod is 5000 ps Hence a raw estimation of the delay can be calculated with the formula delay halfperiod05 and then converted to hex The result is entered as Raw delay in Table 2 Enter the DT 2710 into the THRSim11 reset and run Note that the time of the breakpoint stop is 5012 ps Run further and note the second time as 10024 ps These values are entered in Table 2 The resulting halfwave duration is 5012 ps which corresponds to 998 Hz Le a 02 error We consider this good enough and select to stop here 039 v c Try to generate 200 Hz According to Table 2 the corresponding halfperiod is 2500 ps and the raw delay is 1388 Since we know that the MCU adds some extra cycles of its own we select to round down the raw delay to the value 1380 Enter this value in the THRSim11 reset and run Record the times after first and second loop These times are entered in Table 2 as 2510 ps and 5020 ps respectively The corresponding frequency is 1992 kHz ie 04 in error We improve on this error by making a minor adjustment to the DT from 1380 to 1370 The value 1370 gives us the desired frequency of 200 Hz exactly d Try to generate 500 Hz According to Table 2 the corresponding halfperiod is 1000 ps and the raw delay is 07D0 Enter this value in the THRSim11 reset and run Record the times after first and second loop and enter them in Table 2 as 1012 ps and 2023 ps respectively The corresponding frequency is 495 kHz ie 11 in error We improve on this error by making a minor adjustment to the DT from 07d0 to 07c0 The value 07c0 gives us the frequency 499 Hz which is only 03 in error We select to stop here e Try to generate 1000 Hz and 2000 Hz Follow Table 2 for the values of the corresponding half period raw delay and actual DT iterations Notice how accuracy is being improved by small adjustments in second hex digit of the DT 9 Try to generate 5000 Hz According to Table 2 the corresponding halfperiod is 100 ps and the raw delay is 00C8 This is very small delay and we expect some difficulties Enter this value in the THRSim11 reset and run Record the times after first and second loop and enter them in Table 2 as 112 ps and 223 ps respectively The corresponding frequency is 4505 kHz Le 99 in error We try to improve on this error by making minor adjustments to the DT from 00c8 to 00c0 and then to 00b8 00b0 00b4 However the accuracy cannot be reduced below 2 This indicates that we have reached a limit in our capability to finetune the frequency This limit is due to the low value of the desired DT We select to stop here and conclude that 5000 Hz 5 kHz is a practical limit in the squarewave frequency that can be generated with the MCU within 2 accuracy For more details of how these errors are generated in the MCU please see Appendix 4 Dr Victor Giurgiutiu Page 107132010 EMCH 367 Table 2 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION WHAT YOU HAVE LEARNED In this example you have learned Dr Victor Giurgiutiu The use of MCU Timer function as an Output Compare OC device The setting of OMx and OLx bits to select a desired OC event in this example we set OM3O OL31 to generate a toggle on the 0C3 pin The detection of the TOCx match with TNCT and the corresponding OC action The correlation between delay DT with actual frequency of the square wave The accuracy with which frequency can be adjusted The determination of low and high bounds on the frequencies that can be generated with the MCU Page 117132010 EMCH 367 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION This page is intentionally left blank Dr Victor Giurgiutiu Page 127132010 EMCH 367 Fundamentals of Microcontrollers Example OUTPUT COMPARE TIMER FUNCTION Dr Victor Giurgiutiu Page 137132010 EMCH 367 FundamentalsofMicrocontrollersSJgn1mMNTcdoc OUTPUT COMPART TIMER FUNCTION Dr Victor Giurgiutiu Page 1 7132010 EMCH 367 Fundamentals ofMlcrocontrollerS Example NPUT CAPTURE TlMER FUNCTlON EXAMPLE INPUT CAPTURE TIMER FUNCTION OBJECTIVE This example has the following objectives Review the use of MCU Timer function as an Input Capture IC device Review the use of the free running clock TCNT and it overflow ag TOF Review the use of a input capture clock TIC1 and its event ag IC1F Demonstrated how the selection of signal transition to be captured is made here rising edge EDG1A and that the MCU is only sensitive to that particular transition 0 Show the calculation of actual time in ps from the timer readings T1 T0 and overflow count OF PROGRAM EXC This program is an example of timer input capture The process is started when a keystroke is received Then the time is measured until a lowhigh transition is captured on line IC1 In this process the initial time T0 and the capture time T1 as well as the number of overflows are recorded After the input capture the IC1 F ag is reset the over ow counter is zeroed and the process is repeated FLOWCHART AND CODE The program owchart is show to the right of the program instructions Note the variable de nition block in which T0 T1 and NOF are de ned Next the initialization block contains reg X initialization timer IC initialization and SCI initialization The program loop starts at label BEGIN with the over ow counter NOF being zeroed First the RDRF reception data register full flag is checked in a loop to verify if a keystroke has been received When keystroke was received the time counter is read and stored in T0 Then the programs loops on LABEL1 until and input capture IC1 is recorded In this loop TOF is first check to verify if timer overflow takes place When timer over is detected the over ow counter NOF is incremented and TOF is reset Next IC1F is check to verify if input capture on IC1 took place If input capture is not detected the program returns to LABEL1 When input capture is detected the program exits the loop loads the IC1 timer from TIC1 and stores it in the capture time variable T1 The program loops back to the beginning and wait for a new keystroke to restart the process The essential code for the program is shown to the right of the program flowchart This essential code was incorporated into the standard asm template to generate the file ExlCasm Dr Victor Glurgluhu Page 17202010 EMCH 367 Fundamentals ofMIcrocontrollers Example NPUT CAPTURE TIMER FUNCTION Instructions Flowchart Code ORG DATA Define variables RMB 2 i De ne variables Origin oftirne T0 2 bytes RMB 2 Origin oftime T0 2 bytes Capture time T1 2 bytes RMB 1 b Capture time T1 2 bytes Overflow counter NOF1 I byte ovaryquot quot e v NOF1 39 1 initialize REGBASin regx LDAA uuoomoooo H Initialize InitializetirnerIciunction STAA TCTLZX S i IFI TCTL2 LDAA VuOOIIOOOO Ill Initialize IndexXto REG mmahze STAA Iv Initialize timer IC1 function set LDAA cyuoooooooo EDG1Ain TCTL2 gt STAA 1 V Initialize SCI LDAA VuOOOOI IOU vi Wait for a keystroke reception we l KURT 5 set STAA CCRZIX vii Store initial ime SCSR X eer39soefverllow counter NOF1 23 TCNT into TO AN DA Wuomooooo Wait for theinput capture Reset TOF E3ng LABEL XI Che LDD TCNT X xii Jump if no TOF else STD To a Increment over ow counter LDAA 51900 b Reset T STAA NOF1 XIII Check IC1F ZTQEOXOOOO I 0p bECk LABELI LDAA xv Alter input capture d TFLGZ X u xvi Loadan storet1 QNBA ffg EgOOOO E xvii Reset IC1F by writing1 to it INC NOF1 xviii Loop back to iii and do it again LDAA WOOOOOOO STAA I LABEL2 LDAA TFLGI X ANDA VuOOOOOI 00 E0 LABELI a d store measured LDD TICI X time from TICI into TI STD T Resericw LDAA Eyuoooomoo STAA TFLGI X BRA BEGIN SWI Dr Victor Glurgluhu Page 27202010 EMCH 367 Fundamentals ofMlcrocontrollerS Example NPUT CAPTURE TlMER FUNCTlON EXECUTION Open THRSim11 Close the Commands window View CPU registers timer registers port A pins memory list serial transmitter Open and assemble ExCasm Set breakpoints at c01a c02e c03b and at SWI Reset registers and memory Set standard labels LabelSet Standard Labels Set display of TCTL2 TFLG1 TFLGZ to binary Arrange windows for maximum bene t Press the RESET COVVeSPW WWW Updated 5 Program button Your screen should look like this w W rm tat now mm mm e E l zl 39 E Al Ji Comment V62The screen capture does not Show the Standard labels TCTLZ TFLGl etc Did you follow the text step by Step Need u 1 e5 again showtng what l5 Ma a 20 n e ex updated asm program to do updated n captures umnnnaaa initialize anunssea sum 1 2t smn awn swan m an Lam umaeseaaa initialize 3bit word ed a 2 min scc 1x Scalar at a Luau Iueoeiisa initializo TE and RE Semi a 2d sma 5cm Sam BI new NOP win as 2o main man t mx L check if mm id on Scars u 20 Anna Iwalasnsn mask For RDRF Sears 1 r BER LnsELe r 39lquotrlvi r7 urn aulrflml auntr can as o Lon Isua Scazz 3 an sma NnFI sezu so Lona manuanun rent tor so sea s 325 a 25 Sm Inns 161 a stem son r TETLZ H smzl usaaenea Saaza as 25 LaaELI Lona TFLGZAI check tor Tl SKI K mil 3939 332 a 0 mm uztoaaaaoa an leek IFLGI H sum mneooaee Seazc 2v 91 Ben LABEL2 39u if no an VNSKL M 5 82 95 TrLsz N 51925 mnaaonaa Saszi as so um 11993990 rose var D 2 9933 a7 15 an IFLCEX V A SCHIE IE 23 L BELZ LDFIH FLGIX SHOCK I qua39 nail E39 N sagas j Scan 31 an arm nzasasaloe am Hith lcw lash 32 59 5539 27 Gd BEE LREEL loop hack sea r r it tr BE 5 2 l case do ea 10 n a K 552quot 116 EN LDRQ ILEEHBBHJB reset C by writing 1 In it 350 a 23 ST 39F LBIX Scan 25 co sun BEGIN loop back to do it again l a i r r 1 Sim 39Nlmn tmnauuolsw I l L amazeam oun uu iuii m6 new mac r vi iro sPswn MM 2 a Dr Victor Giurgiutiu Page 37202010 EMCH 357 Fuhdamehtats at MtcmcummHevs Examp e NPUT CAPTURE TTMER FUNCTTON a Press the RUN button The program shomd Toop oh LABELO Type tetter T thto the sertaT transrmtter and send The program shomo extt the Toop and Stop at smote At thts potht your Screen ooks We the 49m WW t gg am xmnahn mm mm quotunath Enuuwss nunIn midnu r a x m emu now vt pr Wm rt mm s a mum um sum chuck 5 raw 2 m ucz sauna Ssnls n 2 ma nitmanuals mm for my ms Swan km 21 F In mam Tncv srrrr r7 rvh M Inca rm Inc srrrr Sam n H mm x mm mm in mm srm Vacs arm Sm 2m uvrfluu emu an umaanuau r mnz x emu m I a stag sen Irtaz H stazs unansnss S a t Lmy 5 an mom 39 T r 39 A ms t a up 5M gg usm quott quot SW 3 j 5cn37 u at an memequot mm m ms m n gem u 5 a main m m x sun 1 u saw an 1 L n n n Iznaaauma rm mr By uruing u u u an IanIgtlt a mm new mt mt u u n gm n J re t t M V r n 7 rm NW m t whom mason Am um svavtmquuou xnwu mm arm am an F D chmexurguuu Fag AVIDZulu EMCH 357 Fundamentats at Mtctucunttuttets Examp e NPUT CAPTURE TtMER FUNcTtoN b step You tht nottce tnattne contents ofSCDR 3954 t e ASCH forT nas been toaded tnto act A 0 step agatn Tne screen ooks hkethts 42m m cm 3 t Vsum fufimtiih 7quot l xt r 4 quot1341 I mug an t Mg i tatsaunt min A v Humans ummm mmm YEVLZ sum YEYL2X 2 E E quottutm YE m as 5cm at mm at mm s 2 mm t a scsmt M mm at Mt 21F mats gm c s mm m gm 7quot rm I an A usau zlrn uvrfluu cuuntrr EVER men sen Scan 51 M a Mn W N 3 9 59quot Sanzu x at a museum r 5 M 5 5 3 S 528 1 25 a IFLGZ gtlt 39L 5 03 t u m mm 23 as 25 mam M Irtazx hvck m mm mm sea W t M m mum W m smza mm We at at u Laastz u m m m2 st is mannennn ml 35 at M utmmt m x Stu 1 2 an vFanx JEL mt t at an mantaquot at my m M s 5 1m t to W sand dd 82 s u n n x Scnzf n m u an mastmat run mr by Hung I m u JJJ W 1 2 mm mm tt M latmurmurquot WWSNx MW em xuuw mtg SFIW Imkzyun 1m I You nottce tnat tne contents of TCNT tn tnts case totc nas been toaded tnto ach Tne doubte cutnutatotach ts used stnce tne tttne vatues are tn doubte prectStOn t e ttequne 4 hex dtgtts D chmexurguuu Fag smut1mm EMCH 357 Pundamentats at Mtctucunttuttets Ekampte NPUT CAPTURE TTMEP PUNOTTON o step agatn t mm y 1 5 mama 39 it am m W W m t maggmms ZLd E BJ amtmax r m m mnuhn YEILZ sum mat iom mumz Max559 x tutu mm tinnu nu ma 1 ma scrum IZDIIEBHEH mmm YE no a scrum vttn t t t 3mm 5mm s a mans Lu 9 srsax t chvc aw s m quot1 satn Sums x 2 an a ttxaatanaau mm m m ma swan Stun 2t 5 5 mm quotIn SPFquot t t t 1022 smr WCZ arm m with t 1004 SW Vacs m a s n 1 mm mm rm K stm sen a want HEW N sum Sail t nzmaanuan 7 Y F Ltn N stm on 51 t a mm x v m tt Swan t t t t mtz tt stazt momma Ixsn H smzz sag sum In a I39Lmnn unn YnF my mat N staza momma smz 21 01 mam 1 n tar Ixsxl tt sum sue m nz W25 19mm 553 a uztnnmsa mr x 55535 21 mm a mam chuck Ur u W t t m j Scu39n w a a I39Lunaamen am my mr usk quot x 5mm Sm Scans zt e tnazu 1 Duck u Wm m n NDFV tt suns Sal d mm 41 a St n u 1 Scalf x to ln a unasanmn 7 or at unzng t a 1 kW 1 21 St a mum mu m scan 2 a an m w 1 my t a 12 gm 1 r t tetmttzwtct not Vmax mot we a You nottce tnattne content Of ach tot me ammo but you may get sometntng etset nas oeen toaoeo tn memory at tocatton To tt takes two cOnSecuttve memoty Ocattonst and ts toaoeo as 10 fOHOWed oy tc At tnts stage Tne ttmet count TNCT yatue was captured and stored tnto To as tntttat ttme a cneck tot TOP Swttcn otsotay Of accA to otnaty step Tne yatue OfTFLGZ uuotooooom ts toaoeo tnto accA o step 2 ttmes Tne yatue tn accA ts ANDred wttn tne TOP mask uDTOOOOOOO Stnce TOP was not set tne tesutt ts Zero and tne BEO Operattomumps to LABEL2 c cneck tottctP step once Tne yatue otTPtet 00000000 ts toaoeo tnto act A step 2 ttmes Tne yatue tn act A ts ANDred wttn tne tctP mask uuoooootom Stnce tctP was not set tne tesutt ts Zero and tne BEO Operattomumps to LABEL1 o You are back at LABEL1 step tntougn tne TOP cneck and stop wnen you ate at 0035 e Toggte tct otn tn PortA otns wtnoow tom 0 to t Nottce that as btt 2 tn TPtet gets atso set Tnts ott ts tne tctP ML and tt detects tnat a ttansttton nas taken otace on ttne tct D chmelurguuu Fag own1mm EMCH 367 Fundamentals ofMicrocontrollerS Example NPUT CAPTURE TlMER FUNCTlON 3 Step The value in TFLG1 00000100 gets loaded into accA Step again AccA is ANDed with the C1F mask 00000100 The result is 00000100 ie nonzero Step again Since the result of the previous operation was nonzero the BEQ operation does not branch and you proceed to line c03b LO 339 Change display of accA to hex Step The value in TIC1 for me 2994 but you may get something else is loaded in ach The double accumulator ach is needed since the timer values are in double precision ie four hex long Step again The value in ach for me 2994 but you may have something else is stored as the captured time in T1 Note that two memory location are used and the storage is done as 29 followed by 94 You will do this now on automatic Press the Run button Then press the send button in the serial transmitter to start the inputcapture process Your program stops at the breakpoint c01a 35 Step The TCNT value mine is cf13 yours may differ gets captured in ach Step two times The TCNT value ends up in T0 in my case cf13 yours may differ 3 Run Toggle pin C1 in port A window As you toggle from 1 to 0 nothing happens since you only set EDG1A1 in the initialization section This means that you programmed the MCU to only recognize raising edges on line C1 ie transitions from 0 to 1 3 Toggle again now from 0 to 1 Note that the loop is exited and the program stops at the breakpoint c03b Run again several times and consolidate your understanding of the way the program runs Try sending different characters and notice that the program is only sensitive to you sending a character but insensitive to what character you sent 8 1 When you are content with your understanding remove all breakpoint but SWI Set a new breakpoint at Run go the sending and the toggling and after it stops at the Calculate the time taken between your sending of the character start of the process and your toggling of C1 from low to high stop of the process AtmmE T1T0 10000 NOF05 p5 6227 49c8 10000O 05 ps 3119 us 31 ms ADVWS T1T0 10000 NOF05 p5 7777 7777 10000O 05 us 7777 us 7777 ms Dr Victor Giurgiuuu Page 77202010 EMCH 367 Fundamentals ofMlcrocol itrollerS Example NPUT CAPTURE TlMER FUNCTlON q Try to wait for the NOF to change to 1 before you toggle the IC1 pin write below the values of T0 T1 NOF My results Your results To 872e T1 366e NOF 1 AtmmE T1T0 10000 NOF05 p5 366e 872e 10000 1 05 ps 55200 us 552 ms AUWUS T1T0 10000 NOF05 p5 7777 7777 10000 1 05 ps 77777 us 7777 ms Note The results from u and t do not need to agree They depend on human factor like when you decide to toggle the IC1 bit WHAT YOU HAVE LEARNED In this example you have learned The use of MCU Timer function as an lnput Capture IC device The use of the free running clock TCNT and it over ow flag TOF The use of a input capture clock TIC1 and its event ag IC1F The selection of signal transition to be captured here rising edge EDG1A and the fact that the MCU is only sensitive to that particular transition The calculation of actual time in ps from the timer readings T1 T0 and over ow count NOF Dr Victor Glurgluhu Page 87202010 EMCH 367 Fundamenta s owacrocontroHerS EXamp e NPUT CAPTURE T MER FUNCT ON Dr chtor Glurgxuhu Page 1 7202010 men 357 runoenemos owroomnmuers Examme 2 EXAMPLE 2 OBJECTWE ans srmpre exampre nas the quuvwng opreouyes Fammanze the userthh the THRSrmM srmorator enyrronment ntruduce the usertu the syntax and cuncepts orAssempry asm anguage nstrumthe usertu mterpretthe Lrst LST rue Teaen the usertu perfurm the srmorauon and quthhE sieprbyrs tep resorts ntruduce ADDA uperatmn PROGRAM EXZ asm prugram rs yery srmpre n perfurms the amhmetm uperatmn 3 2 5 usmg the ADDA TD arm P Hm Luadthe nomper re n mn rmmeorate mooe uu m number the operand 2 Nuts thatthe rmmeorate mooe rs agam oseo Tne symbuh representatmn or 1an proeess s rmmeorate mode A 2 9A rmmeorate mode We srgnrnes that number 3 rs uaded mm accA number 2 rs uaded mm rmmeorate memury and the cuntent or am rs added In or memory Wrth the resort bemg put back mm am EXECU HON 1 Open THRSrmM 2 MaxrmrzeTHRSrmM Wmduvv 3 crose the Cummandswmduw 4 Open rue EXZ asm 5 Assemth Me by pressmg the Assemth buttun 314 Donng assembw yo ye mse A Happy dwsk onye thh the Me n t u mu ned m the 7 no way the assembher Wm nno the we path AWAKDEF ASM Wnen Execuung the Assembw orreeuye NCLUDE E sey you get error Dv Mamewrgumu Pager memo men 357 rundenentats thaammmHers Examme 2 a Ttte vvmduvvs by pressmg tne THE buttun 7 Set a break pbtnttb tne ttne ebntatntng tne bpebde rnnernetnte 5 Tu db set seteettne hnE ngnt EMEK and enbse Set reakpmnt Tne ttne beebrnes arnber cnange tet deetrnat tne dtsptay rnetde pt regtsters At a tn tne CF39U Regts ters thduvv Tu achteve tntst ngnt chck un tne ttne and seteet Deetrnat Pdtzerbstn t e reset regts tersD X Y Tu achteve tntst ntgnttgnt tne hnE type tn tne venues and ntt Enter Untess ybd magnet USE Wu natves uf D Yuur screen snbutd uuk We tnts 7 Mat my next Tne rnernetry address at tne ntgnttgnted met as gtven tn tne ttrst n umn ts EEIEIEI Tnts rneanstnat tne prugram ebdnter PC at EEIEIEI ndeed tn tne CPU regtsters thduvv ybd ean see F39C EEIEIEI Tne F39C vatde tndteates tne memury address at tne tnstrdettbn tet be Executed next m Usetne Step buttbntblltb step tnrbdgn tne prugram Fur tne Step buttun tet be aettvet ybd need tet be tn tne LST Wmduvv Hence seteet tne LST thduvv ttybd have nett dbne set atready Dv mateturetmtd Page 2 mama EMCH 357 rundanetttats thaammmHers Exanpte 2 Press tne step buttctn ctnce thur screen snctutd uuk WE tnts tn tne CPU regtsters thdbwts PCcum Tne ttne scum tttt a ttwtu be executed next Wnen tne Step buttctn ts pressed 11 Press tne step buttctn agatn thur screen snctutd uuk WE tnts mu 12quot239quot 39 quotquotrt Tne green ntgnttgnt nas muved tct tne next hnE startth at addressCEE3 tt nasturnbed by 2 cbunts because tne ttne tnat nas tust been executed nad th obcbdes E rnacntne tnstructtbns tn L SE and us Eacn obcbde taxes ub bne rnernctty address nence tne prugram t r t as Can be readtty vert ed tn tne CPU regtsters thduvv tntct aCCA thu can verttytnts by nutmg tnatt tn tne CPU regtsters vvtrtduvv yuU see A 3 at mateturdtuttu Page 3 mama EMCH 367 Fundamentals of Mlci ocoritrollers Example 2 12 Press the Step button again The screen looks like this My mily w my The execution of the previous instruction has performed the addition between the contents of accA ie 3 and the number kept in the immediate memory ie 2 The result of the operation has been put back into accA This means that the arithmetic operation 3 2 5 has been executed The result of the addition is shown in the CPU registers window the accA has become A 5 as expected The green highlight has moved to the next line which starts at memory address c005 In the CPU registers window the program counter indicates PC c005 The line c005 contains the opcode mnemonic SWI which signi es the end of the program You are done Do not press the Step again because itwill throw you out of the program area 0 To rerun the program you have to place the program counter again at the beginning of the program Select the line c001 ie where the meaningful part of the program starts Right click and select Place program counter on The line that was selected becomes green highlighted You can now step again through the program and see how it operates You can also press the Run button and the program will automatically execute up to the next breakpoint In our case the program will run all the way to the SWI instruction where the breakpoint is placed WHAT YOU HAVE LEARNED In this simple exercise you have learned quite a few things New words and concepts Opcode opcode mnemonic immediate mode Assembly language asm list file LST reset program counter PC break point registers Microprocessor opcode mnemonics LDAA and ADDA Meaning of immediate mode and how to invoke it by using the symbol Symbolic representation of the operations and their meaning Open and customize THRSim11 environment Assemble an asm le Interpret an LST file Dr Victor Glui glutlu Page 4 7292010 EMCH 367 Fundamentals of Microcontrollers Example 2 0 Tile the THRSim11 windows remember that the tiling seguence follows the sequence in which ou accessed the files with the most recentl accessed window tiled in the left u er corner 0 Put a value in a memory address eg when you put zeros in the registers 0 Set a break point 0 Step through the program simulation and follow the changes taking place in the CPU registers window 0 See how program execution is affecting accA Identify the results of the calculation ie 3 2 5 makes accA to show Dr ctor Giurgiutiu Page 5 7292010 EMCH 367 Fundamentals of Microcontrollers Example 2 This page is left intentionally blank Dr ctor Giurgiutiu Page 6 7292010 EMCH 367 Fundamentals of Microcontrollers az2ZL2IPstdoc Dr ctor Giurgiutiu Page 1 7292010 EMCH 367 Fundamentals of Microcontrollers Example 1 EXAMPLE 1 OBJECTIVE This simple example has the following objectives 0 Familiarize the user with the THRSim11 simulator environment 0 Introduce the user to the syntax and concepts of Assembly asm language 0 Familiarize the user the way arithmetic operations are handled by the microcontroller o Instruct the user to interpret the List LST file 0 Teach the user to perform the simulation and follow the stepbystep results 0 Introduce the LDAA LDAB and ABA operations 0 Introduce immediate addressing mode 0 Introduce inherent addressing mode PROGRAM Ex1asm program is very simple It performs the arithmetic operation 3 2 5 using the ABA operation in immediate mode To achieve this the program does the following operations 0 Load the number 3 into accA using the opcode mnemonic LDAA with operand 3 The symbol signifies that the number 3 is used immediately For this reason this mode of operation is called immediate mode Load the number 2 into accB using the opcode mnemonic LDAB with operand 2 Le using immediate mode Add the number in accA ie 3 with the number in accB ie 2 using the opcode mnemonic ABA and no operand This mode which uses no operant is called inherent mode The symbolic representation of this process is 3 9 A immediate mode 2 9 B immediate mode A B 9 A inherent mode This signifies that number 3 is loaded into accA number 2 is loaded into accB and the content of accA is added to the content of accB with the result being put back into accA EXECUTION 1 Open THRSim11 Maximize THRSim11 window Close the Commands window Open file Ex1asm P9 Dr ctor Giurgiutiu Page 1 7162010 men 357 runoenentots thaammmHers Exonptet El 5 Assernbte ttte by bresstng tne Assernbte button W Durtng assembty you rnust naye tnserteo tn tne A Happy dtsk onye tne uppy dtsk thn tne ttte VARDEF ASM tn tnts way tne assernbter Wtu ttno tne ttte batn AWAKDEF ASM mnen Executtng tne Assernbty otreettye NCLUDE Etset you get error a Ttte vvmduvvs by pressmg tne THE button 7 Set a break botnt to tne ttne eontatntng tne obeooe rnnernonte SN To do say seteettne hnE ngnt EMEK ano enose Set reakpmnt Tne ttne beeornes arnber cnange to oeetrnat tne otsbtay mode or regtsters At a tn tne CF39U Regts ters vvmduvv Tu aenteye tntst ngnt chck on tne ttne ano seteot Deetrnat Putzerostn t e reset regts tersD X Y Tu aenteye tntst ntgnttgnt tne may type tn tne venues and ntt Enter Untess you ntt entert tne two natyes of D Yuur screen snouto uuk We tnts 7 II E L MIN El in 5E m J u on 3 New mun nzr m tttttt M or M zw yii W quot39 Ilium 32 you t u m r mm mm Sum to n J m m quotnitquot m o u u no mt w m em m Mm 39m if mm 2339 32 1 C39 Tne green ntgnttgnt tn tne LSTvvtnduvv tnoteates nnten ttne or prugram tsto be Executed next Tne memory address or tne ntgnttgnteo may as gtyen tn tne ttrst cummn ts EEIEIEI Tnts rneans tnat tne prugram eounter PC atcEIEIEI ndeed tn tne CPU regtsters thooyyt you ean see c euuu m Usetne Step bunun to stebtnrougntne prugr rn Fur tne Step button to be aettyet you need to be tn tne LST vvmduvv Heneet seteet tne LST thooyyt ttyou naye not done so atreaoy Dv MHDYGNVEHAM Page 2 memo EMCH357 w e u m Snquot Fundamema s m MtaammmHers 31 gag t Emmet W the CPU regtsters wthduwts Pceum The hhe eum t Wm be executed next when the Step buttun S pressed 11 Press the step butch IE agam Yuur sereeh shuutd uuk We thts Wm M W at ma Huh I a mu Wm mm W M m w aw mug y t wt u m srrrt M u w m mt m memewmm Mamas v Em we rumm m jr nmcwni 39nwn m m g My m u m matm m S V4a page n M e w W 7h mm u EMCH 367 Fundamentals of Microcoi itrollers Example 1 The green highlight has moved to the next line starting at address c003 It has jumped by 2 counts because the line that has just been executed had to Opcodes ie machine instructions in it 86 and 03 Each Opcode takes up one memory address hence the program has move forward by 2 locations The current value of the program counter is PC c003 as can be readily verified in the CPU registers window The result of executing the previous instruction is now apparent The number 3 has been loaded into accA You can verify this by noting that in the CPU registers window you see A 3 12 Press the Step button again The screen looks like this A m Elle Edit ieavth Mew Execute Label Eveakvmnt Canned Mndaw deb e e gaaazmm gtMee ll rmj extrise x v BE o m 1 u A AA n 2i A m a Start nf min prngram e Define prngram variables mu Pnnnmm mu m Senna n1 mn N P new wequot W we mquot a mm Scum Eh n3 Lima 113 mu Pnnmmn Senna c5 n2 SIN P new typing W we um ha 1 em a m mu SFFFE reset uectnr srrre en n run Stunt set tn start nf prngram e run nr main prngram 3m mu SFFFE reset uect m min set e m g vl l gti 4 I L A jsimuntee time n la snaju Snzjx1 x1 N 1 Nn 2 0 Enjx snmjv SnunanP snmjpc Sennsj 1 k cycles a The execution of the previous instruction has loaded the number 2 into accB just as the number 3 was loaded into accA The result of this operation is apparent in the CPU registers window where now we can see B 2 13 Press the Step button again The screen looks like this Dr Victor Giui giutiu Page 4 7162010 EMCH 367 Fundamentals of Microcoritrollers Example I 49129 le at seam Mew tame tale team We mm M awaiting gtbmi lil 3 extw V V BE 0 mu 7 Diem 2 x Start at main prngram x nerine prngram variables S sm mu Pnnnnmvl mu Dan 5 scnnn n1 rnnr N P snnn P sn1rr x negin typing ynur cane e Start at main prngram Scum 35 as Low as minimum 393 WWW Senna c5 n2 Scans 11 e End at main Erniram SFFFE E M mkm DEme39 um Stunt P e aegin typing ynur cane Loan ua Loan uz an I um mu SFFFE ST RI reset uectnr set tn start at prngram e End at main prngram m SFFFE Stunt l L reset 021 set tn st ISimulaten time 4 4 n it Snsln n2I31 x1 N 1 Nn 2 0 cnlx Snnmllv SnunnISP snmiec Sc l 1 k cycles The execution of the previous instruction has performed the addition between the contents of accA ie 3 and the contents of accB ie 2 The result of the operation has been put back into accA This means that the arithmetic operation 3 2 5 has been executed The result of the addition is shown in the CPU registers window the accA has become A 5 as expected The green highlight has moved to the next line which starts at memory address c006 In the CPU registers window the program counter indicates PC c006 The move of the program counter was only by one memory location because the operation ABA just executed does not have operand inherent mode and only requires one Opcode The line c006 contains the opcode mnemonic SWI which signifies the end of the program You are done Do not press the Step again because it will throw you out of the program area To rerun the program you have to place the program counter again at the beginning of the program Select the line c001 ie where the meaningful part of the program starts Right click and select PIace program counter on The line that was selected becomes green highlighted You can now step again through the program and see how it operates You can the program will automatically execute up to the next also press the Run button will run all the way to the SWI instruction where the and breakpoint In our case the program breakpoint is placed WHAT YOU HAVE LEARNED In this simple exercise you have learned quite a few things Dr Victor Giui giutiu w words and concepts Opcode opcode mnemonic immediate mode Assembly language asm list file LST reset program counter PC break point registers Microprocessor opcode mnemonics LDAA LDAB and ABA Meaning of immediate mode and how to invoke it by using the symbol Meaning of inherent mode Page 5 7162010 EMCH 367 Fundamentals of Microcontrollers Example 1 o Symbolic representation of the operations and their meaning 0 Open and customize THRSim11 environment 0 Assemble an asm file 0 Interpret an LST file 0 Tile the THRSim11 windows remember that the tiling seguence follows the sequence in which ou accessed the files with the most recentl accessed window tiled in the left u er corner 0 Put a value in a memory address eg when you put zeros in the registers 0 Set a break point 0 Step through the program simulation and follow the changes taking place in the CPU registers window 0 See how program execution is affecting accA and accB Identify the results of the calculation ie 3 2 5 makes accA to take the value A 5 Dr ctor Giurgiutiu Page 6 7162010 EMCH 367 Fundamentals of Microcontrollers Example 1 Dr ctor Giurgiutiu Page 1 7162010 EMCH 367 Fundamentals of Microcontrollers Example SCI TRANSMISSION EXAMPLE SCI TRANSMISSION OBJECTIVE This example has the following objectives 0 Review the use of serial communication interface SCI fortransmission o Illustrate the sending ofa character through SCI PROGRAM SCI TRANSMIT This program is an example of SCI transmission The character T is being sent to SCDR when TDRE is set Instructions Flowchart a Load REGBAS in reg X START LDX R EGBAS LD 00110000 b Initialize BAUD9600 STAA c initialize 8bit word 39 ItIaIIZe REQBAS 39 reg X LDAA 00000000 Initialize SCI STAA SCCR1X d Initialize TE and RE BAUD 9500 LDAA 00001100 8bit word STAA X e Load character 39T39 in AccB TE1 RE1 LABEL2 LDAB T Send the character to the terminal LABEL3 LDAA SCSRX AN DA 10000000 f Check if TDRE is set g Store accB to SCDR h Branch back to v i SWI Load T in accB Check if TDRE is set Load SCSR into accA AND with mask 10000000 age3 333 Loop if zero SWI Store AccB to SCDR You are here when the transmission reg is empty FLOWCHART AND CODE The program flowchart is show to the right of the program instructions Note the initialization block which contains reg X initialization and SCI initialization After initialization the character T is loaded into accB Then the status of TDRE transmission data register empty flag is checked in a loop When TDRE is found set the loop is exited and the contents of accB is stored in SCDR serial communication data register This operation automatically resets TDRE Now the program loops back to the beginning and tries to send again The essential code for the program is shown to the right of the program flowchart This essential code was incorporated into the standard asm template to generate the file SCItransmitasm EXECUTION Open THRSim11 Close the Commands window View serial registers View serial receiver Open and assemble SCItransmitasm Set breakpoint at STAB SCDRX instruction and at SWI Reset registers Set standard labels LabelSet Standard Labels Set display of accA to binary Set display of BAUD SCCR1 SCCR2 SCSR to binary Arrange windows for maximum benefit Reset A B X Press the RESET button Your screen should look like this Dr Victor Giurgiutiu Page 17142010 EMCH 357 Fundamentals ulMlcrucuntrullers Example SCl TRANSMlSSlON H iizir ygg E02 Edd gearcn law Ex cutz Label Breakpoml anhzct nundow Hen easements gt l quotl meals I z EELJQJ Hi t n A sPcn n 1n20 Sun at Start Inaquot program tSPSR I1 51M Sun nnc Pnnnnan 2 Sun anuo n 1n2n xnnnnnnnn scum n s1n2c xnnnnnnnn ccnz n 1n2n xnnnnnnnn m sum it 1n2e cc zumnnnn sum it S1n2r x11nnnnnn Sun st a a man cnaracter 39 c6 5 Lnauz Loan 11 e senn tne cnaracter tn tne terminal Lanna Loan scsRx cne anon l m 530mg gear Basel l7 mac agraaggTaw Note that the reset value olSCSR is quotn11000000 ie it has the ags TDRE and TC set This indicates that the transmitter is readyto transmit a Press the RUN button The program should loop on LABEL3 and exit the loop when the condition TDRE1 is satisfy This condhion is checked with the mask nn10000000 The mask is applied on the value found in SCSR When bk 7 in SCSR is set the mask senses h and the condition for exiting the loop is satis ed Since TDRE1 from the reset the loop is passed through and exited Dr VlE39 X megmu men142010 EMCH 357 FundamentalsulMicmcuntmllevs Example SCl TRANSMlSSlON b When the check TDRE loop is exited the program gets to the line STAB SCDRX This line is a breakpointAt this momentthe screen looks like this A 1 n Edit izarch iizw Exzcutz Label Erzakpomt annzct indow Help 335 gtbizu 39l gammy BE H u quotm L u D 11 7 mm xmnnnnnn spun n 1nzu sun D LDX um unnnnnnn 55 LL stunt cc x11n11nnn gllings l gee 4 gm ii M 7 Hquot JEWEL mi 3 mm SFFFE r252 He D an FDR Smut set 39I rem i We miscquot a Dale W 1 lln Sonia Ssnls1 gtlt1 M 11 quot1 2 0 cnlgtlt 1 an Snunnlsp mm m Ljncu Eye 5 c Step manuallyto the next line which stores accB into SCDR This store operation automatically resets TDRE The screen looks like this Dr thanmngmtm Page 37142010 EMCH 357 Fundamentals ulMicrucuntmllers Example SCl TRANSMlSSlON e Start program PR stunt the tErmina ehe transmission lasnn We h set a Delmar Note that SCSR is 00000000 This proves that TDRE has been reset by the storing to SCDRAIso note that the value 54 from accB has not yet arrived in SCDR The reason lorthis is that the simulator has an internal delaywhen running SCI in manual mode 1 Press RUN again The program loops several times on LABEL3 before exiting While looping you can see SCSR00000 TDRE When exiting SCSR10000000 When the program pausethe screen looks like this 4E1 Elle Edit gearch grew Execute Label Ereakpomt Cgm lzct l dQW Help AMAEIFJJ hblm quotl SXMEIJ W CEE 0 g jl 39k a mg a 4 a sun sPcn h 51m sue e Start hm program a 55 mu h 51m sun I sense we h 51 she 1n nn mm x 1nnn h 1n2n xmmnnnn H v sum h smze xnnnnnnnn a e Ln Sun co 5 Unith LIJRH u39l39 send the character tn the terhi e um Scan 35 2e Lanna um scsim che scn1a on an anon ux1nnnnnnn nho Sums 2 a Lexus an e th am here when the franltlniltltinn L BELZ J lasnn Wane ll SlaviBDalal sme l 0 Mix 1 an Sunnis em in equot him some He Silan Ssuls1 x1 Nl 11 N Note that SCSR10000000 ieTDRE1The transmission olthe characterwas done and SCI is readyto transmit again Dr Vlc39 i megmu Pag247142010 EMCH 367 FundamentalsniMleLnntmllelS Example SClTRANSMlSSlON e Press RUN again 2times Note that the characterT has appeared in the serial receiverwindow Yourscreen capture looks like this JELI Elle gdlr zarch 1w Emma Label 372prth cgnmm indolw Help a Na gtH5 quotl quotat aimmg v BE o 7 v D lth 13 u A human 5 m x11n11nnn gee l amt lyi39i 52mm l imne HEM 8 Data Tsmp WWW w mm l Press RUN again You get an add ional character in the serial receiver window Your screen capture looks like this a Start main prngram um mannaquot 19 1 in 5mm ml 95 an um mmoono smn muuuuunn 5m scum 9 Luau LRHELZ 339 Send the terminal LRBELS Ch 5 ND Dr thanmrgmhu Page 57142010 EMCH 367 Fundamentals of Microcontrollers Example SCI TRANSMISSION WHAT YOU HAVE LEARNED In this example you have learned 0 The use of serial communication interface SCI for transmission 0 The sending of a character through SCI 0 New words and notations SCSR SCDR TDRE Dr Victor Giurgiutiu Page 67142010 EMCH 367 Fundamentals of Microcontrollers Example SCI TRANSMISSION Dr Victor Giurgiutiu Page 77142010 EMCH 367 Fundamentals of Microcontrollers Example SCI TRANSMISSION Dr Victor Giurgiutiu Page 1 7142010 EMCH 367 Fundamentals ofMicrocontrollers Example SQUARE WAVE EXAMPLE SQUARE WAVE OBJECTIVE This example has the following objectives Review the use parallel ports Illustrate the generation of a square wave using Port B output and a waiting sequence Demonstrate the use ofa subroutine to shorten the length ofa program Examine the relation between displayed simulation time and clock cycles in THRSim11 simulator 0V At L t mil At SquareWave leH Half L Half l Wave Wave Figure 1 Square wave schematics showing the halfwave duration At and the low L and high H states PROGRAMS This example uses two programs that produce the same output the generation of a square wave of programmable L The 39 L is r 39 using the variable DELAY The square wave electrical signal is output through second pin of Port B ie pin PB1 The difference between the first and second program consist in the use of a subroutine The use of a subroutine compresses the code and shortens the total length of the program Dr Victor Giurgiutiu Page 17202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE PROGRAM SQWA1 Instructions Flowchart Code DELAY RMB 1 De ne variable DELAY at 0000 De ne DELAY gt0000 Sta quot 339quot pr gram Load REGBAS quot1 reg X Initialize REGBAS in reg X ORG PROGRAM Send low signal I Send low SI nal START LDX REGBAS Load 00000000 quot1 300A Load 00000000 in accA Begin typing your code Store accA in Port B Store aCCA in Port B Send low signal Load DELAY into accB Load DELAY into accB BEGIN LDAA oooooooo Decrease accB in a loop until zero Decrease accB by 1 STAA PORTBYX Loop until zero Send high signal LDAB DELAY Load 00000010 in accA Send hi h Si 339 LABEL1 SUBB 1 St A P t B Load 00000010 in accA ore 5 C 39 or Store accA in Port B BHI LABEL1 Load DELAY into accB Send high Signal Load DELAY into accB Decrease accB by 1 LDAA 00000010 Bram Ck 0 0 Loop until zero STAA PORTBX SWI LDAB DELAY LABEL2 SUBB 1 Decrease accB in a loop until zero BHI LABEL2 BRA BEGIN SWI FLOWCHART AND CODE The program flowchart is show to the right of the program instructions Note the send low signal and send high signal blocks Also note the two wait blocks one sending the low signal the other after sending the high signal The wait blocks are not detailed since they have been covered in a previous example and can be directly cloned from there the code reuse concept The essential code for this program is shown to the left of the flowchart The file Sqwav1asm is the result of incorporating this code in the standard template EXECUTION Open THRSim11 Close the Commands window Open memory list port registers and THRSim11 IO box Open and assemble Sqwav1asm Set breakpoint at SWI as an insurance against the program running wild Reset the registers Set standard labels LabelSet Standard Labels Set display of accA to binary Set display of PORTB to binary Tile windows Arrange windows for maximum benefit memory 0000 only registers A through X sufficient of asm and LST windows to show the code Reset DELAY A B X Your screen should look like this Dr Victor Giurgiutiu Page 27202010 EMCH 367 ansmm Elle gdk earch Miaw Elma Label greakpoint annect Mnduw eIp ilth ayglml v t 86 nary and 22 86 37 d6 o8 H 22 DB 4 Simulated time DHmw if Begln typmg y x Send 10w BEGIN LDRH LDRH L BEL1 SUBB as sand high LDRR STR I LDRB LRBELZ SUBS BHI 8003001 52 our code u nnunuuao x DEan LaHEL1 200050913 PuRTBx DEan 1 LnnELz EGIN SFFFE STRRT 391 Fundamentals of Microcontrollers GIURGIUTIU Uictor at Define program variables BEG DRTR DELRV 4 Start main program DRE PR GBRN STSRT LDX EGBOS 4 Begin typing your code Send low BEGIN LDRR WEBBBBBBU ST PDRTBX LDRB DELRV LRBEL1 SUBB 1 BHI LRHEL1 Send high le 330811813 ST n FDR LDRB DEL LRBEL2 SUBB 31 BHI LRBELZ BRR GIN 8N1 one SFFFE FDB ST RT INCLUDE U RDEF SM reset set to Example SQUARE WAVE 93 SP SMFF CI 211018008 STRA PC For m P94 Pm PM PM Pan 0 STRA P05 PD4PD3FDIFD1FDD 0 O O O O O M E n mm mm 05m in 30mm sen L l l 5 J A glam a 41 la i il may lv Sssac ls n1FFch scnunlnlnck Cycles quotI a Put 04 into variable DELAY Reset the simulator The PORTB register is 00000000 and all the lights in the THRSim11 IO box are off b Note the initialization readings clock cycles 2 simulated time 00000010 sec 10 ps These values are entered as N1 and T1 in the quotInitializequot row of Table 1 c Make one step through the program The REGBAS value of 1000 is being loaded into X This will assist with accessing the port registers in Extended mode using register X Your screen looks li Dr Victor Giurgiutiu ke this Page 37202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE u um E39 Edit iearch Miew Execube Labei Ereakooint Cgflnect window Help w Ml39 wgia must Emitle Sq wavLLST El Am 39 U RDEF SM39 CE 10 M3 STRRT LDX REGBQS J INCLUDE at Begin typing yuur Earle GIURGIUTIU Uictnr it Send 1qu as Define program variables D T Scans a7 lilo smn PURTBX DELm39 RMB Semi d6 00 Loan DELM as Start main program Sc 9 EB 81 L BEL1 SUBB R1 ORE PROGR M Scum 22 Ft BHI LnBEL1 5mm LDx minan as Semi high at Begin typing your code SEEN 86 82 LDRR 829503000018 Send an I Swim a u smn PURTBx BEGIN Lona ml lm 6811 d6 Bl LD B DEL V STAR PORTBX H 5313 an 31 LnBELz suns 11 LD B DELmI an lg l PIJRT REGRRS M 1808 3B0 A Sums 22 Fc EH LRBEL2 LnBEL1 suits in PM M 1M mummy 8817 2 ea BR BEGIN BHI L BEL1 PBRTC39 M 1303 a m senu nign mm M W W LD Wununumn mm 4318 Sm URI FFFE re 3199 Pumax PM M Sums Sm FFFE 0 FDR STRRT 39 LD B DEL V 39 SB L BELZ suits in Sm BHI LRBELZ ERR BEGIN Still mm sFFFE res STRA Fcnpmwcwmspmpczvcwcn FDE STRRT set to O STRA ms mun FDZ Pm FDD 39J 1 0 O O O O m 39J A 3 1 L a j simulated time 03800825 sec in Sun a son x 1nuoiv Sssac 1s B1FF Pc 0083 iclack cycles 5 d This is the end of the initialization cycle and the beginning of the lowsignal part L of the square wave Step twice Your screen looks like this Dr Victor Giurgiutiu Page 47202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE 39 lele MR Elle Eda geach Miew Egemte Label BJeakDuint Cymect Mndow Help e 1ng gimlri smm Lox Means 1 MNCLIIDE 39nunnnEFasr1j 9 338390039 4 Begin typing ynur tune BlU GlUTIlI Uictur B a if Send low as DeFine prngram variables D 53939 A c003 36 00 BEGIN Lima 0200000000 Dam X 18M c005 27 on sun rummx DEan R119 1 V 5831 Start main prngram SP 531 scam c 01 LnnEL1 sum in am PRUBRRN Scum 22 n 0H1 L BEL1 3mm Lnx humans 06 961101010 Send high Begin typing your cnde scan 06 02 Loan Wunuaumn Send 100 V snm Pmmmc Beam LDRR 0200000000 Lima 05an Stan PDRTEX x LnnELz sum 01 LDRB DELRV quotL LIJ 0H LaBELz L BEL1 8083 01 l mm BEE N LnaEu M is send nigh Lona 0200000010 um SFFFE ri smn Pnnmx ffFe c0 00 FDB STRHT V Lnnn DELM39 PM M 51m 3 mm2 5quot mm M 1007 300 l 301 LnnELz mm BEGIN J 501 Jim SFFFE reset FDB STRRT set tn j 41 4 3 1 4 simulated time 00000055 sec 9 3005 00lx 1000 5831 ls B1FF ch 3007 lnlock cycles 1 e Note the start up readings clock cycles 11 simulated time 00000055 sec 55 us These values are entered as N2 and T2 in the Initialize row and as N1 and T1 in the first L row of Table 1 Dr Victor Giurgiutiu Page 57202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE Table 1 ANAT ATAN f Step through the program until PORTB becomes OOOOOO1O and PB1 in THRSim11 IO box turns on Your screen looks like this Dr Victor Giurgiutiu Page 67202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE mks 1 Elle Edit gearch mew gecube Label greakpolnt annect mnan Help 15 Dblgmg39I Ital 54le quot9 El 0 El 51 D IiEBHRS A HINELHDE URR DEF SM n 9500000010 as Begin typing your code GIURGIUTIU Uictur 393 9 a 59m law Define program variables D 3020 5003 so 00 BEGIN Lona 0200000000 0010 X 1809 39 12005 a7 00 3100 90010 oran RMB 1 391 583 c007 06 00 L000 Dam in Start main program SP 91 Senna c0 01 LnBEL1 sum 01 000 anzmm 3000 22 h BHI LnnEL1 3min LDX unsunns 3930 611010000 6 Send high Begin typing your code 7 a 5200 an 02 Loan 01300000010 as Send lulu 2 Hiya c00F a7 00 100 90010 BEGIN len 0200000000 RRquot D m DELquot quotI 3Wquot 5quot smn Pmmmc E D x 5quot c 1 BE 3 NE 33 35quot Puma 0120003 1 1000 500 A LQBEU PORTB M 1000 7500000010 Sen nigh PORTB M 1003 300 Loan R0000010 000 SFFFE re smn FDRTB Lm omv LaBELz sum 01 LnBELz mm BEGIN l 301 000 SFFFE FDB 10M 39l ALI J a 4 1 a l Simulated time 00000200 sec la 02 It 00 X 1000lv 5830 ls 01 W 0011 lcluck cycles 0 Note the clock cycles and the simulated time as N2 40 and T2 200 the first L row of Table 1 Compute AN 29 and AT 145 Also compute ANAT 2000 and ATAN 0500 Enter the current values N2 40 and T2 200 as N1 40 and T1 200 in the first H row of Table 1 g Step through the program until PORTB becomes again 00000000 and PB1 in THRSim11 IO box turns off Your screen looks like this Dr Victor Giurgiutiu Page 77202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE n lRSimll 7 El x lJJ Eile Edit earch Miew Egewte Label geakpnlnt annect Endaw lelp a t Sc O ca 10 m3 3mm Lnx REGBRS 1 MN LUDE 39nunBDEFnsw Begin typing your code as IURBIUTIU Uictur Sand low 4 DEFine program variables scone so no BEGIN LBRB 819508906000 Dam scans a7 on smn PORTLX DELR39I er Start main program Sc g on B1 LABEL1 SUBB B1 mm PRUGRRM l scum 22 n LnBEL1 Send high Begin typing your code Sc d so n2 len u znauaama as Send low 395 Sc F a7 mo smn roman BEGIN Lona 9 MT quotElquotV quot 999 5 sum as an Lama 05an smn P RT X all scma ca 131 LHBELZ sum in LDRB DELRV S M 51mm Sm A c 15 22 H Bquot LnBELz LNBEL1 SUBB a1 1 1 WWW l sum 20 ea mm BEGIN Bin mum on 5 m Send hing 5 LD amountian 03 nBG SFFFE re smn roman SM FFFe no no FDB 3mm Lima DELni WINE M Sun Sun LnBELz was 31 mm M 103 so BHI LABEL2 39 a Ban 7 SIM ma SFFFE rESEt STRA 8FE5PE4PDGFCZPC3VE30 FoB 5mm s n 0 STRA FD5FD4FD3FD2PD FDO A O O O O O t J Li A lsimulated time 8000536 sec la 33MB San liTswmllv 583 lsa smrr PG 5000 l nck cycles Note the clock cycles and the simulated time as N2 72 and T2 360 in Table 1 Compute AN 32 and AT 160 Also compute ANAT 2000 and ATAN 0500 Enter the N2 and T2 values of this H row as N1 and T1 values on the next L row h You are now again in a lowsignal state Step through the program until the light PB1 comes on again Your screen looks like this Dr Victor Giurgiutiu Page 87202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE w Elle Edit gearch view Execute Label realqaulnt annect V ndow Help gt av1LS jg El scum ca 13 on 5min Lox uREms I INCLUDE 39 U DEF SN39 l 9 1300011310 as egin typing yuur cane ar uiunciunu Uictnr B 300 4 Send law DeFine program variables 5003 86 on BEGIN LDRH u znuaon oa Dam 39 scans a7 nu Stan Pnnmx nEm a Scull d6 9 L RB DELR I Start main program scum ca 1 L BEL1 SUBB in RI PRUGHRM 5188 22 FC 8quot LRBEL1 START LDx uREcBnS as Semi high Begin typing your code x scan1 so 2 LDRR u zmmmlmn 4 Send law A Scam a7 an smn Pmmmi BEGIN LD R u zounuum S smn PORTBX c013 en 01 LRBELZ SUBB LD B DELmI Sums 22 in am LnaELz LREEH sum in PMquot N 322quot M 31 gggnwmn ill c 17 29 ea mm BEGIN BHI L BEL1 P 0 M 1033 38 y m Send nigh LDM magnum PimmL M 31095 Sim am FFFE n STRR Pumnx 533 quot1133338 33 was new Fm LnBELz suns 331 Bill LnBELz BRR BEGIN l SNI Inc SFFFE reset I O O O FDB 3mm set to RA Wagggmgg STRA PD5 P04 P03 FBI PDI PD j 0 O O O O O 31 A Ll l L z Simulated tine ILBWBSBS sec in 0218 130 lx 3100 l 5831 3 81 ch 5811lcluck cycles 1 1 Observe the N2 and T2 values and compare them with the appropriate values in Table 1 i Repeat this until all the values in the 04 portion of Table 1 have been observed Note that the ratios ANAT and ATAN are consistently 2000 and 0500 as theoretically predicted Also note the wavelength of your square wave The low L portion of the signal has 29 cycles ie 145 ps while the high H portion has 32 cycles ie 160 ps The H portion is longer since in includes an additional operation BRA which brings us back to the beginning of the program However at higher wavelength these differences will fade away These observations are important for future use of the MCU as a timing device 39 5 Set breakpoints at c007 and c011 These points correspond to the moments just after the sending of 00000000 to PORTB and the sending of 00000010 to PORTB respectively These breakpoints will allow us to run the program automatically ensuring that it will stop each time the signal status is changed 5 Reset the MCU Observe again the clock cycles and the simulated time and verify that they correspond to the N12 and T110 on row O4 lnitialize in Table 1 m Run to the first breakpoint Verify N211 and T255 in Table 1 n Run to the next breakpoint You have run through the first L lap Verify N240 and T2200 on the corresponding row in Table 1 0 Run to the next breakpoint You have run through the first H lap Verify N272 and T2360 on the corresponding row in Table 1 p Repeat until you have exhausted the 04 portion of Table 2 Observe the ratios ANAT and ATAN Note that the ratios ANAT and ATAN are consistently 2000 and 0500 as theoretically predicted Dr Victor Giurgiutiu Page 97202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE q Put 40 into the variable DELAY Reset the simulator Repeat the above procedure and verify the values entered in Table 2 under the 40 section Observe the durations of the L and H halfwaves of the square wave They are 164165 ps and 166 ps respectively The consistency of the L and H parts of signal has greatly improved Observe the ratios ANAT and ATAN Note that the ratios ANAT and ATAN are consistently 2000 and 0500 as theoretically predicted PROGRAM SQ WA V2 Instructions Flowchart Code i Define variable DELAY RMB 1 DELAY at 0000 St n De ne DELAY gtoooo a ma39quot pr 9ram Load REGBAS m quot3939 X Initialize REGBAS in reg X ORG PROGRAM I Send low Signal I Send low 5i nal START LDX REGBAS Load 00000000 In accA Load 00000000 in accA BEGIN LDAA 00000000 Store accA in Port B Store accA in Port B STAA PORTB X Jump to subroutine WAIT Jump to SUbFOUtme I JSR SRWAT Send high signal Send high signal LDAA 00000010 gisg scrifagigm 3312239323 w Jump to subroutine WAIT Jump to subroutine JSR SR WA39T Branch backto iii BRA BEGIN SWI SWI subroutine WAlT SR WAIT SRWAIT LDAB DELAY ii Load DELAY Load DELAY into accB LABEL1 SUBB 1 Into accB Decrease accB BHI LABEL1 III Decrease LOOP Um zero DELAY Return from subroutine RTS iv Loop until zero SWI v Return from subroutine FLOWCHART AND CODE The program flowchart is show to the left of the program instructions Note the send low signal and send high signal blocks Also note that the two wait blocks of the program Sqwav1 have been replaced by a single subroutine block that is repeatedly called The essential code for this program is shown to the left of the flowchart The file Sqwav2asm is the result of incorporating this code in the standard template EXECUTION Open and assemble Sqwav2asm Set breakpoint at SWI and reset registers Set standard labels LabelSet Standard Labels Set display of accA to binary Set display of PORTB to binary Tile and arrange windows for maximum benefit memory 0000 only registers A through X sufficient of asm and LST windows to show the code Reset DELAY A B X DO NOT RESET THE SP stack pointer REGISTER BECAUSE IF YOU DO SO ACCESS TO YOUR SUBROUTINE WILL NOT WORK Dr Victor Giurgiutiu Page 107202010 EMCH 367 Fundamentals of Microconlrollers Example SQUARE WAVE a Put 04 into variable DELAY Reset the simulator The PORTB register is 00000000 and all the lights in the THRSim l l IO box are off Step through the program until you reach subroutine Your screen will look like this e variables am nztav e Start an Slant HEGIN 1a mmmmmmmm o SFFFE re SFFFE reset uectnr 0 O O O O 0 mm n m tn 5m 7 b Step through the subroutine until you get to RTS and are ready to jump back to the program Your screen looks like this i varianles varianles nave unrn nstnv I 1 x Start prngram prngram annnnn rnnnnan 1n as SIRRV HREEBRS azniu azuunnnnnn Pnnrax 1a S iw ll uznnnnnn1n anrnx n2 an an 13 snwn11 rn 92c sniwnrr WEN m L EL1 srrFE nun SFFFE reset uectnr srnnT svnnr set to start at After another step you are back into the main program 8 Dr Victor Giurgiutiu Page 117202010 EMCH 367 Fundamentals of Microcomrollers Example SQUARE WAVE variables an n 1 may m m was Paws m m m m o O o O o O o 0 mm m Pcwcnwcwcwcawczwci m in 0 5va m Puwm m Pm m SFFFE m srm reset mm O O O O 0 0 mm mm m tn sun at d As you stepfurther you observe that the Port B pin 1 is toggled and the light PB1 in the IO box comes on The main program is again ready to jump to the subroutine variables Darn 1 w str MW mmmmmmmm n1 mun so in mm a m o SFFFE re mu F E reset I12 tn 0 O O O O O c r srnnr set tn start at e Further stepping takes you back into the subroutine and out again f Run the program on automatic You will notice how the subroutine is accessed every time the PB1 light changes g Put breakpoints at the two JSR lines Run the program on automatic and record in Table 2 the values recorded for DELAY 04 and for DELAY 40 h Compare the values from Table 2 with those in Table 1 You will notice i For same values of delay say DELAY 04 the duration of the half waves are different in Table 2 20 us and 215 us from those in Table 1 145 us and 16 us This difference is due to the different way in which the two programs were constructed Dr Victor Gimgiuu39u Page 127202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE ii At low delay values DELAY 04 the difference between the durations of the L and H half waves is significant 75 As the delay increased this difference fades away At DELAY 40 the difference has come down to 09 Table 2 WHAT YOU HAVE LEARNED In this example you have learned 0 The use of Port B o The use of displayed clock cycles and simulated time and their relative accuracy 0 The fact that the roundoff error becomes less severe as the magnitude of the number increases 0 The usefulness of subroutines for shortening programs 0 The use of Port B to generate a square wave 0 New words and notations subroutine jump to subroutine JSR return from subroutine RTS square wave wavelength IO InputOutput IO box accuracy roundoff Dr Victor Giurgiutiu Page 137202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE This page is intentionally left blank Dr Victor Giurgiutiu Page 147202010 EMCH 367 Fundamentals of Microcontrollers Example SQUARE WAVE Dr Victor Giurgiutiu Page 1 7202010 EMCH 367 Fundamentals of Microcontrollers Example LONG DELAY EXAMPLE LONG DELAY OBJECTIVE This example has the following objectives 0 Present a subroutine that can implement a long delay between stepper motor steps 0 Introduce the concept of how to achieve double precision delays 4hex using single precision 2hex variables PROGRAM EXLONGDELAY This program illustrates the use of subroutine DLAYSR This subroutine performs a long delay action using TOC1 Although the delay is in double precision 4hex the controlling variable DELAY is simple precision This is one of the special features of this subroutine DELAY controls the higher 2hex digits This is how this works First clear the OC1F flag which is bit 7 in TFLG1 When doing this we use the OR operation in preserve the other bits in TFLG1 We load DELAY in accA which is the higher part of ach Then we fill accB ie the lower part of ach with 00 If DELAYXX then the value in ach is XX00 Next add TCNT to ach and store the result in TOC1 This is the new time Step in place until OC1F is set When the number of cycles XX00 have elapsed you are done The subroutine return control to the main program A stepper motor is controlled by sending binary patterns step sequences to its controller board Eight distinct binary patterns SO S7 are recognized by the stepper motor controller board in your lab When these patterns are hit in increasing order one after the other the motion is called half speed forward If only the odd sequences are hit ie every second pattern the motion is full speed forward If the patterns are hit in decreasing order the motion is respectively halfspeed backward and full speed backward The corresponding step sizes are respectively 1 2 1 2 Table 1 Using 2 s complement 8bit signed numbers convention these values correspond to the variable STEP taking hex values 01 02 ff fe Table 1 Stepper motor speed definitions The program is intended for stepper motor control The steppermotor speed is controlled through the delay inserted between steps A short delay ensures a high speed while a long delay produces a slow speed The shortest delay that can be physically accommodated by the stepper motor dynamics is 5 ms For a 2 MHz processor 05 pscycle this corresponds to 10000 2710 cycles The maximum delay is obviously ffff Since we use a single precision variable DELAY we need to round the numbers 2710 and ffff to 2 significant hex numbers We get 2800 and ff00 To maintain delay Dr Victor Giurgiutiu Page 17292010 EMCH 367 Fundamentals of Microcontrollers Example LONG DELAY integrity the first number was rounded up the second number was rounded down Hence the single precision variable DELAY can take values between 28 and ff FLOWCHART AND CODE The program flowchart is show below The essential code for this program is shown to the right of the flowchart The essential code was incorporated into the standard template asm to generate the code file ExLongDelayasm Please refer to this file for more coding details and coding style Flowchart Code Define variables 0 DELAY 1byte ORG DATA DELAY RMB 1 OR G PROGRAM START LDX REGBAS JS DLAYSR Initialize XR EGBAS Jump to subroutine DELAYSR SW DLAYSR LDAA 10000000 ORAA STAA TF LG1 X LDAA DELAY LDAB 3500 ADDD TCNTX STD TOC1 X LABEL5 LDAA TFLG1X ANDA 10000000 BEQ LABEL5 RTS o ClearOC1F 0 Add DELAY to TCNT and store in T w Step in place until 0C1 F is set EXECUTION Open THRSim11 Close the Commands window Open and assemble ExLongDelayasm View CPU registers timer registers memory list for variable DELAY Arrange windows for maximum benefit Reset registers Set standard labels LabelSet Standard Labels Press the RESET button Set breakpoints at SWI and RTS Put 28 in DELAY Your screen should look like this Dr Victor Giurgiutiu Page 27292010 EMCH 367 Fundamentals of Mlcrocontrollers Example LONG DELAY rnutihe 39 39 e perrnrhs a nelay actinn usihy THE the Sxx lehyth nf the nelay is put in the higher part 39 n e r h39l the layer part is Filled h u her nf cycles sxxnn haye elap DL Vix ux1nnnnnnn clear E1F TFLG1X Preserue nther hits in TFLG put nttnv in higher 0 put an in layer 0 L HELS check E1F and step in place a Step through the program The program should initialize X1000 and then turn control to the subroutine DLAY SR b Step through the subroutine Observe how rst the ag 001 F is reset 0 Then note that the value of DELAY is loaded in accA ie in higher part of ach then 00 is loaded in accB ie the lower part of ach and nally the value of TCNT is added to ach The result is stored in TOC1 Your screen should look like this nelay suhrnutihe This suhrnutihe perrnrhs a nelay actinn usihy T E1 x lehyth nf the nelay is put in the higher part e nf noun while the layer part is rillen with um when the huhher nf cycles sxxnn haue elapsee the SIR returns DL Vix clear E1F Preserue nther hits in TFLG1 put nttnv in higher 0 put an in layer 0 Note that the value of TOC1 is close to 2800 Dr Victor Glurglullu Page 37292010 EMCH 367 Fundamentals of Mlcrocontrollers Example LONG DELAY d Let the program run It should loop continuously on LABEL5 while checking for OC1F When CNT goes over the value of TOC1 the ag OC1F bit 7 in TFLG1 gets set and the code is ready to return to the main program Your screen looks like this nLavixn clear nc1F Preserue ntner hits in ran1 put nstnv in higher 0 put an in lnwer n check nc1F and step in place You are done e Repeat the above procedure for other values in DELAY 30 40 80 and ff Make sure that you understand the way this subroutine works WHAT YOU HAVE LEARNED In this example you have learned 0 A subroutine that can implement a long delay between stepper motor steps 0 How to achieve double precision delays 4hex using single precision 2hex variables The single precision variable DELAY was used The variable was loaded into the higher part of double ach The higher part of ach is accA Hence the variable was loaded in accA using single precision arithmetic The lower part of the double precision accumulator ach which is the single precision accumulator accB was loaded with 00 Hence if DELAYXX at the end of the process achXX00 Dr Victor Gxurgxubu Page 47292010 EMCH 367 Fundamentals of Microcontrollers Example LONG DELAY Dr Victor Giurgiutiu Page 1 7292010 EMCH 367 Fundamentals of Microcontrollers Example 9 EXAMPLE 9 OBJECTIVE This exercise has the following objectives 0 Introduce hex subtraction 0 Introduce hex subtraction with negative results using the free borrow concept 0 Show the decimal equivalent of hex subtraction with negative results using free borrow Note To facilitate understanding the same numbers are used in both decimal and the hex cases PROGRAM The program ex9asm performs the following arithmetic operations Od 06 07 hex using the opcode mnemonics LDAA LDAB SBA 00 05 fb hex using the opcode mnemonics LDAA LDAB SBA III 0 5 251 decimal equivalent of 8bit hex arithmetic using the opcode mnemonics LDAA LDAB SBA IV Oe 3a d4 hex using the opcode mnemonics LDAA LDAB SBA V 14 58 212 decimal equivalent of 8bit hex arithmetic using the opcode mnemonics LDAA LDAB SBA Dr ctor Giurgiutiu Page 1 7162010 EMCH 3B7 Fundamentais uf Micrucuntruiiers Exampie a CODING AND EXECUTION Open TH RSim1 1 Maximize TH RSim11 window Close the Commands window Open ex9asm Assemble tie the windows set the breakpoint and reset the registers Your screen looks like this 1 Eiie get geavch yew teem Lahei Eveakvmnt cennett Mndaw deiD Elma gtgtl mg ll IIzJ BX EEEVV BE 0 5 39 quot 5 tnr Xnnnnnmn typ ng ynur cane Sun at 39snies S znn um um sum Scum 36 m1 mm as e Start nf min prngram Sm Senna 3925 n In as mu Piman P Sm Scans 1n m min NW I sum 2 uiii e aegin typing ynur cane I WNW Sc M an Low as Sc 3925 n a as e uii sum 1n m um uSnn e 39 um um sum u an um an m Sc n ch us mm as e uiii Sc f 1n m um uSnn Lona uSnS Sum ne um uSne m sum 3925 33 um 11533 e x semi sn um an e mm as Sums ne um mu m Sum ch 33 me use e x Sum 1n m um uSne Lona uSas 2 Elm nf min prngram m Sums if m e xi mu SFFFE reset nectar um um sme en an m mm set tn start was an m e End nf main prngram 4 VJ 4 gt 4 l 39 simmmemm We inw ixm We isvm mm e Dr Vi r Giurgiutiu Page 2 7iBZEI1EI EMCH 367 Fundamentals of Mlcrocontrollers Example 9 SECTION 00 06 07 HEX USING THE OPCODE MNEMONICS LDAA LDAB SBA Load and assemble ex9asm Set accA display to hex Step through section vii of the code At the end of this section your screen looks like this El it eaich Mew Execute Label Eveakvmnl Egrmecl Mindaw elv eaamreagtumw quotgumav a H e Senna n1 mn N P Begin typing ynur cane uii Scum u an um um i Start nf min mmquot Senna 5 n6 Loan 11th mm Pnnmmrl rnnr N P x Hegin typing ynur cnne cc mmmn Sc M an LDM quotSun r Scum 5 n5 Loan quotSn 2 vii Senna 1n Elm LDM quotSn1 e ix Loan 11th Sennh 35 an Lona un nn Senna c5 n5 Lona us i uiii Sc f 1n Elm LDM quotSun e Loan quotSn Sc 1 u at um quotSue m cu12 6 3a Lima usaa x ix scniu 1n nn Lona an xi Lona us Sc 15 35 n2 Lona u1h nn Sam c5 33 mu m i x Sc 1 1 um um quotSue Loan quot33 x End nf main prngram nn Sums if m e xi nun srrrz r Lona u1h Sfffe an an rna stunt 5 Loan uss m a nu nf main prngram m mu SFFFE reset uectnr rna rnnr set tn start 41 t lSimuleledlime Dunnnzasec lAsna lBsns lxsnnnn lvsnnnn lspsnnnu lPEcDU5 lElackEycles 58 During the execution of this section hex number 0d was loaded into accA hex number 06 was loaded into accB and then accB was subtracted from accA The result of the arithmetic operation remained in accA The result was 07 A hex borrow did not happen since the number in accB was less than the number in accA and the LSD of the number in accB was also less than the LSD of the number in accA Dr Victor Glurglutlu Page 3 7162010 EMCH 367 Fundamentals of Mlcrocontrollers Example 9 SECTION 00 05 FB HEX USING THE OPCODE MNEMONICS LDAA LDAB SBA Set accA accB displays to hex Step through section viii of the code At the end of this section your screen looks like this u u l Elle Edit ieaich Mew Execute Label Eneekppnl grins2 WW Help gtHmgtl IIgj XMQ3J BE a0 53 quot 3mm NnP J s h Eegin typing ynnr cane uINELuDE 39aINILIEFaI139 Sn e Define prngram variahlES thns I 2 vii mu nan Snunn senm up an um am e Start as main prngram sum Senna uh uh LINE 11th mm PREMIva P Sunnn Scnn5 1n in mm nnr 2 viii e Eegin typing ynur tune I xnnnnm Scunh Eh nn LINE unn Senna 6 us was as e uii Senna 1n Ea LINE 115m ix LINE 11th m Sc n 6 us was as e uiii S nut 1n Ea LINE unn e x LINE uSns Scmn Eh ne LINE une Ea Scmz c6 33 um 11533 e ix Scmu 1n Ea LINE an I x xi LINE us Sums Eh ne LINE mu Ea sum to 33 mu m e x Sum 1n um um usne LINE quot33 2 End a main prngram m Sums if m x xi mu SFFFE r LINE mu 39Sfffe E M FDE 3mm 5 LINE 1153 m e End nf main prngram m mu SFFFE reset uectnr rna STEEL set tn start 4 lSimulaledlime EIEIEIEIEI332I lASIh lama lxsnunu Visnnnn 793mm liPEScEIUb ElackEyAcles 55 During the execution of this section hex number 00 was loaded into accA hex number 05 was loaded into accB and then accB was subtracted from accA The result of the arithmetic operation remained in accA The result was fb This is equivalent to the hex operation 000100 0050fb and indicates that a hex free borrow happened Dr Victor Glurglutlu Page 4 7162010 EMCH 367 Fundamentals of Mlcrocontrollers Example 9 SECTION 0 5 257 DECMAL EQUIVALENT OF 8BITHEXARITHMETIC USING THE OPCODE MNEMONICS LDAA LDAB SBA Set accA and accB displays to decimal Step through section ix of the code At the end of this section your screen looks like this Uquot a le gal Seal2h yew Execute Label Bieakvmnl Egrmecl wmaw Help a Hm Irj39 lttl 9 BE 0 ExSLST EEK quot 39 cnnn n1 mun NW A e u munquot Uictnr 2 Begin typing ynur cane ulNEL DE 39auan70 ram39 5 e Define prngram variables 0 anns e uii mu nan x Sunnn Scum u an um am e my nf min prngram r v sum Senna 5 n6 Loan 11th mm Pnnmmrl 39 Sunnn senns 1n mm mm Hquot e uiii e Begin typing ynur cn e m xnnnnm Sc M an LDM uSnn 39 sum ch us was an e uii Sc a 1n um um usnn e ix um usna Scum M an mm In Sim sennn ch us was as e uiii Scnnf 1n um um usnn e x um um quot nn Scmz c6 33 um 11533 e ix Scmu 1n Sim mm an x xi was as Sums M ne LDM mu Ha Sam 5 33 LINE 1153 x x Scnw 1n Sim LDM uSne Loan quot33 a mm M min prngnm nn Sums 3 m x xi um Sr n um mu Sfffe an an FDH SWRT 51 um 1153 um e End nf main prngram m mu SFFFE reset uectnr rim mun set tn start lt1 During the execution ofthis section decimal number 0 was loaded into accA and decimal number 5 into accB Then accB was subtracted from accA The result of the subtraction remained in accA The result was 251 We notice that the following decimal arithmetic operation happened 05251 This operation is equivalent to 02561255 This indicates that although the operation was displayed in decimal a hex free borrow actually happened since 256100 Dr Victor Glurglutlu Page 5 7162010 EMCH 367 Fundamentals of Mlcrocontrollers Example 9 SECTION 05 3A 04 HEX USING THE OPCODE MNEMONICS LDAA LDAB SBA Set accA accB displays to hex Step through section x of the code At the end of this section your screen looks like this m m it aich Mew Execute Label Eieakvmnl Egrmecl indaw Help sand ItglaX tEe BEN m unu rfnr neg n typ ng ynur cn E u Lquot Mullins am e Define prngram variables e uii mu new Scum as an um um e Start nf min prngram Senna uh uh LINE IIth mu Piman scans 1n SH mn NnP e uiii r e Begin typing ynur cane r cc xnnnnm Sc u an um usnn Senna 6 us was as e uii Senna 1n sin I LDM uSnn 1x I LINE 11th Scum M an mm In Sim Senna c5 us was as e uiii Scunf 1n m um usnn 2 x r was an Scmn M ne LDM uSne a Scmz c6 33 um 153 e ix Scmu 1n sin I mm an e xi was as SH Scn c5 33 LINE usu x x Scnw 1n Sim LDM uSne LINE quot532 e End nf main prngram Sc 13 if m e xi mu SFFFE LDM mu Sfffe D an FBI SIN LINE usu f e End nf main prngram m mu SFFFE reset uectnr run ranr set tn start I lSimuleledlime unnnnaasec lASdO lBSSe lxsnnnn lvsnnnn lsPsnnnn chscms lEleckEycles 7a During the execution of this section hex number 0e was loaded into accA hex number 3a was loaded into accB and then accB was subtracted from accA The result of the arithmetic operation remained in accA The result was d4 This is equivalent to the hex operation 00e10003a0d4 and indicates that a hex free borrow happened Dr Victor Glurglutlu Page 6 7162010 EMCH 367 Fundamentals of Mlcrocontrollers Example 9 SECTION 74 58 272 DECMAL EQUIVALENT OF 8BITHEXARITHMETIC USING THE OPCODE MNEMONICS LDAA LDAB SBA Set accA and accB displays to decimal Step through section xi of the code At the end of this section your screen looks like this lr39il akvmnl Egrmecl wineaw Help Eie gel Seal2h yew Execute Label Eve sage m gtH5mgtl li laXMQeVV BE H nal gag m e lri Sennn n1 mn Nu m e nl RGl Tlquot Uictnr e aegin typing ynur cane ulNELuDE 39auan70 rasn39 e nerine prngram variables x uii mu Dam senm es mi um am e Start nf main prngram Senna 5 us was uSna mu Pnnnmm Scans in in grain nnr e uiii e aegin typing ynur enne 39 cc xnnnnm Senna u an Loan uSnn scans ch us was as e uii sem 1n m um am e ix um um Scum u an man um um Scnnn ch us mm as e uiii Scnnf 1n m um usnn e x mm usns Scmn in ne Loan uSne sun Scmz c5 33 Loan 11533 e ix Scmu 1n sun man an xi me as m Scan 5 33 was an e x Scnw in sun Loan uSne um 11533 e m n pagan semi at m e xil mu srrre n um mu Sure D an rim m s um an m e m n pagan Sm i mu SFFFE reset uectnr to em set tn em n H isneieleenne UUUUUSSSEE lAm lasae lSlgtltlHDllNlZUVUEl lxsnnnn lvsnnnn lSFSEIEIEIEI chsema lElnckEycles 7a During the execution of this section decimal number 14 was loaded into accA and decimal number 58 into accB Then accB was subtracted from accA The result of the subtraction remained in accA The result w s 212 We notice that the following decimal arithmetic operation happened 1458212 This operation is equivalent to 14256 58212 This indicates that although the operation was displayed in decimal a hex free borrow actually happened since 256100 Dr Victor Glurglutlu Page 7 7162010 EMCH 367 Fundamentals of Microcontrollers Example 9 WHAT YOU HAVE LEARNED In this exercise you have learned 0 Subtraction using SBA opcode mnemonic happened as expected in both decimal and hex arithmetic as long as the minuend is greater than the subtrahend eg 1367 Od0607 0 When the minuend is less than the subtrahend the result of the subtraction operation is calculated using a free borrow eg 0e3a00e100O3a0d4d4 0 Even if decimal display of numbers is used the calculations and the free borrow still happen in hex eg 14581425658212 where 256100 0 New words and notations subtraction minuend subtrahend Dr ctor Giurgiutiu Page 8 7162010 EMCH 367 Fundamentals of Microcontrollers Example 9 Dr ctor Giurgiutiu Page 1 7162010 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc PROGRAMMING THE MICROCONTROLLER ASSEMBLY LANGUAGE Assembly language is of higher level than machine language and hence easier to use An assembly language code consists of a Program statement lines b Comment lines Aprogram statement is a line that contains 4 fields in the following format ltLABELgt ltOPCODE MNEMONICgt ltOPERANDSgt ltcommentsgt OI39 ltLABELgt ltDIRECTIVE MNEMONICgt ltOPERANDSgt ltcommentsgt where indicates an optional field that may not be always required The fields are separated by a tab or space Tab is recommended since it ensures an orderly appearance to your code For the same reason when a field is not used the tab or blank should still to be used such that the fields of the same type stay aligned in same columns When writing ltLABELgt ltOPCODE MN EMONCgt or ltDRECTIVE MN EMONICgt and ltOPERAN DSgt use upper case characters When writing ltcommentsgt use lower case The ltOPCODE MNEMONICSgt correspond to the microcontroller opcodes These mnemonics are found in the Motorola MC68HC11 programming reference guide and related literature The ltDRECTIVE MN EMONICSgt are native to the Assembly language A list of directives is given in Table 1 The directives that you will use often are shown in bold Table 1 Assembler directives The ltOPERANDgt contains a value an expression an address or a label that the opcodes or the directives need The operand could be up to 4 bytes long separated by commas Some opcodes or directives do not require operands inherent mode Dr Victor Giurgiutiu Page 18 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc The constants used in the ltOPERANDgt can be hex decimal binary or octal numbers Table 2 gives the assembler symbols used to this purpose Table 2 Assembler symbols for constants The expressions used in the ltOPERANDgt can use any of the operators listed in Table 3 Table 3 Assembler symbols for expressions unary 31 2 Important conventions used in the ltOPERANDgt are given in Table 4 Table 4 Other important conventions LDAA FF Load accA a program statement a Dr Victor Giurgiutiu Page 19 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc The ltLABELgt is a very powerful concept that can greatly simplify the programmer s task The ltLABELgt consists of a string of alphanumeric characters that make up a name somehow meaningful to the programmer The placement of the ltLABELgt can be in one of the following positions a In the first column and terminates with a tab or blank character b In any column and terminates with a colon There are 3 different usages of the ltLABELgt To assign the name inserted in the ltLABELgt to a location in a program The ltLABELgt will be assigned the address of that location A v 2 To assign the value of an expression or constant to the name inserted in the ltLABELgt using the EQU equate or SET directives a v To define the name of a subroutine macro Essentially this is the same as 1 since an address the subroutine starting address is assigned to the label When labels are assigned to certain addresses one can tell the program to go to that address by referring to the label case 1 above Alternatively one can use the contents of a certain address by referring to its label just like when using variables case 2 above A comment is prefixed by semicolon When the assembler detects an semicolon it knows that the rest of the line is a comment and does not expect any executable instructions from it A comment can be a separate line comment line or can be inserted in a program statement A comment line can be also prefixed by an asterisk The comments either in the comment field or as a separate comment line are of great benefit to the programmer in debugging maintaining or upgrading a program A comment should be brief and specific and not just reiterate its operation A comment that does not convey any new information needs not be inserted When writing a comment use lower case characters A program written in Assembly language is called source le lts extension is ASM When the source file is assembled two files are generated a Object file that can be run in the microcontroller The Motorola object file is in ASCIIHEX format lts generic name is 819 file lts extension is 819 b List file extension LST that contains the original code in Assembly language and the corresponding hex codes resulting from the Assembly process The list file is used by the programmer to verify and debug hisher coding of the program The ASM files can be opened viewed edited and saved in the TH RSM1 1 application Alternatively all three file types ASM LST 819 can be also processed in a text editor eg the Notepad application Examples of ASM and LST files follow Addressing Modes Inherent Mode is implied and requires no programming action Immediate Mode means that the number contained in the operand will be immediately used Direct and Extended Modes use the number contained in the operand to signify an address where the required information should be retrieved from or deposited to The Extended mode is automatically used for addresses greater than FF Index Mode is used by adding the operand to the value already existing in the Index X or Y as selected In this case the operand acts as an offset Relative Mode uses the operand as an offset relative to the present Program Counter value Dr Victor Giurgiutiu Page 20 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc MICROCONTROLLER COMMANDS Section 6 and Section A of M68HC11 Reference Manual The 6811 microcontroller has 145 different commands These commands can be grouped into several categories The categories and the commands in those categories are listed below 1 Arithmetic operations a Addition ABA ABX ABY ADCA ADCB ADDA ADDB ADDD INC INCA lNCB INS INX INY b Subtraction SBA SBCA SBCB SUBA SUBB SUBD DEC DECA DECB DES DEX DEY c Multiplication MUL d Division FDIV lDlV 2 Logical operations note logical operations are carried out on a bit by bit basis a Standard logical operations ANDA ANDB EORA EORB ORAA ORAB COM Boolean inverse COMA COMB b Operations that shift the location of the bits in the register ASL ASLA ASLB ASLD ASR ASRA ASRB LSL LSLA LSLB LSLD LSR LSRA LSRB LSRD ROL ROLA ROLB ROR RORA RORB Operations that compare two numbers BlTA BlTB CBA CMPA CMPB CPD CPX CPY 3 Branching commands BCC BCS BEQ BGE BGT BHl BHS BLE BLO BLS BLT BMI BNE BPL BRA BRCLR BRN BRSET BSR BVC BVS JMP JSR RTS RTI WAI 4 MemoryRegister Functions a Move data into out of memory LDAA LDAB LDD LDS LDX LDY STAA STAB STD STS STX STY b Change the values in memoryregisters BCLR BSET CLC CLl CLR CLRA CLRB CLV COM COMA COMB NEG NEGA NEGB SEC SEl SEV c Transfer data from one register to another TAB TAP TBA TPA TSX TSY TXS TYS XGDX XGDY 5 Stack Pointer Functions PSHA PSHB PSHX PSHY PULA PULB PULX PULY 6 Misc NOP SWI v v v 8 Note Boolean inversion commands COM COMA COMB Dr Victor Giurgiutiu Page 21 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc SAMPLE PROGRAM IN ASSEMBLY LANGUAGE WITH MCU COMMANDS PROBLEM STATEMENT This simple program is an example of addition It performs the operation VARO VAR1 9 SUM In addition the program checks if an overflow happened during the addition process and sets the flag OVERFL accordingly PROGRAM DESCRIPTION 0 The variables are defined in lower memory starting with 0000 in the order VARO VAR1 SUM OVER FL 0 LDAB with zero is used to reset the initial value of the overflow flag optimisticl o LDAA is used to load VARO into AccA o ADDA is used to add accA with VAR1 Result of addition stays in accA o BVC is used to branch over the next instruction ie to LABEL1 if no overflow occurred o If an overflow occurred during the addition process this instruction is reached and COMB is used to invert accB from 00 to FF o Label1 STAA is used to store the result of addition from accA into SUM o STAB is used to store accB 00 or FF depending on the logic just discussed into the overflow flag OVERFL FLOWCHART FLOWCHART Initialize variables VARO 9 Load first variable into accA dd second variable to accA result stayin accA gt Store result of addition from accA into SUM Store current value of overflow flag from accB into OVERFL Dr Victor Giurgiutiu Page 22 11701 EMCH 367 Fundamentals of Microcontrollers 367pck 8011100 ASSEMBLY ASM CODE DEMO ASM This simple program adds the contents of address 0000 labeled VARO to the contents of address 0001 labeled VAR1 and stores the resulting sum at address 0002 labeled SUM provided the addition process happens without overflow If an overflow occurs during the addition process the overflow flag OVERFL stored at address 0003 is set to FF else it stays 00 111111111 lnclude definition of variables for MCGBHCll INCLUDE 39A VARiDEF ASM39 Define program variables ORG DATA VARO RMB 1 reserve 1 byte for VARO VAR1 RMB 1 reserve 1 byte for VAR1 RMB 1 reserve 1 byte for sum OVERFL RMB 1 reserve 1 byte for overflow flag Start main program P OGRAM LDAB 00 assume no overflow optimisticH LDAA VARO load VARO in accumulator A ADDA VAR1 add VAR1 to accumulator A BVC LABEL1 jump if no overflow We have overflowl COMB lnvert accumulator B 00 to FF LABEL1 STAA SUM store result of addition STAB OVERFL store accB into overflow flag SW1 stop the microcontroller LIST LST OUTPUT RESULTING AFTER ASSEMBLY list address object label opcode operand comments or directive DEMOlst generated by MinilDE39s ASM12 V107b Build 52 12291999 163049 1 12456789012345678901245678901234567890124567890123456789 2 3 DEMO ASM 4 This simple program adds the contents of 5 address 0000 labeled VARO to the contents of 6 address 0001 labeled VAR1 and stores the resulting 7 sum at address 0002 labeled SUM provided 8 the addition process happens without overflow 9 10 If an overflow occurs during the addition process 11 the overflow flag OVERFL stored at address 0003 12 is set to FF else it stays 00 13 Dr Victor Giurgiutiu Page 23 11701 EMCH367 14 1 2 3 0000 4 0000 5 fffe 6 1000 7 8 0000 9 0002 10 0003 11 0004 12 0005 13 0007 14 0008 15 0009 16 000a 17 000b 18 0000 19 000d 20 000e 21 0010 22 0012 23 0014 24 0016 25 0018 26 001a 27 0010 28 001e 29 0020 30 0021 31 0022 32 0023 33 0024 34 0025 35 0026 36 0027 37 0028 38 0029 39 002a 40 002b 41 0020 42 002d 43 002e 44 002f 45 0030 46 0031 47 0032 48 0033 49 0034 50 0039 51 003a 52 003b 53 0030 54 003d 55 003e 56 003f Dr Victor Giurgiutiu DATA PROGRAM RESET REGBAS Include definition of variables for MC68HC11 Define variables used by MC68HC11 microcontroller Fundamentals of Microcontrollers 0000 C000 FFFE 1000 00 02 03 04 05 07 08 start of data start of program reset vector register base Page 24 367pck 8011100 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc ist address object label opcode operand comments or directive 57 12345678901234567890123456789012345678901234567890123456789 15 INCLUDE 39A VARiDEF ASM39 l6 l7 Define program variables 18 ORG DATA l9 VARO RMB l reserve 1 byte for VARO 20 VARl RMB l reserve 1 byte for VARl 2l SUM RMB l reserve 1 byte for sum 22 OVERFL RMB l reserve 1 byte for overflow flag 23 24 Start main program 25 ORG PROGRAM 26 cOOO c6 00 LDAB OO assume no overflow optimistici 27 c002 96 OO LDAA VARO load VARl in accumulator A 28 c004 9b 01 ADDA VARl add VAR2 to accumulator A 29 c006 28 Ol BVC LABEL1 jump if no overflow 30 We have overflowi 3l c008 53 COMB lnvert accumulator B 00 to FF 32 c009 97 O2 LABEL1 STAA SUM store result of addition 33 cOOb d7 03 STAB OVERFL store accB into overflow flag 34 cOOd 3f SW1 stop the microcontroller Symbols data 0000 labell cOO9 overfl 0003 program cOOO sum 0002 varO OOOO varl OOOl Dr Victor Giurgiutiu Page 25 11701 EMCH 367 Fundamentals ufMicrucuntrullErs BE7pEkSUl u THRSIM11 You need to install this software on your PC THRSM11 OPTOvs SETUP Before you run the simulator rst time on a certain PC set the Options as shovm it the following windows nmsmv xlmmwnwmuuwmun u ltwmwthWWwWWWWF uw zjmn wumweumnmmmrlm Delault nuiweial system r39 Lowe mai 3 l7 lncludelabelgble r Hexadecimal Expand included was r l9lile u L t if E Ducal Help alum m a mu ha y u is l 17 Haggai r Bemvecunemlvsalabelsbelnraluan ng p RENEE F ReistBBHE ll anallnadng 17 gnnditinn Code Register l7 Index Hagisiei l7 IndexHegistelI l7 tackFuintat l7 Eruglam Fuinlev r 397 Look In a LST uv MAP lieu load new labds Eancd ab Cancel ail Immediately after opening the THRSim11 program close the Commands window You will not use in this course unless otherwise specified Dr VlEtDrGlurglutlu Page 26 ll7Ell EMCH 367 Fundamentals ufMicrucuntrullErs asprsm an GETTWG STARTED WTH PRO GRAWWVG Take a formatted empty floppy disk write on the label EMCH 367 LASTNAME Firstname Email address Contact telephone This way if you loose the disk there is a good chance that you might have it recovered Download the templateasm le and place it on the floppy disk This template will always be a good to start your program Dovmloa the file VARDEFASM and place it in the root of the directory structure on your oppy disk This will allow the programs to nd it when uting the instruction INCLUDE AVARDEFASM ovmload example files from the course website onto this disk For safety make copies into your D folder or PC USWG THE TEMPLA TEASW FLE An asm template le is available on the course website This template has the required instructions to make your program interface properly with the simulator When generating a new program open the templateasm file sav 39t under the newname you wa to create remember to save on a secure area preferably your oppy disk and then start typing in your program in the indicated area R5 mmmamsm Jam E g e awamt What m w wb JJQJJQ Ital 9mm V BE 27 o E 93 35315 gt M 2 umcLunE 39auaninEFam39 a Define prngram variables nun narn Start at main prngram nun Pnnnnan stunt N Hegin typing ynur cane End at main prngram sm SFFFE reset nectar stunt set tn start at prngram After you type and save your program save as often as you can use cm S for productivity assemble the program and test run it Dr VlEtDr Glurglutlu Page 27 llTEll men 357 runememesmmmamues 357m sm dun SCREEIVVWNDOW CAPTURE Tu eagture the nnage uf a WmdDW ur uf the eumg ete screen Press PrintScreen m capture the nnage uf the enure screen Tne captured nnage ean be vwevved an the ehp buar TD aste the ea lured me E mm a dueument n the dueumentvvmduvv an the Edit menu ehek Paste A ternatwe y use cm v n mus L eases yuu vnu need m eapturejustthe amve vnnuew usmg AIM PrimScreen No DEFAULT VWNDOWS Defaun Wmduvvs are enner U LST 35m and CPU regws ters ur U LST asm Memury hst and CPU regwsters as snewn be uvv n the memury hst standard abe s are snewn Hmeven they ean be remuved f yuu use the gun duvvn menu eummand LabeURemwe 3 E1231 J11 1 am we 39 x m y 5 MW 3qu mm 95 352 39LSI L EES m Mamemvgmm Page 25 mm EMCH 357 Fundmemdsmmamamm as 357m sm m 3 a a ahmmgrgh EJEJEEJ 2 a mums m L 4m MM mmwmn m 9 2525 Ei39z ilz iiknymn 1w I m1 31w K m Mamemvgmm Page 29 mm men 357 Fundammtdsmmcmmmm as 357pcksm dun MWHDE EMULATOP MranE rs an mtegrate under H mm deve uped py MGTEK m Germany n rs a pm fur deve upers or embedded suftvvare mp wrde sonyyare m assembherfur Muturu a s BEHCM and Barron mmrucuntruHEr MmHDE mcurpurates an edmor and a a DEmsaBumcmdw Ere gdm yew gdmd Lermmar mdaw gep HD El d EHEJE JtINCLUDE A VAR DEF ASM A xDeflne program varlables one DATA xSLarL o2 maln program one PROGRAM START OF ergln cypnng your oode xEnd o2 maln program WI ASMJJ sch11 Cross Assembler v1 1n Eunld n JUntltledZ asm 25 hues n warmngs n errors n ma seconds TDD returned oode n kl naaam mm 5EpH WUM 4 Wmn MmHDE user ean edm eompne and duvvn uad program In mmrucuntruHer men Ebug program mterawve y As snoyyn abuvey a user ean edd ASM program m edmor Wmduvv 1 men eompne the prugram m were are syntax errors vvarmng messages M be snoyyn m uutput Wmduvv 2 at wasp program n ms epurse MmHDE rs used p duvvn uad epdes mm the MCU Eva uatmn Epard EVE n ms untExI rt acts as a terrmna prpgram Yuu dp nut need In mstaH ms suftvvare pn yuur F39C Dv AclmeVgumu Mean wrm EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc PROGRAMMING FLOW CHART The programming flow chart is shown in the figure below First the source code is written in Assembly language on the TH RSim11 simulator The simulator assembles the asm code and generates a list file LST The simulator is then used to step through the program and debug it until it performs the intended functionality All this can be done remotely in the computer room or on a personal computer Once the program has been debugged it can be taken on a floppy disk to the EMCH 367 lab A 235 The MCU evaluation board EVB hardware is accessed through the MinilDE emulator software installed on the lab computers MinilDE reads the asm file from your floppy disk and transforms it into machine language executable code S19 This code is downloaded to the MCU After downloading the code into the MCU you can make the MCU run your code using the MinilDE interface screens The MinilDE also generates a list file LST that can be used during debugging source cede THRS39 11 List file ASSEMBLY LANGUAGE 4 39m 4 asm Software LST MinilDE 4 39 sm39e Software 39LST Executable code MACHINE LANGUAGE S19 MCU Hardware Figure 1 Flowchart of typical programming steps used in the EMCH 367 course Dr Victor Giurgiutiu Page 31 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc 7 Backup File Assembly Listing Source39Program Objecr code file Object Module Linker Linkmap File Load Module 7 No Load Program into Target System Debug and Test 7 g Y No Figure 2 Flowchart of typical programming steps in a generic programming environment Dr Victor Giurgiutiu Page 32 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc BINARY AND HEX NUMBERS Note To quickly grasp the use of binary and hex arithmetic use your binaryhex pocket calculator and the website httn 39 ntlwnrld quot quot BinaivAdditionhtml The binary number system is a base2 numbering system In binary representation any value is represented using a combination of 139s and 039s For example 1410 11102 in binary The subscript 10 on the first number indicates that the number 14 is represented in the decimal base 10 system The subscript 2 on the second number indicates that 1110 is represented in the binary base 2 system The binary representation is also called quotdigitalquot quotDigitquot also means finger and you can imagine a numbering representation in which you use your 8 digits to for number containing 139s and 039s The ability to represent numbers in terms of 139s and 039s is important because it is the easiest most unambiguous way to represent and communicate information In a computer a 1 is represented by a quothighquot voltage 5V and a O by a quotloW39 voltage OV The binary system is the backbone of all digital computers and other hightech applications THE BINARY SYSTEM To understand how the binary system works let39s first examine howthe conventional base1O system works The base10 or decimal system constructs numbers using increasing powers of 10 For example the number 13510 is constructed using 3 powers of 10 10 101 and 102 These numbers correspond to 110 and 100 The number 13510 is constructed as 1x1003x105x1 or 1x1023x1o15x1oO The equivalent of number 13510 in base two is 100001112 This is constructed as 1x1280x640x320x160x81x41x21x1 or 1x270x260x250x240x231x221x21 1 x20 It can be seen that the only significant difference between the two systems is the base number Each one or zero in the binary representation is called a quotbitquot A collection of eight bits is called a quotbytequot and in a somewhat humorous note a collection of four bits is called a quotnibblequot The bit associated with the highest power of two is called the Most Significant Bit MSB the bit associated with the lowest power of two is the Least Significant Bit LSB bit byte 1 byte 8 bits Hex number nibble 1 nibble 4 bits 2 nibbles 1 byte Dr Victor Giurgiutiu Page 33 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc DECMAL TO BINARY CON VERSION Because most people are more comfortable using and thinking in the decimal system it is important to know how to convert from the decimal to the binary system This is most easily achieved through a series of divisions by two and by tracking the resulting remainders Let39s consider out example of 132102 132 2 66 Remainder O 66 2 33 Remainder O 33 2 16 Remainder 1 13210 10000100 16 2 8 Remainder o f V 8 2 4 Remainder O MSB LSB 4 2 2 Remainder O 2 2 1 Remainder O 1 2 O Remainder 1 The remainder 1 resulting from the last division is the MSB while the first remainder is the LSB of the conversion From this example we see that the decimal number 132 is equal to the binary number 10000100 The conversion from binary to decimal is done in the same manner as the first example by adding together power of two values of the nonzero bits HEXADECMAL HEX NUMBERS As one might have already surmised binary numbers quickly become long and hard to remember For this reason it is more convenient to convert the binary values into hexadecimal numbers hex Hexadecimal numbers are base 16 numbers This requires six additional characters to represent the values 10 11 12 13 14 and 15 These values will be represented by the letters A B C D E and F The counting order in hex is O 1 2 3 4 5 6 7 8 9 A B C D E F The reason hex notations are use is that it allows for a one to one correspondence between the 16bit binary nibble and a single hexadecimal value If the binary number is broken down into nibbles and each nibble is replaced with the corresponding hexadecimal number the conversion is complete Consider 13210 The binary number is 10000100 It can be broken down into two separate nibbles 1000 and 0100 Convert each nibble into the corresponding hex value 8 and 4 respectively and the hex equivalent of 13210 is 8416 This is much more convenient to remember For example the hex number A23E3 is easily converted to 10100010001111100011 in binary without using any difficult calculations To convert decimal to hex numbers it is easiest to convert the decimal number to binary and then convert the binary to hex In addition to these methods there is a conversion chart in the back of the Programming Reference Guide for the conversion from decimal to hex Dr Victor Giurgiutiu Page 34 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc BINARY ARI THME TIC The rules for addition of binary numbers are straightforward OOOO11and11Owithacarryof1ie11102 For example 1001010010 1010010100 0100110001 0100010010 1110000011 0001010001 1111110111 NEGATIVE NUMBERS IN THE COMPUTER 2 S COMPLEMENT NUMBERS Until now we have discussed only positive numbers These numbers were called quotunsigned 8bit integersquot In an 8bit byte we can represent a set of 256 positive numbers in the range O1o2551o However in many operations it is necessary to also have negative numbers For this purpose we introduce quotsigned 8bit integersquot Since we are limited to 8bit representation we remain also limited to a total of 256 numbers However half of them will be negative 12810 through 11o and half will be positive 010 through 12810 The representation of signed positive and negative numbers in the computer is done through the so called 8bit 239s complement representation In this representation the 8th bit indicates the sign of the number 0 1 The signed binary numbers must conform to the obvious laws of signed arithmetic For example in signed decimal arithmetic 310 310 010 When performing signed binary arithmetic the same cancellation law must be verified This is assured when constructing the 239s complement negative binary numbers through the following rule To find the negative of a number in 8bit 239s complement representation simply subtract the number from zero ie X 0 X using 8bit binary arithmetic Example 1 Use the above rule to represent in 8bit 239s complement the number 310 Solution Subtract the 8bit binary representation of 310 from the 8bit binary representation of 010 using 8bit arithmetic 8bit arithmetic implies that you can liberally take from or carry into the 9h bit since only the first 8 bits countl BINARY DECIMAL 00000000 01o 0000001 1 gm 1 1 1 1 1 101 310 Note that in this operation a 1 was liberally borrowed from the 9th bit and used in the subtraction Dr Victor Giurgiutiu Page 35 1I17I01 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc Veri cation We have establish that 310 111111012 Verify that 310 310 010 using 8bit arithmetic BINARY DECIMAL 1 1 1 1 1 101 31o 0000001 1 gm 00000000 010 Note that in this operation a carry of 1 was liberally lost in the 9th bit Example 2 Given the binary number 00110101 find it39s 239s complement Solution Subtract the number from 00000000 ie BINARY HEX DECIMAL 00000000 00 01o 01110101 Mm 10001011 BB 1061o Veri cation 01110101 10001011 100000000 Since the 9th bit is irrelevant the answer is actually 00000000 as expected The rule outlined above can be applied to both binary and hex numbers Example 3 Given the hex number 6A find its 8bit 239s complement Solution Subtract the number from 0016 using 8bit arithmetic H EX DECIMAL OO O10 Mm 96 10610 Veri cation 6A16 9616 100 Since the 9th binary bit is irrelevant the answer is actually 0016 as expected Example 4 110010102 9 CA16 9 20210 Dr Victor Giurgiutiu Page 36 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc NUMERICAL CONVERSION CHART FOR UNSGNED 8BlTBNARYNTEGERS base 10 base base Dr Victor Giurgiutiu Page 37 11701 EMCH 367 NUMERICAL CON VERSION CHART FOR 2 39S COMPLEMENT SIGNED 8Bl T BINARY INTEGERS Fundamentals of Microcontrollers Decimal 8bit 239s complement Hex signed binary 127 01111111 7F 16 0001 0000 10 15 0000 1111 OF 14 0000 1110 0E 13 0000 1101 0D 12 0000 1100 0C 11 0000 1011 OB 10 0000 1010 0A 9 0000 1001 09 8 0000 1000 08 7 0000 0111 07 6 0000 0110 06 5 0000 0101 05 4 0000 0100 04 3 0000 0011 03 2 0000 0010 02 1 0000 0001 01 0 0000 0000 00 1 1111 1111 FF 2 1111 1110 FE 3 1111 1101 FD 4 1111 1100 FC 5 1111 1011 FB 6 1111 1010 FA 7 1111 1001 F9 8 1111 1000 F8 9 1111 0111 F7 10 1111 0110 F6 11 1111 0101 F5 12 1111 0100 F4 13 1111 0011 F3 14 1111 0010 F2 15 1111 0001 F1 16 1111 0000 F0 128 1000 0000 80 Dr Victor Giurgiutiu Page 38 367pck SO1doc 11701 EMCH 367 Fundamentals of LOGIC GATES AND BOOLEAN ALGEBRA Microcontrollers LOGC GATES Circuit IC Symbol Boolean Function Buffer 7407 A v x X A NOT 7404 A 4 gt07X 7 Inverter X A A AND 7408 B1 X X ADB A OR 7432 BDX X A B NAND 7400 A BDH X ADB A 7 NOR 7402 BDX XAB Exclusive OR A X ADEZDB 7486 X XOR B A EBB A X ADB 20 Comparator BDX A 3 Page 39 Dr Victor Giurgiutiu 367pck SO1doc 11701 EMCH 367 Inverting gate Fundamentals of Microcontrollers AND gate 5V Htf1r1r1rltl 1 7404 3 rm rm LHJLJLJLILI 7404 Hex Inverting Gates OR gate 367pck SO1doc V H1 l l ii 7408 LILJLILtJIJ 7408 Quad 2 Input AND Gates XOR gate Dr Victor Giurgiutiu 7432 Quad 2Input OR Gates Page 40 5V A j TENTH 1W 39 7486 Zgt Ll LILJLJLJLI 7486 Quad 2 Input ExclusiveOR Gates 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc BOOLEAN ALGEBRA In formulating mathematical expressions for logic circuits it is important to have knowledge of Boolean algebra which defines the rules for expressing and simplifying binary logic statements The basic Boolean laws and identities are listed below A bar over a symbol indicates the Boolean operation NOT which corresponds to inversion of a signal Fundamental Laws AND NOT A0A A00 A11 A1A 1 A A A AA A ZA double inversion A21 AZ0 Commutative Laws ABBA 2 ABBA Associative Laws ABCABC 3 ABCABC Distributive Laws 4 ABC ABAC Other Useful Identities AABA 5 AABA 6 AZBAB 7 ABAEA 8 ABACABC 9 ABAEAB 10 ABBCECABC 11 ABACECABEC 12 DeMorgan s Laws are also useful in rearranging of simplifying longer Boolean expressions or in converting between AND and OR gates ABC ZEE 13 ABCZBE 14 If we invert both sides of these equations and apply the double NOT law fro Equation 1 we can write DeMorgan s Laws in the following form ABC 15 ABcZEE 16 Dr Victor Giurgiutiu Page 41 11701 EMCH 367 Fundamentals of Microcontrollers 367pck 8011100 This page is left intentionally blank Dr Victor Giurgiutiu Page 42 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc CONDITION CODE REGISTER CCR SX 39NZVC S Stop bit Allows user to turn the microcontroller stop function on or off X XIRQ mask Used to disable interrupts from the XIRQ H Half carry bit Indicates a carry from bit 3 during addition Only updated by ABA ADD and ADC It is used by the BAA in BCD operations setting a hexadecimal number to decimal l Interrupt mask Global interrupt mask Allow user to turn onoff interrupts N Negative bit Set to 1 when the result of an operation is 1 in the MSB Set to 0 when the result of an operation is O in the MSB Z Zero bit Set to 1 when the result of an operation is 0016 Set to 0 when the result of an operation is anything other than 0016 V oVerflow bit Set to 1 when a 239s complement overflow has occurred due to a specific operation 7E16 0416 8216100000102 Note The 1 in the MSB indicates that an overflow occurred The addition yielded a number larger than 7F16 which is the maximum positive value that a 2398 compliment number is allowed C Carry bit Set to 1 when a carry or borrow has occurred in the MSB In addition operations it is set if there was a carry from MSB ln subtractions it is set if a number with a larger absolute value is subtracted from a number with a smaller absolute value It is also used in multiplication and division Dr Victor Giurgiutiu Page 43 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc BUFFALO COMMANDS The monitor BUFFALO program is the resident firmware for the EVB which provides a selfcontained operating environment It interacts with the user through predefined commands The BUFFALO command line format is as follows gtltcommandgtltparametersgtR ETU R N where EVB monitor prompt ltcommandgt Command mnemonic ltparametersgt Expression or address RETURN RETURN keyboard key 1IO39ITEcommand line format is defined using special characters that have the following syntactical meanings lt gt Enclose syntactical variable Enclose optional fields Enclose optional fields repeated These characters are NOT entered by user but are for definition purpose only Fields are separated by any number or space comma or tab characters All input numbers are interpreted as hexadecimal All input commands can be entered either upper or lower case lettering A maximum of 35 characters may be entered on a command line Command line errors may be corrected by backspacing or by aborting the command CRTL XDelete 7 After a command has been entered pressing RETURN a 2quotd time will repeat the command 0301th vvvvv Move memory to new location Next few pages are detailed description and examples for each command Dr Victor Giurgiutiu Page 44 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc AS M AssemblerDisasse mbler ASM ltaddressgt where ltaddressgt is the starting address for the assembler operation Assembler operation defaults to internal RAM if no address is given Each source line is converted into the proper machine language code and is stored in memory overwriting previous data on a linebyline basis at the time of entry The syntax rules for the assembler are as follows a All numerical values are assumed to be hexadecimal b Operands must be separated by one or more space or tab characters Addressing modes are designated as follows a Immediate addressing is designated by preceding the address with a sign b Indexed addressing is designated by a comma The comma must be preceded a one byte relative offset and followed by an X or Y designating which index register to use eg LDAA 00X c Direct and extended addressing is specified by the length of the address operand 1 or 2 digits specifies direct 3 or 4 digits specifies extended Extended addressing can be forced by padding the address operand with leading zeros d Relative offsets for branch instructions are computed by the assembler Therefore the valid operand for any branch instruction is the branchiftrue address not the relative offset Assemblerdisassembler subcommands are as follows Assemble the current line and then disassemble the same address location quot Assemble the current line and then disassemble the previous sequential address location RETURN Assemble the current line and then disassemble the next opcode address CTRL J Assemble the current line If there isn39t a new line to assemble then disassemble the next sequential address location Otherwise disassemble the next opcode address CTRL A Exit the assembler mode of operation EXAMPLE DESCRIPTION gtASM C000 C000 STOP SFFFF gtLDAA 55 Immediate mode addressing requires 86 55 before operand C002 STOP SFFFF gtSTAA C0 Direct mode addressing 97 C0 C004 STOP SFFFF Index mode if offset 0 X will not gtLDS 0X be accepted AB 00 C006 STOP SFFFF gtBRA C500 Branch out of range message Branch out of range C006 STOP SFFFF Branch offsets calculated automatically gtBRA C030 address required as conditional branch 20 28 operand C008 STOP SFFFF gtCTRLA Assembler operation terminated EXAMPLE DESCRIPTION Dr Victor Giurgiutiu Page 45 11701 EMCH 367 gtASM c000 c000 CLR 0800 gtLDY C200 18 CE 62 00 c004 TEST gtLBx C400 CE 64 00 c007 TEST gtLDAA 102E B6 10 2E CO0A TEST gtLDAA 0x 6 00 cooc TEST gtSTAA 102F B7 10 2E c00E INK gtLDAA 102E B6 10 2E c012 TEST gtANDA 80 84 80 c014 TEST gtBEQ c00E 27 F9 C016 BITB 80F6 gtLDAA 102E B6 10 2E C019 BVS C01B gtANDA 20 84 20 C01B STX 00FF gtBEQ C016 27 E9 c010 STX 4065 gtLDAA 102F 2E c020 STAA 00Y gtSTAA 0Y 8 A7 00 c023 STX 00FF gtINX 08 c024 TEST gtINY 18 08 c026 ASRB gtCPX C4IF 86 64 IF c029 ASLD gtBEQ C02E 27 03 C02B STX SOOFF gtJMP CO0C 7E C0 0C C02E MUL gtBRA C02E C030 ILLOP gtCTRLA BF Dr Victor Giurgiutiu Fundamentals of Microcontrollers 367pck 8011100 Enter assemblerdis assembler mode First byte where data is stored IMM mode Point to data to be fetched IMM mode Clear RDRF bit if set EXT mode Get fIrst data byte INX mode Store data in SCI data register EXT mode Read SCI status register EXT mode Send data byte IMM mode Wait for empty transmit data register REL mode Read SCI status register EXT mode Extract RDRF bit fram status register IMM mode Branch true SCI RDR not full Branch false SCL RDR full REL mode Read data from SCI RDR EXT mode Store data byte INY mode Increment fetch pointer INH mo 9 Increment storage pointer INH mode Done sending data IMM mode No get next data byte EXT mode Yes stop here REL mode Exit assemblerdissembler mode Page 46 11701 EMCH 367 Block Fill BF ltaddress1gt ltaddre552gt ltdatagt Fundamentals of Microcontrollers 367pck SO1doc byte of from 000 where ltaddress1gt Lower limit for fiII operation ltaddress2gt Upper limit for fiII operation ltdatagt FiII pattern hexadecimal value EXAMPLE DESCRIPTION gtBF 000 030 FF Fill each memory through C030 with data pattern FF gtBF 000 000 0 CALL Execute Subroutine CALL ltaddressgt Set location COOO to 0 where ltaddressgt is the starting address where user program subroutine execution begins EXAMPLE gtCALL COOO PCOOO YDEFE XF4FF A44 BFE CDO 5OO4A GGO Execute Program G ltaddressgt DESCHPWON Execute program subroutine Displays status of registers at time RTS encountered except P register contents where ltaddressgt is the starting address where user program execution begins EXAMPLE gtG COOO PCOOO YDEFE XF4FF A44 BFE CDO 5OO4A H E LP Help Screen Dr Victor Giurgiutiu DESCRIPTION Execute program subroutine Displays status of registers at time RTS encountered except P register contents Page 47 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc HELP Display monitor commands MD Memory Display MD ltaddress1gt ltaddre552gt Display a block of user memory beginning at address 1 and continuing to address 2 EXAMPLE gtMD C000 CO0F 000 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF M M Memory Modify MM ltaddressgt ExamineModify contents in user memory at specified address in an interactive manner EXAMPLE DESCRIPTION gt1VJM C700 Display memory location C700 C700 44 66RETURN Change data at C700 gtMM C000 Examine location C000 C000 55 80 C2 00 CE C4 Examine next locations using SPACE BAR MOVE Block Move MOVE ltaddresslgt ltaddressZgt ltdestgt where ltaddress1gt Memory starting address ltaddress2gt Memory ending address ltdestgt Destination starting address optional Copymove memory to new memory location If the destination is not specified the block of data residing from addressl to address2 will be moved up one byte EXAMPLE DESCRIPTION gtMOVE E000 E7FF C000 Move data from locations E000 E7FF to locations CO0D C7FF gtMOVE C000 COFF Move data from locations C000 COFF to locations C001 C100 Dr Victor Giurgiutiu Page 48 11701 EMCH 367 RM Register Modify R34lmy aJhe Fundamentals of Microcontrollers 367pck SO1doc The RM command is used to modify the MCU program counter P Y index Y X index X A accumulator A B accumulator B Condition Code Register C and stack pointer S register contents EXAMPLE gtRM PEoo7 Y 7982 X FFOO A 44 B 7O c co 3 0054 9 0007 0020 gtRMX PCOO7 Y7982 XFFOO A44 B7O CCO 30054 XFFOO C020 T Trace Tltngt DESCRIPTION Display P register contents Modify P register contents Display X register contents Modify X register contents Where ltngt is the number 1FF of instructions to execute Monitor program execution on an instructionbyinstruction basis Execution starts at the current program counter PC EXAMPLE gt2 Op 86 PC002 YDEFE XFFFF A44 BOO COO 30048 01137 P COOS Y DEFE X FFFF A 44 B OO C OO s 004B Op Ol P COOG Y DEFE X FFFF A 44 B OO C OO s 004B Dr Victor Giurgiutiu Page 49 DESCRIPTION Single trace Register contents after execution Multiple trace 2 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc DEBUGGING TIPS MICROCONTROLLER PROBLEMS Is the processor plugged into the PC serial port Is the processor plugged into the power supply Is the power supply turned on Is the serial port plugged into the correct connector HARDWARE PROBLEMS Does the component have power Check all voltages Are the chips oriented correctly notch in the correct direction Do the chips straddle the gap in the center of the board Make sure all chips have power not just input amp output lines Verify the direction of diodes and electrolytic capacitors Verify the power at intermediate locations use 5 or 0 volts from the supply instead of chip input to check various conditions Verify that the PC ports are giving the expected output signals Verify chip and transistor pins with the pin diagrams Are there any quotopenquot lines no voltage connection instead of zero volts Verify resistor codes and capacitor values SOF TWARE PROBLEMS Is the correct program currently in memory Is the correct starting location being used G Verify the program with ASM Use trace T to step through and verify branches jumps and data Compare memory locations with expected information after the program stops lnsert SWI at a key location to allow verification of branch memory and accumulator values Do branches and jumps have the correct offsets Have RET and RTI commands been reversed somewhere For serial communications has TE or RE been set For serial communications has TDRE or RDRF been reset For parallel port C has 1007 been set for input or output Has the interrupt mask been cleared CLI Has the stack pointer changed substantially Use the BUFFALO commands to do stepbystep Trace T and BreakPoint BR execution of the program Press F1 for details of the BUFFALO commands Dr Victor Giurgiutiu Page 50 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc REGISTERS INFORMATION R AND 0 REGISTER AND CONTROL Ei T ssmNn E m BIT SUMMARY 3 17 0 5 I 2 1 Earl m m FORquot I Nuwnd we mamm sum PDRYC W Wquot m mm quotW m m FORM mm anrua m nun m FORTE was man man POHYE was cram siwc OCI M man sum 05 1cm mm mm 110 mu mu Tlcz am mu 1 nos aim 5 ma TOCI 91m Sim TDC2 9019 mm TOCJ saw 5 mm c 70c aim 0 ME ma smF Dr Victor Giurgiutiu Page 51 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc PARALLEL PORTS Section 7 of the M68HC11 Reference Manual Parallel communication is communication that occurs simultaneously on many lines thus the word parallel It is used most often when the communicating devices are local to one another For the MC6811 there are two parallel ports to which the user has direct access Port B and Port C Since MC6811 is an 8bit microcontroller each of these parallel ports has 8 bits That is each of the parallel ports has eight separate wires coming out of the microcontroller one wire for each bit of data The two parallel ports are configured differently Parallel Port B is restricted to output only applications Parallel Port C can be used for either input or output Moreover in Parallel Port C not all bits have to be the same type of communication For example the first four bits of Parallel Port C PCO PC3 can be set to read input while the last four bits of Parallel Port C PC4 PC can be set to send output information To use these parallel ports a program must load and store specific numbers to special memory locations These memory locations are referred to as control registers There are three different control registers which are related to Parallel Port operation one related to Parallel Port B and two related to Parallel Port C As Parallel Port B is output only there is only one thing which needs to be specified the output data This will be a signal of either 5V or 0V for each line in the Parallel Port A 0 corresponds to ov a 1 corresponds to 5V To send desired data out Parallel Port B store the twodigit hexadecimal number corresponding to the eight bits of data that you wish to output into memory location 1004 This one action specifies the output voltage on the eight separate output lines For Parallel Port C two aspects of parallel communication must be specified These are the data direction for each pin whether a pin is input or output and the actual data for each pin The data direction for each pin is specified by storing a twodigit hexadecimal number corresponding to the data direction of each individual pin into memory location 1007 A 0 corresponds to input a 1 corresponds to output The specific data for Parallel Port C is in memory location 1003 If the pin is output then the value in that bit location indicates the voltage currently sent out that pin The behavior of Parallel Port C in output is the same as Parallel Port B Changing the value of the bit changes the value of the output voltage If the pin is input the value in that bit location indicates the voltage currently being measured on that pin Writing to an input pin has no effect DO NOT SEND AN INPUT SIGNAL INTO A PIN SPECIFIED FOR OUTPUT THAT WILL FRY THE CHIP Dr Victor Giurgiutiu Page 52 11701 men 357 Fundamema s m Mmmcamm evs 357m sm m THRSM77 SMULATON OF PARALLEL COMMUNCATON The specmc Wmdows that need to be open dunng theTHRSme swmmauon of paraHe commumcauon are Ponregwsters Poanms PonCpms Aglzl He at ieavch Mew Execute Lahe EVeakumnt Canned Mndaw deb DDRD I151 Sun m mam vagumu Page 53 m Wm EMCH 367 Fundamentals ur Micrucuntmllers 367pcllt SEI1 on THE THRSM11IO BOX The TH RSim11 IO box is use among others to perform the simulation of Port B and Port C functions Port B which is only an output port is simulated as the eight LED s PBO PB1 PB7 When a logical 1 signal is sent to a Port B pin PBX the corresponding LED lights up becomes red Port C pins PCO PC1 PC7 can be selected as either input or output using the DDRC register bits in your progr m When selected as input DDRCX 0 x 0 1 7 the switches are used to send signals into the MCU along the PCX line When selected as output DDRCX 1 the switches ip up and down according to the value on that PCX line up 1 down 0 A9231 Elle gait Bannisle OJtlans new a Nell1 linrln This bux cuntains sWitcnes cunnected tc tne BEHCM pins cn F39CEIVF39C7 LED s cunnected tc tne BEHCM pins cn F39ElELF39E LED s cunnected tc tne BEHCM pins cn F39DEIVF39DE STRA sztch LED cunnected tc tne BEHCM pin STROEE A iiiiicuiiic iiiciuueiiieiii cui prugram A sztEh can be tuggled by Ellcklng an it Witn tne muuse cir by yplrlg u tci 7 tcir F39CEI tci F39C7 cirAtcir STRA vvnen pcirt DDRCX Real svvltches Will nut fulluvv tnis behavlur but Will cause a shun circuit 7 Dr VlEtDr Giurgiutiu Page 54 117EI1 EMCH 367 ASCII AND BCD CODES Fundamentals of Microcontrollers 367pck 8011100 Ago I 7 am MA LSD Ascu CHARACTER SET 7Bit Code I II quot I l311115 M or JlO 011 I00 101 no 3911 lg Ls o 1 2 3 4 5 5 7 Dig 39 WW o NUL DLE SP 0 P p 0w I 1 SOH DC1 1 1 A o a q 0 390 2 STX DCZ quot 2 B R b r lt1 39I 3 ETX DC3 3 c s c s 0 4 EOT DC4 4 D T d t quot39 5 ENG NAK 5 E u e u 5 1390 5 ACK SYN amp 6 F v f v a m 7 BEL ETB 39 7 G w 9 w 00 a BS CAN 8 H x h x 9 HT EM 9 l v i y 19w A LF SUB J z j z 101 B VT ESC K k 100 C FF FS lt L I 110 D en es M 1 m 1 1 m7 E S RS gt N n 1 F SI us 7 o o DEL J 2 ca 5 3911 BCD U 4 Decimal 85 4s 25 Is I Decimal 9 1 l l 0 0 0 0 0 303 1001 0001 1 0 0 0 1 Decimalto BCD conversion 2 0 0 1 o 3 0 0 1 1 4 0 1 0 O BCD 0111 0010 l l 5 0 1 0 1 Decimal 7 2 6 0 1 1 0 BCDtodecimal conversion 7 0 1 1 1 r 8 1 0 o 0 9 1 o o 1 Dr Victor Giurgiutiu Page 55 11701 EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc SERIAL COMMUNICATIONS Section 9 of the M68HC11 Reference Manual Serial communications are used when one bit is sent at a time All the data is transferred on one line the bits are transferred sequentially making serial communication much slower than parallel communication The data is specified by holding each bit at a certain voltage for a certain period of time The data is usually sent in character format using the 7bit ASCII American Standard Code for Information Interchange code It specifies a 7 bit binary code for commonly used characters To put the 7bit ASCII into an 8bit byte one fills the 8th bit with O The data byte being sent is bracketed by two bits the start bit 0V and the stop bit 5V An idle line has a voltage of 5V Each data byte is prefixed by a 0V start bit The data bits are then sent from the least significant bit to the most significant bit At the end a 5V stop bit is added All bits are held for the same amount of time The time is specified by the BAUD rate bitssec MC6811 has the capacity to receive and transmit data through the serial communication interface The selection of receive andor transmit modes is done by setting to 1 the RE and TE bits in the Serial Communication Control Register 2 SCCR2 memory location 102D bits 2 and 3 Simultaneous selection of both receive and transmit modes is permitted since MC6811 has separate lines for reception and transmission RxD and TxD through port D pins PDO and PD1 respectively In the receive mode the ReceiveDataRegisterFull RDRF indicates when serial communications data has been received RDRF1 RDRF is bit 5 of the Serial Communication Status Register SCSR at memory location 102E When serial communications data is received it gets placed in the Serial CommunicationDataRegister SCDR memory location 102F As a user you would normally check RDRF until found equal to 1 then load the data from SCDR into an accumulator This sequence of reading RDRF1 and loading data from SCDR will trigger the clearing of RDRF ie will make RDRFO For this reason it is called quotclearing sequencequot In this way MC6811 becomes ready for the reception of the next serial communication data Transmission of data from MC6811 also uses the SerialCommunicationDataRegister SCDR Before placing new data in SCDR for transmission one must first make sure that SCDR is empty ie it has finished transmitting previous data This verification is done by checking the value of Transmit Data Register Empty TDRE bit memory location 102E bit 7 If TDRE 0 then MC6811 is still transmitting data through the serial communication interface lf TDRE 1 then transmission has finished and the data register is empty and ready to receive new data for transmission When data is stored into SCDR for transmission MC6811 automatically adds the start and stop bits to the data sends the data out through the serial communication interface and after transmission is complete makes TDRE1 The clearing sequence for TDRE consists in reading TDRE1 followed by storing of data into SCDR Subsequently MC6811 starts serial communication transmission of the data placed in SCDR lnterrogating the value of specific bits in SCSR RDRF TDRE etc can be done in a number of ways ne way could be to AND the contents of SCSR with the appropriate mask and use a BEQ instruction to loop back if the result is zero ie if the interrogated bit is not yet set For RDRF bit 5 the mask is 20 For TDRE bit 7 the mask is 80 However there are also other ways of branching in correlation with the status of specific bits eg instructions BRCLR BRSET etc Feel free to experiment Serial communication is critical to the operation of modern computers This is how keyboards communicate with the computer and how you will control your programs during labs and project NOTE Please see Section 9 of the M68HC11 Reference Manual for more detailed information on serial communication Dr Victor Giurgiutiu Page 56 11701 EMCH 357 Fundmemdsmmamamm as 357m sm dun THRSM77 SMULATOV OF SEEAL COMMUNCATON The speeme Wmduvvsthat need m be upen dunng the THRSme swmu atmn m sena cummumcatmn are Senax regwsters Serwa transmwtter Senax recewer an In 5e mz ieavch Mew Execute Lahe Eveakvmnt ism We Eliaquot a use m m Mamemvgmm Page 57 mm EMCH 357 Fundamentais ut Mieieeentieiieis 357pex Sm dee THE THRSM11 SEQAL TRANSMITTER The THRSimi 1 39 39 39 39 During simulation with your program running type a character in the transmitter and press the Send button The MCU should receive it and react according to your instructions 42m he get eeeheerx gptiens heiv Eanienis index heex Eiini in 1 settingsl Serial step I Type the text you want te transmit In this windnw and press the Send hetteh Need 1 Sun a Dzla Step This hex eentains the seriai transrnitter The hex is eenneeted te the RXD pin er the sirneiated EEHCM Se the generated seriai signai is send te the EEHCM rniereeentreiier Yuu have te Write EH11 nai nii ii iii a eria transrnitter Yuu can type in the eharaeters yuu Wanttu send te the EEHCM rniereeentreiier p where ddd is the ASCH vaqu er the nen printahie eharaeterte send There are three buttuns in this bux Settings Setting haed rate pang ete Yuu prubabiy Wanttu rnateh the setting er the transrnittervvith the settings yuu use in yuur pregrarn that is receiving the data But yuu can create a rnisrnateh te sirn Whatvviii happen in this errer situatiun Yuu nannng ii i in the thrsirni Luptiuns m initiaiizatien the se iryee exit the simuiatur and run it again iaterthese settings are preserved Send The seieeted text in the edit Wiride Wiii he send te the EEHCM rniereeentreiier if seieeted and send Nete the sirneiater must he running te perfurrn this task Step This buttun ends the transrnissien er data tn the rniereeentreiier Di videi Gieigietie Page 58 mm EMCH 367 Fundamentais pr Micrucummiiers 367pcilt Sm duc THE THRSM1 1SERAL RECEiER The THRSim11 serial receiver acts like the PC monitor in the lab t receives signals sent by the MC With your program running and the serial receiver window open you e a character displayed in the receiver window every time the MCU transmits a character while executing your program r 4in Eiie drt adamark 04 an heiv p h u I se39ngs gear Beset if if Mane I Start a Danni Slap This he The bux is Lu BEHCM EHC H Hui nr n r Yuu a M ai Hu nr senai receiver Printabie characters are nurmaiiy dispiayed Nun printabie characters are dispiayed scu There are three cummand buttuns Settings Setting baud rate pang etc YDU prubabiy Wanttu rnatch the setting at the receiver with the settings ydd use in yuur prugram which is sending the data But ydd can create a mismatch tn simuiate Whatvviii happen in this errur situatiun YDU prubabiy Hamhig thrsimi Luptiuns m initiaiizatiun nle su ifyuu exit the simuiatur and run it again iater these settings are preserved Ciear Reset Resets the receiver Parity andpr framing Errurs Wiii be remuved a TD ciearthese cummunicatiun errur ags press the reset buttun Dr Victur Giurgiutiu Page 59 wwm EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc TIMER FUNCTIONS Section 10 of the M68HC11 Reference Manual Timer functions allowthe microcontroller to determine quottimequot by counting the number of machine cycles between events The timer is based on the Timer Counter register TCNT 100E 1OOF The timer counter register increments once every machine cycle Once the timer counter register reaches FFFF the next machine cycle causes the register to quotoverfloW39 go from FFFF to 0000 To let the user know that this has happened the microcontroller sets a flag TOF the Timer Overflow Flag bit 7 of 1025 1 implies that there has been a timer overflow 0 implies that there has not been a timer overflow To use TOF as a counting tool you must clear TOF Here clearing TOF is obtain by writing a 1 to it unusual but true for all timer flags see Section 1024 on page 1014 in the Reference Manual When clearing a flag it is important that you do not interfere with the other bits in the register The timer is also linked to external lines allowing the microcontroller to record the value of the timer counter when an input voltage changes These functions are called input capture functions They detect a signal transition At the time that the signal transition is detected the input capture function automatically records the value in the timer counter in a separate memory location and sets a flag leF to let the user knowthat there has been an input capture Value 1 implies that there has been an input capture 0 implies that there has not Each flag is cleared by writing a 1 to the flag in the control registers The type of signal transition that causes an input capture is determined by the edge bits EDGXB and EDGXA Because these two bits act together there are four different modes for each input capture disabled lowtohigh detection hightolow detection and both lowtohigh and hightolow detection MC6811 has three individual input captures All act in the same way with separate memory locations EDG bits and lCF39s Another timer function is the output compare function When the value in the timer counter register reaches the value in the output compare register the microcontroller sends a signal out on the selected pin In essence the microcontroller schedules when to send the signal out There are four commonly used output compares on the MC6811 They are OC2 0C3 OC4 and 0C5 As the timer is a two byte register each of the output compare registers is a twobyte register To set a value for output compare simply store the twobyte number to the output compare registers Once the timer counter reaches the value in a timer outputcompare register an OCxF output compare flag is set to let the user knowthat an output compare has occurred 1 indicates that output compare has occurred 0 indicates that output compare has not occurred To clear an output compare flag write a 1 to OCxF The signal sent out of the microcontroller on output compare is controlled by two bits acting together the OMx and OLx bits The four available options are i disabled ii send out 0V iii send out 5V and iv toggle the output voltage Each of the timer outputcompare functions has output compare registers OM and CL bits and output compare flags in the control registers The timer counts and measures events in terms of machine cycles ln Lab 3 you measure the clock speed of the microcontroller In essence you calculate a conversion factor between machine cycles and real time Using the timer functions of the microcontroller and the conversion factor that you derive you can use the microcontroller for data acquisition involving time measurement Dr Victor Giurgiutiu Page 60 11701 mm 357 Fundmemdsmmamamm as 35m Sm m THRSM77 SMULATOV OF TMEP FUNCTOVS THRSme Hm Twmer regwsters PunA pm Number m C uck ydes mus n11 EH2 mz ieavch Mew Execute Lahe Eveakumnt gnne WW He v n 51 n 51 Pin P 7 E1 X m1 J 39v Agm number nf Elnck cycles n m Mamemvgmm Page 51 mm EMCH 367 Fundamentals of Microcontrollers 367pck SO1doc ANALOGTODIGITAL CONVERSION Section 12 of the M68HC11 Reference Manual An analogtodigital converter AD takes an analog voltage such as those produced by many electronic measuring devices and converts it to a digital value MC6811 has an 8bit analogtodigital converter The range of measurement is from 0V to 5V This allows the microcontroller to interface with such devices as potentiometers cermets thermocouples LVDT39s etc MC6811 has many different ways that analogtodigital conversions can be made as there are 8 separate lines or channels that the AID can utilize All of the options are controlled by one control register ADCTL in 1030 The results of the AID conversions are stored in four separate memory locations 1031 1032 1033 and 1034 ADR1 ADR2 ADR3 and ADR4 respectively There are two different modes that MC6811 can use to take data These are determined bythe value of SCAN bit 5 in 1030 lf SCAN 1 then the microcontroller continuously scans for data along the AD lines Every time a new measurement is made the data is stored in the appropriate memory location If SCAN 0 then four conversions are made one on each specified line The results of these four conversions are stored in the specified memory locations As soon as all four conversions are completed the AD stops making conversions The lines specified to take data are determined by bits CD CA bits 3 O in 1030 The meanings of these bits are specified by MU LT bit 4 in 1030 lf MU LT 0 then four consecutive conversions are performed on the same data line The results of the conversions are stored in ADR1 ADR4 CD CA specify the single line for all four conversions Table 12 1 shows the values of CD CA for each input line If MULT 1 then one conversion is made on each of four separate lines The results are stored in ADR1 ADR4 Only CD and CC have any effect in determining which four lines take the data The four lines and the location of the AD data are shown in Table 12 1 To start the AD conversions write the value to 1030 that configures SCAN MULT CD CC CB and CA for the desired data acquisition This action automatically clears the Conversion Complete Flag CCF in ADCTL bit 7 of 1030 CCF is set when four AD conversions are completed If SCAN 1 CCF is set after the first four conversions are completed and remains set until a subsequent write to ADCTL 1030 There is no interrupt for CCF As such polling operations must be used to monitor CCF Once the microcontroller has completed the conversions CCF is set The data in ADR1 ADR4 represents valid conversion values It takes 128 machine cycles to make four eightbit conversions At 2 MHz this is an impressive data acquisition rate There are many types of AD conversion techniques MC6811 uses a successive approximation technique Some other types of ADs are the counter integrative and flash ADs Dr Victor Giurgiutiu Page 62 11701 EMCH 357 Fundmemdsmmamamm as 357m sm dun THRSw 1 SIMULA TOA OF ANALOG TO DGTAL CONVEPSOA The speeme Wmduvvs that need m be upen dunng me THRSme swmu atmn elf ana ug m mgnax unversmn are AD unvener regwsters Shders E pen JEILI mu mll 5e mz iearch Mew Execute Lahe Eveakvmnt Canned Mndaw ew i Mtge noevl n S1n3n sun non1 n 1n31 sun annz I1 S1n32 alum I1 Swaa mm M Swan Sun AHA EEHEEHZIEHZIEI m Mamemvgmm Page 53 mm
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'