ece 4510/5530 microcontroller applications chapter 2bazuinb/ece4510/ch02.pdf · ece 4510/5530...
TRANSCRIPT
ECE 4510/5530Microcontroller Applications
Chapter 2
Dr. Bradley J. BazuinAssociate Professor
Department of Electrical and Computer EngineeringCollege of Engineering and Applied Sciences
ECE 2510 2
Chapter 2 Overview
• Software Development• Software Development Environment
– ICC12 Compiler/Assembler/Linker/Loader– D-Bug12 Microcontroller Resident Debugger
• Assembly Programming– Assembly Language Code Syntax– Assembler Directives– Assembly Language Command Utilization
• Multiple Byte/Word Precision Math• Binary Coded Decimals (BCD)• Branching• Other Instructions• Loops for time delay
ECE 2510 3
Software Development
• System Engineering– Define system architecture and architectural elements– Partition system for engineering elements (e.g. antenna, RF,
digital/programmable logic, DSP, general CPU, real-time software, command & control software with GUI
• Software Development (DSP and/or CPU)– Design– Code– Test– SW-SW Integration– SW-HW Integration– System Integration– Acceptance Testing
ECE 2510 4
Software Development Issues
• Software development starts with problem definition– Problem presented by the application must be fully understood
before any program can be written
• Next step is to lay out an overall plan of how to solve the problem– The plan is also called an algorithm– Algorithm is a sequence of computational steps that transforms the
input into the output– An algorithm can be expressed in pseudo code that is very much
like C or Pascal (or the target language for the code)– An algorithm provides not only the overall plan for solving the
problem but also documentation for the S/W to be developed
ECE 2510 5
Software Development Issues
• An alternative for providing the overall plan for solving software problems is the use of flowcharts– A flowcharts shows the way a program operates– It illustrates the logic flow of the program
• Flowchart symbols are classified as:– Terminal– Process– Input or Output– Decision– Subroutine
ECE 2510 6
Software Development Flowchart
Decision
On-page connector
ECE 2510 7
Software Development Flowchart
• Terminal – Used at the beginning and the end of each program– When used at the beginning of a program, the word start is written inside
the symbol– When used at the end of a program, the word stop is written inside it
• Process – Indicates what must be done at this point in the program execution– Operations specified by the process box could be
• Shifting the contents of one general purpose register to a peripheral register• Decrementing a loop count, etc
• Input/Output – Used to represent data that are either read or displayed by the computer
ECE 2510 8
Software Development Flowchart
• Decision – Contains a question that can be answered yes or no– A decision box has two exits, also marked yes or no– Computer will take one action if the answer is yes and will take a different action if
the answer is no• On-page connector – Indicates that the flowchart continues elsewhere on the
same page. The place where it is continued will have same label as the on-page connector
• Off-page connector – Indicates that the flowchart continues on another page• After the programmer is satisfied with the flowchart, it is converted to source
code using assembly or C language
S u b r o u t i n e
A
B
o f f - p a g e c o n n e c t o r
Decisionyes
no
A
on-page connector
off-
ECE 2510 9
Example FlowchartStart:
ADD3STORE
Load contents of memory location $1000 into Accumulator A
Add contents of memory location $1001 to Accumulator A
End: ADD3STORE
Add contents of memory location $1002 to Accumulator A
Store the contents of accumulator A at memory location $1010
• Example– Write a program to add the numbers
stored at memory locations $1000, $1001 and $1002 and store the result at memory location $1010
• Pseudo Code:– Step1: Load contents of memory
location $1000 into Accumulator A– Step2: Add contents of memory location
$1001 into Accumulator A– Step3: Add contents of memory location
$1002 into Accumulator A– Step4: Store the contents of accumulator
A at memory location $1010
ECE 2510 10
Software development Issues
• Assembly program:.area prog (abs)
.text ; Start of the program_main::Ldaa $1000 ; [$1000] AAdda $1001 ; [A] + [$1001] AAdda $1002 ; [A] + [$1002] AStaa $1010 ;[A] $1010
swi
ECE 2510 11
Software Development Testing
• Next major step in software development is testing the program– Testing a program means testing for anomalies– The first test is for normal inputs that are always expected– If the results are as expected, then the border line inputs are tested– Then maximum and minimum values are tested– Then illegal input values are tested
• If the algorithm includes several branches, then enough values must be used to exercise all the possible branches– This is to make sure program will operate correctly under all
possible circumstances
ECE 2510 12
Software Development Testing (2)
• Testing will likely involve more software development– Software to exercise the tests (provide inputs, store & check
outputs)– Generating test data is a non-trivial task– A software test bench is often required
ECE 2510 13
Software Development Environment
• Create a project in the environment• Load files containing code into the project• For high-level languages: Compile into assembly language• For assembly language: Assemble into object code module• Link multiple object code modules into machine code
module• Load machine code module onto the target host• Executing machine code
– For development: Use a monitor program or debugger to run machine code
– For users: Execute machine resident code
ECE 2510 14
The Steps to CPU Code (1)
• The Hierarchy of operations: making object files
ECE 2510 15
The Steps to CPU Code (2)
• Object Code to machine embedded software hierarchy
ECE 2510 16
Your Software Tools
• Software Development Environment– The Imagecraft Freescale CPU12 Development Tools– ICCV7 for CPU12 – refereed to as ICC12 around WMU
• http://www.imagecraft.com/
• NoICE with the background debugging module (BDM)– ICE refers to an “In-Circuit Emulator”
ECE 2510 17
Code File Generation
• Assembly Language– Assembly Language directives
• Instruction to the assembler about the code– Assembly Language Code
• C Language– C language “PRAGMA”
• Instructions to the compiler/assembler about the code– C Language Code
ECE 2510 18
Assembly Language Program Structure
• Assembly program consists of a sequence of statements that tells the controller to perform the desired operation– Lab1 task1 and task2 code!
• HCS12 assembly programs consists of three sections– Assembler Directives – Assembly Language Instructions– Comments
ECE 2510
Assembly Program Elements
• Assembler directives– Defines data and symbol– Reserves and initializes memory locations– Sets assembler and linking condition– Specifies output format– Specifies the end of a program
• Assembly language instructions– HCS12/MC9S12 instructions
• Comments– Explains the function of a single or a group of instructions
ECE 2510
Fields of a HCS12 Instruction
• Label field– Optional– Starts with a letter and followed by
letters, digits, or special symbols – Can start from any column if ended
with “:”– Must start from column 1 if not
ended with “:”• Operation field (opcode)
– Contains the mnemonic of a machine instruction or an assembler directive
– Separated from the label by at least one space
• Operand field– Follows the operation field and is
separated from the operation field by at least one space
– Contains operands for instructions or arguments for assembler directives
• Comment field– Any line starts with an * or ; is a
comment– Separated from the operand and
operation field for at least one space– Optional
label:[:] operation operands ;comments
ECE 2510
Exampleloop ADDA #$40 ; add 40 to accumulator A
(1) “loop” is a label(2) “ADDA” is an instruction mnemonic(3) “#$40” is the operand(4) “add #$40 to accumulator A” is a comment
movb 0,X,0,Y ; memory to memory copy
(1) no label field(b) “movb” is an instruction mnemonic(c) “0,X,0,Y” is the operand field(d) “; memory to memory copy” is a comment
Identify the Four Fields of an Instruction
ECE 2510 22
Names
• All names in the assembler must conform to the following specification: (‘_’ | [a-Z]) [ [a-Z] | [0-9] | ‘_’ ] *
• That is, a name must start with either an underscore ( _) or an alphabetic character, followed by a sequence of alphabetic characters, digits, or underscores.
• In this document, names and symbols are synonyms for each other. A name is either the name of a symbol, which is a constant value, or the name of a label, which is the value of the Program Counter (PC) at that moment. A name can be up to 30 characters in length. Names are case-sensitive except for instruction mnemonics and assembler directives.
Imagecraft, “Assembler Syntax”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 23
Name Visibility
• A symbol may either be used only within a program module or it can be made visible to other modules. – In the former case, the symbol is said to be a local symbol.– In the latter case, it is called a global symbol.
• If a name is not defined within the file in which it is referenced, then it is assumed to be defined in another module and its value will be resolved by the linker. – The linker is sometimes referred to as a relocatable linker precisely
because one of its purposes is to relocate the values of global symbols to their final addresses.
Imagecraft, “Assembler Syntax”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 24
Label Field
• Labels are symbols defined by the user to identify memory locations in the program and data areas of the assembly module
• For most instructions and assembler directives, the label is optional
• Naming Rules for forming a Label– Label field can begin in column1 or in any column– Should be terminated by a colon (:)– Can begin with A-Z or a – z or _ – ICC12 assembler does not recognize labels starting with @
• Most assemblers restrict the number of characters in a label namebegin: ldaa #10print: jsr hexout
ECE 2510 25
The Operation Field
• This field specifies an assembler instruction, a directive, or a macro cell
• Assembler instructions or directives are case insensitive• Operation field must start in column one (only limited to
some assemblers)• If a label is present, the instruction or directive must be
separated from the label field by at least one space• Examples:
adda #$02True = $01
ECE 2510 26
The Operand Field
• The operand field follows the operation field and is separated from the operation field by at least one space
• The operand field is composed of one or more operands separated by commas, followed by optional space or tab characters
• Operand field is used to supply arguments to the assembler instruction, directive or macro that has been used in the operation field
ExampleTCNT = $0084 ;$0084 is the operand fieldTC0 = $0090 ; $0090 is the operand field
ECE 2510 27
The Comment Field
• Comment field is optional and is mainly used for documentation purpose
• The comment field is ignored by the assembler• Usually, any line beginning with * or // or ; is a comment• ICC12 software used in the ECE2510 lab recognizes
semicolon ( ; ) as a comment• Ex:
Dec lp_cnt ; Decrement the loop count
ECE 2510 28
Assembler Directives
• Assembler Directives look just like the instructions in an assembly language program
• Assembler directives tell the assembler to perform an operation other than creating the machine code for an instruction
• Assembler directives are commands to the assembler• Assembler directives are case insensitive• Assembler directives vary with the assembler• Note: Please do not follow the assembler directives
mentioned in the course textbook. Those directives are based on a assembler different from the one used in the lab
ECE 2510 29
Assembler Directives
• “Universal” Assembler Directives (UAD) are generally available in all assembly language development environments. The text describes one example set.
• The Imagecraft ICC12 Assembler Directives may be found on-line at
– http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm– Select Tool References and then select Assembler Directives
– It is also on the password web site as a *.pdf file.
ECE 2510
ICC12 Memory Address Setting
• .org <value>– Sets the Program Counter (PC) to value. This directive is only
valid for areas with the abs attribute. Note that value is a byte address.
• Example: – .area interrupt_vectors(abs)– .org $1300
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510
ICC12 Memory Areas
.area <name> [(attributes)]– Defines a memory region to load the following code or data. The linker
gathers all areas with the same name together and either concatenates or overlays them depending on the area's attributes.
– The attributes are:• abs, or <- absolute area• rel <- relocatable area
– followed by• con, or <- concatenated• ovr <- overlay
– Starting address of an absolute area is specified within the assembly file– Starting address of a relocatable area is specified as a command option to
the linker– For an area with the con attribute, the linker concatenates areas of that name one
after another. For an area with the ovr attribute, for each file, the linker starts an area at the same address.
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 32
ICC12 Program Text and Main
.text– Sets to starting address of the program area. – Program area for the MC9S12DP256 should always be set to
$122A– .text should be used before start of the main program
_main:: – should follow .text indicating the start of the main program
ECE 2510 33
ICC12 Data Array Assignments
.byte <expr> [,<expr>]*
.word <expr> [,<expr>]*
.long <expr> [,<expr>]*– These directives define constants. The three directives denote byte
constant, word constant (2 bytes), and long word constant (4 bytes), respectively. Word and long word constants are output in little endian format, the format used by the AVR microcontrollers. Note that .long can only have constant values as operands. The other two may contain relocatable expressions.
Example: Temp1: .word label,foo Temp2: .byte $12, $AA, $34, $56, $74Temp3: .word $1234, $ABCD, $1111, $1212
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 34
ICC12 Data Reserved Space
.blkb <value> ; block reserve for bytes
.blkw <value> ; block reserve for words
.blkl <value> ; block reserve for long words– These directives reserve space without giving them values. The
number of items reserved is given by the operand.
Examples:Table1: .blkb $64 ;100 byte storage areaTable2: .blkw 100 ;100 word storage areaTable3: .blkl $0A ;10 long word (4 byte) storage area
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 35
ICC12 Text String Assignment
.ascii "strings"
.asciz "strings"– These directives are used to define strings, which must be enclosed in a
delimiter pair. The delimiter can be any character as long as the beginning delimiter matches the closing delimiter. Within the delimiters, any printable ASCII characters are valid, plus the following C-style escape characters, all of which start with a backslash (\):
\e escape\b backspace\f form feed\n line feed\r carriage return\t tab\<up to 3 octal digits> character with value equal to the octal digits
• .asciz adds a NUL character (\0) at the end. It is acceptable to embed \0 within the string.
Examples: .asciz "Hello World\n".asciz "123\0456" Imagecraft, “Assembler Directives”, see
http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 36
ASCII (American Standard Code for Information Interchange ) table
ECE 2510 37
ICC12 Symbol Value
<symbol> = <value>– Defines a numeric constant value for a symbol.
Example: foo = 5
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 38
ICC12 Global Symbol
.globl <symbol> [, <symbol>]– Makes the symbols defined in the current module visible to other
modules– Otherwise, symbols are local to the current module
ECE 2510 39
ICC12 Macro Definition
.macro <macroname>– Defines a macro. The body of the macro consists of all the statements up
to the .endmacro statement. Any assembly statement is allowed in a macro body except for another macro statement. Within a macro body, the expression @digit, where digit is between 0 and 9, is replaced by the corresponding macro argument when the macro is invoked. You cannot define a macro name that conflicts with an instruction mnemonic or an assembly directive. See .endmacro and Macro Invocation.
For example, the following defines a macro named foo:.macro foo
lds @0,amov @1,@0
.endmacro– Invoking foo with two arguments:
foo R10,R11– is equivalent to writing:
lds R10,amov R11,R10
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 40
ICC12 Macro Invoking
<macro> [<arg0> [,<args>]*]– Invokes a macro by writing the macro name as an assembly command
followed by a number of arguments. The assembler replaces the statement with the body of the macro, expanding expressions of the form @digit with the corresponding macro argument. You may specify more arguments than are needed by the macro body, but it is an error if you specify fewer arguments than needed.
Example: foo bar,x
Invokes the macro named foo with two arguments, bar and x
Imagecraft, “Assembler Directives”, see http://www.dragonsgate.net/pub/help/icc12/wwhelp/wwhimpl/js/html/wwhelp.htm
ECE 2510 41
Example Assembly Program: Task1.area program(abs) ; command to indicate the absolute start of the program.org $1000 ; command forces the controller to start the program from memory location 1000Array1: .byte $01,$02,$03,$04,$05,$06,$07,$08,$09,$0A
; This command declares an array of name Array1 and initializes the array with ; the values provided starting from memory location 1000
.org $1020Array2: .byte $00,$00,$00,$00,$00,$00,$00,$00,$00,$00
;This command declares an array of name Array2 and initializes the ; array to zeros starting from memory location 1020
.text_main:: ;Label indicating the start of main program
Ldx #Array1 ;loads index register X with start address of Array1Ldy #Array2 ;loads index register Y with start address of Array2Ldab #$0A ;Loads B accumulator with value 10 for counter
Loop: ;labelLdaa 1,x+ ;Loads Array1 into accumulator A and increments value in X tStaa 1,y+ ;Stores accumulator A to Array2 and increments value of YDbne b,Loop ;Decrement Value of B accumulator and if its not equal to zero then loop backswi
ECE 2510 42
C Programming Notes
• See Dr. Atashbar’s C Programming Notes on the class web site
ECE 2510 43
Basic C Program Syntax• C program should start with the include files given below
#include <mc9s12dp512.h> // header file for addresses of //registers
#include <stdio.h> // standard input-output header – The mc9s12dp512.h files contains vector addresses for all the peripheral
devices available in the MC9S12DP512 microcontroller• Indicate the start of the main C program structure
Main(){
}• Address Implementation: The syntax to force the data or data array to
start from a particular memory is – Data types supported by C are– Unsigned char byte 0 – 255– Signed char byte -128 – 127– Unsigned short/unsigned int word 0 – 65535– Signed short/signed int word -32768 – 32767– Also support unsigned/signed long, double, float
ECE 2510 44
Basic C Program Syntax
• for absolute address starting at <address> specified#pragma abs_address: <address>
…#pragma end_abs_address
– This is equivalent to the assembly language.area prog (abs).org $1020
• Example:#pragma abs_address: 0x1020unsigned char volatile temp = 0x12#pragma end_abs_address
ECE 2510 45
Basic C Program Syntax
• Define: This syntax is used to declare constants that will be used in the C programs. The syntax for declaring the constants is#define Period 0x1000#define Edge 0x1002
• The above syntax is used to declare constants– Constant qualifier declares variables whose values do not change during
program execution• Volatile qualifier provides a way to tell the compiler that the value of
the variable may change in ways not known to the compilerUnsigned char volatile Temp1 = 0x00;Unsigned char volatile Temp2[0x0A];
ECE 2510 46
Basic C Program Syntax (2)
• Declare a word or an array of words with or without initialized dataUnsigned int volatile Temp3[ ] = {0x1212, 0xAB34, 0x1122};
• The following syntax is used to declare a character string arrayUnsigned char volatile array[ ] = “John”;
• Main()• C program must define a function called main• In general, your main routine performs some initialization
stuff and then executes an infinite loop or SWI
ECE 2510 47
Example C Program#include <hcs12dp256.h> //header file to be included for the controller#include <stdio.h>#define STOP 0 //defining constants STOP with value 0#define SIZE 16 //defining constants SIZE with value 16char i; //defining i as a character//Process of declaring an Array1 starting from memory location 1020 and initialized with values from 00 to 0x0f#pragma abs_address:0x1020unsigned char volatile Array1[ ]={00,01,02,03,04,05,06,07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};#pragma end_abs_address//Process of declaring an Array2 starting from memory location 1040 and initialized with values from 00 to 0x0f#pragma abs_address:0x1040unsigned char volatile Array2[ ] = {00,01,02,03,04,05,06,07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};#pragma end_abs_address//Process of declaring an Array3 starting from memory location 1060 and initialized with values 0x00#pragma abs_address:0x1060unsigned char volatile Array3[ ] = {00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00};#pragma end_abs_addressmain(){//The for loop goes sixteen times and adds contents of Array1 with Array2 and stores the result in Array3for(i=0;i<SIZE;i++){Array3[i] = Array1[i] + Array2[i];}asm(“swi”);return(0);}
Arithmetic in Assembly Language
• Note that in C, if you define the correct variable type, the C compiler will do this for you!
• You may also require the correct C libraries:#include <stdio.h> //standard input-output package#include <ctype.h> //character class tests (alpha, digit, etc.)#include <math.h> //math functions (sin, cos, sqrt, etc.)
ECE 4510/5530
48
ECE 2510 49
Arithmetic in Microcontrollers
• Binary/Hex Byte or Word– Unsigned addition/subtraction
• Two’s complement subtraction– Signed addition/subtraction
• Two’s complement– Floating point addition/subtraction
• Exponent, mantissa
• Double Word – Carry and Borrow
SKIP TO SLIDE CODE FLOW(SLIDE 84)
ECE 4510/5530
50
ECE 2510 51
Programs to do Arithmetic
• Example 2.3, p. 47– Add 3 memory location bytes. Store result in memory.
• Example 2.4, p. 48– Add 2 memory locations and subtract a third. Store result in
memory.
• Example 2.5, p. 48– Subtract a constant from memory locations.
• Example 2.6, p. 49– Add 2 words in memory. Store result in memory.
• Example 2.7, p. 51– Add 2 4-byte numbers. Store result in memory.
ECE 2510
Example 2.3 Write a program to add the values of memory locations at $1000, $1001, and $1002, and save the result at $1100.Solution:Step 1
A m[$1000]Step 2
A A + m[$1001]Step 3
A A + m[$1002]Step 4
$1100 A
Codeldaa $1000adda $1501adda $1002staa $1100
Example 2.3 (1 of 5)
ECE 2510 53
Example 2.4 Write a program to subtract the contents of the memory location at $1005 from the sum of the memory locations at $1000 and $1002, and store the difference at $1100.
Solution:
ldaa $1000
adda $1002
suba $1005
staa $1000
Start
A [$1000]
A [A ]+ [$1002]
A [A ]+ [$1005]
$1010 [A]
Sto p
Figu re 2 .2 L o gic flo w o f p ro gram 2.4
Example 2.4 (2 of 5)
ECE 2510 54
Example 2.5 Write a program to subtract 5 from four memory locations at $1000, $1001, $1002, and $1003.
Solution:
Example 2.5 (3 of 5)
ECE 2510 55
Example 2.6 Write a program to add two 16-bit numbers that are stored at $1000-$1001 and $1002-$1003 and store the sum at $1100-$1101.
Code:
ldd $1000
addd$1002
std $1100
The Carry Flag- bit 0 of the CCR register- set to 1 when the addition operation produces a carry 1- set to 1 when the subtraction operation produces a borrow 1- enables the user to implement multi-precision arithmetic
Example 2.6 (4 of 5)
ECE 2510
Example 2.7 Write a program to add two 4-byte numbers that are stored at $1000-$1003 and $1004-$1007, and store the sum at $1010-$1013.
Code: Addition starts from the LSB and proceeds toward MSB.
ldd $1002 ; add and save the least significant two bytesaddd $1006 ; “std $1012 ; “
ldaa $1001 ; add and save the second most significant bytesadca $1005 ; “staa $1011 ; “
ldaa $1000 ; add and save the most significant bytesadca $1004 ; “staa $1010 ; “
Example 2.7 (5 of 5)
ECE 2510
Example 2.8 Write a program to subtract the hex number stored at $1004-$1007 from the the hex number stored at $1000-$1003 and save the result at $1100-$1103.
Code: The subtraction starts from the LSBs and proceeds toward the MSBs.ldd $1002 ; subtract and save the least significant two bytes/ wordssubd $1006 ; “std $1102 ; “
ldaa $1001 ; subtract and save the difference of the second to mostsbca $1005 ; significant bytesstaa $1001 ; “
ldaa $1000 ; subtract and save the difference of the most significant sbca $1004 ; bytesstaa $1100 ; “
Bonus Example 2.8
ECE 2510 58
Multi-Precision Arithmetic
• Programs can also be written to add numbers larger than 16 bits
• Multi-precision arithmetic: Arithmetic performed in a 16-bit microprocessor/microcontroller on numbers that are larger than 16 bits is called multi-precision arithmetic– Make use of the carry flag of the condition code register– Carry flag can be thought of as a temporary 9th bi that is appended
to any 8-bit register or 17th bit that is appended to any 16-bit register
ECE 2510 59
Multi-precision Addition (unsigned)
• Ex: To add the hex number $1A598183 to $76548290, HCS12 has to perform multi-precision addition
$ 1A598183$ 76548290---------------$ 90AE0413
• Multi-precision addition is performed one byte at a time, beginning with the least significant byte
ECE 2510 60
Multi-precision Addition
• Lest significant 16-bit numbers can be added usingLDD #$8183ADDD #$8290STD $1002
• Result of this addition can result in a carry• Add next bytes with the CCR carry
Ldaa #$59ADCA #$54STAA $1001
• Result of this addition can result in a carry• Add next bytes with the CCR carry
LDAA #$1AADCA #$76STAA $1000
ECE 2510 61
Multi-precision Subtraction
• Ex: To subtract hex numbers $98765432 and $16757284 HCS12 has to perform multi-precision subtraction
• LS WordLDD #$ 5432SUBD #$7284STD $1002
• Next ByteLDAA #$76SBCA #$75STAA $1001
• MS ByteLDAA #$98SBCA #$16STAA $1000
ECE 2510 62
Binary-Coded-Decimal
• Although computers work internally with binary numbers, the input and output equipment generally uses decimal numbers– Since most logic circuits only accepts two-valued signals, the decimal
numbers needs to be coded in terms of binary signals
• This representation is called binary-coded-decimal (BCD)Ex: 2538 0010 0101 0011 1000 bcd– Advantage of BCD encoding method is the simplicity of input/output
conversion– Disadvantage is the complexity of arithmetic processing, it must be
converted into and out of binary for processing!
• The HCS12 microcontroller uses binary numbers. – Numbers may be enter as a BCD, but the will be treated as binary
numbers by the normal arithmetic commands.
ECE 2510 63
Binary-Coded-Decimal
• So how are BCD values processed? – Option 1
• Translate BCD to binary on input• Operate in binary• Translate binary to BCD before output (add a correction factor)
– A special instruction supports this … DAA
– Option 2• Adjust the result of BCD arithmetic after every operation
– Determining and adding correction factors based on results• The DAA instruction can help• Dedicated “BCD representation” memory locations
(all numbers in memory do not have the same “value”)
ECE 2510 64
Binary-Coded-Decimal Addition
• Addition of $25 with $31 produces a result of $56 according to the rules of binary addition– This is also a correct BCD answer, 25 + 31 = 56
• Problem occurs when addition of two BCD digits generates a sum greater than 9, because the sum is incorrect in the decimal number system (needs to be between 0 and 9)– Ex: $18 + $47 = $5F according to rules of binary addition and a
result of 18 + 47 = 65 according to the rules of decimal addition
• BCD sum correction factors – Adding $6 to every sum digit greater than 9 (A-F), or– Adding $6 to every sum digit that had a carry of 1 to the next
higher digit (half carry and carry bits in the CCR)
ECE 2510 65
Binary-Coded-Decimal Addition
• Example:$9898
--------------$130 Not correct since 98 + 98 = 196
– In the above addition 8 + 8 resulted in a half-carry and 9 + 9 resulted in a carry.
• Applying adjustments$130
+66-------------
196
ECE 2510 66
Complete BCD Adjustment Rules
• From the explanation of the DAA command
ECE 2510 67
Binary-Coded-Decimal Addition
• HCS12 provides a Decimal Adjust Accumulator instruction (DAA), which takes care of all these detailed detection and correction operations– There is no necessity of writing program to detect illegal BCD sum
following a BCD addition– The DAA instruction monitors the BCD additions and the C and H
flags and automatically adds $6 to any required nibble
• Rules for using DAA instruction:– Can only be used for BCD addition. Does not work for subtraction
or hex arithmetic– DAA instruction must be used immediately after one of the three
instructions that leaves their sum in accumulator A (adda, adca, aba)
– Numbers added must be legal BCD numbers to begin with
ECE 2510 68
BCD Example Code
• Example 2.9: Add BCD numbers at locations $1000 and $1001, store the result in $1010
ldaa $1000adda $1001daastaa $1010
• Multi-precision BCD Addition– Perform one byte at a time from LSB to MSB– DAA provides the correct carry flag (adca)
ECE 2510 69
BCD Translation
• BCD to Binary– Mask off each BCD digit, multiply by the appropriate “digit
factor” in binary (10, 100, 1000, etc), sum the results.
• Binary to BCD– Divided by 10, the remainder is a BCD digit the result contains the
next higher BCD location– Repeat until all digits are generated.
ECE 2510 70
Multiplication and Division
• 8-bit x 8-bit 16-bit• 16-bit x 16-bit 32-bit• 16-bit x 16-bit + 32-bit 32-bit
• 16-bit 16-bit 16-bit + Rem• 32-bit 16-bit 16-bit + Rem
Mnemonic Function Operation
MUL 8 by 8 multiply (unsigned) (A) × (B) A : B
EMUL 16 by 16 multiply (unsigned) (D) × (Y) Y : D
EMULS 16 by 16 multiply (signed) (D) × (Y) Y : D
EMACS Multiply and accumulate (signed) 16 bit by 16 bit 32 bit
((M(X):M(X+1)) × (M(Y):M(Y+1))) + (M ~ M + 3) M ~ M + 3
EDIV 32 by 16 divide (unsigned) (Y : D) ÷ (X) Y, Remainder D
EDIVS 32 by 16 divide (signed) (Y : D) ÷ (X) Y, Remainder D
FDIV 16 by 16 fractional divide (D) ÷ (X) X, Remainder D
IDIV 16 by 16 integer divide (unsigned) (D) ÷ (X) X, Remainder D
IDIVS 16 by 16 integer divide (signed) (D) ÷ (X) X, Remainder D
ECE 2510 71
Example 2.10 Write an instruction sequence to multiply the 16-bit numbers stored at $1000-$1001 and $1002-$1003 and store the product at $1100-$1103.
Solution:ldd $1000ldy $1002emul ; (D) × (Y) Y : D sty $1100std $1102
Example 2.11 Write an instruction sequence to divide the 16-bit number stored at $1020-$1021 into the 16-bit number stored at $1005-$1006 and store the quotient and remainder at $1100 and $1102, respectively.
Solution:ldd $1005ldx $1020idiv ; (D) ÷ (X) X, Remainder Dstx $1100 ; store the quotientstd $1102 ; store the remainder
Multiplication and Division (2 of 2)
ECE 2510 72
Multiply and Accumulate Instructions
• EMACS Multiply and Accumulate Instruction• Multiply and Accumulate instructions multiplies two 16-
bit operands stored in memory and adds the 32-bit result to a third memory location (32-bit)– Operand1 operand1 is fetched from a location pointed to by
index register X– Operand2 operand2 is fetched from a location pointed to by
index register Y– Before the instruction is executed, the X and Y index registers
must contain values that point to the most significant bytes of the source operands
– The most significant bytes of the 32-bit result is specified by an extended address supplied with the instruction
ECE 2510 73
Multiply and Accumulate Instructions
• Ex: Assembly program to compute the following the expression using the EMACS instruction– (X) and (Y) are in memory location $1020 and $1030– Result should be stored in memory location $1050
; (X)*(Y) + ($1050)Ldx $1020 ;assume $1020 contains $1A23Ldy $1030 ;assume $1030 contains $22B2Ldd #00 ;Initialize the upper word of sum addressStd $1050 ;16-bits stored in upper word of 2-word resultLdd #$1234 ;a 16-bit immediate value to addStd $1052 ;16-bits stored in lower word of 2-word resultEMACS $1050 ;multiply memory pointed to by X an Y, add to
result address $1050
• Performs [m(Y:Y+1)] x [m(X:X+1)] + [1050:1051:1052:1053] [1050:1051:1052:1053]
ECE 2510 74
EMACS
• For more example code see textbook problems:– 2.26 and 2.27 perform math operations that use EMACS– Textbook CD code ex02_26.asm and ex02_27.asm have solutions
ECE 2510 75
Multi-precision Multiplication
• HCS12 provides instructions for performing unsigned 8-bit by 8-bit and both signed and un-signed 16-bit by 16-bit multiplications
• Since HCS12 is a 16-bit microcontroller, it can be used to perform complicated operations in many sophisticated applications
• Ex: Application can be 32-bit by 32-bit multiplication– Since there is no 32-bit by 32-bit multiplication instruction, we will have
to break it into two 16-bit halves and use the 16-bit by 16-bit multiply instructions
– Assume M and N are the multiplicand and multiplier, respectively– Two numbers can be broken down as follows– M = MH:ML and NH:NL
• Note: A memory operand must be specified using the extended or indexed addressing modes
ECE 2510 76
16-bit
P ~ P+1 P+2 ~ P+3 P+4 ~ P+5 P+6 ~ P+7
upper half
upper half
upper half
upper half lower half
lower half
lower half
lower half
Address
partial product MLNL
partial product MHNL
partial product MLNH
partial product MHNH
Final product M × N
msb lsb
Note: msb stands for most significant byte and lsb for least significant byte
Figure 2.3 Unsigned 32-bit by 32-bit multiplication
16-bit 16-bit 16-bit
Illustration of 32-bit by 32-bit Multiplication
• Two 32-bit numbers M and N are divided into two 16-bit halves– M = MHML– N = NHNL
ECE 2510 77
Multi-precision Multiplication
• Since 32-bit by 32-bit results in a 64-bit result– Step1: Allocate 8 bytes to hold the product. Assume these eight
bytes are located at P, P+1, P+2, P+3, P+4, P+5, P+6, P+7– Step2: Compute the partial product MLNL (in Y:D) and save it at
locations P+4 to P+7– Step3: Compute the partial product MHNH (in Y:D) and save it at
locations P to P+3– Step4: Compute the partial product MHNL (in Y:D) and add it to
memory locations P+2 to P+5. Carry flag may be set to 1 after this addition
– Step5: Add the Carry flag to memory location P+1 using ADCA instruction. This addition may also set the Carry flag to 1. So again add the C flag to memory location P
ECE 2510 78
Multi-precision Multiplication
• Continued– Step 6: Generate the partial product MLNH (in Y:D) and add it to
memory locations P+2 to P+5. The carry flag may be set to 1 after this addition
– Add the Carry flag to memory location P+1 using ADCA instruction. This addition may also set the Carry flag to 1. So again add the C flag to memory location P
• Refer to textbook p. 48 – 49 for the assembly program– eg02_12.asm on the textbook CD
• Text problem 2.11– Solution is provided on the CD ex02_11.asm
ECE 2510 79
Translating Unsigned Binary to BCD/ ASCII for Human-readable Output
• Binary Considerations– 8-bits unsigned 3 BCD digits– 8-bits signed sign plus 3 BCD digits– 16-bits unsigned 5 BCD digits– 8-bits signed sign plus 5 BCD digits
• BCD to ASCII– Numbers add $30– Minus sign $2D (for signed numbers)
• Conversion process– (If signed, negative, set flag and negate binary number)– Divide by 10, keep the remainder as the digit, use the quotient and
repeat
ECE 2510 80
ASCII (American Standard Code for Information Interchange ) table
ECE 2510 81
Write a program to convert the 16-bit number stored at $1000-$1001 to BCD format and store the result at $1010-$1014. Convert each BCD digit into its ASCII code and store it in one byte.
Solution: - A binary number can be converted to BCD format by using repeated division by 10.- The largest 16-bit binary number is 65535 which has five decimal digits.- The first division by 10 generates the least significant digit, the second division by 10 obtains the second least significant digit, and so on..org $1000data: .word 12345 ; data to be tested.org $1010result: .blkb 5 ; reserve bytes to store the result
.text_main::
ldd dataldy #resultldx #10idiv ; (D) ÷ (X) X, Remainder Daddb #$30 ; convert the digit into ASCII codestab 4,Y ; save the least significant digitxgdx ; exchange D and X registers
Example 2.13 (1)
ECE 2510 82
ldx #10idiv ; (D) ÷ (X) X, Remainder Dadcb #$30stab 3,Y ; save the second to least significant digitxgdx
ldx #10idiv ; (D) ÷ (X) X, Remainder Daddb #$30stab 2,Y ; save the middle digitxgdx
ldx #10idiv ; (D) ÷ (X) X, Remainder Daddb #$30stab 1,Y ; save the second most significant digitxgdx
addb #$30stab 0,Y ; save the most significant digitend
Example 2.13 (2)
START CODE FLOW
ECE 4510/5530
83
ECE 2510 84
Branch Instructions
• Branch instructions cause program flow to change when specific condition exist
• Branches are used to perform:– Infinite execution– Conditional operations– Loops– Time delay (software controlled)
ECE 2510 85
Branch instructions
• HCS12 has three kinds of branch instructions– Short branches– Long branches– Bit conditional branches
• Branch instructions can also be classified by the type of condition that must be satisfied in order for a branch to be taken– Unary (unconditional) branch instructions always execute– Simple branches are taken when a specific bit in the CCR register is in a
specific state as a result of the previous operation– Unsigned branches are taken when a comparison or a test of unsigned
quantities result in a specific combination of CCR bits– Signed branches are taken when comparison or test of signed quantities
result in a specific combination of CCR bits
ECE 2510 86
Figure 2.4 An infinite loop
S
Figure 2.5 For looping construct
I i1
I i2 ?
S
yes
I I + 1
(a) For I = i1 to i2 DO S
no
I i2
I i1 ?
S
yes
I I - 1
(b) For I = i2 downto i1 DO S
no
C Strue
false
Figure 2.6 The While ... Do looping construct
Figure 2.7 The Repeat ... Until looping construct
initialize C
S
Ctrue
false
Loop Flowchart Diagrams
ECE 2510 87
Program Loop Concepts• Types of program loops: finite and infinite loops
• Looping mechanisms in text:– do statement S forever
– For i = n1 to n2 do statement S orFor i = n2 downto n1 do statement S
– While C do statement S
– Repeat statement S until C
• Program loops are implemented by using the conditional branch instructions and the execution of these instructions depends on the contents of the CCR register.
ECE 2510 88
Program Loops in C - syntax
• Looping mechanisms (Chapter 3: Control Flow. 3.4 & 3.6)– While loop
• while(expr) {}
– For loop• for(expr1;expr2;expr3) {
}
– Do loop• do {
} while (expr);
From “Essential C”,see Section 2 on Control Structures, p. 11-14
Example Code
while(state == 1){printf("Hello World!\n\r");delayby100ms(2);char_in = checkchar();if (!(char_in ==0)){
state = 2;printf("On to state 2.\n\r");
}}
while(state == 2){printf("State2\n\r");delayby100ms(10);if (count == 4){
state = 3;printf("On to state 3.\n\r");
}count++;
}
// Main program infinite loopwhile(1){
// Multiple state conditional test structure for real time codingif (state & 0x80) // Most significant flag bit test{ PTP ^= LEDBIT; // Perform desired function (toggle LED)
state &= ~(0x80); } // Clear the state flag bit else if (state & 0x40){
state &= ~(0x40); // Clear the state flag bitstate |= (0x20); } // Set the next state flag bit
else if (state & 0x20){state &= ~(0x20); // Clear the state flag bitstate |= (0x08); } // Set another state flag bit
else if (state & 0x10){state &= ~(0x10); } // Clear the state flag bit
else if (state & 0x08){state &= ~(0x08); } // Clear the state flag bit
else if (state & 0x04){state &= ~(0x04); } // Clear the state flag bit
else if (state & 0x02){state &= ~(0x02); } // Clear the state flag bit
else if (state & 0x01){state &= ~(0x01); } // Clear the state flag bit
else{asm("nop"); } / If there are no state bits set, do this
// Things to be done every loop placeholderasm("nop");asm("nop");asm("nop");
}return(0);} // end of main()ECE
4510/553089
Implementing C Flow Control
• All the wonderful branch instructions …..
• For C the next things to know is function calls– Passing by stack and stack operations are also important
ECE 4510/5530
90
ECE 2510 91
Program Loops in Assembly
• Implement the desired flow diagram
• Use normal accumulator operations to determine the expressions. This sets the CCR bits.
• Select the appropriate branch to use the CCR bits to either set the PC to the branch target address or keep going.
ECE 2510 92
Branch Instructions
• Basic Branching– Set the CCR bits using an instruction
• Inc/Dec, Add/Sub, Boolean Logic, Compare/Test, Bit Test– Branch using:
• Unary (unconditional) branch instruction• Simple branch instruction• Unsigned branch instruction• Signed branch instruction
• Bit conditional branching– Self contained bit testing and branching instruction– BRCLR or BRSET
• Loop Primitive Instructions– Self contained counter branches, where a counter is Inc/Dec/Nop,
tested, and branching is based on the counter results– [D/B/T]beq or [D/B/T]bne
ECE 2510 93
Basic Branching
• Unary, Simple, Unsigned, Signed
Unary and Simple Branch Instructions
Mnemonic Function Equation or Operation
Unary Branches
BRA Branch always 1 = 1
BRN Branch never 1 = 0
Simple Branches
BCC Branch if carry clear C = 0
BCS Branch if carry set C = 1
BEQ Branch if equal Z = 1
BMI Branch if minus N = 1
BNE Branch if not equal Z = 0
BPL Branch if plus N = 0
BVC Branch if overflow clear V = 0
BVS Branch if overflow set V = 1
Unsigned and Signed Branch Instructions
Mnemonic Function Relation Equation or Operation
Unsigned Branches
BHI Branch if higher R > M C + Z = 0
BHS Branch if higher or same R ≥ M C = 0
BLO Branch if lower R < M C = 1
BLS Branch if lower or same R ≤ M C+ Z = 1
Signed Branches
BGE Branch if greater than or equal R ≥ M N V = 0
BGT Branch if greater than R > M Z + (N V) = 0
BLE Branch if less than or equal R ≤ M Z+ (N V) = 1
BLT Branch if less than R < M N V = 1
ECE 2510 94
Unary Branches/Do Forever
• BRA/LBRA Branch always or Long Branch always– This instruction performs an unconditional branch/long branch to
the specified locationLoop:
ldaa 1,x+adda #$12
bra Loop
• BRN/LBRN Branch Never or Long Branch Never– BRN/LBRN is included in the instruction set to provide a
complement to the bra/lbra instruction– Instruction is useful during program debug, to negate the effect of
another branch instruction
Figure 2.4 An infinite loop
S
ECE 2510 95
Simple Branches
• Branches Based on a single CCR bit– BCC/LBCC Branch/Long Branch if carry clear (C flag 0)– BCS/LBCS Branch/Long Branch if carry set (C flag 1)– BEQ/LBEQ Branch/Long Branch if equal to zero (Z flag 1)– BMI/LBMI Branch/Long Branch if minus (N flag 1)– BNE/LBNE Branch/Long Branch if not equal to zero (Z flag 0)– BPL/LBPL Branch/Long Branch if plus (N flag 0)– BVC/LBVC Branch/Long Branch if overflow clear (V flag 0)– BVS/LBVS Branch/Long Branch if overflow set (V flag 1)
ECE 2510 96
Simple Branches
• Ex: Assume X contains $1000 and Y contains $1020Loop:
Ldaa 1,x+Ldab 1,y+AbaBcs Loop1 ; Branch/Long Branch if carry set------Bra Loop
Loop1:Staa $1050
ECE 2510 97
Simple Branches/Repeat S Until C
.org $1000Testv: .byte test_value_initTestc: .byte test_condition_init
Loop:---------Ldaa Testc ; Assume cond. in ASuba Testv ; subtract test_value from conditionBeq Loop
Continue:Nop
Figure 2.7 The Repeat ... Until looping construct
initialize C
S
Ctrue
false
ECE 2510 98
Reference Manual: Unary and Simple Branch Instructions
Mnemonic Function Equation or Operation
Unary Branches
BRA Branch always 1 = 1
BRN Branch never 1 = 0
Simple Branches
BCC Branch if carry clear C = 0
BCS Branch if carry set C = 1
BEQ Branch if equal Z = 1
BMI Branch if minus N = 1
BNE Branch if not equal Z = 0
BPL Branch if plus N = 0
BVC Branch if overflow clear V = 0
BVS Branch if overflow set V = 1
ECE 2510 99
Unsigned Branches
• BHI/LBHI Branch/Long Branch if higher (C + Z flag 0)– Instruction can be used after comparing or subtracting un-signed values– Branch occurs if CPU register value is higher than the value in memory– Cannot be used for instructions that do not affect the carry bit
• BHS/LBHS Branch/Long Branch if higher or same (C flag 0)– Instruction can be used after comparing or subtracting un-signed values– Same as Branch/Long branch if carry clear instruction– Branch occurs if CPU register value is higher than or equal to the value in
the memory– Instruction can be used after comparing or subtracting un-signed values– Cannot be used for instructions that do not affect the carry bit
ECE 2510 100
Unsigned Branches
• BLO/LBLO Branch/Long Branch if lower (C flag 1)– Instruction can be used after comparing or subtracting un-signed values– Same as branch if Carry set instruction– Branch occurs if CPU register value is less than the value in the memory– Cannot be used for instructions that do not affect the carry bit
• BLS/LBLS Branch/Long branch if lower or same (C + Z flag 1)– Instruction can be used after comparing or subtracting un-signed values– Branch occurs if CPU register value is less than the value in the memory– Cannot be used for instructions that do not affect the carry bit
ECE 2510 101
Unsigned Branches Example
• Ex: Assume X has value $1000 and Y has value $1050Loop:
Ldaa 1,x+suba #$32Bhi Loop1---------
Loop1:Staa 1,y+
Bra Loop
ECE 2510 102
Signed Branches
• BGE/LBGE Branch or Long Branch if greater than or equal – BGE/LBGE can be used to branch after comparing or subtracting
signed two’s complement values (NV=0)– Branch occurs if the CPU register value is greater than or equal to
the value in memory
• BGT/LBGT Branch or Long Branch if greater than– BGT/LBGT can be used to branch after comparing or subtracting
signed two’s complement values (Z+(NV)=0)– Branch occurs if the CPU register value is greater than the value in
memory
ECE 2510 103
Signed Branches
• BLE/LBLE Branch/Long Branch if less than or equal to– BLE/LBLE can be used to branch after subtracting or comparing
signed two’s complement values (Z+(NV)=1)– Branch occurs if CPU register value is less than or equal to the
value in memory
• BLT/LBLT Branch/Long Branch if less than– BLT/LBLT can be used to branch after subtracting or comparing
signed two’s complement values (NV=1)– Branch occurs if CPU register value is less than to the value in
memory
ECE 2510 104
Signed Branches/ For ii=n to m do
• Ex: Assume X contains $1000 and Y contains $1020.org $1040.byte loopstart,loopindex,loopend
Ldx #$1040 ; Set x to loop value add.Ldaa 0,x ; Set initial loopindexStaa 1,xLoop:
Ldaa 2,x ; Load loopend indexSuba 1,x ; sutract loopindexBgt Loop1 ; Branch out if A> (m)---Inc 1,x ; Increment loopindex
Bra LoopLoop1:Nop
Figure 2.5 For looping construct
I i1
I i2 ?
S
yes
I I + 1
(a) For I = i1 to i2 DO S
no
I i2
I i1 ?
S
yes
I I - 1
(b) For I = i2 downto i1 DO S
no
ECE 2510 105
Bit Condition Branch Instructions
• Certain applications needs to make branch decisions based on the value of a few bits– HCS12 provides two special conditional branch instructions for this
purpose
• Brclr opr, msk, rel– Opr Specifies the memory location to be checked and can be specified
using direct, extended, and all indexed addressing modes– Msk is an 8-bit mask that specifies the bits of the memory location to
be checked. Bits to be checked corresponds to the bit positions that are 1’s in the mask
– Rel is the branch offset and is specified in 8-bit relative mode.
• This instruction tells the HCS12 to perform a bitwise logical AND on the contents of the specified memory location and the mask supplied with the instruction, then branch if the result is zero.
ECE 2510 106
Bit Condition Branch
• Test bits against a mask to see if they are set (1) or cleared (0) and then branch based on the result
• Check the whether sets of bits are set (1) or cleared (0).brclr A, %01010101, Loop
brxxx address, bit_mask, loop_target
Mnemonic Function Equation or Operation
BRCLR Branch if selected bits clear (M) • (mm) = 0
BRSET Branch if selected bits set (~M) • (mm) = 0
ECE 2510 107
Bit Condition Branch Instructions
• Ex:Here: brclr $1020, $81, here ;$81=10000001
ldd #$AB2F
– The HCS12 will continue to execute the first instruction if the Most Significant bit and the least Significant bit of the memory location $1020 are 0
– Next instruction will be executed if MSb or LSb or both MSb and LSB are 1
ECE 2510 108
Solution: A number divisible by 4 would have the least significant two bits equal 0s.N = 20.org $1000array: .byte 2,3,4,8,12,13,19,24,33,32,20,18,53,52,80,82,90,94,100,102total: .blkb 1.text_main::
clr total ; initialize total to 0ldx #array ; use index register X as the array pointerldab #N ; use B as the loop count
loop: brclr 0,x,$03,yes ; check bits 1 and 0bra chkend
yes: inc totalchkend: inx
dbne b,loopswi
Write a program to compute the number of elements that are divisible by 4 in an array of N 8-bit elements. Use the repeat S until C looping construct.
Example 2.17: Repeat S until C
ECE 2510 109
Bit Condition Branch instructions
• Brset opr, msk, rel– Opr same as brclr instructions– Msk is an 8-bit mask that specifies the bits of the memory
location to be checked. Bits to be checked corresponds to the bit positions that are 1’s in the mask
– Rel same as brclr instruction
• The instruction tells the HCS12 to perform logical AND of the contents of the specified memory location inverted and the mask supplied with the instruction, then branch if the result is zero
• Branch occurs only if all bits corresponding to 1’s in the mask byte are 1’s
ECE 2510 110
Bit Condition branch Instructions
• Ex:– Loop:– Inc count– -----– -----– -----– Brset $1020, $E0, Loop
• The branch will be taken if the Most Significant three bits of the memory location $1020 are 1’s
ECE 2510 111
Advanced Loop Primitive Instructions
• A lot of the program loops are implemented by incrementing or decrementing a loop count– The branch is taken when either the loop count is equal to zero or
not equal to zero, depending on the application
• HCS12 provides a set of loop primitive instructions for implementing this type of looping mechanisms– These instructions test a counter value in a register or accumulator
for zero or non-zero value as a branch condition– There are predecrement, preincrement, and test-only versions of
these instructions
ECE 2510 112
Advanced Loop Primitive Instructions
• Incrementing, decrementing or Testing a counter that is built in to the instruction
Mnemonic Function Equation or Operation
DBEQ Decrement counter and branch if = 0, (counter = A, B, D, X, Y, or SP)
(counter) – 1 counter, If (counter) = 0, then branch; else continue to next instruction
DBNE Decrement counter and branch if ≠ 0, (counter = A, B, D, X, Y, or SP)
(counter) – 1 counter, If (counter) not = 0, then branch; else continue to next instruction
IBEQ Increment counter and branch if = 0, (counter = A, B, D, X, Y, or SP)
(counter) + 1 counter, If (counter) = 0, then branch; else continue to next instruction
IBNE Increment counter and branch if ≠ 0, (counter = A, B, D, X, Y, or SP)
(counter) + 1 counter, If (counter) not = 0, then branch; else continue to next instruction
TBEQ Test counter and branch if = 0, (counter = A, B, D, X,Y, or SP)
If (counter) = 0, then branch; else continue to next instruction
TBNE Test counter and branch if ≠ 0, (counter = A, B, D, X,Y, or SP)
If (counter) not = 0, then branch; else continue to next instruction
ECE 2510 113
Advanced Loop Primitive Instructions
Pre-Auto-Decrement counter register• DBEQ CNTR, rel Decrement counter and branch if = 0
– Subtract one from the specified counter register A, B, D, X, Y, or SP and branch to the specified relative destination if the counter register has reached zero
• DBNE CNTR, rel Decrement counter and branch if not = 0– Subtract one from the specified counter register A, B, D, X, Y, or SP and
branch to the specified relative destination if the counter register has not been decremented to zero
ECE 2510 114
Advanced Loop Primitive Instructions
Pre-Auto-Increment counter register• IBEQ CNTR, rel Increment and branch if = 0
– Add one to the specified counter register A, B, D, X, Y, or SP and branch to the specified relative destination if the counter register has reached zero
• IBNE CNTR, rel Increment and Branch if not = 0– Add one to the specified counter register A, B, D, X, Y, or SP and branch
to the specified relative destination if the counter register has not been decremented to zero
ECE 2510 115
Advanced Loop Primitive Instructions
Test counter register• TBEQ CNTR, rel Test and branch if Equal to Zero
– Tests the specified counter register A, B, D, X, Y, or SP and branches to the specified relative destination if the counter register is zero
• TBNE CNTR, rel Test and branch if not Equal to Zero– Tests the specified counter register A, B, D, X, Y, or SP and branches to
the specified relative destination if the counter register value is not zero
ECE 2510 116
Example: Advanced Loop Instructions
• Ex: Write a program to find the maximum number from an array of 10, 8-bit Unsigned Numbers
.area prog(abs)
.org $1020Array: .byte $01, $03, $05, $14, $13, $76, $33, $29, $11, $02
.text_main::
ldaa #$00ldab #$0Aldx #Array
Loop: cmpa 0,x bhi check_endldaa 0,x
check_end:inxdbne b, Loopstaa $1050swi
ECE 2510 117
Loop Primitive Instructions
ECE 2510 118
Loop Primitive Equivalence
• DBNE B, Loop1– decB– bne Loop1
• IBEQ X, Loop2– inX– beq Loop3
• TBNE A, Loop4 ;equivalence for A and B only– tstA– bne Loop5
ECE 2510 119
Additional Support for Loops/Branches
• Set the CCR but do not save the accumulator result– Compare Instructions– Test Instructions
Mnemonic Function Operation
CBA Compare A to B (A) – (B)
CMPA Compare A to memory (A) – (M)
CMPB Compare B to memory (B) – (M)
CPD Compare D to memory (16-bit) (A : B) – (M : M + 1)
CPS Compare SP to memory (16-bit) (SP) – (M : M + 1)
CPX Compare X to memory (16-bit) (X) – (M : M + 1)
CPY Compare Y to memory (16-bit) (Y) – (M : M + 1)
TST Test memory for zero or minus (M) – $00
TSTA Test A for zero or minus (A) – $00
TSTB Test B for zero or minus (B) – $00
ECE 2510 120
Compare and Test Instructions
• HCS12 has a set of compare instructions that are dedicated to the settings of condition flags (CCR)– Compare and test instructions perform subtraction between a pair
of registers or between a register and a memory location or between a register and an immediate value
– Result of the operation is not stored, but condition codes are set by the operation
• In HCS12, most instructions update condition code flags automatically, so it is often unnecessary to include a separate test or compare instructions, but they exist!
ECE 2510 121
Compare Data Instructions
• CBA Compare A to B– Compares the contents of accumulator A to the content of
accumulator B (A – B) and sets the condition codes– Condition code values can be used for arithmetic and logical
conditional branches– Contents of the accumulator A and B are not changing by this
operation
• CMPA Compare A to Memory– Compares contents of accumulator A to the contents of memory
location M (A – M) and sets the condition codes– Condition code values can be used for arithmetic and logical
conditional branches– Contents of the accumulator A or memory location M are not
changed
ECE 2510 122
Compare Data Instructions
• CMPB Compare B to memory– Similar to CMPA but contents of accumulator B are compared to
memory M
• CPD Compare D to memory– Compares the contents of double accumulator D with a 16-bit
value at the specified memory location and sets the condition codes– The compare is accomplished internally by a 16-bit subtract of
(M:M+1) from D– Contents of accumulator D or memory locations are not changed
ECE 2510 123
Compare Index Instructions
• CPX Compare Index register X– Compares the content of index register X with a 16-bit value at the
address specified and sets the condition codes accordingly– The compare is accomplished internally by a 16-bit subtract of
(M:M+1) from index register X– Contents of index registers X or Memory location are not changed
• CPY Compare Index register Y– Similar to CPX but compares index register Y with a 16-bit value
at the address specified and sets the condition codes accordingly
• CPS Compare SP to memory– Compares the contents of SP with a 16-bit value at the address
specified
LOOP EXAMPLES
ECE 2510 124
ECE 2510 125
Write a program to add an array of N 8-bit numbers and store the sum at memory locations $1000~$1001. Use the For i = n1 to n2 do looping construct.
Start
i 0sum 0
i = N?
no
sum sum + array[i]
i i + 1
Stop
Figure 2.9 Logic flow of example 2.14
yes
Solution:N = 20 ;array count
.org $1000 ; starting address on SRAMsum: .blkb 2 ; reserve 2-byte memory array sum, using
; 2-byte variablei: .blkb 1 ; array index, variable I as index
.text ;starting of the program_main::
ldaa #0staa istaa sum ; initializing sum 0staa sum+1 ; initializing sum 0
Example 2.14 (1)
continued
ECE 2510 126
Start
i 0sum 0
i = N?
no
sum sum + array[i]
i i + 1
Stop
Figure 2.9 Logic flow of example 2.14
yes
loop: ldab icmpb #N ; is i = N?beq doneldx #array ;use index reg X as a pointer to the arrayabx ; adds B to X to compute the address of
; array[i]ldab 0,X ; place array[i] in B, sum sum + array[i]ldy sum ; place sum in Yaby ; sum sum + array[i]sty sum ; update sum
inc i ; increment the loop count by 1bra loop
done: swi
array: .byte 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 ;define constant byte
Example 2.14 (2)
ECE 2510 127
Start
max_val array[0]i N-1
max_val < array[i] ?
max_val array[i]
yes
no
i i - 1
i = 0?
Stop
yes
no
Figure 2.10 Logic flow of example 2.15
Write a program to find the maximum element from an array of N 8-bit elements using the repeat S until C looping construct.
Solution: Next page
Example 2.15 (1)
ECE 2510 128
N = 20.org $1000max_val .blkb 1 ; memory location to hold array max.text ; start program_main::
ldaa array ; set array[0] as the temporary array maxstaa max_val ; “ldx #array+N-1 ; start from the end of the array ldab #N-1 ; use B to hold variable I and initialize to N - 1
loop: ldaa max_valcmpa 0,x ;compare max_val with array[i]bge chk_end ; no update if max_val is largerldaa 0,x ; update max_val or movb 0,X,max_valstaa max_val ; “
chk_end: dex ; move the array pointerdbne b,loop ; finish all the comparison yet?
forever: bra forever
Array: .byte 1,3,5,6,19,41,53,28,13,42,76,14.byte 20,54,64,74,29,33,41,45
Example 2.15 (2)
ECE 2510 129
More Instructions
• INC/DEC• AND/OR/EOR• COM/NEG• Shift and Rotate
ECE 2510 130
Decrementing and Incrementing Instructions
• Programs often need to add 1 or subtract 1 from a variable – Add or Subtract instructions can be used to achieve this, but would
be more efficient to use a single instruction– HCS12 has a few instructions to increment or decrement a variable
by 1
• DEC Decrement memory by 1 (M -1 M)• DECA Decrement accumulator A by 1 (A – 1 A)• DECB Decrement accumulator B by 1 (B – 1 B)• DES Decrement SP by 1 (SP – 1 SP) • DEX Decrement X by 1 (X – 1 X)• DEY Decrement Y by 1 (Y – 1 Y)
ECE 2510 131
Increment Instructions
• INC Increment memory by 1 (M +1 M)• INCA Increment accumulator A by 1 (A + 1 A)• INCB Increment accumulator B by 1 (B + 1 B)• INS Increment SP by 1 (SP + 1 SP) • INX Increment X by 1 (X + 1 X)• INY Increment Y by 1 (Y+ 1 Y)
ECE 2510 132
Boolean Logic Instructions
• Dealing with I/O port pins requires change of the values of a few bits– For these type of applications, the boolean logic instructions come
in handy
• Anda AND A with memory [A] and [M] A• Andb AND B with memory [B] and [M] B• Andcc AND CCR with memory [CCR] and [M]
CCR• Eora Ex-OR A with memory [A] ex-or [M] A• Eorb Ex-OR B with memory [B] ex-or [M] B• Oraa OR A with memory [A] or [M] A• Orbb OR B with memory [B] or [M] B
ECE 2510 133
Boolean Logic Instructions
• Orcc OR CCR with memory [CCR] or [M] CCR• Clc Clear C bit in CCR• Cli Clear I bit in CCR• Clv Clear V bit in CCR• Com One’s complement memory FF – [m] M• Coma One’s complement A FF – [A] A• Comb One’s complement B FF – [B] B• Neg 2’s complement memory• Nega 2’s complement A• Negb 2’s complement B
ECE 2510 134
Shift and Rotate Instructions
• Shift or Rotate instruction shifts or rotates the operand by one bit
• HCS12 has shift instructions that can operate on accumulators A, B and D or a memory location
ECE 2510 135
Shift and Rotate TableShift and Rotate Instructions
Mnemonic Function Operation Logical Shifts LSL LSLA LSLB
Logic shift left memory Logic shift left A Logic shift left B
LSLD Logic shift left D
LSR LSRA LSRB
Logic shift right memory Logic shift right A Logic shift right B
LSRD Logic shift right D
Arithmetic Shifts
ASL ASLA ASLB
Arithmetic shift left memory Arithmetic shift left A Arithmetic shift left B
ASLD Arithmetic shift left D
ASR ASRA ASRB
Arithmetic shift right memory Arithmetic shift right A Arithmetic shift right B
Rotates ROL ROLA ROLB
Rotate left memory through carry Rotate left A through carry Rotate left B through carry
ECE 2510 136
Logical Shift Left Instructions
• Lsl Logical Shift Left memory• Lsla Logical Shift Left A• Lslb Logical Shift Left B• Ldld Logical Shift Left D
ECE 2510 137
Logical Shift Instructions
• Ex:Ldaa #$95Lsla
Initial A
Result A
ECE 2510 138
Logical Shift Instruct
• Ex:Ldaa #$08 Produces a result of $8 * $2 = $10 = decimal 16Ldab #$02mul
• Can be implemented by
Ldaa #$08 ;0000 1000Lsla ;0001 0000 = $10 = decimal 16
ECE 2510 139
Logical Shift Right Instruct
• Lsr Logical Shift Right Memory• Lsra Logical Shift Right A• Lsrb Logical Shift Right B• Lsrd Logical Shift Right D
ECE 2510 140
Logical Shift Instructions
• Ex:Ldaa #$95Lsra
1 0 0 1 0 1 0 1
0 1 0 0 1 0 1 0
C
1
Initial A
Result A
ECE 2510 141
Logical Shift instructions
• Logical Shift Right instructions can be implemented when performing division of Unsigned numbers
• EX:• 32/4 = 8 $20/$4 • Can be implemented by Logical Shift Right the operand
twiceldaa #$20 ; (A)=$20=0010 0000 Lsra ; 0001 0000 $10 Decimal 16Lsra ; 0000 1000 $08
ECE 2510 142
Arithmetic Shift Left Instructions
• Asl Arithmetic Shift Left Memory• Asla Arithmetic Shift Left A• Aslb Arithmetic Shift Left B• Asld Arithmetic Shift Left D
• Arithmetic Shift left instructions are similar to Logical Shift Left instructions
ECE 2510 143
Arithmetic Shift Right Instructions
• Asr Arithmetic Shift Right Memory• Asra Arithmetic Shift Right A• Asrb Arithmetic Shift Right B
• Note: no D version
ECE 2510 144
Arithmetic Shift Instructions
• Arithmetic Shift Right instructions plays a major role when performing division of signed numbers by an operand that is a power of 2
• Ex:• -8/2 = -4• -8 in two’s complement representation is • 0000 1000 1’s Complement 1111 0111• 2’s Complement + 1• -------------------• 11111000
Ldaa #$F8 ; (A)=11111000 = -8Asra ; (A)=11111100 = -4
ECE 2510 145
Rotate Instructions
• Rol Rotate Left Memory through Carry• Rola Rotate Left A through Carry• Rolb Rotate Left B through Carry
b7 b0
C
ECE 2510 146
Rotate instructions
• Ex: CCR Carry Flag = 1Ldab #$BD 10111101Rolb when executed
• C B7 -------------------B0• 1 1 0 1 1 1 1 0 1• Rolb produces a result of• C B7 -------------------B0• 1 0 1 1 1 1 0 1 1
Original value New value
[B] = 10111101C = 1
[B] = 01111011C = 1
Figure 14b. Execution result of ROLB
1 1 1 1 1 0 10
0 01 1 1 1 1 1 1
1
Figure 2.14a Operation of the instruction ROLB
accumulator B
C flag
ECE 2510 147
Rotate Instructions
• Ror Rotate Right memory through carry• Rora Rotate Right A through carry• Rorb Rotate Right B through carry
b7 b0
C
ECE 2510 148
Rotate Instructions
• Ex: CCR Carry flag = 1Ldab #$BD ; 1011 1101Rolb ; when executed
• C B7 -------------------B0• 1 1 0 1 1 1 1 0 1• Rolb produces a result of• C B7 -------------------B0• 1 1 1 0 1 1 1 1 0
ECE 2510
Write a program to count the number of 0s in the 16-bit number stored at $1000-$1001 and save the result in $1005.Solution:
* The 16-bit number is shifted to the right 16 time.* If the bit shifted out is a 0 then increment the 0s count by 1.
.org $1000indata: .byte $23,$55 ; test datazero_cnt .blkb 1lp_cnt .blkb 1.text_main::
clr zero_cnt ; initialize the 0s count to 0ldaa #16 ; the bits in a wordstaa lp_cntldd indata ; place the number in D
Loop: lsrd ; shift the lsb of D to the C flagbcs chkend ; is the C flag a 0?inc zero_cnt ; increment 1s count if the lsb is a 1
chkend: dec lp_cnt ; check to see if D is already 0bne loopswi
Example 2.23
ECE 2510 150
Shift a Multi-byte Number (1 of 3)
• For shifting right– The bit 7 of each byte will receive the bit 0 of its immediate left
byte with the exception of the most significant byte which will receive a 0.
– Each byte will be shifted to the right by 1 bit. The bit 0 of the least significant byte will be lost.
• Suppose there is a k-byte number that is stored at loc to loc+k-1.– Method for shifting right
• Step 1: Shift the byte at loc to the right one place.• Step 2: Rotate the byte at loc+1 to the right one place.• Step 3: Repeat Step 2 for the remaining bytes.
ECE 2510 151
Shift a Multi-byte Number (2 of 3)
• For shifting left– The bit 0 of each byte will receive the bit 7 of its immediate right
byte with the exception of the least significant byte which will receive a 0.
– Each byte will be shifted to the left by 1 bit. The bit 7 of the most significant byte will be lost.
• Suppose there is a k-byte number that is stored at loc to loc+k-1.– Method for shifting left
• Step 1: Shift the byte at loc+k-1 to the left one place.• Step 2: Rotate the byte at loc+k-2 to the left one place.• Step 3: Repeat Step 2 for the remaining bytes.
ECE 2510 152
ldab #4 ; set up the loop countldx #$1120 ; use X as the pointer to the left most byte
lsr32N: lsr 0,X ; logical shift right memoryror 1,X ; rotate right memory though carryror 2,X ; rotate right memory though carryror 3,X ; rotate right memory through carrydbne b, lsr32N ; decrement the counter and branch if not zero
Shift a Multi-byte Number (3 of 3)
• Example 2.24 Write a program to shift the 32-bit number stored at $1120-$1123 to the right four places.
• Solution:
ECE 2510 153
Bit Test and Manipulate Instruction
• These instructions use a mask value to test or change the value of individual bits in an accumulator or in a memory location
Bit Test and Manipulation Instructions Mnemonic Function Operation
BCLR Clear bits in memory (M) • (not(mm)) M
BITA Bit test A (A) • (M)
BITB Bit test B (B) • (M)
BSET Set bits in memory (M) + (mm) M
ECE 2510 154
Bit Test Instruction
• Bita <opr>• Bitb <opr>
– These instructions provide a convenient means of testing bits without altering the value of either operand
• Bita #$44– Tests bit 6 and bit 2 of accumulator A and updates the Z and N
flags of the CCR register accordingly
• Bitb #$22– Tests bit 5 and bit 1 of the accumulator B and updates the Z and N
flags of CCR register accordingly
ECE 2510 155
Bit Manipulate Instruction
• Bclr <opr>, msk8 clear bits in memory– Opr can be specified using direct, extended, and indexed
(exclude Indirect) addressing modes– Msk8 msk8 is an 8-bit value
• Bset <opr>, msk8 set bits in memory– Opr can be specified using direct, extended, and indexed
(exclude Indirect) addressing modes– Msk8 msk8 is an 8-bit value
• Ex:Bclr 0,x,$81 clears the most significant and least significant bits of
the memory location pointed to by index registerBclr $1020,$FF clears the contents of memory location $1020 to
$FF
STACKS
ECE 4510/5530
156
ECE 2510 157
Simple Stack Operations
• A simple means to store and retrieve register values temporarilyStack Operation Instructions
Mnemonic Function Operation
PSHA Push A (SP) – 1 SP; (A) M(SP)
PSHB Push B (SP) – 1 SP; (B) M(SP)
PSHC Push CCR (SP) – 1 SP; (A) M(SP)
PSHD Push D (SP) – 2 SP; (A : B) M(SP) : M(SP+1)
PSHX Push X (SP) – 2 SP; (X) M(SP) : M(SP+1)
PSHY Push Y (SP) – 2 SP; (Y) M(SP) : M(SP+1)
PULA Pull A (M(SP)) A; (SP) + 1 SP
PULB Pull B (M(SP)) B; (SP) + 1 SP
PULC Pull CCR (M(SP)) CCR; (SP) + 1 SP
PULD Pull D (M(SP) : M(SP+1)) A : B; (SP) + 2 SP
PULX Pull X (M(SP) : M(SP+1)) X; (SP) + 2 SP
PULY Pull Y (M(SP) : M(SP+1)) Y; (SP) + 2 SP
ECE 2510 158
Stack Memory
pshA ; A=$55, SP=$3C00pre-decrement SP
$55
low address
Stack pointer
$3C00
empty
empty
empty
empty
$3BFF
pulD ; Read stack wordpost-increment SP twice
$34
low address
Stack pointer
$3C00
$12
$CD
$AB
empty
$3BFF
$3BFE
$3BFD
$3BFC
low address
Stack pointer
$3C00
empty
$3BFF $34$12$3BFE
$3BFD
$3BFC
$CD
$AB
SP = $3BFF D=A:B=$ABCD, SP = $3BFE
ECE 2510 159
Stack Worksheet
• This worksheet is on line for “planning” stack operations– Initialize the SP to $3C00
lds #$3C00– Keep track of data and SP
address content comment $3BE0 $3BE1 $3BE2 $3BE3 $3BE4 $3BE5 $3BE6 $3BE7 $3BE8 $3BE9 $3BEA $3BEB $3BEC $3BED $3BEE $3BEF $3BF0 $3BF1 $3BF2 $3BF3 $3BF4 $3BF5 $3BF6 $3BF7 $3BF8 $3BF9 $3BFA $3BFB $3BFC $3BFD $3BFE $3BFF $3C00 Do Not Use Stack Pointer Should Start Here
SOFTWARE TIME DELAY
ECE 4510/5530
160
ECE 2510 161
Creating Time Delays
• There are many applications that require the generation of time delays. – Program loops are often used to create a certain amount of delay
unless the time delay needs to be very accurate.
• The creation of a time delay involves two steps:– Select a sequence of instructions that takes a certain amount of
time to execute. (a basic unit)– Repeat the selected instruction sequence for an appropriate number
of times. (Delay = Number x basic unit)
ECE 2510 162
Program Execution Time
• The HCS12 uses the bus clock (E clock) as a timing reference.– The frequency of the E clock is half of that of the onboard clock
oscillator (clock, 48 MHz, E-clock, 24 MHz).– Execution times of the instructions are also measured in E clock
cycles
• Execution times of each instruction can be obtained from Appendix A of the textbook or from the reference manual– Number of letters in the column “Access Detail” of Appendix A
indicates the number of E cycles that a specific instruction takes to execute that particular instruction
– For example access detail column of PULA instruction contains three letters UFO which indicates that the PULA instruction takes 3 E cycles to complete
ECE 2510 163
Program Execution Time
• Speed of the E clock varies from controller to controller– Higher E clock indicates higher processing times– The E clock for the HCS12 is 24 MHz = 41.67ns– The least amount of time HCS12 takes to execute an instruction is
41.67ns– So HCS12 can only be used in applications that require a per
instruction computation time of >= 41.67ns
• How to Computing Program Execution Time– Count all the E Cycles in the code– Multiply by 41.67 nsec
ECE 2510 164
Program Execution Time
Example:• The following instruction takes 14E cycles for 1 loop
Loop: psha ; 2E cyclespula ; 3E cyclespsha ; 2E cyclespula ; 3E cyclesnop ; 1E cycleDbne X,Loop ; 3E cycles condition not satisfied
; 3E cycle condition satisfied– Assume that the HCS12 runs under a crystal oscillator with a
frequency of 16 MHz, with an E freq. of 8 MHz.The E-clock period is then 125 ns.
– Therefore, each repeated loop would take 14*125=1750ns=1.75us to execute. Total delay 1.75usec x X_value
ECE 2510 165
Program Execution Time
• Example: find delay created if E = 41.67ns = 1/24 MHz.ldx #$1234 ; 2E
Loop1:ldy #$ABCD ; 2E
Loop2: dbne Y, Loop2 ; 3E taken/3E notdbne X, Loop1 ; 3E taken/3E not
• Total time – Inner loop: (2 + ($ABCD-1)*3 + 3) E Cycles – Assume IL ≈ (($ABCD)*3 )*41.67ns ≈ 43981*3/24 MHz – IL = 0.005497625 sec– Outer loop: (2+$1234*IL+($1234-1)*3 +3) * 41.67ns– Total = ($1234*$ABCD*3+$1234*(3+2)+2) * 41.67ns– Total ≈ (4660*(43981)*3) /24 MHz ≈ 25.629515 sec
ECE 2510 166
Program Execution
• How many E cycles in 0.001 sec?– 24 MHz * 0.001 sec 24000 E-cycles– Or 8000*3 inner loops. Use $1F40
• How many inner loops needed for 1 sec?– 1 sec/0.001 sec 1000 or $03E8
• If we used these numbers in the last program …– Total = ($03E8*$1F40*3 +$03E8 *5+2) * 41.67ns– Total ≈ (1000*(8000)*3) /24 MHz ≈ 1.000 sec
(off by ~ 208 usec)
• Comment: if the average instruction requires 3 E cycles– The machine would average 24/3 8 Mips
ECE 2510 167
Loop: psha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclespsha ; 2 E cyclespula ; 3 E cyclesnop ; 1 E cyclenop ; 1 E cycledbne d,loop ; 3 E cycles when condition is not satisfied
; 3 E cycles when condition is satisfied
Program Execution Time
000,000,24
3371337 regD
Time
ECE 2510 168
Write a program loop to create a delay of 100 ms, assuming E=125ns..Solution: A delay of 100 ms can be created by repeating the previous loop 20,000 times.The following instruction sequence creates a delay of 100 ms.
ldx #20000 ; 2 E cyclesloop psha ; 2 E cycles
pula ; 3 E cyclespshapulapshapulapshapulapshapulapshapulapshapulanop ; 1 E cyclenop ; 1 E cycledbne x,loop ; 3 E cycles/3 E cycles
(2(ldx)+40*(20000-1)+ 40)*E ≈ 20000*E ≈ 20000*125ns ≈ 100ms.
Software Delay: Example 2.25
MHz
DTime reg
000,000,8401402
sec
401402000,800 regD
204$000,20 EDreg
ECE 2510 169
ldab #100out_loop ldx #20000in_loop psha ; 2 E cycles
pula ; 3 E cyclespshapulapshapulapshapulapshapulapshapulapshapulanop ; 1 E cyclenop ; 1 E cycledbne x,in_loop ; 3 E cyclesdbne b,out_loop ; 3 E cycles
Write an instruction sequence to create a delay of 10 seconds.Solution: By repeating the previous instruction sequence 100 times, we can create a delay of approximately 10 seconds.
Example 2.26
ECE 2510 170
Software Time Delays
• Time delays created by program loops are not accurate– Some overhead is required to set up the loop count– To reduce the overheads one can adjust the number to be placed in
the index registers– By doing so one can achieve closer to the required time delays
• Program loops are not advisable to use in applications requiring precise timing calculation– Interrupts may exist that could significantly change time delays
• Typically, Microcontroller Timer modules are used in applications requiring precise timing calculations– Enhanced Capture Timer– 8 PWM channels