Module 1 presentation - 2011 Edition by D. G. Meyer...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1 Microcontroller Assembly Language Programming Techniques 1 Module 1 Desired Outcome: "An ability to write programs for a computer in assembly language" Part A: Microcontroller Architecture and Programming Model Part B: Microcontroller Instruction Set Overview Part C: Assembly Language Programming Techniques Control Structures Part D: Assembly Language Programming Techniques Control Structure Applications Part E: Assembly Language Programming Techniques Table Lookup Part F: Assembly Language Programming Techniques Parameter Passing Part G: Assembly Language Programming Techniques Macros and Structured Programming 2 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-A Microcontroller Architecture and Programming Model 3 Reading Assignment: Meyer Chp 3, pp. 1-29 Instructional Objectives: To learn about differences in "world views" regarding the role of microprocessors To learn about the characteristics that distinguish microprocessors To learn about the Freescale 68HC(S)12 architecture and programming model 4 Outline Characteristics that distinguish microprocessors Taxonomy of microprocessors from an application viewpoint Challenges in selecting an educationappropriate microprocessor Basic architecture of the Freescale 68HC(S)12 Instruction formats and data types of the 68HC(S)12 5 Introduction Two basic "world views" regarding the role of microprocessors are applicable general-purpose view: a microprocessor is an integral part of a machine that runs "shrink-wrapped" software (or on which user-programmed applications can be developed and run) user programmable embedded view: a microprocessor is a basic digital system building block that can be used to build intelligent products non-user-programmable 6 Introduction Why this distinction is important: different architectural/organizational characteristics of microprocessors can make them more/less suited for a given application the "goodness" or "badness" of a particular microprocessor can only be evaluated in the context of the intended application 7 Characteristics That Distinguish Ps General-purpose applications generally require processors that have the following characteristics: support time-sharing operating systems support virtual memory, with multi-level cache and dynamic RAM support for DMA-driven I/O large register sets integrated floating point hardware primary view of interrupts is that they are "irritations" (called "exceptions") 8 Characteristics That Distinguish Ps Embedded applications generally require processors that have the following characteristics: flexible interrupt structure interrupts are a "way of life" in event-driven systems fast context switch (generally implies need for small register set) mixture of digital and analog I/O (to facilitate a variety of interfaces with external devices) amenability of assembly-level patching for time-critical code segments 9 Taxonomy of Microprocessors Common acronyms CISC: complex instruction set computer RISC: reduced instruction set computer -or- reduced instruction set cycles DSP: digital signal processor Bit-width (ALU size) of current devices ranges from 4 to 64 10 Taxonomy of Microprocessors P 11 Taxonomy of Microprocessors P General Purpose 12 Taxonomy of Microprocessors P General Purpose CISC 32 64 13 Taxonomy of Microprocessors P General Purpose CISC RISC 32 64 32 64 14 Taxonomy of Microprocessors P General Purpose CISC RISC Embedded Control 32 64 32 64 15 Taxonomy of Microprocessors P General Purpose CISC RISC 4 32 64 32 64 CISC 8 16 32 Embedded Control 16 Taxonomy of Microprocessors P General Purpose CISC RISC 4 32 64 32 64 CISC 8 16 32 8 Embedded Control RISC 16 32 64 17 Taxonomy of Microprocessors P General Purpose CISC RISC 4 32 64 32 64 CISC 8 16 32 DSP 8 Embedded Control RISC 16 32 64 18 Taxonomy of Microprocessors P General Purpose CISC RISC 4 32 64 32 64 CISC 8 16 32 DSP Integer 16 24 F.P. 32 19 Embedded Control RISC 8 16 32 64 Choosing an Education-Appropriate P Goals: introduce basic concepts of computer architecture and machine instruction sets provide hands-on experience with a "real" device expose students to the "embedded world" Many devices currently available can be used to achieve these goals We will use the Freescale 68HC(S)12 as our "architecture of choice" and focus on one variant, the 9S12C32 20 Freescale 9S12C32 Development Kit Boot/Run Switch BDM connector Switch / LED input/output COM port 9S12C32 D.C. power Microcontroller Module Docking Board 21 Overview of 9S12C32 22 Overview of 9S12C32 Several things to note..... The HCS12 CPU has the same architecture and programming model as the HC12 23 Overview of 9S12C32 Several things to note..... The 9S12C32 module has 2K of SRAM and 32K of Flash (no EEROM) 24 Overview of 9S12C32 Several things to note..... The 48-pin version of the chip on this module does not have Ports A & B padded out 25 Overview of 9S12C32 Several things to note..... External interrupt pins are on Port E 26 Overview of 9S12C32 Several things to note..... Real-time interrupt (RTI) module 27 Overview of 9S12C32 Several things to note..... Analog-to-digital (ATD) converter module inputs are on Port PAD 28 Overview of 9S12C32 Several things to note..... Timer (TIM) module I/O on Port T 29 Overview of 9S12C32 Several things to note..... Pulse width modulator (PWM) here, I/O shared with TIM module on Port T MODRR register setting determines whether these Port T pins are mapped to the TIM or PWM 30 Overview of 9S12C32 Several things to note..... Asynchronous serial communications interface (SCI) on Port S 31 Overview of 9S12C32 Several things to note..... Controller area network (MSCAN) on Port M 32 Overview of 9S12C32 Several things to note..... Synchronous peripheral interface (SPI) on Port M 33 Memory Usages SRAM Variables Stack Buffers Test code Flash "Turn-key" application code Fixed message strings Static data Vectors (resets and interrupts) 34 9S12C32 Memory Map test code, data, variables, stack 2K SRAM (mappable) Default (reset) location is 800-FFF firmware (application code) 30K Flash 8000-F7FF 2K Resident Debugger F800-FFFF interrupt vectors 35 Overview of 68HC(S)12 Architecture 36 Freescale 68HC(S)12 Programming Model D 7 15 15 15 15 A 0 7 B 0 0 Accumulators X Y SP PC Index Registers 0 0 0 Stack Pointer Program Counter 37 Register Usage and Functions Accumulators "A" and "B" (8-bit) arithmetic calculations logical manipulation of data can be concatenated together to form a 16-bit accumulator (referred to as "D") Program Counter "PC" (16-bit) points to next instruction to be executed Stack Pointer "SP" (16-bit) points to top stack item used for subroutine linkage, interrupts also have PSH/PUL instructions 38 Register Usage and Functions Index Registers "X" and "Y" (16-bit) used as pointers to operands (typically within some type of data structure or string) may be modified by addition of a constant or a register (accumulator) offset auto increment/decrement supported 39 Condition Code Register 7 6 5 4 3 2 1 0 S X H I N Z V C Condition Code Register (CCR) Carry/Borrow Flag Overflow Flag Zero Flag Negative Flag IRQ Mask Half-Carry XIRQ Mask Stop Disable 40 ALU Condition Codes "C" "carry/borrow" flag (carry out of the sign position for addition, complement of carry out of sign position for subtraction subtraction) "V" "overflow" flag (set if two's complement overflow has occurred) "Z" "zero" flag (set if result of computation is zero) "N" "negative" flag (most significant bit (sign) of computation) "H" "half carry" flag (carry out of the lower 4-bits (nibble), only valid after ADD) 41 Machine Control Condition Codes " I " "IRQ interrupt mask" "0" IRQ is not masked (enabled) "1" IRQ is masked (disabled) "X" "XIRQ interrupt mask" "0" XIRQ is not masked (enabled) "1" XIRQ is masked (disabled) "S" "STOP instruction disable" "0" STOP instruction is enabled "1" STOP instruction is disabled 42 Instruction Formats and Data Types Instruction length varies from one to six bytes Opcodes may be one or two bytes A "postbyte" may follow an opcode to provide additional information about the type of addressing mode used An offset (one or two bytes) may follow a postbyte Data types supported include: bit, byte (8bit), word (16-bit), double word (32-bit), packed BCD, and unsigned fractions 43 Addressing Modes Definition: The CPU uses an addressing mode to determine the effective address of where an operand is stored in memory Commonly used addressing modes "immediate" (data immediately follows opcode, i.e., is part of the instruction) "extended / absolute" (absolute address of where operand is stored in memory) "relative" (desired location is calculated relative to the current value in the PC) "indexed" (an index register is used to point to the operand many variations with offset) "indirect" (the operand pointer is in memory) 44 Illustrative Instructions LDAA addr "load accumulator A with the contents of memory location addr" "store the contents of accumulator A at memory location addr" STAA addr addr represents the effective address 45 Illustrative Instructions ADDA addr "add the contents of memory location addr to accumulator A" "subtract the contents of memory location addr from accumulator A" SUBA addr A In each case, the result is stored in ____ 46 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-B Microcontroller Instruction Set Overview 47 Reading Assignment: Meyer Chp 3, pp. 30-82 Instructional Objectives: To learn about the 68HC(S)12 instructions that comprise the various groups To discover the "tools in the toolbox" Outline: Introduction Notation Addressing Modes Instruction Groups Who are these people? (And, what are they doing??) 48 Introduction The instruction set of any computer can best be understood by dividing into groups of related instructions: data transfer arithmetic logical transfer of control (branch/jump) machine control "special" 49 Notation - 1 Notation prefix of $ or suffix of h or H prefix of ! or suffix of t or T prefix of % or suffix of b or B ( ) ; : addr rb rw, rwh, rwl How Used denotes a hexadecimal (base 16) number denotes a decimal (base 10) number denotes a binary (base 2) number denotes the contents of a register or memory location denotes the beginning of a comment indicates the concatenation of two quantities shorthand for the effective address in memory at which an operand is stored shorthand for a byte-length register, e.g., A or B shorthand for a word-length register, e.g., X, Y, D, SP, where rwh denotes the high byte of that register and rwl the low byte Examples $1234 = 1234h = 1234H = 123416 !1234 = 1234t = 1234T = 123410 %10101010 = 10101010b = 10101010B = 101010102 (A) (0800h) LDAA 0800h ; (A) = (0800h) 16-bit result in (A):(B) (D) 32-bit result in (D):(X) LDAA addr ; (A) = (addr) STArb 0800h ; (0800h) = (rb) LDrw 0800h ; (rw) = (0800h):(0801h) ; -or; (rwh) = (0800h) ; (rwl) = (0801h) 50 Notation - 2 Notation # How Used indicates use of immediate addressing mode when used before a constant that appears in an instructions operand field indicates use of indexed addressing mode when placed between two entities in the operand field indicates use of indirect addressing mode when used to bracket the operand field denotes an assignment or "copy" (the arrow points toward the destination) denotes the exchange (or "swap") of contents shorthand for number of instruction execution cycles indicates a (bit-wise) complement LDAA LDAA LDAA LDAA Examples #80h ; (A) = 80h #$12 ; (A) = 12h #$A5 ; (A) = A5h #10101010b ; (A) = AAh , LDAA 2,X ; (A) = ((X) + 2) STAA D,Y ; ((D)+(Y)) = (A) STAA [2,X] ; (((X)+2):((X)+3)) = (A) LDAA [D,Y] ; (A) = (((D)+(Y)):((D)+(Y)+1)) (A) (B) means load the A register with the contents of the B register (the contents of B remains the same) (D) (X) means exchange the contents of the D and X registers assuming an 8 MHz bus clock, each cycle is 125 ns (nanoseconds) mask means the bit-wise complement of mask 51 [ ] ~ Addressing Mode Summary - 1 Icon Abbrev. INH Name Inherent/Register Description Operand(s) is (are) contained in registers; "inherent" means name of register part of instruction mnemonic Operand data "immediately follows" opcode; pound sign (#) denotes use of immediate data Effective address of operand ("absolute" location in memory) follows opcode; called "direct" if the address can be contained in a single byte, or "extended" if two bytes are required Examples DAA # IMM Immediate LDAA LDAA #$FF #1 DIR/EXT Direct/Extended LDAA STAA $FF 900h ;direct ;extended 52 Addressing Mode Summary - 2 Icon Abbrev. . IDX IDX1 IDX2 Name Indexed with Constant Offset Description Effective address is determined by adding a (signed) constant offset (5bit, 8-bit, or 16-bit) to an index register (which may be X, Y, SP, or PC) Effective address is determined by adding an (unsigned) accumulator (A, B, or D) to an index register (X, Y, SP, or PC) Effective address is determined by an index register (X, Y, or SP) that can be modified prior to its use (pre-inc/dec) or following its use (postinc/dec); the amount of pre/post modification possible ranges from 1 to 8 Examples LDAA STAA LDAA STAA 0,X 1,Y 5,SP 2,PC IDX Indexed with Accumulator Offset LDAA STAA LDAA B,X B,Y D,X IDX Indexed with Auto Pre-/PostIncrement or Decrement STAA LDAA STAA LDAA 1,-X 1,X+ 8,+X 8,X- ;pre-dec ;post-inc ;pre-inc ;post-dec 53 Addressing Mode Summary - 3 Icon [.] Abbrev. [IDX2] Name Indexed-Indirect with Constant Offset Description Indexed with constant offset addressing mode is used to access a 16-bit pointer in memory, which is then used as the effective address of the operand; brackets denote use of indirection Indexed with accumulator (D) offset mode is used to access a 16-bit pointer in memory, which is then used as the effective address of the operand; brackets denote use of indirection Examples LDAA STAA [4,X] [2,Y] [D,IDX] Indexed-Indirect with Accumulator Offset LDAA STAA [D,Y] [D,X] 54 Clicker Quiz 55 1. When an 8-bit accumulator offset indexed addressing mode is used: A. the 8-bit accumulator offset is zero-extended to 16-bits before being added to the named index register B. the 8-bit accumulator offset is sign-extended to 16-bits before being added to the named index register C. the 16-bit index register is truncated to 8-bits before being added to the 8-bit accumulator offset D. the 8-bit accumulator offset is shifted left eight positions before being added to the index register E. none of the above 56 2. The name of the addressing mode used by the instruction STAA [2,X+] is: A. indexed with auto-post-increment by two B. indexed with auto-pre-increment by two C. indirect indexed with auto-pre-increment by two D. indirect indexed with auto-post-increment by two E. none of the above 57 Data Transfer Group The "theme" that links members of this group together is transfer of data load store exchange move (transfer) stack manipulation 58 Load and Store Registers Description Load Register Mnemonic LDArb addr rb = A, B addr = # . [.] Operation (rb) (addr) CC N Z V0 Examples LDAA LDAA LDAB LDAA LDAA LDAB LDAA LDAA LDD LDS LDX LDY LDX STAA STAB STAA STAA STAB STAA STAA STD STX STY STX STS #1 $FF 900h 1,X B,Y 2,Y+ [0,Y] [D,X] #1 #$A00 900h A,X [D,Y] $FF 900h 1,X B,Y 2,Y+ [0,Y] [D,X] 900h 2,Y A,X [2,Y] [D,Y] Mode # . . . [.] [.] # # . [.] . . . [.] [.] . . [.] [.] ~ 1 3 3 3 3 3 6 6 2 2 3 3 6 2 3 2 2 2 5 5 3 2 2 5 5 LDrw addr rw = D, X, Y, S addr = # . [.] Store Register STArb addr rb = A, B addr = . [.] (rw) (addr) N Z V0 N Z V0 (addr) (rb) STrw addr rw = D, X, Y, S addr = . [.] (addr) (rw) N Z V0 59 Short Cut for Conversion Among Powers of 2 Method: Size Log2R Groupings when converting a number from base "A" to base "B", where A and B are powers of 2 (e.g., 2, 4, 8, and 16), a "short cut" can be used an n-digit binary number can be written for each base A digit in the original number, where n = log2A starting at the least significant position, the converted binary digits can be regrouped into m-digit binary numbers, where m = log2B 60 Short Cut for Conversion Among Powers of 2 Exercise: Convert (110101)2 to base 16 (hex) Exercise: Convert (A3F)16 to base 2 (binary) 61 Short Cut for Conversion Among Powers of 2 Exercise: Convert (110101)2 to base 16 (hex) 0011 0101 (3 5)16 Exercise: Convert (A3F)16 to base 2 (binary) 62 Short Cut for Conversion Among Powers of 2 Exercise: Convert (110101)2 to base 16 (hex) 0011 0101 (3 5)16 Exercise: Convert (A3F)16 to base 2 (binary) (1010 0011 1111)2 63 Load Effective Address Description Mnemonic Load LEArw addr Effective rw = X, Y, S Address addr = . Operation (rw) addr CC Examples LEAX LEAY LEAX LEAS LEAY LEAS LEAX 2,Y B,X D,SP 1,X+ 2,-X 200t,SP 1000t,SP Mode . . . . . . . ~ 2 2 2 2 2 2 2 The LEA instruction provides a convenient means for incrementing or decrementing an index register an arbitrary amount (as such, it could also be construed as an "arithmetic group" instruction) 64 Exchange Description Exchange Register Contents Mnemonic EXG rb1,rb2 rb = A, B, CCR EXG rw1,rw2 rw = D, X, Y, S EXG rb,rw rb = A, B, CCR rw = D, X, Y, S EXG rw,rb rw = D, X, Y, S rb = A, B, CCR Operation (rb1) (rb2) (rw1) (rw2) $00 (rwh) (rb) (rwl) (rwh) $00 (rwl) (rb) CC EXG EXG EXG EXG EXG EXG EXG EXG EXG EXG "rwh" is the high byte of a wordlength register Examples A,B A,CCR D,X X,Y A,X B,Y CCR,D X,A Y,B D,CCR Mode ~ 1 1 1 1 1 1 1 1 1 1 "rwl" is the low byte of a wordlength register Mismatched exchanges (byte word) are "legal" but not very useful 65 Transfer (Move) Register Description Mnemonic Transfer TFR rb1,rb2 (Move) rb = A, B, CCR Register TFR rw1,rw2 rw = D, X, Y, S TFR rw,rb rw = D, X, Y, S rb = A, B, CCR TFR rb,rw rb = A, B, CCR rw = D, X, Y, S Operation (rb1) (rb2) (rw1) (rw2) (rwl) (rb) (rb) (rw) rwh padded with sign of rb CC "rwl" is the low byte of a wordlength register Examples TFR TFR TFR TFR TFR TFR TFR TFR TFR TFR A,B A,CCR X,D D,Y X,A Y,B X,CCR A,X B,Y CCR,D Mode ~ 1 1 1 1 1 1 1 1 1 1 The (mismatched) byte word TFR instruction performs a sign extension 66 Move Memory Description Mnemonic MOVB addr1,addr2 Move Memory addr1 = # . addr2 = . Operation (addr1) (addr2) CC Examples MOVB MOVB MOVB MOVB MOVB MOVB MOVW MOVW MOVW MOVW MOVW MOVW #$FF,$900 #2,0,X $900,$901 $900,1,X 1,X-,$900 1,X+,2,Y+ #$FFFF,$900 #1,0,X $900,$902 $900,2,X 2,X-,$900 2,X+,4,Y+ Mode # #. . . .. # #. . . .. ~ 4 4 6 5 5 5 5 4 6 5 5 5 MOVW addr1,addr2 addr1 = # . addr2 = . (addr1) (addr2) (addr1+1) (addr2+1) Note the six addressing mode permutations (source destination) possible 67 Stack Manipulation Description Push register onto stack Mnemonic PSHrb rb = A, B, C Operation (SP) (SP) 1 ((SP)) (rb) (SP) (SP) 1 ((SP)) (rwl) (SP) (SP) 1 ((SP)) (rwh) (rb) ((SP)) (SP) (SP) + 1 (rwh) ((SP)) (SP) (SP) + 1 (rwl) ((SP)) (SP) (SP) + 1 CC Examples PSHA PSHB PSHC Mode ~ 2 2 2 2 2 2 3 3 3 3 3 3 PSHrw rw = D, X, Y PSHD PSHX PSHY Pull (pop) register from stack PULrb rb = A, B, C * PULA PULB PULC PULrw rw = D, X, Y PULD PULX PULY * PULC affects all the condition code bits, with the exception of X, which cannot be set by a software instruction once it is cleared. 68 Clicker Quiz 69 1. The name of the addressing mode used by the instruction EXG A,B is: A. immediate B. inherent C. direct D. extended E. none of the above 70 2. If a 16-bit item is pushed onto the HC(S)12 stack, the SP register points to: A. the low byte of the top stack item B. the high byte of the top stack item C. the next available stack location D. the next instruction to execute E. none of the above 71 3. If (D)=$AABB, the result in (D) after executing the instruction TFR D,A will be: A. $AAAA B. $BBBB C. $AABB D. $FFAA E. none of the above 72 4. If (D)=$AABB, the result in (D) after executing the instruction TFR A,D will be: A. $AAAA B. $BBBB C. $AABB D. $FFAA E. none of the above 73 5. If N = +16t, the instruction LDAA N,Y will occupy the following number of bytes: A. 1 B. 2 C. 3 D. 4 E. none of the above 74 6. If N = -16t, the instruction LDAA N,Y will occupy the following number of bytes: A. 1 B. 2 C. 3 D. 4 E. none of the above 75 7. Given that at least four bytes have been pushed onto the HC(S)12 stack, execution of the instruction LEAS 4,SP causes: A. four additional bytes to be allocated on the stack B. the top four bytes of the stack to be de-allocated C. the bottom four bytes of the stack to be de-allocated D. the stack origin to be moved four locations E. none of the above 76 8. If (X)=$8000, execution of the instruction LEAX 1,X+ causes X to be loaded with the value: A. $7FFF B. $8000 C. $8001 D. $8002 E. none of the above 77 9. Execution of the instruction LEAY 1,X+ causes: A. nothing to happen B. (X) (X)+1 C. (Y) (X)+1 D. both B and C E. none of the above 78 10. Execution of the instruction LEAY 1,+X causes: A. nothing to happen B. (X) (X)+1 C. (Y) (X)+1 D. both B and C E. none of the above 79 Arithmetic Group The "theme" that links members of this group together is arithmetic add subtract complement compare/test increment/decrement multiply divide min/max 80 Add/Subtract Description Add contents of memory location to register Mnemonic ADDrb addr rb = A, B addr = # . [.] ADCrb addr rb = A, B addr = # . [.] ADDD addr addr = # . [.] Subtract contents of memory location from register SUBrb addr rb = A, B addr = # . [.] SBCrb addr rb = A, B addr = # . [.] SUBD addr addr = # . [.] (D) (D) (addr):(addr+1) (rb) (rb) (addr) (C) (rb) (rb) (addr) (D) (D) + (addr):(addr+1) (rb) (rb) + (addr) + (C) Operation (rb) (rb) + (addr) CC N Z V C H N Z V C H N Z V C N Z V C N Z V C N Z V C Examples ADDA ADDB ADDA ADDB ADDA ADCA ADCB ADCA ADCB ADCA ADDD ADDD ADDD ADDD SUBA SUBB SUBA SUBB SUBA SBCA SBCB SBCA SBCB SBCA SUBD SUBD SUBD SUBD #1 $900 1,X A,X [2,Y] #1 $900 1,X A,X [2,Y] #1 $900 1,X [2,Y] #1 $900 1,X A,X [2,Y] #1 $900 1,X A,X [2,Y] #1 $900 1,X [2,Y] Mode # . . [.] # . . [.] # . [.] # . . [.] # . . [.] # . [.] ~ 1 3 3 3 6 1 3 3 3 6 2 3 3 6 1 3 3 3 6 1 3 3 3 6 2 3 3 6 81 Overflow Detection Summarization: Overflow occurs if two positive numbers are added and a negative result is obtained, or if two negative numbers are added and a positive result is obtained (or, if numbers of like sign are added and a result with the opposite sign is obtained) Overflow cannot occur when adding numbers of opposite sign Another way to detect overflow: If the carry in to the sign position is different than the carry out of the sign position, then overflow has occurred 82 Other Conditions of Interest In addition to overflow, other conditions of interest following an arithmetic operation include the following: ZERO the result of the computation was 00...0 NEGATIVE the result of the computation was a negative number CARRY/BORROW the computation produced a carry out of the sign position after an addition, or produced a borrow out of the sign position after a subtraction (the complement of the carry out) These conditions are sometimes referred to as "condition codes" or "flags" 83 Register-to-Register Add Description Add registers Mnemonic ABA Operation (A) (A) + (B) CC N Z V C H Examples ABA Mode ~ 2 ABrw rw = X, Y (rw) $00:(B) + (rw) ABX ABY 2 2 ABX and ABY are "legacy" instructions that are translated (by the assembler program) into LEAX B,X and LEAY B,Y (respectively) 84 Decimal Adjust Description Decimal Adjust A Mnemonic DAA Operation decimal adjust the result of ADD, ADC, or ABA CC N Z V? C Examples DAA Mode ~ 3 Decimal adjust only works correctly after byte adds it does NOT perform a conversion, but rather a correction ("adjust") 85 ADD of BCD Operands Followed by DAA 47 +68 --0100 0111 +0110 1000 ----------- ----------DAA ----------86 ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------- ----------DAA ----------87 ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------1010 1111 ----------DAA ----------88 result of ADD ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------1010 1111 +0110 ----------- result of ADD since L.N. > 9, add 6 to adjust DAA ----------89 ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------1010 1111 +0110 ----------1011 0101 ----------90 result of ADD since L.N. > 9, add 6 to adjust DAA ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------1010 1111 +0110 ----------1011 0101 +0110 ----------- result of ADD since L.N. > 9, add 6 to adjust DAA since U.N. > 9, add 6 to adjust 91 ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------1010 1111 +0110 ----------1011 0101 +0110 ----------1 0001 0101 result of ADD since L.N. > 9, add 6 to adjust DAA since U.N. > 9, add 6 to adjust CF is hundred's position 92 ADD of BCD Operands Followed by DAA 47 +68 --115 0100 0111 +0110 1000 ----------1010 1111 +0110 ----------1011 0101 +0110 ----------1 0001 0101 ten's one's result of ADD since L.N. > 9, add 6 to adjust DAA since U.N. > 9, add 6 to adjust CF is hundred's position 93 Complement Description Ones' complement Mnemonic COMrb rb = A, B COM addr addr = . [.] Two's complement NEGrb rb = A, B NEG addr addr = . [.] (rb) $00 (rb) Operation (rb) $FF (rb) CC N Z V0 C1 N Z V0 C1 N Z V C N Z V C Examples COMA Mode ~ 1 (addr) $FF (addr) COM COM COM COM NEGB $900 1,X B,X [D,Y] . . [.] 4 3 3 6 1 (addr) $00 (addr) NEG NEG NEG NEG $900 1,X B,X [D,Y] . . [.] 4 3 3 6 Since COM performs a "bit-wise" complement, it can also be viewed as a member of the "logical group" 94 Compare/Test Description Compare Accumulators Compare Register with Memory Mnemonic CBA Operation set CCR based on (A) (B) CC N Z V C N Z V C N Z V C N Z V0 C0 N Z V0 C0 Examples CBA Mode ~ 2 CMPrb addr rb = A, B addr = # . [.] CPrw addr rw = D, X, Y, S addr = # . [.] TSTrb rb = A, B set CCR based on (rb) (addr) set CCR based on (rw) (addr):(addr+1) Test for Zero set CCR based on (rb) $00 CMPA CMPB CMPA CMPB CPD CPX CPY CPS TSTA TSTB #2 $900 2,X [2,Y] #2 $900 2,X [2,Y] # . [.] # . [.] 1 3 3 6 2 3 3 6 1 1 TST addr addr = . [.] set CCR based on (addr) $00 TST TST TST $900 1,X [2,Y] # . [.] 3 3 6 Note that CMP sets the condition code bits based on subtracting the operand from the named register 95 Increment/Decrement Description Increment Mnemonic INCr r = A, B INrw rw = X, Y, S INC addr addr = . [.] Decrement DECr r = A, B DErw rw = X, Y, S DEC addr addr = . [.] (r) (r) 1 Operation (r) (r) + 1 CC N Z V Z N Z V N Z V Z N Z V Examples INCA Mode ~ 1 (rw) (rw) + 1 (addr) (addr) + 1 INX INY INS INC INC INC INC DECB 1 1 4 3 3 6 1 $900 1,X B,X [D,Y] . . [.] (rw) (rw) 1 (addr) (addr) 1 DEX DEY DES DEC DEC DEC DEC 1 1 4 3 3 6 $900 1,X B,X [D,Y] . . [.] ADDA #1 INCA (INC and DEC do not affect the "C" condition code bit "on purpose" - Why?) 96 Multiply Description 8x8 unsigned integer multiply 16x16 unsigned integer multiply 16x16 signed integer multiply Mnemonic MUL EMUL EMULS Operation (D) (A) x (B) (Y):(D) (D) x (Y) (Y):(D) (D) x (Y) CC C N Z C N Z C Examples MUL EMUL Mode ~ 3 3 EMULS 3 Description 16x16 integer multiply and accumulate Mnemonic EMACS addr addr = special Operation (addr):(addr+1):(addr+2):(addr+3) (addr):(addr+1):(addr+2):(addr+3) + ( ((X)) x ((Y)) ) CC N V Z C Examples EMACS $900 ~ 13 The EMACS instruction can be used for performing signal processing algorithms (e.g., digital filtering) 97 Divide Description 1616 unsigned integer divide 1616 signed integer divide 3216 unsigned integer divide 3216 signed integer divide 3216 unsigned fraction divide Mnemonic IDIV IDIVS Operation (X) (D) (X) (D) remainder (X) (D) (X) (D) remainder (Y) (Y):(D) (X) (D) remainder (Y) (Y):(D) (X) (D) remainder (X) (D) (X) (D) remainder CC V0 Z C N V Z C N V Z C N V Z C V Z C Examples IDIV Mode ~ 12 IDIVS 12 EDIV EDIV 11 EDIVS EDIVS 12 FDIV FDIV 12 The FDIV instruction assumes the operands are unsigned binary fractions 0.2-1 2-2 2-3 2-4 ... binary point 98 Min/Max - 1 Description Unsigned 8-bit Minimum Mnemonic MINA addr addr = . [.] MINM addr addr = . [.] Unsigned 8-bit Maximum MAXA addr addr = . [.] MAXM addr addr = . [.] (addr) max {(A), (addr)} (A) max {(A), (addr)} (addr) min {(A), (addr)} Operation (A) min {(A), (addr)} CC N Z V C N Z V C N Z V C N Z V C Examples MINA MINA MINA MINA MINA MINM MINM MINM MINM MINM MAXA MAXA MAXA MAXA MAXA MAXM MAXM MAXM MAXM MAXM 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] Mode . . . [.] [.] . . . [.] [.] . . . [.] [.] . . . [.] [.] ~ 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 MIN/MAX instructions are not typically included in most microcontroller instruction sets, and therefore could also be included in the "special" group 99 Min/Max - 2 Description Unsigned 16-bit Minimum Mnemonic EMIND addr addr = . [.] EMINM addr addr = . [.] Unsigned 16-bit Maximum EMAXD addr addr = . [.] EMAXM addr addr = . [.] (addr):(addr+1) max {(D), (addr):(addr+1)} (D) max {(D), (addr):(addr+1)} (addr):(addr+1) min {(D), (addr):(addr+1)} Operation (D) min {(D), (addr):(addr+1)} CC N Z V C N Z V C N Z V C N Z V C Examples EMIND EMIND EMIND EMIND EMIND EMINM EMINM EMINM EMINM EMINM EMAXD EMAXD EMAXD EMAXD EMAXD EMAXM EMAXM EMAXM EMAXM EMAXM 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] Mode . . . [.] [.] . . . [.] [.] . . . [.] [.] . . . [.] [.] ~ 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 100 Clicker Quiz 101 1. The name of the addressing mode used by the instruction DAA is: A. immediate B. inherent C. direct D. extended E. none of the above 102 2. When multiplying unsigned words using the EMUL instruction, the carry flag (C): A. can be used to implement extended precision multiplication B. can be used to round the lower 16-bits of the result C. can be used to round the upper 16-bits of the result D. has no use or "social significance" E. none of the above 103 3. If (D)=$8000 and (X)=$FFFF, the value in (X) after executing IDIVS is: A. $0000 B. $7FFF C. $8000 D. $FFFF E. none of the above 104 4. If (D)=$8000 and (X)=$0000, the value in (X) after executing IDIVS is: A. $0000 B. $7FFF C. $8000 D. $FFFF E. none of the above 105 5. If (D)=$8000 and (X)=$0000, the condition code bit that is set (to indicate a "divide by zero" has been attempted) after executing IDIVS is: A. C (carry/borrow) B. N (negative) C. V (overflow) D. Z (zero) E. none of the above 106 6. The only overflow case (causing V to be set) that can occur when executing IDIVS is: A. (D) = $7FFF, (X) = $8000 B. (D) = $8000, (X) = $7FFF C. (D) = $7FFF, (X) = $FFFF D. (D) = $8000, (X) = $FFFF E. none of the above 107 7. The result produced by FDIV when dividing $2000 by $8000 is: A. $0000 B. $4000 C. $8000 D. $FFFF E. none of the above 108 Logical Group The "theme" that links members of this group together is logical manipulation and testing of data boolean clear/set/complement bit test shift and rotate 109 Boolean Operations (AND, OR, XOR) Description Mnemonic AND ANDrb addr rb = A, B addr = # . [.] Operation (rb) (rb) (addr) CC N Z V0 Examples ANDA ANDA ANDB ANDA ANDA ANDB ANDA ANDA ANDCC #1 $FF 900h 1,X B,Y 2,Y+ [0,Y] [D,X] #$FE Mode # . . . [.] [.] # ~ 1 3 3 3 3 3 6 6 1 ANDCC ANDCC addr addr = # ORrb addr rb = A, B addr = # . [.] (CCR) (CCR) data all N Z V0 OR (rb) (rb) (addr) ANDCC can be used to clear CCR bits ORCC ORCC addr addr = # EORrb addr rb = A, B addr = # . [.] (CCR) (CCR) data all N Z V0 ORA ORA ORB ORA ORA ORB ORA ORA ORCC #1 $FF 900h 1,X B,Y 2,Y+ [0,Y] [D,X] #1 # . . . [.] [.] # 1 3 3 3 3 3 6 6 1 XOR (rb) (rb) (addr) EORA EORA EORB EORA EORA EORB EORA EORA #1 $FF 900h 1,X B,Y 2,Y+ [0,Y] [D,X] # . . . [.] [.] ORCC can be used to set CCR bits 1 3 3 3 3 3 6 6 110 Condition Code Set/Clear Description Clear C bit of CCR Set C bit of CCR Clear V bit of CCR Set V bit of CCR Clear I bit of CCR Set I bit of CCR Mnemonic CLC SEC CLV SEV CLI SEI Operation (C) 0 (C) 1 (V) 0 (V) 1 (I) 0 (I) 1 CC (C) 0 (C) 1 (V) 0 (V) 1 (I) 0 (I) 1 Examples CLC SEC CLV SEV CLI SEI Mode ~ 1 1 1 1 1 1 These are all "legacy" instructions ANDCC and ORCC provide a more general way of setting/clearing individual condition code bits (or groups of bits) 111 Byte Clear and Complement Description Clear Mnemonic CLRrb rb = A, B CLR addr addr = . [.] Complement COMrb rb = A, B COM addr addr = . [.] (rb) $FF (rb) Operation (rb) $00 CC N0 Z1 V0 C0 N0 Z1 V0 C0 N Z V0 C1 N Z V0 C1 Examples CLRA Mode ~ 1 (addr) $00 CLR CLR CLR CLR COMA $900 1,X B,X [D,Y] . . [.] 3 2 2 5 1 (addr) $FF (addr) COM COM COM COM $900 1,X B,X [D,Y] . . [.] 4 3 3 6 Recall that COM was also considered a member of the arithmetic group 112 Bit Clear/Set and Test Description Bit clear Mnemonic BCLR addr,mask addr = . Bit set BSET addr,mask addr = . (addr) (addr) mask8 Operation (addr) (addr) mask8 CC N Z V0 Examples BCLR BCLR BCLR BCLR BCLR BSET BSET BSET BSET BSET $50,$FE $900,$FE 1,X,$01 2,X+,$F0 1000t,Y,$02 $50,$FE $900,$FE 1,X,$01 2,X+,$F0 1000t,Y,$02 Mode . . . . . . ~ 4 4 4 4 6 4 4 4 4 6 N Z V0 113 Bit Clear/Set and Test Description Bit clear Mnemonic BCLR addr,mask addr = . Bit set BSET addr,mask addr = . (addr) (addr) mask8 Operation (addr) (addr) mask8 CC N Z V0 Examples BCLR BCLR BCLR BCLR BCLR BSET BSET BSET BSET BSET $50,$FE $900,$FE 1,X,$01 2,X+,$F0 1000t,Y,$02 $50,$FE $900,$FE 1,X,$01 2,X+,$F0 1000t,Y,$02 Mode . . . . . . ~ 4 4 4 4 6 4 4 4 4 6 N Z V0 Description Bit test Mnemonic BITrb addr rb = A, B addr = # . [.] Operation set CCR based on (rb) (addr) CC N Z V0 Examples BITA BITA BITB BITA BITA BITB BITA BITA #1 $FF 900h 1,X B,Y 2,Y+ [0,Y] [D,X] Mode # . . . [.] [.] ~ 1 3 3 3 3 3 6 6 These instructions will prove to be very useful for setting/clearing and testing bits of control/status registers 114 Rotate Description Rotate left through carry Mnemonic ROLrb rb = A, B ROL addr C Operation C CC N Z V C N Z V C N Z V C N Z V C Examples ROLA Mode ~ 1 r7 ... r0 m7 ... m 0 addr = . [.] Rotate right through carry RORrb rb = A, B ROR addr C C ROL ROL ROL ROL RORA $900 1,X B,X [D,Y] . . [.] 4 3 3 6 1 r7 ... r0 m7 ... m 0 addr = . [.] ROR ROR ROR ROR $900 1,X B,X [D,Y] . . [.] 4 3 3 6 Note that these are 9-bit rotate operations, where the "C" bit is appended as the most significant position 115 Arithmetic Shift Description Arithmetic shift left Mnemonic ASLrb rb = A, B ASLrw rw = D ASL addr addr = . [.] Arithmetic shift right ASRrb rb = A, B ASR addr addr = . [.] m7 ... m 0 C Operation C C CC 0 0 Examples ASLA ASLD ASL ASL ASL ASL ASRA $900 1,X B,X [D,Y] Mode ~ 1 1 r7 ... r0 a7 ... a0 b7 ... b0 N Z V C N Z V C N Z V C N Z V C C m7 ... m0 0 . . [.] 4 3 3 6 1 r7 ... r0 C ASR ASR ASR ASR $900 1,X B,X [D,Y] . . [.] 4 3 3 6 Arithmetic shifts are sign-preserving when shifting left, the sign is preserved in the "C" bit; when shifting right, the sign bit is replicated 116 Logical Shift Description Logical shift left Mnemonic LSLrb rb = A, B LSLrw rw = D LSL addr addr = . [.] Logical shift right LSRrb rb = A, B LSRrw rw = D LSR addr addr = . [.] 0 Operation C C CC 0 0 Examples LSLA LSLD LSL LSL LSL LSL LSRA LSRD LSR LSR LSR LSR $900 1,X B,X [D,Y] $900 1,X B,X [D,Y] Mode ~ 1 1 r7 ... r0 a7 ... a0 b7 ... b0 N Z V C N Z V C N Z V C N Z V C C m7 ... m0 0 . . [.] 0 r7 ... r0 a7 ... a0 b7 ... b0 C 4 3 3 6 1 1 C 0 m7 ... m0 C . . [.] 4 3 3 6 Logical shifts are "zero-fill" shifts note that ASL and LSL are equivalent (they generate the same opcode) Note the 16-bit variants of LSL/ASL and LSR 117 Transfer-of-Control Group The "theme" that links members of this group together is transfer-of-control from one location of a program to another unconditional jumps and branches subroutine linkage conditional branches compound test and branch 118 Unconditional Jump Description Jump Mnemonic JMP addr addr = . [.] Operation (PC) addr CC Examples JMP JMP JMP JMP JMP JMP $900 0,X 100t,Y 1000t,S [D,Y] [1000t,S] Mode . . . [.] [.] ~ 3 3 3 4 6 6 Indexed jumps can be used to implement "computed go-to" transfers Indirect jumps can be used to implement "vector" tables 119 Unconditional Branch Description (Short) Branch Long Branch Mnemonic BRA rel8 LBRA rel16 Operation (PC) (PC) + rel8* (PC) (PC) + rel16* CC Examples BRA label Mode ~ 2 4 LBRA label *Calculation of the two's complement relative offset must take into account the byte-length of the branch instruction. The "short" branch (BRA) instruction occupies two bytes while the "long" branch (LBRA) instruction occupies four bytes. Because the program counter is automatically incremented as a by-product of the instruction fetch, the offset calculation must compensate for this. 0800 0800 [01] 20FE -2 0802 [04] 1820FFFC 0806 -4 Symbol Table LONG SHORT 0802 0800 1 2 3 4 5 6 7 8 9 org short long bra lbra end 800h short long 2-byte instruction 4-byte instruction 120 Subroutine Linkage Description Jump to Subroutine Mnemonic JSR addr addr = . [.] Operation (SP) (SP) 2 ((SP)) (PCh) ((SP)+1) (PCl) (PC) addr CC Examples JSR JSR JSR JSR JSR JSR JSR BSR $20 $900 0,X 100t,Y 1000t,S [D,Y] [1000t,S] label Mode . . . [.] [.] ~ 4 4 4 4 5 7 7 4 Branch to Subroutine BSR rel8* Return from Subroutine RTS (SP) (SP) 2 ((SP)) (PCh) ((SP)+1) (PCl) (PC) (PC) + rel8* (PCh) ((SP)) (PCl) ((SP)+1) (SP) (SP) + 2 RTS 4 *Calculation of the two's complement relative offset must take into account the byte-length of the BSR instruction, which is two bytes. The indirect version of JSR can be used to implement a subroutine jump table 121 Conditional Branches Simple Description Branch if carry clear C=0 Branch if carry set C=1 Branch if not equal Z=0 Branch if equal Z=1 Mnemonic BCC rel8 LBCC rel16 BCS rel8 LBCS rel16 BNE rel8 LBNE rel16 BEQ rel8 LBEQ rel16 Operation* (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 CC Examples BCC label LBCC label BCS label Mode ~** 3/1 4/3 3/1 4/3 3/1 4/3 3/1 4/3 LBCS label BNE label LBNE label BEQ label LBEQ label *Operation performed if branch is taken. If branch is not taken, the instruction effectively becomes a "no operation" (NOP). Calculation of the two's complement relative offset must take into account the byte-length of the branch instruction itself (2 for short, 4 for long). **The first number indicates the number of cycles consumed if the branch is taken; the second number indicates the number of cycles consumed if the branch is not taken. 122 Conditional Branches Simple Description Branch if positive N=0 Branch if negative N=1 Branch if overflow clear V=0 Branch if overflow set V=1 Branch never (No-op) Mnemonic BPL rel8 LBPL rel16 BMI rel8 LBMI rel16 BVC rel8 LBVC rel16 BVS rel8 LBVS rel16 BRN rel8 LBRN rel16 Operation* (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 CC Examples BPL label LBPL label BMI label Mode ~** 3/1 4/3 3/1 4/3 3/1 4/3 3/1 4/3 1 3 LBMI label BVC label LBVC label BVS label LBVS label BRN label LBRN label *Operation performed if branch is taken. If branch is not taken, the instruction effectively becomes a "no operation" (NOP). Calculation of the two's complement relative offset must take into account the byte-length of the branch instruction itself (2 for short, 4 for long). **The first number indicates the number of cycles consumed if the branch is taken; the second number indicates the number of cycles consumed if the branch is not taken. 123 Conditional Branches Signed Description Branch if greater than Z + (N V) = 0 Branch if less than or equal to Z + (N V) = 1 Branch if greater than or equal NV=0 Branch if less than NV=1 Mnemonic BGT rel8 LBGT rel16 BLE rel8 LBLE rel16 BGE rel8 LBGE rel16 BLT rel8 LBLT rel16 Operation* (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 CC Examples BGT label LBGT label BLT label Mode ~** 3/1 4/3 3/1 4/3 3/1 4/3 3/1 4/3 LBLT label BGE label LBGE label BLT label LBLT label *Operation performed if branch is taken. If branch is not taken, the instruction effectively becomes a "no operation" (NOP). Calculation of the two's complement relative offset must take into account the byte-length of the branch instruction itself (2 for short, 4 for long). **The first number indicates the number of cycles consumed if the branch is taken; the second number indicates the number of cycles consumed if the branch is not taken. 124 Derivation of Signed Conditionals R1 R0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 (R) M1 M0 (M) ? C Z N V 0 0 0 0 (R) = (M) 0 1 0 0 0 0 1 +1 (R) < (M) 1 0 1 0 0 1 0 -2 (R) > (M) 1 0 1 1 0 1 1 -1 (R) > (M) 1 0 0 0 +1 0 0 0 (R) > (M) 0 0 0 0 +1 0 1 +1 (R) = (M) 0 1 0 0 +1 1 0 -2 (R) > (M) 1 0 1 1 +1 1 1 -1 (R) > (M) 1 0 1 1 -2 0 0 0 (R) < (M) 0 0 1 0 -2 0 1 +1 (R) < (M) 0 0 0 1 -2 1 0 -2 (R) = (M) 0 1 0 0 -2 1 1 -1 (R) < (M) 1 0 1 0 -1 0 0 0 (R) < (M) 0 0 1 0 -1 0 1 +1 (R) < (M) 0 0 1 0 -1 1 0 -2 (R) > (M) 0 0 0 0 -1 1 1 -1 (R) = (M) 0 1 0 0 Z=1 (R) = (M) Z + (N V) = 0 (R) > (M) NV=1 (R) < (M) 125 Derivation of Signed Conditionals C 0 4 12 C 8 N 1 1 5 0 d 7 d 13 9 1 d 11 V BLE condition = Z + (N V) BGT condition = (Z + (N V)) 0 3 d 15 V d N 2 6 d d Z d 14 1 10 0 Z d 0 Z V 126 Derivation of Signed Conditionals C 0 4 12 C 8 0 N 1 5 0 d 7 d 13 9 0 d 11 V BLT condition = NV + NV =NV BGE condition = (N V) 1 3 d 15 V d N 2 6 d d Z d 14 0 10 1 Z d 1 Z V 127 Conditional Branches Unsigned Description Branch if higher than C+Z=0 Branch if lower than or same C+Z=1 Branch if higher than or same C=0 Branch if lower than C=1 Mnemonic BHI rel8 LBHI rel16 BLS rel8 LBLS rel16 BHS rel8 LBHS rel16 BLO rel8 LBLO rel16 Operation* (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 (PC) (PC) + rel8 (PC) (PC) + rel16 CC Examples BHI label LBHI label BLS label Mode ~** 3/1 4/3 3/1 4/3 3/1 4/3 3/1 4/3 LBLS label BHS label LBHS label BLO label LBLO label *Operation performed if branch is taken. If branch is not taken, the instruction effectively becomes a "no operation" (NOP). Calculation of the two's complement relative offset must take into account the byte-length of the branch instruction itself (2 for short, 4 for long). **The first number indicates the number of cycles consumed if the branch is taken; the second number indicates the number of cycles consumed if the branch is not taken. 128 Derivation of Unsigned Conditionals R1 R0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 (R) M1 M0 (M) ? C Z N 0 0 0 0 (R) = (M) 0 1 0 0 0 1 +1 (R) < (M) 1 0 1 0 1 0 +2 (R) < (M) 1 0 1 0 1 1 +3 (R) < (M) 1 0 0 +1 0 0 0 (R) > (M) 0 0 0 +1 0 1 +1 (R) = (M) 0 1 0 +1 1 0 +2 (R) < (M) 1 0 1 +1 1 1 +3 (R) < (M) 1 0 1 +2 0 0 0 (R) > (M) 0 0 1 +2 0 1 +1 (R) > (M) 0 0 0 +2 1 0 +2 (R) = (M) 0 1 0 +2 1 1 +3 (R) < (M) 1 0 1 +3 0 0 0 (R) > (M) 0 0 1 +3 0 1 +1 (R) > (M) 0 0 1 +3 1 0 +2 (R) > (M) 0 0 0 +3 1 1 +3 (R) = (M) 0 1 0 V 0 0 1 0 0 0 1 1 0 1 0 0 0 0 0 0 Z=1 (R) = (M) C+Z=0 (R) > (M) C=1 (R) < (M) 129 Derivation of Unsigned Conditionals C 0 4 12 C 8 1 N 1 5 0 d 7 d 13 9 0 d 11 V BLS condition =C+Z BHI condition = (C + Z) 1 3 d 15 V d N 2 6 d d Z d 14 0 10 1 Z d 0 Z V 130 Derivation of Unsigned Conditionals C 0 4 12 C 8 1 N 1 5 1 d 7 d 13 9 0 d 11 V 1 3 d 15 BLO condition =C BHS condition = C V d N 2 6 d d Z d 14 0 10 1 Z d 0 Z V 131 Signed vs. Unsigned Conditionals Example: Difference between BGT and BHI ; signed conditional LDAA CMPA BGT #$01 #$FF label ;interpret as +1 ;interpret as -1 ;branch taken ; unsigned conditional LDAA CMPA BHI #$01 #$FF label ;interpret as 1 ;interpret as 25510 ;branch not taken 132 Bit Test and Branch Description Mnemonic BRCLR addr,mask8,rel8 Branch if bits clear addr = . Operation IF (addr) mask8 = 0 THEN (PC) (PC) + rel8 IF (addr) mask8 = 0 THEN (PC) (PC) + rel8 CC Examples BRCLR $50,01,label BRCLR BRCLR BRCLR BRCLR BRCLR BRSET BRSET BRSET BRSET BRSET BRSET $900,01,label 0,X,$FF,label 10t,X,01,label 100t,Y,02,label 1000t,S,03,label $50,01,label $900,01,label 0,X,$FF,label 10t,X,01,label 100t,Y,02,label 1000t,S,03,label M . . . . . . . . ~ 4 5 4 4 6 8 4 5 4 4 6 8 Branch if bits set BRSET addr,mask8,rel8 addr = . These instructions are very useful for testing status registers (of on-chip peripheral devices) and branching based on the state of a single bit or a set of bits 133 Register Test and Branch Description Test Register and Branch if Zero Test Register and Branch if Not Zero Mnemonic TBEQ r,rel9 r = A,B,D,X,Y,S TBNE r,rel9 r = A,B,D,X,Y,S Operation IF (r) = 0 THEN (PC) (PC) + rel9 IF (r) 0 THEN (PC) (PC) + rel9 CC Examples TBEQ TBEQ A,label Y,label X,label Mode ~ 3 3 3 3 TBNE TBNE SP,label "Compound" test and branch instructions (such as these and the ones on the next slide) can greatly simplify management and control of loop structures Note that, for these instructions, the relative offset is extended to 9-bits 134 INC/DEC Register, Test and Branch Description INC Register and Branch if Zero INC Register and Branch if Not Zero DEC Register and Branch if Zero DEC Register and Branch if Not Zero Mnemonic IBEQ r,rel9 r = A,B,D,X,Y,SP IBNE r,rel9 r = A,B,D,X,Y,SP DBEQ r,rel9 r = A,B,D,X,Y,SP DBNE r,rel9 r = A,B,D,X,Y,SP Operation (r) (r) + 1 IF (r) = 0 THEN (PC) (PC) + rel9 (r) (r) + 1 IF (r) 0 THEN (PC) (PC) + rel9 (r) (r) 1 IF (r) = 0 THEN (PC) (PC) + rel9 (r) (r) 1 IF (r) 0 THEN (PC) (PC) + rel9 CC Examples IBEQ A,label IBEQ Y,label X,label Mode ~ 3 3 3 3 3 3 3 3 IBNE IBNE SP,label DBEQ DBEQ A,label Y,label X,label DBNE DBNE SP,label Note that, for these instructions, the relative offset is extended to 9-bits 135 Clicker Quiz 136 iloop org jmp lbra $8000 iloop iloop 1. The address to which the JMP instruction transfers control is: A. $8000 B. $8001 C. $8002 D. $8003 E. none of the above 137 iloop org lbra jmp $8000 iloop iloop 2. The offset assembled for the LBRA instruction is: A. $0000 B. $0001 C. $0002 D. $0003 E. none of the above 138 Machine Control Group The "theme" that links members of this group together is machine control in response to interrupts and exceptions Definition: An interrupt is an unexpected (asynchronous), hardware-induced subroutine call Example: A sensor firing or a button being pressed could be used to generate an interrupt Definition: An exception is an unexpected run-time anomaly Example: Fetching an unimplemented instruction opcode would cause an exception ("trap") 139 Machine Control - 1 Description Return from Interrupt Mnemonic Operation RTI (CCR) ((SP)), (SP) (SP) + 1, (D) ((SP)), (SP) (SP) + 2, (X) ((SP)), (SP) (SP) + 2, (Y) ((SP)), (SP) (SP) + 2, (PC) ((SP)), (SP) (SP) + 2 (SP) (SP) 2, ((SP)) (PC), (SP) (SP) 2, ((SP)) (Y), (SP) (SP) 2, ((SP)) (X), (SP) (SP) 2, ((SP)) (D), (SP) (SP) 1, ((SP)) (CCR), I bit of CCR 1, (PC) (Trap Vector) (SP) (SP) 2, ((SP)) (PC), (SP) (SP) 2, ((SP)) (Y), (SP) (SP) 2, ((SP)) (X), (SP) (SP) 2, ((SP)) (D), (SP) (SP) 1, ((SP)) (CCR), I bit of CCR 1, (PC) (SWI Vector) CC all1 Examples RTI M ~ 8/102 Unimplemented Opcode Trap TRAP $18 tn3 11 Software Interrupt SWI SWI 9 RTI affects all the condition code bits, with the exception of X, which cannot be set by a software instruction once it is cleared. 2 Normal execution requires 8 cycles. If another interrupt is pending when the RTI is executed, 10 cycles are consumed. 3 Unimplemented 2-byte opcodes are those where the first opcode byte is $18 and the second opcode byte ranges from $30 to $39 or $40 to $FF. 1 140 Machine Control - 2 Description Enter Background Debug Mode W ait for Interrupt Mnemonic BGND Operation Like a software interrupt, but no registers are stacked routines in the BDM ROM control operation (SP) (SP) 2, ((SP)) (SP) (SP) 2, ((SP)) (SP) (SP) 2, ((SP)) (SP) (SP) 2, ((SP)) (SP) (SP) 1, ((SP)) Stop CPU Clocks (SP) (SP) 2, ((SP)) (SP) (SP) 2, ((SP)) (SP) (SP) 2, ((SP)) (SP) (SP) 2, ((SP)) (SP) (SP) 1, ((SP)) Stop All Clocks (PC), (Y), (X), (D), (CCR), (PC), (Y), (X), (D), (CCR), CC Examples BGND M ~ 5 W AI WAI 8/5 4 Stop Processing STOP STOP 9/5 4 No-operation NOP NOP 1 4 The cycles listed correspond to entering and exiting WAI or STOP 141 Special Group The "theme" that links members of this group together is special instructions not normally found on "generic" microcontrollers min/max multiply and accumulate table lookup and interpolate fuzzy logic 142 Min/Max - 1 Description Unsigned 8-bit Minimum Mnemonic MINA addr addr = . [.] MINM addr addr = . [.] Unsigned 8-bit Maximum MAXA addr addr = . [.] MAXM addr addr = . [.] (addr) max {(A), (addr)} (A) max {(A), (addr)} (addr) min {(A), (addr)} Operation (A) min {(A), (addr)} CC N Z V C N Z V C N Z V C N Z V C Examples MINA MINA MINA MINA MINA MINM MINM MINM MINM MINM MAXA MAXA MAXA MAXA MAXA MAXM MAXM MAXM MAXM MAXM 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] Mode . . . [.] [.] . . . [.] [.] . . . [.] [.] . . . [.] [.] ~ 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 The min/max instructions were also included in the arithmetic group 143 Min/Max - 2 Description Unsigned 16-bit Minimum Mnemonic EMIND addr addr = . [.] EMINM addr addr = . [.] Unsigned 16-bit Maximum EMAXD addr addr = . [.] EMAXM addr addr = . [.] (addr):(addr+1) max {(D), (addr):(addr+1)} (D) max {(D), (addr):(addr+1)} (addr):(addr+1) min {(D), (addr):(addr+1)} Operation (D) min {(D), (addr):(addr+1)} CC N Z V C N Z V C N Z V C N Z V C Examples EMIND EMIND EMIND EMIND EMIND EMINM EMINM EMINM EMINM EMINM EMAXD EMAXD EMAXD EMAXD EMAXD EMAXM EMAXM EMAXM EMAXM EMAXM 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] 0,X 2,X+ 1000t,Y [D,X] [2,Y] Mode . . . [.] [.] . . . [.] [.] . . . [.] [.] . . . [.] [.] ~ 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 4 4 5 7 7 144 Multiply and Accumulate Description 16x16 integer multiply and accumulate Mnemonic EMACS addr addr = special Operation (addr):(addr+1):(addr+2):(addr+3) (addr):(addr+1):(addr+2):(addr+3) + ( ((X)) x ((Y)) ) CC N V Z C Examples EMACS $900 ~ 13 The "multiply and accumulate" operation is a staple of most digital signal processing (DSP) algorithms. The 9S12C32 (running at 24 MHz) is "fast enough" to perform DSP functions on audio signals (of approx. 10 KHz bandwidth) 145 Table Lookup and Interpolate Description Table Lookup and Interpolate Mnemonic TBL addr addr = .* ETBL addr addr = .* (D) (addr):(addr+1) + { (B) X { (addr+2):(addr+3) (addr):(addr+1) } } Operation (A) (addr) + { (B) X {(addr+1) (addr) } } CC N Z C? Examples TBL 0,X TBL 2,X+ TBL 2,YTBL 16t,PC TBL 15t,SP ETBL 0,X ETBL 2,X+ ETBL 2,YETBL 16t,PC ETBL 15t,SP Mode . . . . . . . . . . ~ 8 8 8 8 8 10 10 10 10 10 N Z C? *Only indexed modes with "short" constant offsets (requiring no extension bytes) can be used. Y interpolated value calculated desired lookup point X X1 XL X2 146 Y2 YL Y1 Fuzzy Logic Description Determine Grade of Membership Mnemonic MEM Operation ((Y)) grade of membership (Y) (Y) + 1 (X) (X) + 4 MIN MAX rule evaluation CC N? Z? V? C? H? N? Z? V1 C? H? N? Z? V1 C? H? N? Z1 V? C? H? Examples MEM ~ 5 Fuzzy Logic Rule Evaluation REV REV * Fuzzy Logic Rule Evaluation (Weighted) Weighted Average REVW MIN MAX rule evaluation with optional rule weighting; C bit in CCR selects weighted (1) or unweighted (0) rule evaluation Performs weighted average calculations on values stored in memory REVW * WAV WAV * *Number of cycles varies based on number of elements in rule list. These instructions take so many cycles that provisions have been added to allow them to be interrupted in progress 147 Fun Things to Think About The 68HC(S)12 has about 200 different instructions (of which there are about 1000 variants) how many instructions are really needed to make a viable computer? PIC microcontrollers have as few as 33 The 68HC(S)12 has a fairly simple programming model (in terms of user accessible registers) can a viable computer be built with even fewer registers? The 68HC05 has just A and X registers What capabilities would a much larger register set afford? Less "memory traffic" (load/store idea) 148 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-C Assembly Language Programming Techniques: Control Structures 149 Outline Introduction Pseudo Ops Expressions Constants Strings Basic control structures IF-THEN-ELSE CASE FOR loops DO loops WHILE loops REPEAT loops Assembly-style FOR and DO loops 150 Introduction The basic idea of a control structure is to allow controlled execution of a certain block of code The control structures described here will be relatively generic (i.e., not tied to any specific high-level language) The basic concepts covered here are applicable to assembly-level programming in general Note that each assembler program will have its own conventions and "peculiarities" (e.g, comments delineated by semicolons, etc.) 151 Pseudo Ops A pseudo op is an assembler directive, i.e., it tells the assembler to "do something" but does not generate any executable code in and of itself Each assembler program has its own set of pseudo ops that it recognizes 152 Pseudo Ops The pseudo ops recognized by the assembler program include the following: RMB: reserve memory byte allocates memory (only) for a variable or array EQU: equate a symbol (label) with a numeric value (mainly used to improve the readability of assembly code) FCB (or DB): form constant byte (or define byte) assign an initial value to an 8-bit (byte) variable or array FDB (or DW): form double byte (or define word assign an initial value to a 16-bit (word) variable or array 153 Pseudo Ops The pseudo ops recognized by assembler program include the following: FCC: form constant character used with quoted strings ORG: originate code sets the assembler program's internal location counter to the address specified (if this statement is missing, 0000h is assumed) INCLUDE: include the specified assembly source file at the current location END: indicates the end of the assembly source file 154 Expressions Expressions can also be included in the operation field of certain instructions It is important to remember, however, that these expressions are evaluated at assembly time (not during program execution) Examples: ldaa bne staa #2value/37 exit+1 mem+2 155 Constants Hexadecimal values can be specified using either a prefix of "$" (CW) or a suffix of "h" (other assemblers - note that all hexadecimal constants specified using a suffix of "h" must have a leading digit in the range of 0-9) Examples: $A7 is the same as 0A7h $3A is the same as 3Ah Decimal values can be specified using a suffix of "t" (CW default base no suffix) Binary values can be specified using a suffix of "b" (CW prefix of %) Example: 01100111b is the same as 67h 156 Strings Quoted strings are converted to equivalent ASCII characters by the assembler program Examples: cmpa #'J' string fcc "Hello world" 157 Labels Labels are symbols used to represent memory locations in which program or data are stored When used in the operand field of a transferof-control instruction, the assembler converts these symbols to absolute locations (for "jump" instructions) or signed relative offsets (for "branch" instructions) Examples: org $800 jmp iloop ; address is $803 iloop bra iloop ; offset is $FE 158 IF-THEN-ELSE true false condition evaluation 159 CASE 160 CASE CHAR := `a' CHAR := `b' CHAR := `c' 161 FOR Loop: 0-255 iterations (ascending) Note: Range is -128 to +127 162 FOR Loop: 0-255 iterations (ascending) K := M if K > N then exit completion check is done at the TOP of the loop K := K + 1 163 FOR Loop: 0-255 iterations (descending) 164 FOR Loop: 0-255 iterations (descending) K := M if K < N then exit K := K - 1 165 FOR Loop: 0 - 65,535 iterations Note: Range is -32,768 to +32,767 166 FOR Loop: 0 - 65,535 iterations K := M if K > N then exit Note: No instruction is available to INC or DEC a double-byte (16-bit) memory location K := K + 1 167 WHILE Loop End-of-Transmission (CTRL-D) = $04 completion check at top of loop Note: Code block must affect the completion condition 168 REPEAT Loop code block is executed at least once completion check at bottom of loop 169 "Assembly Style" FOR (0 - 255) Key: Use registers as loop counters Basic idea: Count (B) down, and use the ZERO condition as a completion indicator the calculation of ITER+1 is done at assembly time make use of "compound" decrement and branch instruction 170 "Assembly Style" FOR (0 - 65,535) Note: In "assembly style" FOR constructs, the loop overhead is reduced to 3 instructions 171 "Assembly Style" DO (1 - 256) code block is executed at least once completion check at bottom of loop 172 "Assembly Style" DO (1 - 65,536) Note: In "assembly style" DO constructs, the loop overhead is reduced to 2 instructions 173 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-D Assembly Language Programming Techniques: Control Structure Applications 174 Outline "Straight-line" programming example Control structure programming examples Software delay Extended-precision binary add Extended-precision decimal subtract 175 Basic Programming Example: Write a complete 68HC(S)12 assembly program that converts a 4-digit BCD number, stored at locations $900 and $901, into its 16-bit binary equivalent, stored at locations $902 and $903. Illustration: If locations $900 and $901 contain 20BCD and 48BCD, respectively (which represent 204810), the program should produce the 16-bit result 080016 in locations $902 and $903. 176 Solution - 1 ; ; ; ; ; ; ; ; ; 4-digit packed BCD number is in (900h):(901h) 16-bit converted binary number is in (902h):(903h) Method: Binary = ((((Thousands Dig) X 10) + (Hundreds Dig)) X 10 + (Tens Dig)) X 10 + (Ones Dig) org 800h ; ; process thousands digits ; convw ldaa $900 ; get most significant two digits ; of BCD number lsra ; move thousands position to lower nibble lsra lsra lsra ldab #10t mul ; (D) = (Thousands Dig) X 10 std $902 ; use result location as an accumulator 177 Solution - 2 ; ; process hundreds digit ; ldab $900 ; reload most significant two digits andb #$0F ; mask off upper nibble clra ; zero extend addd $902 ; add hundreds digit to running total ldy #10t emul ; multiply running total by 10 std $902 ; save in result accumulator ; ; process tens digit ; ldab $901 ; get least significant two digits ; of BCD number lsrb ; move tens position to lower nibble lsrb lsrb lsrb clra ; zero extend addd $902 ; add tens digit to running total ldy #10t emul ; multiply running total by 10 std $902 178 Solution - 3 ; ; process ones digit ; ldab $901 ; andb #$0F ; clra ; addd $902 ; std $902 ; stop ; ; ; test data declaration ; org 900h bcd fdb $2048 bin fdb $0000 end reload least significant two digits mask off upper nibble zero extend add to running total store final result DONE 179 Solution - 3 ; ; process ones digit ; ldab $901 ; andb #$0F ; clra ; addd $902 ; std $902 ; stop ; ; ; test data declaration ; org 900h bcd fdb $2048 bin fdb $0000 end reload least significant two digits mask off upper nibble zero extend add to running total store final result DONE Question: How many cycles are required to perform a conversion? ____________ 60 180 Software Delay Software delay routines can be used in applications requiring non-precision time delays (intervals) Example application: key de-bouncing Question: Why are the delays provided by software routines (potentially) non-precision? - parameter-dependent overhead - interrupt processing Question: For applications that require precision delays, what approach should be used instead? - timer module 181 Software Delay Method: utilize doubly-nested loop construct inner loop to provide one millisecond (1 ms) of delay construct outer loop to control the number of times the inner loop is entered total execution time will be approximately equal to the number of times the inner loop is executed Entry/Exit conditions: at entry, (A) = number of milliseconds to delay at exit, all registers should be unchanged 182 delay pshx psha pshc ldx loopi dbne x,loopi [3] #_______ [2] [2] [2] [2] loopo dbne pulc pula pulx rts a,loopo [3] [3] [3] [3] [5] 183 Software Delay Note: Need to know clock speed of CPU to do this here, assume it is 8 MHz, i.e., each cycle is 125 ns Execution time analysis: formula for total cycles consumed Total Cycles = (A) [ (X)3 + 5] + 20 solve for (A) = 1 (i.e., 1 ms delay) 8000 = (1) [ (X)3 + 5] + 20 Here, X ~ 265810 solve for (A) = 100 (i.e., 100 ms delay) 800,000 = (100) [ (X)3 + 5] + 20 Here, X ~ 266410 So, what value should be used?? 184 delay pshx psha pshc ldx loopi dbne x,loopi [3] [2] [2] [2] loopo 2661t #______ [2] dbne pulc pula pulx rts a,loopo [3] [3] [3] [3] [5] 185 Clicker Quiz 186 N equ org ? $800 ; ; ; #XA ; #YA ; #0,ACM ; #0,ACM+2 ; #N ; ACM 2,x 2,y b,loop ; ; ; ; ; ; ; ; 4 ?,?,? ?,?,? 187 (2) (2) (2) (2) (2) (5) (5) (1) (13) (2) (2) (3) (3) (3) (3) (5) macme pshb pshx pshy ldx ldy movw movw ldab loop emacs leax leay dbne puly pulx pulb rts ACM XA YA rmb fdb fdb 1. If N=0, the total number of cycles consumed by "macme" is: A. 55 B. 235 C. 5135 D. 5155 E. none of these N equ org ? $800 ; ; ; #XA ; #YA ; #0,ACM ; #0,ACM+2 ; #N ; ACM 2,x 2,y b,loop ; ; ; ; ; ; ; ; 4 ?,?,? ?,?,? 188 (2) (2) (2) (2) (2) (5) (5) (1) (13) (2) (2) (3) (3) (3) (3) (5) macme pshb pshx pshy ldx ldy movw movw ldab loop emacs leax leay dbne puly pulx pulb rts ACM XA YA rmb fdb fdb 2. If N=1, the total number of cycles consumed by "macme" is: A. 55 B. 235 C. 5135 D. 5155 E. none of these N equ org ? $800 ; ; ; #XA ; #YA ; #0,ACM ; #0,ACM+2 ; #N ; ACM 2,x 2,y b,loop ; ; ; ; ; ; ; ; 4 ?,?,? ?,?,? 189 (2) (2) (2) (2) (2) (5) (5) (1) (13) (2) (2) (3) (3) (3) (3) (5) macme pshb pshx pshy ldx ldy movw movw ldab loop emacs leax leay dbne puly pulx pulb rts ACM XA YA rmb fdb fdb 3. If N=10, the total number of cycles consumed by "macme" is: A. 55 B. 235 C. 5135 D. 5155 E. none of these N equ org ? $800 ; ; ; #XA ; #YA ; #0,ACM ; #0,ACM+2 ; #N ; ACM 2,x 2,y b,loop ; ; ; ; ; ; ; ; 4 ?,?,? ?,?,? 190 (2) (2) (2) (2) (2) (5) (5) (1) (13) (2) (2) (3) (3) (3) (3) (5) macme pshb pshx pshy ldx ldy movw movw ldab loop emacs leax leay dbne puly pulx pulb rts ACM XA YA rmb fdb fdb 4. If N=255, the total number of cycles consumed by "macme" is: A. 55 B. 235 C. 5135 D. 5155 E. none of these Extended Precision Binary Add Extended (sometimes called "infinite") precision arithmetic routines are based on using the carry flag (CF) to propagate a carry (or borrow) forward, starting with the least significant byte and ending with the most significant byte For addition, the operands are called the "augend" (the number on top) and the "addend" (the number on the bottom) Index registers are typically used as pointers to the operand and result arrays Auto-increment/decrement addressing can be used as a convenient means of "bumping" the pointers after each iteration 191 Extended Precision Binary Add (augend) (augend) + (addend) (augend) + (addend) --------------(result) (X) (Y) (X) 192 Note: Here, the result overwrites the augend Extended Precision Binary Add 193 Basic Extended Precision Modifications Modifying the extended precision binary ADD routine to perform a binary SUBTRACT or decimal ADD is fairly straight-forward Note: For subtraction, the operands are called the "minuend" (the number on the top) and the "subtrahend" (the number on the bottom) Question: What modification(s) are necessary for each case? 194 Extended Precision Binary Subtract sbca 195 Extended Precision Decimal Add daa 196 Extended Precision Decimal Subtract Writing an extended precision decimal subtract routine, however, is a bit more challenging Question: Why? There is no "decimal adjust after subtraction" instruction 197 Extended Precision Decimal Subtract Form the radix complement of the subtrahend first, then add it to the minuend and perform a decimal adjust (result)BCD (minuend)BCD + [ 99BCD (subhend)BCD + 1] radix (10's) complement of subtrahend DAA 198 Extended Precision Decimal Subtract Add 1 to get radix complement and propagate carry 199 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-E Assembly Language Programming Techniques: Table-Lookup 200 Outline Table lookup techniques and applications Linear index Non-linear index Lookup and interpolate (using TBL) Jump tables Example Application 201 Table Lookup Table lookup is a common technique used in a variety of microcontroller-based systems Applications include the following: data conversion (e.g., linear log) waveform generation linearization of device characteristics (e.g., thermocouple) jump tables for code module execution 202 Table Lookup - Linear Index 203 Table Lookup - Linear Index 204 Table Lookup - Non-linear Index A non-linear index simply means that the index only takes on a subset of all possible values, i.e., there are don't cares in the table Example: Packed BCD number used as a table lookup index, say for a calendar program (note that there is no "month 00", nor are there months "0A" through "0F") Question: In such an application, is it more efficient to use the "raw" BCD value as a table lookup index (thus "wasting" space in the table), or convert the BCD value to binary before using it as a lookup index (thus "saving" space in the table)? A "pair-o-docs": Sometimes, in order to save space, you have to waste it! 205 Table Lookup - Non-linear Index wasted space 206 Table Lookup - Non-linear Index Note: Same code as "normal" case 207 Lookup and Interpolate (TBL) The "TBL" instruction can be used to perform a linear interpolation on values that fall between a pair of data entries stored in memory Example: Estimation of room temperature based on data read from an analog input channel interfaced to a silicon diode circuit Operation performed: (A) (addr) + [ (B) X { (addr+1) (addr) } ] where indexed addressing mode is used and (B) is interpreted as a binary fraction* *of form 0 . 2-1 2-2 2-3 2-4 ... (unsigned) 208 Lookup and Interpolate (TBL) Use of TBL instruction: set up index register to point to table entry "X1" (the table entry closest to, but less than or equal to, the desired lookup value) "X2" is the table entry that follows "X1", and "XL" is the desired lookup point (between "X1" and "X2") along the X-axis calculate (XL-X1) (X2-X1) and place the resulting binary fraction in the B register (typically requires use of FDIV instruction) execute the TBL instruction; the result placed in the A register will be the interpolated result along the Y-axis: (A) Y1 + [ (B) X (Y2 Y1) ] 209 Lookup and Interpolate (TBL) TBL in action... Y Y2 YL Y1 X X1 XL X2 210 Clicker Quiz 211 halt table org ldx ldab tbl staa ldab tbl staa bra fcb fcb fcb $800 #table #$40 0,x lookup #$C0 1,x lookup+1 halt 8 16 24 2 1. The (base 10) value that gets stored at location lookup is: A. B. C. D. E. 8 10 16 22 none of the above lookup rmb 212 halt table org ldx ldab tbl staa ldab tbl staa bra fcb fcb fcb $800 #table #$40 0,x lookup #$C0 1,x lookup+1 halt 8 16 24 2 2. The (base 10) value that gets stored at location lookup+1 is: A. B. C. D. E. 8 10 16 22 none of the above lookup rmb 213 Jump Tables A jump table is a special form of lookup table that contains addresses of subroutines Note: Here, the table entries are "double-byte" (16-bits) in length, since they represent addresses in memory Applications: select ("vector to") a specific interrupt service routine under hardware control select a function/subroutine to execute based on an input stream that has been parsed by a command interpreter 214 Jump Tables +0 +2 +4 (N-1)*2 * puts desired return address on stack 215 Jump Tables note use of indirect addressing mode 216 Example Application Write an interactive "stupid quote" generator that prompts the user for a single character identifier (here, "a" through "f") and prints the corresponding quote on the emulated terminal screen. If the character entered is "out of range", an error message should be printed. If the character q is entered, the program should terminate. The user interface should function as follows (user input is in bold): Welcome to the Stupid Quote Generator Where do you want to go today (a-f)? a Windows Vista will solve all your problems Where do you want to go today (a-f)? d We only ship *bug-free* software (i.e., all the bugs are free) Where do you want to go today (a-f)? g Message index is out of range Where do you want to go today (a-f)? 2 Message index is out of range Where do you want to go today (a-f)? q Nice talking at you... 217 Example Application This program consists of three modular components: a main program that implements the user interface. a pmsgx subroutine that prints the string pointed to by X at entry and terminates when an ASCII null character is encountered. a lookup subroutine that is passed the message index (in the range of 0 to N-1) in the A register and returns the starting address of the desired message string in the X register. In addition, two I/O library routines are provided: inchar -- inputs an ASCII character from the terminal keyboard and returns it in the A register outchar -- prints the ASCII character passed to it in the A register on the terminal screen 218 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-F Assembly Language Programming Techniques: Parameter Passing 219 Outline Introduction Parameter passing techniques Call by value (using registers) Call by name (global parameter area) Following "call" instruction Using the stack Example Application 220 Introduction There are several basic ways in which parameters can be passed to subroutines Each technique has its associated advantages and disadvantages, depending on the application The choice of which parameter passing technique is "best" is highly application dependent 221 Method 1: Call by Value (Registers) The "call by value" method of passing parameters uses the CPU registers available in the programming model It can only be used in cases where there is a small number (i.e., less than 4) of parameters, such as conversion and device driver routines For the 68HC12, the registers available for this purpose are A, B, X, and Y Example: Packed BCD to binary conversion Calling sequence: Conditions at Exit: (A) packed BCD number jsr bcdb (A) unchanged (B) converted binary 222 Method 1: Call by Value (Registers) conv binary = (10 x u.n.) + l.n. "BAB" (B) (A) + (B) 223 Method 2: Call by Name (Global Area) The "call by name" method of passing parameters uses a CPU index register as a pointer to the beginning of a global parameter area Where used: pass a character string pass a data structure (e.g., an array) 224 Method 2: Call by Name (Global Area) Example: Subroutine that sorts an array in ascending order Data structure declaration: 225 Method 2: Call by Name (Global Area) Calling sequence: ldx #AA ; X register points to jsr sortem ; start of data structure Conditions at exit: X unchanged (still points to beginning of data structure) array sorted in ascending order Method: "Bubble Sort" use pairwise comparison and exchange use X register to point to AA[i] use Y register to point to AA[i+1] 226 initialize X and Y pointers Note: B J 227 Method 3: Following "Call" Instruction The "data following call" method of passing parameters uses space allocated between the "call" (here, JSR or BSR) instruction and the next instruction to provide a private parameter area Since the data immediately follows the "call", the top stack item ("return address") will be pointing to this data upon entry to the subroutine Note that the code contained in the subroutine must correct the return address on the stack before executing an RTS instruction to return to the calling program 228 Method 3: Following "Call" Instruction desired return address return address placed on stack points here 229 Method 3: Following "Call" Instruction 230 Method 4: Using the Stack The system stack is the technique most commonly used by high-level language compilers While this method has a significant amount of "overhead" associated with it (in terms of the complexity of the calling and exit sequences), it makes possible two important features associated with modern high-level languages: recursion (the ability of a subroutine to call itself) reentrancy (the ability of a code module to be shared among quasi-simultaneously executing tasks) 231 Method 4: Using the Stack Note: Here, data is stored in high order byte first format (also referred to as "big endian") 232 Method 4: Using the Stack #N #N 233 Method 4: Using the Stack sum: msb +0 +1 . . . +(N-2) lsb +(N-1) 234 Method 4: Using the Stack 235 Stack State at Entry to "epadds" #N #N SP 236 Stack State at Entry to "epadds" #N #N #N SP MSB augend MSB addend 237 Stack State at Entry to "epadds" #N SP LSB augend LSB addend #N MSB augend MSB addend 238 Stack State at Entry to "epadds" #N SP N LSB augend LSB addend #N MSB augend MSB addend 239 Stack State at Entry to "epadds" SP #N MSB return addr LSB return addr N LSB augend LSB addend #N MSB augend MSB addend 240 Stack State as "epadds" Runs SP MSB return addr LSB return addr N LSB augend LSB addend MSB augend X X* *after post-increment by 1 MSB addend 241 Stack State as "epadds" Runs SP MSB return addr LSB return addr N LSB augend LSB addend MSB augend MSB addend 242 X Stack State as "epadds" Runs SP MSB return addr LSB return addr N LSB result LSB addend MSB augend MSB addend X X** **after post-increment by 2 243 Stack State Just Before "epadds" Returns SP MSB return addr LSB return addr N LSB result LSB addend X MSB result MSB addend X** **after post-increment by 2 244 Exit Sequence Following Return From "epadds" SP SP* MSB return addr LSB return addr N LSB result LSB addend MSB result MSB addend *after post-increment by 1 X sum: msb +0 +1 . . . +(N-2) lsb +(N-1) 245 Exit Sequence Following Return From "epadds" SP MSB return addr LSB return addr N LSB result LSB addend MSB result MSB addend SP** **after post-increment by 2 X sum: msb +0 +1 . . . +(N-2) lsb +(N-1) 246 Exit Sequence Following Return From "epadds" MSB return addr LSB return addr N LSB result LSB addend SP SP** MSB result MSB addend **after post-increment by 2 X sum: msb +0 +1 . . . +(N-2) lsb +(N-1) 247 Exit Sequence Following Return From "epadds" MSB return addr LSB return addr N LSB result LSB addend MSB result MSB addend SP SP** X sum: msb +0 +1 . . . +(N-2) lsb +(N-1) 248 Exit Sequence Following Return From "epadds" MSB return addr LSB return addr N LSB result LSB addend MSB result MSB addend SP X sum: msb +0 +1 . . . +(N-2) lsb +(N-1) 249 Example Application Write a program that prompts a user for a five-digit access code (or "PIN"), checks it against a valid combination stored in memory, prompts the user to enter the code a second time if an error is made, and denies access if the PIN is entered incorrectly the second time. For security, the digits of the PIN should be echoed to the screen as "*" characters. Three possible scenarios are outlined below: 1 Welcome to the MegaMoney ATM! Enter PIN: ***** Access granted Enter PIN: ***** Error in PIN try again... valid code first try invalid code first try valid code second try invalid code first try 2 Enter PIN: ***** Access granted Enter PIN: ***** Error in PIN try again... 3 Enter PIN: ***** invalid code second try Sorry access denied Your money is our money until you can figure out how to withdraw it!! 250 STEP 1: Write a subroutine checkp that compares the 5-digit PIN entered by the user against a 5-digit PIN stored in memory. At entry to checkp, the PIN entered by the user is pushed onto the stack (in the order that it was entered), as five separate bytes each containing a single BCD digit (i.e., it is in "unpacked" format). Also at entry to checkp, the X register points to the valid 5-digit code stored in memory; it, too, is stored in "unpacked" format, in five consecutive bytes. At exit, checkp should return with the carry flag set (C=1) if the two combinations match, or with the carry flag clear (C=0) if the two combinations do not match. Also at exit, the combination tested should be removed from the stack and the X register should be restored to its original value (no other registers need to saved/restored). 251 checkp ; ; Subroutine checkp compares the 5-digit code stored in memory ; (pointed to by X) with the 5-digit code passed on the stack ; ; If the two codes match, checkp returns with C=1; else, C=0 ; The 5-byte code passed to this routine is de-allocated before exit ; The X register retains its original value ; puly ; save return address in Y ldab #NDIGS ; B used as loop counter and decb ; as pointer offset ; Comparison loop checkl pula ; get digit of combination entered cmpa b,x ; compare with valid code bne checkb ; if mismatch, know combo is bad decb bpl checkl ; B ranges from 4 to 0 ; If "fall through", all digits match sec ; return with CF = 1 pshy ; restore return address saved in Y rts ; note that X is unchanged ; If "mismatch" occurs, de-allocate remainder of combination ; that was passed on the stack and return with CF = 0 checkb leas b,sp ; de-allocate rest of combination clc ; return with CF = 0 pshy ; restore return address saved in Y rts ; note that X is unchanged 252 STEP 2: Write a main program that prints a welcome message, prompts the user to enter a PIN, checks the PIN using the checkp routine, gives the user a second chance if necessary, checks the second PIN entered using checkp, and prints a sarcastic message if the user fails to enter a valid PIN the second time. The main program should also provide storage for the valid 5-digit combination (of your choice). The main program should simply terminate with a STOP instruction after the "access granted" or "access denied" message is printed. 253 ; ATM access code verifier ; ; Tests 5-digit code entered by user ; and compares it with 5-digit code ; stored in memory CR LF NULL NDIGS NTRYS ; ; ; ; ; ; ; ; ; ; ; ; ; ; equ equ equ equ equ 0dh 0ah 00h 5 2 ; number of digits in combination ; number of trys allowed Start of main program 1. 2. 3. 4. 5. Welcome user Prompt for PIN Input 5-digit PIN (echo "*" as code entered) Call checkp to see if PIN is valid If PIN is not valid then if this is the second try then print "access denied" and exit else print "try again" and goto 2 endif else print "access granted" and exit endif 254 org main movb jsr fcb fcb fcb prompt jsr fcb ldab pmptlp jsr jsr psha ldaa jsr dbne ldx jsr lbcs dec beq jsr fcb fcb fcb bra 800h #NTRYS,ntry ; initialize number of trys pmsg CR,LF "Welcome to the MegaMoney ATM" CR,LF,NULL pmsg "Enter your 5-digit PIN: ",NULL #NDIGS inchar ; get character atoh ; convert ASCII to HEX ; place on stack #'*' outchar ; echo * b,pmptlp #combo ; X points to valid combination checkp wasgood ntry goaway ; give user another chance ; if still has any trys left ; else, deny access to user pmsg CR,LF "Error in PIN - try again" CR,LF,NULL prompt 255 ; Uh oh...user ran out of chances goaway jsr fcb fcb fcb fcb fcb stop wasgood jsr fcb fcb fcb stop pmsg CR,LF "Access granted" CR,LF,NULL pmsg CR,LF "Sorry - Access Denied" CR,LF "Your Money is Our Money Until You Can Figure Out Your PIN!" CR,LF,NULL ; Combination declaration combo fcb 7,6,5,9,4 ntry rmb 1 ; number of trys 256 Clicker Quiz 257 dlyv ldaa loopo ldab loopi nop nop dbne dbne rts #N*16-1 #N*16-1 b,loopi a,loopo [2] [2] [1] [1] [3] [3] [5] 1. The maximum value N can be is: A. 4 B. 16 C. 64 D. 256 E. none of the above 258 dlyv ldaa loopo ldab loopi nop nop dbne dbne rts #N*16-1 #N*16-1 b,loopi a,loopo [2] [2] [1] [1] [3] [3] [5] 2. If N = 1, the total number of cycles consumed is: A. 17 B. 1207 C. 1360 D. 1367 E. none of the above 259 2011 Edition by D. G. Meyer Microcontroller-Based Digital System Design Module 1-G Assembly Language Programming Techniques: Macros and Structured Programming Methodology 260 Outline Macros and conditional assembly Structured programming methodology Recommended programming procedure 261 Macros Definition: A macro associates a symbol (name) with a group (or set) of instructions, to be substituted in a source program where that symbol is used Form of a macro definition: name MACRO {macro body} ENDM Macro expansion is done at assembly time (listing of the expanded macro in the output file can be enabled or disabled) Note: Before a macro can be invoked in a program, it must be defined 262 Macros Where used: to define "new" instructions Example: "BAB" ;(B) (A) + (B) psha addb 1,sp+ to provide a "short-hand" notation for frequently used operations Example: "RIGHT4A" ;shift (A) right 4 places lsra lsra lsra lsra 263 Macros Illustration of in-line substitution lls4a MACRO lsla lsla lsla lsla ENDM org fcb $800 ____ data main ; storage location lsla lsla lsla lsla ldaa data llsa4 staa data 264 Macros Macros can also have arguments specified, as well as contain labels (but, labels can become multiply-defined if macro invoked more than once) Example: n-bit logical left shift of (A) llsla llsla MACRO pshb pshc ldab #\1 lsla decb bne loop pulc pulb ENDM n loop Note: Direct substitution occurs at assembly time with the parameter(s) listed on the macro invocation line 265 Macros Can avoid use of labels in macros by using symbol for location counter ($) $ = starting address of instruction being assembled llsla n llsla addr addr+1 addr+2 MACRO pshb pshc ldab #\1 lsla ; desired "loop" address decb bne $-2 pulc pulb ENDM 266 Macros Example: HLL-looking print macro print print "Print this string" RET equ LF equ NULL equ MACRO jsr pmsg fcb RET,LF fcc \1 fcb RET,LF fcb NULL ENDM $0d $0a $00 "most useful" macro! 267 Comparison of Macros and Subroutines Macros: macro invocation generates in-line code macro expansion done at assembly time a given program may contain many (expanded) versions of the same macro, due to parameter substitution Subroutines: subroutine call causes a branch to another part of the program subroutine call performed at execution time a given program will usually contain only a single version of a given subroutine 268 Clicker Quiz 269 1. Invocation of a macro does not: A. cause a branch to another part of the program B. generate in-line code C. happen at assembly time D. allow substitution parameters E. none of the above 270 2. Macro parameter substitution occurs: A. when the macro is called B. when the macro is defined C. when the macro is invoked D. when the macro is executed E. none of the above 271 dad MACRO psh\1 addd 2,sp+ ENDM 3. The function performed by the macro invocation dad x is: A. (D) (D) + (X) B. (D) 2(X) C. (D) 2(D) D. (D) 2(SP) E. none of the above 272 dad MACRO psh\1 addd 2,sp+ ENDM 4. The function performed by the macro invocation dad d is: A. (D) (D) + (X) B. (D) 2(X) C. (D) 2(D) D. (D) 2(SP) E. none of the above 273 Conditional Assembly The purpose of conditional assembly directives in an assembly source file is: to allow easy insertion and removal of debugging code to allow configuration of a single source file for multiple versions of a target system (e.g., with different feature sets) 274 Conditional Assembly IF / ELSE / ENDIF directives are used to define conditional assembly code blocks IF value1 == value2 (or other conditional) ; block of code assembled if ; conditional is true ELSE ; block of code assembled if ; conditional is false ENDIF IMPORTANT: Conditional assembly directives are evaluated at assembly time! 275 Conditional Assembly Example: IF debug == 1 ldaa test jsr outchar ELSE ldaa value jsr outchar ENDIF 276 Clicker Quiz 277 1. IF / ELSE / ENDIF directives are not: A. used to define conditional assembly blocks B. evaluated at assembly time C. controlled by evaluation of conditionals D. used to control execution of code blocks E. none of the above 278 2. IF / ELSE / ENDIF directives do not: A. assemble into machine code B. utilize C-like conditionals C. provide a means of customizing assembly of a source file for different target systems D. provide a means of controlling the insertion of debugging code E. none of the above 279 Structured Programming Methodology As programs get larger, they get: harder to organize harder to write harder to debug A useful strategy for breaking down a large programming task into small, manageable parts ("code modules") is: top-down organization, followed by bottom-up coding/debugging 280 Structured Programming Methodology Outline of basic top-down, bottom-up strategy write a series of English statements (which will eventually become the program's comments) describing the basic steps the program must perform break each of these main tasks into a series of subtasks which must be performed (i.e., explain each major task in greater detail, again using written comments) further break down each of these subtasks until your English descriptions (comments) translate more or less one-to-one directly into code 281 Structured Programming Methodology Outline of basic top-down, bottom-up strategy define subtasks ("subroutines") that are common to several major tasks; identify parameters which must be passed, and draw a block diagram illustrating the hierarchical arrangement of these subtasks flowchart (or outline) each of these subtasks (each should be small enough that it can be flowcharted or outlined on a single page) finally, write code for each subtask, starting at the bottom of the hierarchical tree and working up ("bottom-up" coding), testing each code module as it is written note that the "main" program should merely be a series of subroutine calls 282 Recommended Programming Procedure Read the program specification (several times) to gain an understanding of the basic functionality required and how the user will interface with (i.e., provide input to) the program Based on the program specification, identify primary tasks and data structures; form a high-level block diagram of the program Based on the program specification, flowchart (or outline) each routine, starting with "main" use English statements or pseudo-code, not assembly language or register references* *Why? Because at this point, the program is being designed, NOT implemented! 283 Recommended Programming Procedure Review the initial program design based on the following: logical correctness module length structural soundness relegation of common code segments to subroutines Code the primary data structures along with each individual routine, based on the flowchart/outline developed previously (begin with "main" and consider register usage before coding each routine) Comment as you write code Debug routines one at a time using instruction tracing, breakpoints, and other debugger functions 284 Modular Programming Example One of the files generated by the assembler program is an "S-record" (or "object file") An S-record contains all the information necessary to load object code into the target system's memory start code "S" record type (1 data record, 9 end record) number of bytes address at which machine code is to be stored machine code/data bytes checksum byte A loader program (that typically runs on the target system) translates the S-record file into a memory image 285 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 286 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 287 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 288 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 289 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 290 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 291 S-Record Loader Sample S-record: S1070800F236723D19 S9030000FC Record No. 1 2 Start Code S S Record Type 1 9 No. of Bytes 07 03 Address Field 0800 0000 Data Field F236723D none Checksum 19 FC 292 S-Record Loader Checksum calculation: S1070800F236723D19 S9030000FC 07 08 00 F2 36 72 +3D ____ E6h in binary: 11100110B complement: 00011001B (checksum) checksum = 19h 293 Clicker Quiz 294 1. For the S-Record S1 06 09 01 02 03 04 __, the checksum should be: A. $19 B. $25 C. $DA D. $E6 E. none of the above 295 2. For the S-Record S1 06 09 01 02 03 04 E6, the value loaded into location $902 is: A. $01 B. $02 C. $03 D. $04 E. none of the above 296 Basic Algorithm for S-Record Loader Loop until "S" (start code) is received Read record type (1 or 9) Read the total number of record bytes (single byte) Read the load address (two bytes) Read the data fields and store each value in consecutive locations, starting at the specified address Read and process the checksum 297 Routines That Need to be Written FNDSTRT find start of S-record RECTP read and check validity of record type GETNUM read the data byte count GETADDR read in memory load address GETDAT read in data fields of record (up to the checksum byte) CHECK read and process the checksum byte PMSG print message string GETBYTE read two ASCII characters and return value as a hex byte GETWORD read four ASCII characters and return value as a hex word ATOH convert ASCII character to hex equivalent 298 Outline of "main" Program ; ; main -- Implements main record-processing loop. Checks for ; end record and download errors. main clr error ; Clear the error flag jsr pmsg fcb 'Ready to load S-record...' fcb RET,LF,NULL recloop jsr ldaa cmpa bne ldaa bne jsr fcb fcb stop errmsg jsr fcb fcb stop getrec rectyp #ENDREC recloop ; Read and process next record ; Get type of last record loaded ; Was it an end record? ; No: Then process next record error ; Check error counter errmsg ; If error count not zero, print message pmsg '*** Your file loaded correctly!' RET,LF,NULL pmsg '*** An error occurred while loading your file...' RET,LF,NULL 299 Outline of "main" Program ; ; Global variables and equates ; DATREC equ ENDREC equ NULL equ RECTYP rmb BYTSUM rmb ERROR rmb 1 9 0 1 1 1 ; Data record type ; End record type ; ASCII null character ; S-Record type (DATREC or ENDREC) ; Current byte sum (for checksum calculation) ; Error flag byte (00 = OK, 01 = error) Note: The variables (RECTYP, BYTSUM, ERROR) must be stored in SRAM 300 Loader Program Subroutines ; ; getrec -- Process an individual S-record ; getrec jsr jsr jsr jsr jsr jsr rts ; ; findstrt -- Just loop until an S (for start of record) is found on ; fndstrt jsr cmpa bne rts serial input inchar #'S' fndstrt ; Read in next character ; Is it the start of a record? ; ; No: Then keep waiting for S Yes: Exit routine 301 fndstrt rectp getnum getaddr getdat check ; Loop until (S)tart char found ; Read the record type ; Read in count of bytes in a record ; Read in memory storage address ; Read in record data bytes ; Add to checksum value ; Exit routine Loader Program Subroutines ; ; rectp -- Read in 1-byte record type, check for validity, and store ; in memory ; rectp jsr inchar ; Read record type from serial input suba #'0' ; Convert record type from ASCII to hex staa RECTYP ; Store record type in memory cmpa #ENDREC ; Is it a valid record type (end)? beq endtp ; Yes: Then exit routine cmpa #DATREC ; No: Is it a data record type? beq endtp ; Yes: The exit routine inc ERROR ; No: Then set error flag endtp rts ; Exit routine 302 Loader Program Subroutines ; ; getnum -- Read in count of data bytes (plus two for record ; destination address) to load. Note that the byte count ; is returned in the B reg. Also, reset the byte sum. ; getnum jsr getbyte ; Read in two ASCII chars (byte count) staa BYTSUM ; Store count in memory ; (for byte summing) tfr a,b ; Save byte count in B for later use rts ; Exit routine 303 Loader Program Subroutines ; ; getaddr -; ; ; ; getaddr pshb jsr tfr adda staa addb stab pulb subb rts Read in the destination memory-address of the data about to be loaded. Also add each byte received to byte sum and decrement byte count by 2. Routine returns the target in the X register. ; ; ; ; ; ; ; ; ; ; Save byte count Get the 16-bit target address Store address in X for later use Include upper byte of addr in sum Update byte sum Include lower byte of addr in sum Update byte sum Restore byte count Dec count by 2 since addr is 2 bytes Exit routine getword d,x BYTSUM BYTSUM BYTSUM BYTSUM #02h 304 Loader Program Subroutines ; ; getdat -- Read in the record data bytes, and place them in memory ; (as pointed to by X). Update the byte count and stop ; reading data when only the checksum value remains. ; getdat ldaa RECTYP ; Get record type cmpa #ENDREC ; Is this an end record? beq yesend ; Yes: Then no data to receive ; No: Then get the record data getlp jsr getbyte ; Read in the next data byte staa 1,x+ ; Store in memory, and inc pointer adda BYTSUM ; Add received byte to byte sum staa BYTSUM ; Update byte sum in memory decb ; Dec count of bytes left to receive cmpb #01 ; Last data byte received? bne getlp ; No: Get next data byte yesend rts ; Yes: Then exit routine 305 Loader Program Subroutines ; ; check -- Reads the checksum byte, compares with computed one's ; complement, and set error flag (if necessary) to indicate ; parity error. ; check jsr getbyte; Read in the checksum byte adda BYTSUM ; Add checksum to the byte sum in memory cmpa #0ffh ; Is there a checksum error? beq endck ; No: Then don't set error flag inc ERROR ; Yes: Then set error flag endck rts ; Exit routine 306 Loader Program Subroutines ; ; pmsg -- Print string following call to routine. Note that ; subroutine return address points to string, and is ; adjusted to point to next valid instruction ; pmsg pulx ; Get pointer to string (return addr) ploop ldaa 1,x+ ; Get next character of string cmpa #NULL ; Test for string termination beq pexit ; Exit if ASCII null encountered jsr outchar ; Print character on terminal screen bra ploop ; Process next string character pexit pshx ; Place corrected return address on stack rts ; Exit routine 307 Loader Program Subroutines ; getbyte - Inputs two ASCII characters from the HC12 SCI and ; converts them to two hexadecimal digits packed into a ; single byte. Returns byte equivalent in A register. getbyte pshc jsr inchar ; get first ASCII character jsr outchar ; echo character jsr atoh ; convert ASCII character to hex bcs errhex1 ; if not hex, go to error routine asla ; shift converted hex digit asla ; to upper nibble asla asla psha ; save on stack temporarily get2 jsr inchar ; get second ASCII character jsr outchar ; echo to screen jsr atoh ; convert ASCII character to hex bcs errhex2 ; if not hex, go to error routine oraa 1,sp+ ; OR converted hex digits together pulc rts ; get ? to prompt for new character errhex1 ldaa #'?' jsr outchar bra getbyte errhex2 ldaa #'?' jsr outchar bra get2 308 Loader Program Subroutines ; getword Get four ASCII characters and return value as a hex word ; in the D register getword jsr bcs tfr jsr bcs exg andcc rts badval orcc rts getbyte badval a,b getbyte badval a,b #$FE ; ; ; ; ; ; ; get first byte of the data entered is there an error in the first byte? save MSB in B get second byte of data entered is there an error in the second byte? put MSB in A and LSB in B no errors, clear Z flag #$01 ; error, set Z flag 309 Loader Program Subroutines ; atoh -- Converts an ASCII character to a hexadecimal digit ; ASCII character passed via A register ; Converted hexadecimal digit returned in A register, ; CF = 0, result OK; CF = 1, error occurred (invalid input) atoh pshb pshx pshy suba #$30 ; subtract "bias" to get ASCII equivalent blt outhex cmpa #$0a bge cont1 quithx clc ; return with CF = 0 to indicate result OK puly pulx pulb rts cont1 suba #$07 cmpa #$09 blt outhex cmpa #$10 blt quithx suba #$20 cmpa #$09 blt outhex cmpa #$10 blt quithx outhex sec ; set CF = 1 to indicate error puly pulx pulb rts 310 ...
View Full Document

This note was uploaded on 02/05/2012 for the course ECE 362 taught by Professor Staff during the Spring '08 term at Purdue University-West Lafayette.

Ask a homework question - tutors are online