EMCH 367 Microcontrollers in Mechanical Engineering

Transcription

EMCH 367 Microcontrollers in Mechanical Engineering
EMCH 367
Microcontrollers
in
Mechanical Engineering
http://www.me.sc.edu/courses/emch367
USC-DME Notes, Edition 8/19/08, revised by Victor Giurgiutiu
© 2006 Victor Giurgiutiu
Dr. Victor Giurgiutiu
8/19/2008
Dr. Victor Giurgiutiu
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
TABLE OF CONTENTS
GENERAL INFORMATION ................................................................................................................................. 1
SYLLABUS .............................................................................................................................................................. 1
Instructional Objectives ..................................................................................................................................... 1
Course Description ............................................................................................................................................ 2
Topics................................................................................................................................................................. 2
GRADING POLICY ................................................................................................................................................... 2
HOMEWORK REQUIREMENTS ................................................................................................................................. 3
LABORATORY REQUIREMENTS .............................................................................................................................. 3
PROJECT REQUIREMENTS ....................................................................................................................................... 3
ELECTRONIC FILES REQUIREMENTS ....................................................................................................................... 3
NOTES: THE NETWORK ADDRESS FOR PLACING THE HOMEWORK AND LAB REPORT FILES WILL BE PROVIDED BY
YOUR TA. ............................................................................................................................................................... 3
ADDITIONAL REFERENCES ..................................................................................................................................... 4
TEST FORMAT ......................................................................................................................................................... 4
EMCH 367 LAB....................................................................................................................................................... 5
LAB OBJECTIVE ...................................................................................................................................................... 5
LAB GRADING POLICIES......................................................................................................................................... 6
LAB POLICIES ......................................................................................................................................................... 6
EMCH 367 PROJECT ........................................................................................................................................... 6
PROJECT OBJECTIVE............................................................................................................................................... 6
HOW THE PROJECT WILL WORK ............................................................................................................................ 7
PROJECT PROCEDURE ............................................................................................................................................. 9
Getting Partners: ............................................................................................................................................... 9
Writing the Project Proposal ............................................................................................................................. 9
Project Presentation ........................................................................................................................................ 10
Project Report.................................................................................................................................................. 10
Guidance on cost estimation ............................................................................................................................ 10
ANSWERS TO FREQUENTLY ASKED QUESTIONS .................................................................................................. 11
Where do I get project ideas? .......................................................................................................................... 11
Once I have an idea, what do I do? ................................................................................................................. 11
How do I get assistance from my TA's? ........................................................................................................... 11
When do I sign up for my project presentation? .............................................................................................. 12
When and how do I get hardware for the project? .......................................................................................... 12
When is the lab available for project work? .................................................................................................... 12
PROJECT GRADING POLICY .................................................................................................................................. 13
PROGRAMMING THE MICROCONTROLLER ............................................................................................ 14
THRSIM11 SIMULATOR ....................................................................................................................................... 14
THRSim11 Options setup ................................................................................................................................. 14
Getting Started with Programming.................................................................................................................. 16
Using the template.asm File............................................................................................................................. 16
Screen/Window Capture .................................................................................................................................. 16
Default Windows.............................................................................................................................................. 17
MiniIDE Emulator ........................................................................................................................................... 19
PROGRAMMING FLOW CHART ............................................................................................................................. 21
BINARY AND HEX NUMBERS ............................................................................................................................... 23
The Binary System............................................................................................................................................ 23
Dr. Victor Giurgiutiu
Page i
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
Decimal to Binary Conversion: ....................................................................................................................... 24
Hexadecimal (Hex) Numbers ........................................................................................................................... 24
Binary Arithmetic............................................................................................................................................. 25
Negative Numbers in the Computer (2’s Complement numbers)..................................................................... 25
Numerical Conversion Chart for unsigned 8-bit binary integers .................................................................... 27
Numerical Conversion Chart for 2's complement signed 8-bit binary integers .............................................. 28
LOGIC GATES AND BOOLEAN ALGEBRA................................................................................................... 29
Logic Gates ...................................................................................................................................................... 29
Boolean Algebra .............................................................................................................................................. 31
CONDITION CODE REGISTER (CCR) .................................................................................................................... 32
BUFFALO COMMANDS ....................................................................................................................................... 33
BUFFALO COMMANDS ....................................................................................................................................... 33
DEBUGGING TIPS.................................................................................................................................................. 39
Microcontroller Problems ............................................................................................................................... 39
Hardware Problems......................................................................................................................................... 39
Software Problems ........................................................................................................................................... 39
THRSIM11 SIMULATION OF PARALLEL COMMUNICATION ................................................................................. 40
The THRSim11IO Box...................................................................................................................................... 41
ASCII AND BCD CODES................................................................................................................................... 42
THRSim11 Simulation of Serial Communication............................................................................................. 43
The THRSim11 Serial Transmitter................................................................................................................... 44
The THRSim11Serial Receiver......................................................................................................................... 45
THRSIM11 SIMULATION OF TIMER FUNCTIONS .................................................................................................. 46
THRSIM11 SIMULATION OF ANALOG TO DIGITAL CONVERSION ........................................................................ 47
EE ENGINEERING BASICS ............................................................................................................................... 48
BASIC MULTIMETER OPERATION ......................................................................................................................... 49
Basic Multimeter Information.......................................................................................................................... 49
Basic Measurement Procedures....................................................................................................................... 49
Multimeter Troubleshooting ............................................................................................................................ 49
BASIC OSCILLOSCOPE OPERATION ...................................................................................................................... 50
Basic Measurement Principles......................................................................................................................... 50
Trigger ............................................................................................................................................................. 51
Oscilloscope Troubleshooting.......................................................................................................................... 51
RESISTORS ............................................................................................................................................................ 52
Chart To Read Resistors .................................................................................................................................. 52
Resistors Available in the EMCH 367 Lab ...................................................................................................... 52
EMITTER-DETECTOR ............................................................................................................................................ 53
OPEN COLLECTOR COMPARATOR ......................................................................................................................... 54
OPEN COLLECTOR BUFFER .................................................................................................................................... 55
OP AMP ................................................................................................................................................................. 56
POWER TRANSISTOR ............................................................................................................................................. 56
PORT PROTECTION................................................................................................................................................ 57
generic input to microcontroller ports............................................................................................................. 57
port a protection .............................................................................................................................................. 58
optoisolator (open collector) ........................................................................................................................... 58
KEYBOARD AND DISPLAY CIRCUITS ..................................................................................................................... 59
EMCH367 HARDWARE LIST................................................................................................................................. 60
INTRODUCTION TO FUNCTIONAL MODULES ......................................................................................................... 65
ATTACHMENT 1: EMCH 367 PROJECT PROPOSAL ................................................................................. 66
Dr. Victor Giurgiutiu
Page ii
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
ATTACHMENT 2: PROJECT REPORT TEMPLATE.................................................................................... 67
1. EXECUTIVE SUMMARY ..................................................................................................................................... 71
2. INTRODUCTION ................................................................................................................................................. 71
3. TECHNICAL DESCRIPTION ................................................................................................................................ 71
3.1 System Overview ...................................................................................................................................... 71
3.2 Hardware Design ..................................................................................................................................... 71
3.3 Software Design........................................................................................................................................ 71
3.4 Acceptance Tests ...................................................................................................................................... 71
4. ECONOMIC ASPECTS......................................................................................................................................... 72
4.1 Prototype Costs ........................................................................................................................................ 72
4.2 Production Costs, Production Price, and Retail Price.......................................................................... 72
4.3 Commercial Feasibility............................................................................................................................ 72
5. CONCLUSIONS .................................................................................................................................................. 73
6. REFERENCES ..................................................................................................................................................... 73
ATTACHMENT 3: PRESENTATION TEMPLATE ........................................................................................ 74
EXAMPLES ........................................................................................................................................................... 76
EXAMPLES OVERVIEW.................................................................................................................................... 77
EXAMPLE 1........................................................................................................................................................... 82
OBJECTIVE............................................................................................................................................................ 82
PROGRAM ............................................................................................................................................................. 82
EXECUTION ........................................................................................................................................................... 82
WHAT YOU HAVE LEARNED ................................................................................................................................. 86
EXAMPLE 2........................................................................................................................................................... 88
OBJECTIVE............................................................................................................................................................ 88
PROGRAM ............................................................................................................................................................. 88
EXECUTION ........................................................................................................................................................... 88
WHAT YOU HAVE LEARNED ................................................................................................................................. 91
EXAMPLE 3........................................................................................................................................................... 94
OBJECTIVE............................................................................................................................................................ 94
PROGRAM ............................................................................................................................................................. 94
EXECUTION ........................................................................................................................................................... 94
WHAT YOU HAVE LEARNED ................................................................................................................................. 95
EXAMPLE 4........................................................................................................................................................... 96
OBJECTIVE............................................................................................................................................................ 96
PROGRAM ............................................................................................................................................................. 96
EXECUTION ........................................................................................................................................................... 96
Path 1 ............................................................................................................................................................... 98
Path 2 ............................................................................................................................................................. 100
WHAT YOU HAVE LEARNED ............................................................................................................................... 101
EXAMPLE 5......................................................................................................................................................... 102
OBJECTIVE.......................................................................................................................................................... 102
PROGRAM ........................................................................................................................................................... 102
EXECUTION ......................................................................................................................................................... 102
WHAT YOU HAVE LEARNED ............................................................................................................................... 103
Dr. Victor Giurgiutiu
Page iii
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
EXAMPLE 6......................................................................................................................................................... 104
OBJECTIVE.......................................................................................................................................................... 104
PROGRAM ........................................................................................................................................................... 104
EXECUTION ......................................................................................................................................................... 105
WHAT YOU HAVE LEARNED ............................................................................................................................... 109
EXAMPLE 7......................................................................................................................................................... 110
OBJECTIVE.......................................................................................................................................................... 110
PROGRAM ........................................................................................................................................................... 110
CODING AND EXECUTION ................................................................................................................................... 110
Section: 15 + 27 = 42 (decimal) using the opcode mnemonics LDAA, LDAB, ABA..................................... 111
Section: $0f + $1b = $2a (hex half-carry) using the opcode mnemonics LDAA, LDAB, ABA ..................... 112
$ff + $01 = $00 (MSB carry) using the opcode mnemonics LDAA, ADDA .................................................. 115
255 + 1 = 0 (decimal equivalent of hex MSB carry) using the opcode mnemonics LDAA, ADDA............... 116
WHAT YOU HAVE LEARNED ............................................................................................................................... 118
EXAMPLE 8......................................................................................................................................................... 120
OBJECTIVE.......................................................................................................................................................... 120
PROGRAM ........................................................................................................................................................... 120
CODING AND EXECUTION ................................................................................................................................... 120
Section: 7 – 1 = 6 (decimal) using the opcode mnemonics LDAA, SUBA..................................................... 122
Section: $07 - $01 = $06 (hex) using the opcode mnemonics LDAA, SUBA................................................. 123
Section: 10 - 1 = 9 (decimal) using the opcode mnemonics LDAA, SUBA.................................................... 124
Section: $10 - $01 = $0f (hex) using the opcode mnemonics LDAA, SUBA.................................................. 125
Section: $00 - $01 = $ff (hex) using the opcode mnemonics LDAA, SUBA .................................................. 126
Section: 0 - 1 = 255 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA, SUBA
....................................................................................................................................................................... 127
using calculator to obtain hex negative numbers for –100............................................................................ 127
WHAT YOU HAVE LEARNED ............................................................................................................................... 128
EXAMPLE 9......................................................................................................................................................... 130
OBJECTIVE.......................................................................................................................................................... 130
PROGRAM ........................................................................................................................................................... 130
CODING AND EXECUTION ................................................................................................................................... 131
Section: $0d - $06 = $07 (hex) using the opcode mnemonics LDAA, LDAB, SBA........................................ 132
Section: $00 - $05 = $fb (hex) using the opcode mnemonics LDAA, LDAB, SBA ........................................ 133
Section: 0 - 5 = 251 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA, LDAB,
SBA................................................................................................................................................................. 134
Section: $0e - $3a = $d4 (hex) using the opcode mnemonics LDAA, LDAB, SBA........................................ 135
Section: 14 - 58 = 212 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
LDAB, SBA..................................................................................................................................................... 136
WHAT YOU HAVE LEARNED ............................................................................................................................... 137
EXAMPLE 10....................................................................................................................................................... 139
OBJECTIVE.......................................................................................................................................................... 139
PROGRAM ........................................................................................................................................................... 139
CODING AND EXECUTION ................................................................................................................................... 140
Section: Represent numbers one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen,
fourteen, fifteen, sixteen, seventeen in decimal, binary, and hex .................................................................. 141
Section: Perform 3 + 2 = 5 in binary and hex using LDAA, LDAB, ABA ..................................................... 146
Dr. Victor Giurgiutiu
Page iv
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
Section: Perform 13 – 6 =7 in binary and hex using LDAA, LDAB, SBA ..................................................... 148
Section: Perform $0f + $01 = $10 in binary and hex using LDAA, ADDA (half carry or bit 3 carry)......... 151
Section: Perform $10 -$01 = $0f in binary and hex using LDAA, SUBA...................................................... 155
Section: Perform $ff + $01 = $00 in binary and hex using LDAA, ADDA (MSB carry) .............................. 156
Section: Perform $00 - $01 = $ff in binary and hex using LDAA, SUBA...................................................... 159
Section: 1 AND 0 = 0 using LDAA, ANDA ................................................................................................... 161
Section: 1 OR 0 = 1 using LDAA, ORAA ...................................................................................................... 162
Section: 1 XOR 0 = 1 using LDAA, EORA.................................................................................................... 163
Section: 1 OR 1 = 1 using LDAA, ORAA ...................................................................................................... 164
Section: 1 XOR 1 = 0 using LDAA, EORA.................................................................................................... 165
Section: %11111111 NAND %00000000 = %11111111 using LDAA, ANDA, COMA ............................... 166
Section: %00000000 NOR %11111111 = %00000000 using LDAA, ORAA, COMA .................................. 168
Section: %10101110 AND %00000010 = %00000010 using LDAA, ANDA (masking)............................... 170
WHAT YOU HAVE LEARNED ............................................................................................................................... 172
EXAMPLE DELAY............................................................................................................................................. 175
OBJECTIVE ...................................................................................................................................................... 175
PROGRAM ........................................................................................................................................................... 175
CODING ............................................................................................................................................................... 175
EXECUTION ......................................................................................................................................................... 176
WHAT YOU HAVE LEARNED ............................................................................................................................... 184
EXAMPLE SQUARE WAVE............................................................................................................................. 185
OBJECTIVE ...................................................................................................................................................... 185
PROGRAMS.......................................................................................................................................................... 185
Program sq_wav1 .......................................................................................................................................... 186
FLOWCHART AND CODE ..................................................................................................................................... 186
EXECUTION ......................................................................................................................................................... 186
Program sq_wav2 .......................................................................................................................................... 194
FLOWCHART AND CODE ..................................................................................................................................... 194
EXECUTION ......................................................................................................................................................... 194
WHAT YOU HAVE LEARNED ............................................................................................................................... 197
EXAMPLE BUTTONS BOX.............................................................................................................................. 199
OBJECTIVE ...................................................................................................................................................... 199
PROGRAMS.......................................................................................................................................................... 199
Program Buttons_bx ...................................................................................................................................... 199
FLOWCHART AND CODE ..................................................................................................................................... 199
EXECUTION ......................................................................................................................................................... 200
WHAT YOU HAVE LEARNED ............................................................................................................................... 202
EXAMPLE SCI TRANSMISSION .................................................................................................................... 203
OBJECTIVE ...................................................................................................................................................... 203
PROGRAM SCI_TRANSMIT .................................................................................................................................... 203
FLOWCHART AND CODE ..................................................................................................................................... 203
EXECUTION ......................................................................................................................................................... 203
WHAT YOU HAVE LEARNED ............................................................................................................................... 207
EXAMPLE SCI RECEPTION ........................................................................................................................... 209
OBJECTIVE ...................................................................................................................................................... 209
PROGRAM SCI_RECEPT ...................................................................................................................................... 209
Dr. Victor Giurgiutiu
Page v
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
FLOWCHART AND CODE ..................................................................................................................................... 209
EXECUTION ......................................................................................................................................................... 209
WHAT YOU HAVE LEARNED ............................................................................................................................... 212
EXAMPLE INPUT CAPTURE TIMER FUNCTION ..................................................................................... 213
OBJECTIVE ...................................................................................................................................................... 213
PROGRAM EX_IC................................................................................................................................................ 213
FLOWCHART AND CODE ..................................................................................................................................... 213
EXECUTION ......................................................................................................................................................... 215
WHAT YOU HAVE LEARNED ............................................................................................................................... 220
EXAMPLE OUTPUT COMPARE TIMER FUNCTION................................................................................ 221
OBJECTIVE ...................................................................................................................................................... 221
PROGRAM EX_OC............................................................................................................................................... 221
FLOWCHART AND CODE ..................................................................................................................................... 221
EXECUTION ......................................................................................................................................................... 223
WHAT YOU HAVE LEARNED ............................................................................................................................... 231
EXAMPLE RPM_1 ............................................................................................................................................. 233
OBJECTIVE ...................................................................................................................................................... 233
PROGRAM EX_RPM_1 ....................................................................................................................................... 233
FLOWCHART AND CODE ..................................................................................................................................... 234
EXECUTION ......................................................................................................................................................... 235
WHAT YOU HAVE LEARNED ............................................................................................................................... 242
EXAMPLE RPM_2 ............................................................................................................................................. 243
OBJECTIVE ...................................................................................................................................................... 243
PROGRAM EX_RPM_2 ....................................................................................................................................... 243
FLOWCHART AND CODE ..................................................................................................................................... 244
EXECUTION ......................................................................................................................................................... 245
Example 1....................................................................................................................................................... 245
Example 2....................................................................................................................................................... 249
WHAT YOU HAVE LEARNED ............................................................................................................................... 252
EXAMPLE STEP................................................................................................................................................. 253
OBJECTIVE ...................................................................................................................................................... 253
PROGRAM EX_STEP .......................................................................................................................................... 253
FLOWCHART AND CODE ..................................................................................................................................... 255
EXECUTION ......................................................................................................................................................... 257
Case ‘Slow-Forward’ (STEP=$01) ............................................................................................................... 259
Case ‘Full-Forward’ (STEP=$02) ................................................................................................................ 266
Case ‘Half-Backward’ (STEP=$ff)................................................................................................................ 266
Case ‘Full-Backward (STEP=$fe)................................................................................................................. 266
WHAT YOU HAVE LEARNED ............................................................................................................................... 267
EXAMPLE LONG DELAY................................................................................................................................ 269
OBJECTIVE ...................................................................................................................................................... 269
PROGRAM EX_LONG_DELAY ............................................................................................................................. 269
FLOWCHART AND CODE ..................................................................................................................................... 270
EXECUTION ......................................................................................................................................................... 270
WHAT YOU HAVE LEARNED ............................................................................................................................... 272
Dr. Victor Giurgiutiu
Page vi
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
EXAMPLE SORT................................................................................................................................................ 273
OBJECTIVE ...................................................................................................................................................... 273
PROGRAM EX_SORT ........................................................................................................................................... 273
FLOWCHART AND CODE ..................................................................................................................................... 274
EXECUTION ......................................................................................................................................................... 276
Check the keystroke command > (forward)................................................................................................... 277
Check the keystroke command < (backward) ................................................................................................ 280
Check the keystroke command +(increase speed) ......................................................................................... 282
Check the keystroke command -(decrease speed).......................................................................................... 285
Check the keystroke command S (stop).......................................................................................................... 287
Further checks ............................................................................................................................................... 287
WHAT YOU HAVE LEARNED ............................................................................................................................... 288
EXAMPLE – A/D CONVERTER ...................................................................................................................... 289
OBJECTIVE.......................................................................................................................................................... 289
PROGRAM A/D CONVERTER ............................................................................................................................... 289
Single channel, single conversion, Mult=0, Scan=0 ..................................................................................... 289
FLOWCHART AND CODE ..................................................................................................................................... 289
EXECUTION ......................................................................................................................................................... 290
Single channel, continuous conversion, Mult=0, Scan=1 ............................................................................. 295
Multiple channel, Single Conversion, Mult=1, Scan=0 ................................................................................ 296
Multiple channel, Continuous conversion, Mult=1, Scan=1......................................................................... 298
WHAT YOU HAVE LEARNED ............................................................................................................................... 300
HOMEWORK ASSIGNMENTS........................................................................................................................ 301
EXERCISE 1 ........................................................................................................................................................ 303
GENERAL NOTE .................................................................................................................................................. 303
OBJECTIVE.......................................................................................................................................................... 303
PROGRAM ........................................................................................................................................................... 303
CODING AND EXECUTION ................................................................................................................................... 303
WHAT YOU HAVE LEARNED ............................................................................................................................... 305
EXERCISE 2 ........................................................................................................................................................ 307
GENERAL NOTE .................................................................................................................................................. 307
OBJECTIVE.......................................................................................................................................................... 307
PROGRAM ........................................................................................................................................................... 307
CODING AND EXECUTION ................................................................................................................................... 307
WHAT YOU HAVE LEARNED ............................................................................................................................... 309
EXERCISE 3-7..................................................................................................................................................... 311
GENERAL NOTE .................................................................................................................................................. 311
OBJECTIVE.......................................................................................................................................................... 311
PROGRAM ........................................................................................................................................................... 312
CODING AND EXECUTION ................................................................................................................................... 312
Section: 8 + 7 = 15 (decimal) using the opcode mnemonics LDAA, LDAB, ABA......................................... 312
Section: $08 + $07 = $0f (hex) using the opcode mnemonics LDAA, LDAB, ABA....................................... 312
Section: 9 + 9 = 18 (decimal) using the opcode mnemonics LDAA, LDAB, ABA......................................... 313
Section: $09 + $09 = $12 (hex) using the opcode mnemonics LDAA, adda, ................................................ 313
Section: $09 + $09 = $12 (hex) using the opcode mnemonics LDAA, LDAB, ABA...................................... 313
Section: 12 + 29 = 41 (decimal) using the opcode mnemonics LDAA, LDAB, ABA..................................... 314
Dr. Victor Giurgiutiu
Page vii
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
Section: $0c + $1d = $29 (hex) using the opcode mnemonics LDAA, LDAB, ABA ...................................... 314
$ff + $01 = $00 (hex) using the opcode mnemonics LDAA, ADDA .............................................................. 314
255 + 1 = 0 (decimal) using the opcode mnemonics LDAA, ADDA ............................................................. 314
WHAT YOU HAVE LEARNED ............................................................................................................................... 316
EXERCISE 8-9..................................................................................................................................................... 318
GENERAL NOTE .................................................................................................................................................. 318
OBJECTIVE.......................................................................................................................................................... 318
PROGRAM ........................................................................................................................................................... 318
CODING AND EXECUTION ................................................................................................................................... 319
Section: 8 - 1 = 7 (decimal) using the opcode mnemonics LDAA, SUBA...................................................... 319
Section: $08 - $01 = $07 (hex) using the opcode mnemonics LDAA, SUBA................................................. 319
Section: 20 - 1 = 19 (decimal) using the opcode mnemonics LDAA, SUBA ................................................. 319
Section: $20 - $01 = $1f (hex) using the opcode mnemonics LDAA, SUBA.................................................. 320
Section: $00 - $01 = $ff (hex) using the opcode mnemonics LDAA, SUBA .................................................. 320
Section: 0 - 1 = 255 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA, SUBA
....................................................................................................................................................................... 320
Section: $0f - $07 = $08 (hex) using the opcode mnemonics LDAA, LDAB, SBA ........................................ 320
Section: $00 - $07 = $f9 (hex) using the opcode mnemonics LDAA, LDAB, SBA ........................................ 321
Section: 0 - 7 = 249 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA, LDAB,
SBA................................................................................................................................................................. 321
Section: $0f - $2b = $e4 (hex) using the opcode mnemonics LDAA, LDAB, SBA......................................... 321
Section: 15 - 43 = 228 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
LDAB, SBA..................................................................................................................................................... 321
use calculator to obtain hex negative numbers of –56 and –120................................................................... 321
WHAT YOU HAVE LEARNED ............................................................................................................................... 322
EXERCISE 10 ...................................................................................................................................................... 324
GENERAL NOTE .................................................................................................................................................. 324
OBJECTIVE.......................................................................................................................................................... 324
PROGRAM ........................................................................................................................................................... 324
CODING AND EXECUTION ................................................................................................................................... 325
Section: Represent numbers one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen,
fourteen, fifteen, sixteen, seventeen in decimal, binary, and hex ................................................................... 325
Section: Perform 5 + 4 = in binary and hex using LDAA, LDAB, ABA .................................................... 326
Section: Perform 15 – 7 = in binary and hex using LDAA, LDAB, SBA ................................................... 326
Section: Perform $1f + $01 = $ in binary and hex using LDAA, ADDA (bit 3 carry).............................. 326
Section: Perform $20 -$01 = $ in binary and hex using LDAA, SUBA .................................................... 326
Section: Perform $ff + $01 = $ in binary and hex using LDAA, ADDA (MSB carry) .............................. 326
Section: Perform $00 - $01 = $ in binary and hex using LDAA, SUBA .................................................... 326
Section: 0 AND 1 = using LDAA, ANDA .................................................................................................. 327
Section: 0 OR 1 = using LDAA, ORAA ...................................................................................................... 327
Section: 0 XOR 1 = using LDAA, EORA ................................................................................................... 327
Section: 1 OR 1 = using LDAA, ORAA ...................................................................................................... 327
Section: 1 XOR 1 = using LDAA, EORA ................................................................................................... 327
Section: %00000000 NAND %11111111 = %
using LDAA, ANDA, COMA .......................................... 327
Section: %11111111 NOR %00000000 = % using LDAA, ORAA, COMA ............................................... 328
Section: %10101110 AND %00001000 = %
using LDAA, ANDA (masking) ........................................ 328
WHAT YOU HAVE LEARNED ............................................................................................................................... 328
EXERCISE DELAY ............................................................................................................................................ 330
Dr. Victor Giurgiutiu
Page viii
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
PROGRAM ........................................................................................................................................................... 330
FLOWCHART ....................................................................................................................................................... 330
CODING ............................................................................................................................................................... 330
EXECUTION ......................................................................................................................................................... 330
WHAT YOU HAVE LEARNED ............................................................................................................................... 333
EXERCISE SQUARE WAVE ............................................................................................................................ 334
PROGRAMS.......................................................................................................................................................... 334
Program sq_wav1 .......................................................................................................................................... 334
FLOWCHART ....................................................................................................................................................... 334
CODING ............................................................................................................................................................... 334
EXECUTION ......................................................................................................................................................... 335
FLOWCHART ....................................................................................................................................................... 338
CODING ............................................................................................................................................................... 338
EXECUTION ......................................................................................................................................................... 338
WHAT YOU HAVE LEARNED ............................................................................................................................... 339
EXERCISE BUTTONS BOX ............................................................................................................................. 340
GOALS AND OBJECTIVES ..................................................................................................................................... 340
BASIC CONCEPTS ............................................................................................................................................... 340
PROGRAM BUTTONS_BX .................................................................................................................................... 340
FLOWCHART ....................................................................................................................................................... 341
CODING ............................................................................................................................................................... 341
EXECUTION ......................................................................................................................................................... 341
WHAT YOU HAVE LEARNED ............................................................................................................................... 342
EXERCISE -- SERIAL COMMUNICATION.................................................................................................. 344
OBJECTIVE.......................................................................................................................................................... 344
BASIC CONCEPTS ............................................................................................................................................... 344
PROGRAM ECHO ................................................................................................................................................. 345
Instructions .................................................................................................................................................... 346
FLOWCHART ....................................................................................................................................................... 346
CODING ............................................................................................................................................................... 346
EXECUTION ......................................................................................................................................................... 347
EXERCISE TIMER FUNCTIONS .................................................................................................................... 348
GOALS AND OBJECTIVES ..................................................................................................................................... 348
PART I -- BASIC CONCEPTS ................................................................................................................................ 348
PART II: INPUT CAPTURE – BOLT DROP EXPERIMENT TIMER PROGRAM ........................................................... 350
FLOWCHART ................................................................................................................................................ 352
coding............................................................................................................................................................. 352
execution ........................................................................................................................................................ 352
PART III: OUTPUT COMPARE – SQUARE WAVE GENERATION ............................................................................ 353
Flowchart....................................................................................................................................................... 353
Coding............................................................................................................................................................ 353
Execution........................................................................................................................................................ 353
EXERCISE DC MOTOR TACHOMETER...................................................................................................... 356
GOALS AND OBJECTIVES ..................................................................................................................................... 356
PART I – THEORY OF DC MOTORS (30%)........................................................................................................... 356
PART II – DC MOTOR TACHOMETER PROGRAM (70%)...................................................................................... 357
Dr. Victor Giurgiutiu
Page ix
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
The program Instructions .............................................................................................................................. 359
FLOWCHART ................................................................................................................................................ 359
CODING ........................................................................................................................................................ 359
EXECUTION ......................................................................................................................................................... 359
Verification of Case 1 of Example_RPM_2 ................................................................................................... 360
Verification OF Case 2 of Example_RPM_2 ................................................................................................. 362
WHAT YOU HAVE LEARNED ............................................................................................................................... 364
EXERCISE – STEPPER MOTOR..................................................................................................................... 366
OBJECTIVE.......................................................................................................................................................... 366
BASIC CONCEPTS ............................................................................................................................................... 366
PROGRAM STEPPER MOTOR ................................................................................................................................ 367
flowchart ........................................................................................................................................................ 368
coding............................................................................................................................................................. 368
execution ........................................................................................................................................................ 368
WHAT YOU HAVE LEARNED ............................................................................................................................... 369
EXERCISE – A/D CONVERTER...................................................................................................................... 370
OBJECTIVE.......................................................................................................................................................... 370
BASIC CONCEPTS ............................................................................................................................................... 370
PROGRAM A/D CONVERTER ............................................................................................................................... 371
Program Description ..................................................................................................................................... 371
flowchart ........................................................................................................................................................ 371
coding............................................................................................................................................................. 371
execution ........................................................................................................................................................ 372
WHAT YOU HAVE LEARNED ............................................................................................................................... 372
LABS ..................................................................................................................................................................... 374
LAB HANDOUT.................................................................................................................................................. 375
MINIIDE INSTRUCTIONS ............................................................................................................................... 375
LAB 1 - BASIC PROGRAMMING ................................................................................................................... 380
OBJECTIVE ...................................................................................................................................................... 380
PREREQUISITES ............................................................................................................................................. 380
PROCEDURE.................................................................................................................................................... 380
LAB 2 – PARALLEL AND SERIAL COMMUNICATION ........................................................................... 384
OBJECTIVE ...................................................................................................................................................... 384
PREREQUISITES ............................................................................................................................................. 384
PROCEDURE.................................................................................................................................................... 384
WARM UP EXERCISES ................................................................................................................................ 385
SQUARE WAVE............................................................................................................................................... 386
BUTTONS BOX................................................................................................................................................ 387
SERIAL COMMUNICATION ECHO .............................................................................................................. 388
LAB 3 – TIMER FUNCTIONS: BOLT DROP AND SQUARE WAVE ........................................................ 392
OBJECTIVE.......................................................................................................................................................... 392
PREREQUISITES ............................................................................................................................................. 392
PROCEDURE.................................................................................................................................................... 392
PART I – BOLT DROP EXPERIMENT (50%) ......................................................................................................... 393
Wiring Diagram ............................................................................................................................................. 393
Dr. Victor Giurgiutiu
Page x
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Table of Contents
Bolt Drop Circuit Diagram............................................................................................................................ 394
Pre-test Procedure ......................................................................................................................................... 394
Test Procedure ............................................................................................................................................... 395
PART II – SQUARE WAVE GENERATION WITH TIMER FUNCTIONS (50%).......................................................... 397
Wiring Diagram ............................................................................................................................................. 397
Test Procedure ............................................................................................................................................... 397
LAB 4 – DC MOTOR TACHOMETER............................................................................................................ 398
OBJECTIVE.......................................................................................................................................................... 398
PREREQUISITES ............................................................................................................................................. 398
PROCEDURE.................................................................................................................................................... 398
EXPERIMENTAL SETUP ....................................................................................................................................... 398
Wiring Diagram ............................................................................................................................................. 399
Circuit Diagram............................................................................................................................................. 399
PRE-TEST PROCEDURE ....................................................................................................................................... 400
PART I –DC MOTOR SPEED-VOLTAGE CHARACTERISTIC (30%)......................................................................... 400
PART II – DC MOTOR TACHOMETER (70%)....................................................................................................... 401
LAB 5 STEPPER MOTOR AND A/D CONVERSION ................................................................................... 404
OBJECTIVE.......................................................................................................................................................... 404
PART I – STEPPER MOTORS .......................................................................................................................... 404
PREREQUISITES ............................................................................................................................................. 404
PROCEDURE.................................................................................................................................................... 404
EXPERIMENTAL SETUP ....................................................................................................................................... 404
Circuit Diagram............................................................................................................................................. 405
Wiring Diagram ............................................................................................................................................. 405
PRE-TEST PROCEDURE ....................................................................................................................................... 405
STEPPER MOTOR CONTROL PROGRAM ................................................................................................................ 406
PART II – A/D CONVERSION .......................................................................................................................... 407
PREREQUISITES ............................................................................................................................................. 407
PROCEDURE.................................................................................................................................................... 407
EXPERIMENTAL SETUP ....................................................................................................................................... 407
Wiring Diagram ............................................................................................................................................. 408
EQUIPMENT LIST ................................................................................................................................................ 408
PRE-TEST PROCEDURE ....................................................................................................................................... 408
AD CONVERTION TEST PROCEDURE .............................................................................................................. 408
APPENDIX 1 HEX_BCD.................................................................................................................................... 410
APPENDIX 2 HOW TO SOLDER..................................................................................................................... 412
HOW TO SOLDER ................................................................................................................................................ 412
COLD SOLDER JOINTS ........................................................................................................................................ 414
TIPS AND TRICKS................................................................................................................................................ 414
APPENDIX 3 FLOW CHART TEMPLATE .................................................................................................... 416
BASIC FLOWCHART COMPONENTS ..................................................................................................................... 416
EXAMPLE FLOWCHART – DELAY PROGRAM ...................................................................................................... 416
APPENDIX 4 EXPLANATION OF EXAMPLE OUTPUT COMPAE TIMER FUNCTION..................... 418
Dr. Victor Giurgiutiu
Page xi
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Microcontrollers in Mechanical Engineering
Page xii
Table of Contents
8/19/2008
GENERAL INFORMATION
SYLLABUS
Catalog Data:
Description:
Textbooks:
References:
Content Category:
Coordinator:
TA’s:
Required tools:
Website:
EMCH 367 Fundamentals of Microcontrollers
Credit: 3 hours
Prerequisite: EECE 221 Basic Electric Circuits,
EMCH 361 Measurements and Instrumentation
Study of microcontrollers and their applications as measurement and control
devices in mechanical systems
Giurgiutiu, V. and Lyshevski, S. E. “Micromechatronics”, CRC Press 2004
“EMCH 367 Fundamentals of Microcontrollers (USC-DME Notes)”
M68HC11 Reference manual; MC68HC11A8 programming reference guide,
Motorola, Inc. + additional references.
Basic Science: 20%, Engineering Science 80%
Lingyu (Lucy) Yu, 777-0619 (O), 777-0106 (FAX) [email protected]
Office Location: 300 Main St. (Old SCE&G Building); Room A236
Office Hours: 10:00 am - 11:00 am Monday – Friday and when door is open
TA’s are assigned for each section – see assignment list in the general lab
information section.
PC with THRSim11 installed (USC rooms B202 and A235 have it!)
Pocket calculator with Hex, Bin, and Oct, and logics operators (e.g., TI-34)
http://www.me.sc.edu/courses/emch367
INSTRUCTIONAL OBJECTIVES
During the course:
1. The student will gain knowledge about the microcontroller and how it can be used in modern
machinery.
2. The student will achieve comprehension of the microcontroller principles, functions, and its
interaction with the rest of the world via sensors, actuators, and programming.
3. The student will gain hands-on experience through lab work and course project.
4. The student will develop analysis, synthesis, and communication skills through the course project.
After the course [Dept. Objectives and Outcomes] (Assessment method)
1. Students will be able to demonstrate knowledge and comprehension of the microcontroller and of
its use for sensing and actuation control of engineering systems, and of its role in modern society
[1.1, 1.2, 5.1] (1, 2, 3, 4)
2. Students will be able to demonstrate application ability by programming the microcontroller to
perform sensing and actuation control functions [1.2] (1, 2, 3, 4)
3. Students will be able to demonstrate application ability by performing laboratory experiments for
demonstrating the sensing and actuation control functions of the microcontroller [1.3] (2, 4).
4. Students will be able to demonstrate synthesis ability by designing, constructing and testing, in a
teamwork environment, proof-of-concept demonstrations of the microcontroller sensing and
actuation control functions in solving practical engineering problems [1.3, 3.1, 3.2, 4.3] (4)
5. Students will be able to demonstrate communication ability by presenting in written and oral format,
in a teamwork environment, the project development and results, and by performing hand-on
demonstrations [4.1, 4.3] (4)
6. The student will be better prepared for the job market in the third millennium.
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
COURSE DESCRIPTION
This course is designed to give mechanical engineers a basic understanding of microcontrollers and their
use in a mechanical engineering environment. This study of microcontrollers will consist of the
following main parts:
TOPICS
1. Review of circuits and semiconductor devices
2. Digital logic and arithmetic; Boolean algebra; Logic gates.
3. Basic microcontroller architecture; internal data handling and control, arithmetic-logic unit (ALU),
input-output.
4. Microcontroller programming language and opcodes (Assembly).
5. Digital sensing and control through input and output parallel communication
6. Control through asynchronous serial communication
7. Sensing and control through timer input capture and output compare functions
8. Actuation control via digital to analog conversion; digital control of DC motor actuation
9. Direct digital control of stepper motor actuators
10. Sensing of sensor signals through analog to digital conversion; sampling theory.
11. Design project.
Assessment Methods:
1. Homework
2. Labwork
3. Tests
4. Project
GRADING POLICY
The final grade consists of grades from attendance, two tests, laboratory experiments and a final project:
Attendance
Homework
Labs
Circuit practice
Tests (2 x 10% each)
Project
5%
25%
25%
5%
20%
20%
Attendance is REQUIRED and takes 5% in the final grade. If you have a good excuse, please notify the
instructor ahead of time (no late excuse will be accepted). However, this should not happen over three
times. Absence without a reason will be one point off and five will be the maximum.
Homework, labs, tests, circuit practice and project must be completely done/submitted, and borrowed
items must be returned before final grade can be calculated. (Otherwise, a grade of Incomplete will
be assigned.)
Guidelines for letter grade assignment of the final grades are:
94%-100%
88%-93%
82%-87%
76%-81%
70%-75%
65%-69%
60%-64%
≤ 60%
Dr. Victor Giurgiutiu
A
B+
B
C+
C
D+
D
F
Page 2
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
HOMEWORK REQUIREMENTS
Homework, as assigned in the Schedule, is due on the day shown in the schedule, before the class starts.
Homework should be submitted to your section TA for grading.
Printed paper of Homework is preferred.
Homework should be completed independently. Copied homework will be dealt with in accordance to
the Honor Code of the University of South Carolina.
If the homework is not handed on time, it is late, and the following penalty system applies:
ƒ Up to 3 days from the due date, 10 points
ƒ After 3 days from the due date, 50 points
After one week, ALL points will be penalized.
LABORATORY REQUIREMENTS
All students are required to attend their laboratory sections. Labs meet once a week, three hours a
session. Students are encouraged to do the labs in groups of two students. Students should bring
corresponding lab pages of the course package and home works to the labs. Other lab policies will be
announced on the day of lab orientation.
PROJECT REQUIREMENTS
All students will be required to complete a practical project for this course. In addition to this final
deadline, several other intermediate "milestones" are required. For in-depth information on the specific
project requirements see the project section.
ELECTRONIC FILES REQUIREMENTS
• LASTNAME_Firstname_Hmwk_X_Y.doc for Word doc homework files, where X is the
homework number and Y is the exercise number or name
• LASTNAME_Firstname_Lab_X.doc for Word doc lab report files, where X is the lab number
• LASTNAME1_LASTNAME2_Proj.doc for Word doc project report files
• LASTNAME1_LASTNAME2_Proj.ppt for PowerPoint project presentation files
• Hw_X_Y.asm for .asm lab files, where X is the homework number and Y is the item number.
Put your last name and first name in the asm file.
• Lab_X_Y.asm for .asm lab files, where X is the lab number and Y is the item number in that lab.
• To write an .asm Assembler file, use the template available on the web site. Before you actually
use it, personalize it by substituting LASTNAME, Firstname with your actual last name and first
name.
Note that the .asm file names are not personalized in order to stay within the standard file name length.
However, you should personalize it inside the document by writing your name as a comment on the first
line. As explained above, this is easiest done in the template.
NOTES: THE NETWORK ADDRESS FOR PLACING THE HOMEWORK AND LAB REPORT
FILES WILL BE PROVIDED BY YOUR TA.
The network address for placing the project report and project presentation files is
\\me-lamss9a\EMCH367_Proj_DROP . You can access it by:
• Click the Start button on the left of the status bar, select Run
• In the command line, type in the \\me-lamss9a\EMCH367_Proj_DROP and Drop your files in
this folder
Note: both project report WORD file and project presentation PowerPoint file are required!
Dr. Victor Giurgiutiu
Page 3
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
ADDITIONAL REFERENCES
1.
Engineer's Mini Notebook Series, Radio Shack, Inc.
Radio Shack publishes a series of simple and easy to understand electronics manuals. Most are written
by Forrest M. Mims, III. They are easy to read and come with many basic descriptions of electronics
concepts and components. In addition, they usually contain complete circuit diagrams that can come
handy in projects.
Title
Schematic Symbols, Device Packages, Design And Testing
Formulas, Tables, and Basic Circuits
Basic Semiconductor Circuits
Op Amp IC Circuits
Digital Logic Circuits
555 Timer Circuits
Communication Projects
Environmental Projects
Optoelectronics Circuits
Science Projects
Sensor Projects
Catalogue #
276-5017
62-5016
62-5013
62-5011
62-5014
62-5010
62-5015
62-5019
276-5012A (*)
62-5018
62-5026
TOTAL
Price
$1.99
$1.99
$1.99
$1.99
$1.99
$1.99
$1.99
$1.99
$1.99
$1.99
$1.99
$21.89
NOTE: (*) It may no longer be available in some stores since Radio Shack is updating this item.
2.
3.
4.
5.
6.
7.
National Semiconductor Databooks
Found in the lab, these books contain all the technical specifications of the electronic devices we
will use. They are generally called "The Blue Books."
Stiffler, A. K., “Design with Microcontrollers for Mechanical Engineers”, McGraw Hill, 1992,
ISBN 0-07-061374-5
Histand, M. B. and Aciatore, D. G., “Introduction to Mechatronics and Measurement Systems”,
WCB McGraw Hill, 1999, ISBN 0-07-029089-X
The Engineering Handbook. Richard C. Dorf (Ed), CRC Press, 1995, ISBN 0-8493-8344-7.
Mark’s Standard Handbook of Mechanical Engineers, E. A. Avallone and T. Baumeister III, 9th
Edition, McGraw Hill, 1987.
The Way Things Work. David Macaulay
An easy-to-understand and sometimes humorous explanation of many of the electro-mechanical
elements discussed in this course. (Transistors, microcontrollers, logic gates, etc. can be found in
this enjoyable book.)
TEST FORMAT
There are two open-book open-note tests in total and the dates are listed in the class schedule. All
students are required to attend the tests. The tests will be hold in a computer lab and students need to
finish the problems in 60 minutes. Test papers and floppy disks containing the test document are given
to students. Students can write answers on either of them and are required to turn in both when the test
is finished. The test problems will include questions, choices, and programming.
Please be aware that the tests are “open book, open notes”. I hope this is good news to you! However, be
warned that PAST TESTS ARE NOT INCLUDED IN THE "OPEN BOOK, OPEN NOTES"
CATEGORY AND HENCE ARE NOT PERMITTED DURING TESTS.
Dr. Victor Giurgiutiu
Page 4
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
EMCH 367 LAB
Lab Objective
This lab will give you hands-on experience with the MC6811 microcontroller and its interfacing
with other electro-mechanical devices. You will work in teams. However, the grading will be
individual, based on pre-lab quiz, your performance, and lab report. The principles learned
during the lab will be applied during the course project period.
Lab 1
Lab 2
Lab 3
Lab 4
Lab 5
Basic Programming
Parallel and Serial Communication
Timer Functions
DC Motor Tachometer
Stepper Motors and AD conversion
It should be noted that the successful completion of the labs is essential to the successful completion of
the project. In most cases, 50% - 75% of project code is little more than lab code. As such, you have a
personal stake in the successful completion of the labs.
Lab location: A235 – Door key will be assigned during final project period.
Dr. Victor Giurgiutiu
Page 5
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
LAB GRADING POLICIES
Individual lab grades will count for 100% of the final lab grade.
1)
50% of the individual lab grade will be based on the preparation work done before
the lab. There will be a prelab quiz (10%) which will be counted in the prelab
points: Pre-Lab points.
2)
25% of the individual lab grade will be based on in lab participation: TA points.
3)
25% of the individual lab grade will be based on the level of success in
completing the lab goals: In-Lab points.
LAB POLICIES
1)
Attendance is mandatory! If you miss a lab and do not make it up you will receive 0% for the
total lab grade!
2)
The completion of the pre-lab assignment is vital to the success of the laboratories. There will be
a 50% penalty for anyone not prepared for the day's lab. Address all questions and prepare all
programs (write, type, save on floppy disk) before coming to the lab. A printed copy of all
codes with annotations is required.
3)
The following must be completed before the lab:
a)
All written questions, predictions, or problems not requiring lab hardware.
b)
Program flowcharts
c)
A printout of all program code for the lab
d)
The programs saved on a floppy disk
4)
If you do not complete a lab, you may choose to hand it late. Labs will be accepted up to 1 week
after your normal laboratory class, in consultation with your lab TA. You must arrange with your
TA a time outside the normal lab hours when you will show the TA your completed lab. This
time cannot be the next lab period!
5)
If you leave the lab prior to the end of the lab period without successfully completing the lab
goals, you will receive no credit for that lab.
6)
If a student needs to change a laboratory section due to an unexpected conflict (i.e. interview,
illness, etc.) and go to a different section, both TA's must agree to the rescheduling. Due to the
limited availability of supplies, labs are limited to a maximum of 9 students.
EMCH 367 PROJECT
One of the best learning experiences that a student can have is to work, HANDS-ON, with tools,
computers, and other devices. For this reason, the EMCH 367 course has a cumulative final project. This
project will involve a team of two students developing a microcontroller-controlled application.
PROJECT OBJECTIVE
Throughout the labs, you have been learning how to apply microcontroller functions to various electromechanical systems. The project will be the application of all of these skills and the culmination of your
efforts. You will work in team, just like in the lab. This will strengthen your team-working aptitudes,
since the grade will be shared equally by the team partners. You and your partner(s) will develop the
project idea and submit a brief proposal prior to the start of the project period to the assigned project TA.
The TA and students will iterate on the project idea until a suitable project is obtained.
Dr. Victor Giurgiutiu
Page 6
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
HOW THE PROJECT WILL WORK
First, you must develop an idea. The idea can come as an improvement to an existing device through the
use of microcontrollers (I'm sure that you can think of a few) or a process which may not have been able
to be done before microcontrollers. Some examples from previous semester projects are available on the
course website. For each idea, there are four conceptual aspects that must be specified:
• how can a process be controlled (using a microcontroller),
• what makes the use of a microcontroller better than that of a physical system,
• how can this process be SIMULATED, and
• IN WHAT WAY DOES THE MICROCONTROLLER THINK?
Description of these aspects follows.
1.
HOW CAN A PROCESS BE CONTROLLED USING A MICROCONTROLLER:
Microcontrollers have a large amount of control capability. Most processes can be controlled through a
combination of a microcontroller and external circuitry. The essential aspect in relation to the project is
to figure out how it should be done. Two steps must be considered: measuring external events, and
acting on the judgments of the microcontroller to reach the project objective.
During the course of the class and lab experience, you will learn many aspects of data acquisition and
communication. These include time measurement (using the input capture functions), time scheduling
(output compare function), parallel communication, serial communication, and measurement of analog
signals (A/D converter). By using a combination of these tools, the microcontroller can determine a lot
about its environment. Similarly, the output compare, parallel communication, and serial communication
can output different signals. These signals, through the proper use of circuitry, can be translated to
useful control over external devices such as motors, magnets, pumps, etc. In this manner, the
microcontroller can become a valuable measuring and control tool. Discussing potential project ideas
with your TA will help.
2.
WHAT MAKES THE USE OF A MICROCONTROLLER BETTER THAN THAT OF
A PHYSICAL SYSTEM:
Now that you have determined that a microcontroller can control your desired system, the following
question arises: why would someone want to use a microcontroller for your system? Some things can be
performed very well using only physical mechanisms (door handles, for example). Why would someone
want to improve upon that by using a computer control? (This is done in a variety of places....) What
benefit does the use of the microcontroller bring? The answer can be rather complex. A few examples
are:
Dr. Victor Giurgiutiu
Page 7
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Rapid learning -smart machinery can learn a new process by being shown once
Record keeping -how many candy bars were bought? when do we run out?
Fast response -try making anti-lock braking without a microcontroller
Discussion about the system qualities that can be improved by using a microcontroller will be also
emphasized in the course. Do not hesitate to talk to the instructor and TA’s about this.
3.
HOW CAN THIS PROCESS BE SIMULATED:
We have very few external resources for this lab. We can't buy a car because someone wants to do an
anti-lock braking system. Moreover, this is a microcontroller project, NOT A PROJECT
INVOLVING THE UNIVERSITY OF SOUTH CAROLINA MACHINE SHOP. We have a
number of simulation tools including Lego, Erector Sets, etc. to model physical systems. We have a
number of pumps, motors (stepper and DC), digital display chips, LED's, IR emitter-detectors,
potentiometers, cermets, etc. Using some combination of these tools, you should be able to simulate the
process. YOU ARE REQUIRED TO BUILD ALL CIRCUITRY ASSOCIATED WITH YOUR
PROJECT. A brief list of available circuitry and other parts is shown below:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Breadboards
Various PINs
Various connectors
BNC miscellaneous
LED's
Buffers
7-Segment Displays
IR Emitter-Detectors
Piston Pumps
Logic Gates
Capacitors
Comparators
Potentiometers
DC Motors
Servo Motors
Various Sensors, including magnetic sensors, motion sensors, E/D, pressure sensors,
temperature sensors, thermocouple, etc
Speakers
Latch
Decade counters
Decoders
Solders
Power Adaptors
Voltage Regulators
Voltage Meters
Solenoids
Wire
Resistors
Miscellaneous Chips
Stepper Motors
Mosfets
Transistors
Dr. Victor Giurgiutiu
Page 8
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
A complete list is provided at the end of the package.
You will be building the external circuitry to the microcontroller. OPTOISOLATOR, 8-PIN LED
DISPLAYS, AND ANY OTHER PROTECTION CIRCUITRY ARE REQUIRED TO STAY IN
THE LAB. If you let the instructor know of a desired part that is not available early enough, there is a
possibility that it can be ordered or purchased through a local distributor. Don't hesitate to discuss
simulation ideas with your TA.
4.
IN WHAT WAY DOES THE MICROCONTROLLER “THINK”:
This is what separates the projects from the labs. In the labs, you develop tools and learn one simple
application. In the project, you combine the tools developed in the lab and develop a methodology for
the microcontroller to make intelligent decisions. A SWITCH DOES NOT MAKE INTELLIGENT
DECISIONS. If I switch on a light switch, that requires very little microcontroller thought. If I switch
on a light because I detected motion, and can then follow and more or less predict the direction of the
motion, then it is no longer a simple switch, but a complex device making intelligent decisions. After
determining the relevant parameters in the environment by making whatever measurements are
necessary, the microcontroller must determine the condition of the surroundings. Are the measured
parameters within tolerances for whatever process is being controlled? If there is an immediate problem,
the microcontroller must act to try to correct the problem immediately.
What about the "long term" control? The best way to control a process is to correct for problems before
they occur, to react to indications that a process may be heading in the wrong direction, and thus prevent
any immediate problems from occurring. The microcontroller is especially adept at performing these
predictive activities. With memory to store the results of the past measurement, the microcontroller can
quickly compare data points and determine trends. Based on these trends, the microcontroller can
predict the state of affairs at a future time. This is often referred to as extrapolation. By extrapolating
over very short time periods (the microcontroller can do this on the order of millionths of seconds), the
microcontroller can obtain a very good approximation of future behavior. It can then act to maintain the
desired external conditions. By comparing the effects of its actions and the behavior of the environment,
the microcontroller can gage its progress in maintaining the control of the external system. This is one
of the primary reasons that people use microcontrollers. THEY THINK!!!! Your project must
think, as well.
PROJECT PROCEDURE
The following are procedural aspects of the project: getting partners, writing a proposal, project
presentation and final report submission.
GETTING PARTNERS:
A project is, by definition, more involved than a laboratory exercise. As such, students will be
allowed to work in teams of two~four. In order to ensure that the teams are developed early
enough for the students to start discussing the project and developing ideas. The project teams
should be emailed to head TA by the deadline shown in the Schedule section of this document.
Any student not able to form a team by the end of class on that date should contact the head TA
by email to request the assignment be done by the head TA ex officio.
WRITING THE PROJECT PROPOSAL
Before going into full development work for the project, a proposal is required. A long, drawn
out doctoral dissertation is not expected or desired. All that is necessary is a short description of
the project idea. Show why a microcontroller would be good for this process, how this project is
Dr. Victor Giurgiutiu
Page 9
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
not a simple “switch”, and how the microcontroller “thinks and takes decisions”. Ideas for
simulation are helpful, but not required. The purpose of this is to make sure that you are thinking
about the project and doing some background development. In addition, progress reports like this
are often useful to organize your thoughts. It will also help you develop the list of hardware
necessary for your project. To ensure that you are thinking about the project ahead of time, the
project proposal is worth 10% of the project grade. The project proposal, including the hardware
list, should be emailed to the instructor by the deadline shown in the Schedule section of this
document. It should be noted that that this date leaves you approximately one month to do the
rest of the work. It should also be noted that labs are wrapping up at that time.
PROJECT PRESENTATION
Formal project presentations will be organized for each group in the lab on the date shown in the
Schedule section of this document. PowerPoint presentations are required. The presentation
should be planned to last 20 min, including real-life demonstration in the lab and questions time.
Consider that any topics related to your project, even remotely, can be asked by the instructor
and the TA's. This includes both hardware and software components of the project, as well as
utility, applicability, and commercialization. There is a very basic template available on the
EMCH 367 website.
PROJECT REPORT
The Project Report should address everything involved in the project. This includes: circuit
diagrams, software flowcharts, a relevant description of your program, the purpose of your
project, and why microcontrollers are a good device for this process. These are all things that you
should be developing through the course of the project. The preparation required for the project
report should be minimal, provided you keep good notes during the project and perform it in an
organized way. Examples of past project reports are available. They may be obtained from your
TA. These reports must stay in the lab. There is also a template available on the EMCH 367
website.
GUIDANCE ON COST ESTIMATION
In the project report, you will be required to give estimation of the prototype cost and of the cost
of producing of 1000 items. Excel spreadsheets are included in the report template to assist you.
For the prototype cost estimation, you need to figure out how much time and rates of pay for the
design (Engineer), production (Technician) and any other technical support (e.g. from your TAs).
The Total Personnel Costs is the sum of the above 3 items. The Total Direct Costs is the sum of
Total Personnel Costs and Materials. The Indirect Costs is estimated as 45% of the Total Direct
Cost (you may put other values, if you have a good reason). The Total Prototype Costs is the sum
of Total Direct Costs and Indirect Costs.
For the production of 1000 items, you need to take wholesale into consideration, which helps
you save money. In the production case, the time for Engineer, Technician and Others is not
simply multiplying the time of prototype by 1000. The reason is that you don’t need to design or
get help for each item. Hence large production runs need less money per unit (economy of
scale!). This also applies to the estimation of Materials. You might pay much less for an item if
Dr. Victor Giurgiutiu
Page 10
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
you buy 1000, compared with the case of one purchase only. In the example in the project report,
the materials cost for prototype is $100, but $50 for 1000 purchase (Profit also needs to be
considered in production runs). In the end, dividing the Total Factory Price by 1000, you get the
Factory Retail Price per Item.
ANSWERS TO FREQUENTLY ASKED QUESTIONS
WHERE DO I GET PROJECT IDEAS?
Look all around you. Microcontrollers touch each and every part of your life. Think about
processes that you take for granted. Think about topics that may interest you personally, and
extend the role of microcontrollers to that topic. Look at some of the suggested readings in the
Class Syllabus. Talk with your TA. Talk with the Head TA or the Instructor.
ONCE I HAVE AN IDEA, WHAT DO I DO?
1)
2)
3)
Each group will probably approach their project differently, since each project has different goals
and objectives. As such, writing one clear-cut approach to doing a Micro project is not an easy
task. The following are guidelines to assist you:
List all tasks that need to be done. Many times, it is helpful to make more lists that are
detailed, as the problem becomes better defined. This also helps to organize your thought
processes and productivity by letting you know where you are in terms of the final
project development.
Look at software development. Outline all the routines that need to be developed. Write
flowcharts for the program as a whole, and for each routine. Without some sort of
organization, a code will not function. Once the flowcharts are completed, write the codes
for the corresponding program segments. Use the concept of Modular Design for these
aspects of the code development. Write the code such that debugging is straightforward.
Start with a base code that works. Then add one piece at a time. Test each program
segment, debugging as you develop the program.
Look at hardware development. Draw circuit diagrams before building your circuits.
Make sure that you understand what each component does. If you have questions, ask
your TA's for assistance. Then, build the circuits. Using the oscilloscope, check how the
circuit responds by itself. If it doesn't work and you are burning out chips, DON'T JUST
KEEP BURNING OUT CHIPS!!! Ask someone for assistance. Once you know that
the hardware is behaving properly, attach the system together.
HOW DO I GET ASSISTANCE FROM MY TA'S?
TA's are a great reference. Typically, they are available right after the laboratory period for
questions. They can also be reached through e-mail. Set up an appointment with them. If they
can't find the answer to your questions, they can refer you to someone who can help. During
project time, each TA has at least four hours a week of office hours. These are hours that they
will be actively engaged in helping students in the lab. Although TA's are encouraged to
schedule these hours during the scheduled lab times, many offer additional times to assist
students. As such, there will be 20+ hours of TA assistance available for the class each week
until projects are completed. A complete list of times will be posted in the lab, on lab doors,
etc. The obvious implication is that the earlier you get progress made on the project, the more
Dr. Victor Giurgiutiu
Page 11
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
TA help time you will have. You will not be restricted to use only your lab time. You can go to
the lab every day if you wish. Project questions take priority over general questions.
WHEN DO I SIGN UP FOR MY PROJECT PRESENTATION?
Sign-up sheets will be made available before the last week of project presentation. There will be
a large variety of time slots available. The scheduling is on first come, first serve basis. If a
group wishes to reschedule with another, both groups must agree.
WHEN AND HOW DO I GET HARDWARE FOR THE PROJECT?
After you have developed your project proposal, you are ready to get the hardware. Every group
that has partners assigned and a project proposal submitted will be issued hardware based on a
checkout sheet reflecting the hardware list sent by you with the Project Proposal. After the end of
Lab 5, groups may start getting their hardware from their project TA. YOU ARE
RESPONSIBLE FOR THIS HARDWARE AND MAKING SURE THAT IT IS
RETURNED TO ITS PROPER LOCATION IN THE LAB ONCE YOUR PROJECT IS
COMPLETED. THIS INCLUDES PROPERLY DISASSEMBLING YOUR PROJECT
AFTER THE PRESENTATION, UNLESS YOU ARE INSTRUCTED OTHERWISE.
Instructions for proper placement of lab equipment will be provided in the lab during the project
time.
WHEN IS THE LAB AVAILABLE FOR PROJECT WORK?
The lab will be available 24 hours a day from project start till project end. You will be issued the
lab door access keys. You must also comply with the building access procedures. This open-door
policy may be restricted if improper use of lab facilities takes place. IF YOU ARE UNSURE
ABOUT ANY ASPECT OF THE HARDWARE YOU ARE USING, DO NOT USE THE
LAB WITHOUT A TA!
Dr. Victor Giurgiutiu
Page 12
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
PROJECT GRADING POLICY
Dr. Victor Giurgiutiu
Page 13
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
PROGRAMMING THE MICROCONTROLLER
First, read the textbook material (pages 712-721) on programming the microcontroller.
Then, follow the instructions below, which are specific to our course.
THRSIM11 SIMULATOR
The THRSim11 is a software program that allows you to write microcontroller programs and simulate
how the microcontroller will react to your program.
You need to install this software on your PC. This software can be downloaded from the course website.
THRSIM11 OPTIONS SETUP
Before you run the THRSim11 simulator first time on a certain PC, set the Options as shown it the
following windows:
Dr. Victor Giurgiutiu
Page 14
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Immediately after opening the THRSim11 program, close the Commands window. You will not use in
this course, unless otherwise specified.
Dr. Victor Giurgiutiu
Page 15
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
GETTING STARTED WITH PROGRAMMING
Take a formatted empty floppy disk and write on the label:
EMCH 367
LASTNAME, Firstname
Email address
Contact telephone #
This way, if you loose the disk, there is a good chance that you might have it recovered.
Go the course website and download the template.asm file and place it on the floppy disk. This template
will always be good to start your programming.
Download the file VAR_DEF.ASM and place it in the root of the directory structure on your floppy disk.
(This will allow the programs to find it when executing the instruction #INCLUDE
‘A:VAR_DEF.ASM’.
Download example files from the course website onto this disk. (For safety, make copies into your
folder or PC.)
USING THE TEMPLATE.ASM FILE
An .asm template file is available on the course website. This template has the required instructions to
make your program interface properly with the simulator. When generating a new program, open the
template.asm file, save it under the new name you want to create (remember to save on a secure area,
preferably your floppy disk), and then start typing in your program in the indicated area.
After you type and save your program (save as often as you can, use Ctrl S for productivity), assemble
the program and test run it.
SCREEN/WINDOW CAPTURE
To capture the image of a window or of the complete screen:
Dr. Victor Giurgiutiu
Page 16
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
• Press Alt + PrintScreen to capture the image of the window that is currently active.
• Press PrintScreen to capture the image of the entire screen.
The captured image can be viewed on the clip board.
To paste the captured image into a document:
• In the document window, on the Edit menu, click Paste. Alternatively, use Ctrl + V.
Note: In most cases, you will need to capture just the active window, using Alt + PrintScreen.
DEFAULT WINDOWS
Default windows are the three windows(*.LST, *.asm, and CPU registers) shown below:
If needed, more windows can be open. For example, four windows can be open (*.LST, *.asm, Memory
list, and CPU registers).
In the memory list, standard labels may be shown. However, they can be removed if you use the pull
down menu command Label/Remove all.
Dr. Victor Giurgiutiu
Page 17
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Microcontrollers in Mechanical Engineering
Page 18
Course Package.doc
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
MINIIDE EMULATOR
MiniIDE is an integrated development environment running under Windows 95/98/Me/NT/2000. It was
developed by MGTEK in Germany. It is a tool for developers of embedded software who write software
in assembler for Motorola's 68HC11 and 68HC12 microcontroller. MiniIDE incorporates an editor and a
serial communication terminal. A command-line cross assembler, which is seamlessly integrated in the
IDE, is also included.
n
o
p
With MiniIDE, user can edit compile and download program to microcontroller, then debug program
interactively. As shown above, a user can edit ASM program in editor window 1; then compile the
program, if there are syntax errors, warning messages will be shown in output window 2; at last,
download the program and interact with the microcontroller in terminal window 3 to debug and run the
program.
In this course, MiniIDE will be used to download codes into the MCU Evaluation Board (EVB). In
this context, it acts as a terminal program during the lab periods. You do not need to install this software
on your PC.
When you open the MINIIDE, click “output window” icon
and “terminal window” icon
to open
the output window and terminal window. You can click “open” icon
to open an ASM program
source code file and you can edit it in the edit window as shown above. To compile the program file,
Dr. Victor Giurgiutiu
Page 19
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
you can click “build current” icon . The compiling information and warning messages will be shown
in the cross compiler output window. After compiling the program file, if there is no error, a S19 file of
the program will be created. That is the machine code file that will run in the EVB Board. After editing
and compiling, you can download the machine code S19 file to the EVB to run it. To do this, you need
connect to the EVB by clicking “terminal connect/disconnect” icon firstly. After clicking, you need to
reset the EVB by pressing the reset button on the EVB. One message will appear in the terminal window
and the EVB is ready to receive the BUFFALO command now. The BUFFALO command will be
introduced in details in later chapters.
Type in LOAD T in the terminal window and click the “download” icon
appear as shown below.
, a pop-up window will
Select your S19 file and click “Open” to download it to the EVB.
A self-teaching viewlet on how to use the MiniIDE software is available from the
HTTP://WWW.ME.SC.EDU/COURSES/EMCH367/
Dr. Victor Giurgiutiu
Page 20
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
PROGRAMMING FLOW CHART
The programming flow chart is shown in the figure below. First, the source code is written in Assembly
language on the THRSim11 simulator. The simulator assembles the .asm code and generates a list file
(*.LST). The simulator is then used to step through the program and debug it until it performs the
intended functionality. All this can be done remotely, in the computer room, or on a personal computer.
Once the program has been debugged, it can be taken on a floppy disk to the EMCH 367 lab (A 235).
The MCU evaluation board (EVB) hardware is accessed through the MiniIDE emulator software
installed on the lab computers. MiniIDE reads the .asm file from your floppy disk and transforms it into
machine language executable code (*.S19). This code is downloaded to the MCU. After downloading
the code into the MCU, you can make the MCU run your code using the MiniIDE interface screens. The
MiniIDE also generates a list file (.LST) that can be used during debugging.
Source code
ASSEMBLY LANGUAGE
*.asm
THRSim11
Software
List file
*.LST
List file
*.LST
MiniIDE
Software
Executable code
MACHINE LANGUAGE
*.S19
MCU
EVB
Hardware
Figure 1 Flowchart of typical programming steps used in the EMCH 367 course.
Dr. Victor Giurgiutiu
Page 21
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Figure 2 Flowchart of typical programming steps in a generic programming environment.
Dr. Victor Giurgiutiu
Page 22
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
BINARY AND HEX NUMBERS
Note: To quickly grasp the use of binary and hex arithmetic, use your binary/hex pocket calculator.
The binary number system is a base-2 numbering system. In binary representation, any value is
represented using a combination of 1's and 0's. For example: 1410 = 11102 in binary. The subscript 10
on the first number indicates that the number 14 is represented in the decimal (base 10) system. The
subscript 2 on the second number indicates that 1110 is represented in the binary (base 2) system.
The binary representation is also called "digital". "Digit" also means finger, and you can imagine a
numbering representation in which you use your 8 digits to for number containing 1's and 0's. The
ability to represent numbers in terms of 1's and 0's is important because it is the easiest most
unambiguous way to represent and communicate information. In a computer, a 1 is represented by a
"high" voltage (5V) and a 0 by a "low" voltage (~0V). The binary system is the backbone of all digital
computers and other high-tech applications.
THE BINARY SYSTEM
To understand how the binary system works, let's first examine how the conventional base-10 system
works. The base 10, or decimal, system constructs numbers using increasing powers of 10. For example,
the number 13510 is constructed using 3 powers of 10: 100, 101, and 102. These numbers correspond to
1,10, and 100. The number 13510 is constructed as:
1 x 100 + 3 x 10 + 5 x 1
or
1 x 102+ 3 x 101 + 5 x 100
The equivalent of number 13510 in base two is 100001112. This is constructed as:
1 x 128+ 0 x 64 + 0 x 32 + 0 x 16 + 0 x 8 + 1 x 4 + 1 x 2 + 1 x 1
or
1 x 27 + 0 x 26 + 0 x 25 + 0 x 24 + 0 x 23+ 1 x 22 + 1 x 21 + 1 x 20
It can be seen that the only significant difference between the two systems is the base number.
Each one or zero in the binary representation is called a "bit". A collection of eight bits is called a "byte"
and, in a somewhat humorous note, a collection of four bits is called a "nibble". The bit associated with
the highest power of two is called the Most Significant Bit (MSB); the bit associated with the lowest
power of two is the Least Significant Bit (LSB).
1
bit
1 0 0 0 0 1 1 1
byte
1 0 0 1
Hex number (nibble)
1 0 0 1 0 0 0 1
2 nibbles = 1 byte
Dr. Victor Giurgiutiu
(1 byte = 8 bits)
Page 23
(1 nibble = 4 bits)
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
DECIMAL TO BINARY CONVERSION:
Because most people are more comfortable using, and thinking in, the decimal system, it is important to
know how to convert from the decimal to the binary system. This is most easily achieved through a
series of divisions by two and by tracking the resulting remainders. Let's consider out example of 13210:
132 ÷2 =
66
Remainder
0
66 ÷ 2 =
33
Remainder
0
33 ÷2 =
16
Remainder
1
13210 = 10000100
16 ÷2 =
8
Remainder
0
8 ÷2 = 4
Remainder
0
MSB
LSB
4 ÷2 = 2
Remainder
0
2 ÷2 = 1
Remainder
0
1 ÷2 = 0
Remainder
1
The remainder 1 resulting from the last division is the MSB, while the first remainder is the LSB of the
conversion. From this example, we see that the decimal number 132 is equal to the binary number
10000100.
The conversion from binary to decimal is done in the same manner as the first example, by adding
together power of two values of the non-zero bits.
HEXADECIMAL (HEX) NUMBERS
As one might have already surmised, binary numbers quickly become long and hard to remember. For
this reason, it is more convenient to convert the binary values into hexadecimal numbers (hex).
Hexadecimal numbers are base 16 numbers. This requires six additional characters to represent the
values 10, 11, 12, 13, 14, and 15. These values will be represented by the letters A, B, C, D, E, and F.
The counting order in hex is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. The reason hex notations are use
is that it allows for a one to one correspondence between the 16-bit binary nibble and a single
hexadecimal value. If the binary number is broken down into nibbles, and each nibble is replaced with
the corresponding hexadecimal number, the conversion is complete. Consider 13210. The binary
number is 10000100. It can be broken down into two separate nibbles: 1000 and 0100. Convert each
nibble into the corresponding hex value (8 and 4, respectively), and the hex equivalent of 13210 is 8416.
This is much more convenient to remember. For example, the hex number A23E3 is easily converted to
10100010001111100011 in binary without using any difficult calculations.
To convert decimal to hex numbers it is easiest to convert the decimal number to binary and then
convert the binary to hex. In addition to these methods, there is a conversion chart in the back of the
Programming Reference Guide for the conversion from decimal to hex.
Dr. Victor Giurgiutiu
Page 24
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
BINARY ARITHMETIC
The rules for addition of binary numbers are straightforward:
0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 0 with a carry of 1, i.e. 1 + 1 = 102.
For example:
01010010
+
10010100
00110001
00010010
10000011
01010001
11110111
+
NEGATIVE NUMBERS IN THE COMPUTER (2’S COMPLEMENT NUMBERS)
Until now, we have discussed only positive numbers. These numbers were called "unsigned 8-bit
integers". In an 8-bit byte, we can represent a set of 256 positive numbers in the range 010-25510.
However, in many operations it is necessary to also have negative numbers. For this purpose, we
introduce "signed 8-bit integers". Since we are limited to 8-bit representation, we remain also limited to
a total of 256 numbers. However, half of them will be negative (-12810 through -110) and half will be
positive (010 through 12710).
The representation of signed (positive and negative) numbers in the computer is done through the socalled 8-bit 2's complement representation. In this representation, the 8th bit indicates the sign of the
number (0 = +, 1 = -).
The signed binary numbers must conform to the obvious laws of signed arithmetic. For example, in
signed decimal arithmetic, -310 + 310 = 010. When performing signed binary arithmetic, the same
cancellation law must be verified. This is assured when constructing the 2's complement negative binary
numbers through the following rule:
To find the negative of a number in 8-bit 2's complement representation, simply subtract the
number from zero, i.e. -X = 0 - X using 8-bit binary arithmetic.
Example 1: Use the above rule to represent in 8-bit 2's complement the number -310
Solution:
Subtract the 8-bit binary representation of 310 from the 8-bit binary representation of 010
using 8-bit arithmetic (8-bit arithmetic implies that you can liberally take from, or carry into the 9th bit,
since only the first 8 bits count!).
BINARY
DECIMAL
00000000
010
00000011
310
11111101
-310
Note that, in this operation, a 1 was liberally borrowed from the 9th bit and used in the subtraction!
Dr. Victor Giurgiutiu
Page 25
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Verification We have establish that -310 = 111111012. Verify that -310 + 310 = 010 using 8-bit
arithmetic.
BINARY
DECIMAL
11111101
-310 00000011
310
00000000
010
Note that, in this operation, a carry of 1 was liberally lost in the 9th bit!
Example 2: Given the binary number 00110101, find it's 2's complement.
Solution: Subtract the number from 00000000, i.e.
BINARY
HEX
DECIMAL
00000000 00 010 01101010
6A
10610
10010110
96
-10610
Verification: 01101010 + 10010110 = (1)00000000. Since the 9th bit is irrelevant, the answer is
actually 00000000, as expected
The rule outlined above can be applied to both binary and hex numbers.
Example 3: Given the hex number 6A, find its 8-bit 2's complement.
Solution: Subtract the number from 0016 using 8-bit arithmetic:
HEX
DECIMAL
00
010
6A
10610
96
-10610
Verification: 6A16 + 9616 = (1)00. Since the 9th binary bit is irrelevant, the answer is actually 0016, as
expected
Example 4: 110010102 Æ CA16 Æ 20210.
Dr. Victor Giurgiutiu
Page 26
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
NUMERICAL CONVERSION CHART FOR UNSIGNED 8-BIT BINARY INTEGERS
Dr. Victor Giurgiutiu
Decimal
(base 10)
4-bit binary
(base 2)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Page 27
Hex
(base
16)
0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
NUMERICAL CONVERSION CHART FOR 2'S COMPLEMENT SIGNED 8-BIT BINARY INTEGERS
Decimal
+127
…
+16
+15
+14
+13
+12
+11
+10
+9
+8
+7
+6
+5
+4
+3
+2
+1
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-16
…
-128
Dr. Victor Giurgiutiu
8-bit 2's complement
signed binary
0111 1111
…
0001 0000
0000 1111
0000 1110
0000 1101
0000 1100
0000 1011
0000 1010
0000 1001
0000 1000
0000 0111
0000 0110
0000 0101
0000 0100
0000 0011
0000 0010
0000 0001
0000 0000
1111 1111
1111 1110
1111 1101
1111 1100
1111 1011
1111 1010
1111 1001
1111 1000
1111 0111
1111 0110
1111 0101
1111 0100
1111 0011
1111 0010
1111 0001
1111 0000
…
1000 0000
Page 28
Hex
7F
…
10
0F
0E
0D
0C
0B
0A
09
08
07
06
05
04
03
02
01
00
FF
FE
FD
FC
FB
FA
F9
F8
F7
F6
F5
F4
F3
F2
F1
F0
…
80
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
LOGIC GATES AND BOOLEAN ALGEBRA
LOGIC GATES
Circuit
IC #
Symbol
Buffer
7407
A
X
X=A
NOT
(Inverter)
7404
A
X
X=A
COMA
AND
7408
X
X = A⋅ B
ANDA
OR
7432
X
X = A+ B
ORAA
NAND
7400
X
X = A⋅ B
NOR
7402
X
X = A+ B
Exclusive OR
XOR
7486
X
X = A⋅ B + A⋅ B
= A⊕ B
Comparator
2901
X
X = A⋅ B + A⋅ B
A
B
A
B
A
B
A
B
A
B
A
B
Boolean Function
HC6811 commands
1)
1)
EORA
2)
1)
During programming, to achieve NAND, use two steps, first AND, then NOT. This means to use first
the commands ANDA and then COMA. (Similar for NOR.)
2)
During programming, to achieve this function, use two steps, first EORA, then NOT. This means to
use first the commands EORA and then COMA.
Dr. Victor Giurgiutiu
Page 29
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Inverting gate
AND gate
OR gate
XOR gate
Dr. Victor Giurgiutiu
Page 30
Course Package.doc
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
BOOLEAN ALGEBRA
In formulating mathematical expressions for logic circuits, it is important to have knowledge of Boolean
algebra, which defines the rules for expressing and simplifying binary logic statements. The basic
Boolean laws and identities are listed below. A bar over a symbol indicates the Boolean operation NOT,
which corresponds to inversion of a signal.
Fundamental Laws
OR
AND
A+0 = A
A +1 = 1
A+ A = A
A⋅ A = A
A+ A =1
A⋅ A = 0
NOT
A⋅ 0 = 0
A ⋅1 = A
(1)
A = A (double inversion)
Commutative Laws
Associative Laws
A+ B = B+ A
A⋅ B = B ⋅ A
(2)
( A + B) + C = A + ( B + C )
( A⋅ B) ⋅C = A⋅( B ⋅C )
(3)
Distributive Laws
A + ( B ⋅C ) = ( A + B) ⋅( A + C )
Other Useful Identities
(4)
A + ( A⋅ B) = A
(5)
A⋅( A + B) = A
(6)
A + A⋅ B = A + B
(7)
(
)
( A + B) ⋅( A + B) = A
( A + B) ⋅( A + C ) = A + ( B ⋅C )
(
)
(8)
(9)
A + B + A⋅ B = A + B
(10)
( A⋅ B) + ( B ⋅C ) + (B ⋅C ) = ( A⋅ B) + C
(11)
( A⋅ B) + ( A⋅C ) + ( B ⋅C ) = ( A⋅ B) + ( B ⋅C )
(12)
DeMorgan’s Laws are also useful in rearranging of simplifying longer Boolean expressions or in
converting between AND and OR gates:
A + B + C + ... = A ⋅ B ⋅ C ⋅ ...
A ⋅ B ⋅ C ⋅ ... = A + B + C + ...
(13)
(14)
If we invert both sides of these equations and apply the double NOT law for Equation (1) we can write
DeMorgan’s Laws in the following form:
Dr. Victor Giurgiutiu
A + B + C + ... = A ⋅ B ⋅ C ⋅ ...
(15)
A ⋅ B ⋅ C ⋅ ... = A + B + C + ...
(16)
Page 31
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
CONDITION CODE REGISTER (CCR)
S
S
=
X
=
H
=
I
=
N
=
Z
=
V
=
C
=
Dr. Victor Giurgiutiu
X
H
I
N
Z
V
C
Stop bit
Allows user to turn the microcontroller stop function on or off.
XIRQ mask
Used to disable interrupts from the XIRQ.
Half carry bit
Indicates a carry from bit 3 during addition. Only updated by ABA, ADD, and ADC. It is
used by the DAA in BCD operations (setting a hexadecimal number to decimal).
Interrupt mask
Global interrupt mask. Allow user to turn on/off interrupts.
Negative bit
Set to 1 when the result of an operation is 1 in the MSB.
Set to 0 when the result of an operation is 0 in the MSB.
Zero bit
Set to 1 when the result of an operation is 0016.
Set to 0 when the result of an operation is anything other than 0016.
oVerflow bit
Set to 1 when a 2's complement overflow has occurred due to a specific operation.
7E16 + 0416 = 8216, 100000102
Note: The 1 in the MSB indicates that an overflow occurred. The addition yielded a
number larger than 7F16, which is the maximum positive value that a 2'S compliment
number is allowed.
Carry bit
Set to 1 when a carry or borrow has occurred in the MSB. In addition operations, it is set
if there was a carry from MSB. In subtractions, it is set if a number with a larger absolute
value is subtracted from a number with a smaller absolute value. It is also used in
multiplication and division.
Page 32
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
BUFFALO COMMANDS
The monitor BUFFALO program is the resident firmware for the evaluation board (EVB), which
provides a self-contained operating environment. It interacts with the user through predefined
commands. The BUFFALO command line format is as follows:
><command>[<parameters>](RETURN)
where:
>
<command>
<parameters>
(RETURN)
EVB monitor prompt.
Command mnemonic.
Expression or address.
RETURN keyboard key
NOTES:
1) The command line format is defined using special characters that have the following syntactical
meanings:
<>
Enclose syntactical variable
[]
Enclose optional fields
[ ]…
Enclose optional fields repeated
These characters are NOT entered by user, but are for definition purpose only.
2)
3)
4)
5)
6)
Fields are separated by any number or space, comma, or tab characters.
All input numbers are interpreted as hexadecimal.
All input commands can be entered either upper or lower case lettering.
A maximum of 35 characters may be entered on a command line.
Command line errors may be corrected by backspacing or by aborting the command (CRTLX/Delete).
7) After a command has been entered, pressing (RETURN) a 2nd time will repeat the command.
Some of the frequently used BUFFALO commands are listed alphabetically in Table 1.
COMMAND
DESCRIPTION
HELP
Display monitor commands
ASM [<addr>]
Assembler/disassembler
BF <address1> <address2> <data>
Block fill memory with data
BR [-][<addr>]
Set up breakpoint
CALL [<address>]
Execute subroutine
GO [<address>]
Execute program
MD [<address1> [<address2>]]
Memory Display
MM [<address>]
Memory Modify
MOVE <address1> <address2>
Move memory to new location
[<destination>]
OFFSET [-]<arg>
Offset for download
RM [p, y, x, a, b, c, s]
Register Modify
T [<n>]
Trace $1~$ff instructions
Dr. Victor Giurgiutiu
Page 33
8/19/2008
EMCH 367
RD
Microcontrollers in Mechanical Engineering
Course Package.doc
Register Display
Next few pages are detailed description and examples for each command.
Dr. Victor Giurgiutiu
Page 34
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
ASM
Assembler/Disassembler
ASM [<address>]
where: <address> is the starting address for the assembler operation.
Assembler operation defaults to internal RAM if no address is given. Each source line is converted into the proper
machine language code and is stored in memory overwriting previous data on a line-by-line basis at the time of entry.
The syntax rules for the assembler are as follows:
(a.) All numerical values are assumed to be hexadecimal.
(b.) Operands must be separated by one or more space or tab characters.
Addressing modes are designated as follows:
(a.) Immediate addressing is designated by pre-ceding the address with a # sign.
(b.) Indexed addressing is designated by a comma. The comma must be preceded a one byte relative offset and followed
by an X or Y designating which index register to use (e.g., LDAA 00,X).
(c.) Direct and extended addressing is specified by the length of the address operand (1 or 2 digits specifies direct, 3 or 4
digits specifies extended). Extended addressing can be forced by padding the address operand with leading zeros.
(d.) Relative offsets for branch instructions are computed by the assembler. Therefore the valid operand for any branch
instruction is the branch-if-true address, not the relative offset.
Assembler/disassembler subcommands are as follows.
/
Assemble the current line and then disassemble the same address location.
^
Assemble the current line and then disassemble the previous sequential address location.
(RETURN)
(CTRL)-J
(CTRL)-A
Assemble the current line and then disassemble the next opcode address.
Assemble the current line. If there isn't a new line to assemble, then disassemble the next
sequential address location. Otherwise, disassemble the next opcode address.
Exit the assembler mode of operation.
EXAMPLE
>ASM C000
C000 STOP $FFFF
>LDAA #55
86 55
C002 STOP $FFFF
>STAA C0
97 C0
C004 STOP $FFFF
>LDS 0,X
AE 00
C006 STOP $FFFF
>BRA C500
Branch out of range
C006 STOP $FFFF
>BRA C030
20 28
C008 STOP $FFFF
>(CTRL)A
DESCRIPTION
Immediate mode addressing, requires #
before operand.
Direct mode addressing.
Index mode, if offset = 0 (,X) will not
be accepted.
Branch out of range message.
Branch offsets calculated automatically,
address required as conditional branch
operand.
Assembler operation terminated.
EXAMPLE
DESCRIPTION
>ASM C000
C000 CLR $0800
>LDY #C200
18 CE C2 00
C004 TEST
>LDX #C400
CE C4 00
C007 TEST
>LDAA 102E
B6 10 2E
C00A TEST
>LDAA 0,X
Enter assembler/disassembler mode.
Dr. Victor Giurgiutiu
First byte where data is stored.
IMM mode
Point to data to be fetched.
IMM mode
Clear RDRF bit if set.
EXT mode
Get f1rst data byte.
Page 35
8/19/2008
EMCH 367
A6 00
C00C TEST
>STAA 102F
B7 10 2F
C00F INX
>LDAA 102E
B6 10 2E
C012 TEST
>ANDA #80
84 80
C014 TEST
>BEQ C00F
27 F9
C016 BITB $80F6
>LDAA 102E
B6 10 2E
C019 BVS $C01B
>ANDA #20
84 20
C01B STX $00FF
>BEQ C016
27 F9
C010 STX $4065
>LDAA 102F
B6 10 2F
C020 STAA $00,Y
>STAA 0,Y
18 A7 00
C023 STX $00FF
>INX
08
C024 TEST
>INY
18 08
C026 ASRB
>CPX #C41F
8C C4 1F
C029 ASLD
>BEQ C02E
27 03
C02B STX SOOFF
>JMP C00C
7E C0 0C
C02E MUL
>BRA C02E
20 FE
C030 ILLOP
>(CTRL)A
Microcontrollers in Mechanical Engineering
Course Package.doc
INX mode
Store data in SCI data register.
EXT mode
Read SCI status register.
EXT mode
Send data byte.
IMM mode
Wait for empty transmit data register.
REL mode
Read SCI status register.
EXT mode
Extract RDRF bit fram status register.
IMM mode
Branch true = SCI RDR not fu11.
Branch false = SCL RDR fu11.
REL mode
Read data from SCI RDR.
EXT mode
Store data byte.
INY mode
Increment fetch pointer.
INH mode
Increment storage pointer.
INH mode
Done sending data?
IMM mode
No, get next data byte.
EXT mode
Yes, stop here.
REL mode
Exit assembler/dissembler mode.
BF
Block
Fill
BF <address1> <address2> <data>
where:
<address1>
Lower limit for fill operation.
<address2>
Upper limit for fill operation.
<data>
Fill pattern hexadecimal value.
EXAMPLE
>BF C000 C030 FF
>BF C000 C000 0
Dr. Victor Giurgiutiu
DESCRIPTION
Fill each byte of memory from C000
through C030 with data pattern FF.
Set location C000 to 0.
Page 36
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
CALL
Execute
Subroutine
CALL [<address>]
where: <address> is the starting address where user program subroutine execution begins.
EXAMPLE
>CALL C000
P-COOO Y-DEFE X-F4FF A-44
B-FE C-DO 5-004A
DESCRIPTION
Execute program subroutine.
Displays status of registers at
time RTS encountered (except
P register contents).
G(GO)
Execute
Program
G [<address>]
where: <address> is the starting address where user program execution begins.
EXAMPLE
>G C000
P-COOO Y-DEFE X-F4FF A-44
B-FE C-DO 5-004A
DESCRIPTION
Execute program subroutine.
Displays status of registers at
time RTS encountered (except
P register contents).
HELP
Help Screen
HELP
Display monitor commands
MD
Memory
Display
MD [<address1> <address2>]
Display a block of user memory beginning at address 1 and continuing to address 2.
EXAMPLE
>MD C000 C00F
C000 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
MM
Memory Modify
MM [<address>]
Examine/Modify contents in user memory at specified address in an interactive manner
EXAMPLE
Dr. Victor Giurgiutiu
DESCRIPTION
Page 37
8/19/2008
EMCH 367
>MM C700
C700 44 66(RETURN)
>MM C000
C000 55 80 C2 00 CE C4
Microcontrollers in Mechanical Engineering
Course Package.doc
Display memory location C700.
Change data at C700
Examine location $C000.
Examine next 1ocation(s) using (SPACE BAR).
RM
Register Modify
RM [p,y,x,a,b,c,s]
The RM command is used to modify the MCU program counter (P), Y index (Y), X index (X), A accumulator (A), B
accumulator (B), Condition Code Register (C), and stack pointer (S) register contents.
EXAMPLE
DESCRIPTION
>RM
P-C007 Y-7982 X-FF00 A-44 B-70 C-C0 S-0054
P-C007 C020
Display P register contents.
>RM X
P-C007 Y-7982 X-FF00 A-44 B-70 C-C0 S-0054
X-FFOO C020
Display X register contents.
Modify P register contents.
Modify X register contents.
T
Trace
T[<n>]
Where: <n> is the number ($1~$FF) of instructions to execute.
Monitor program execution on an instruction-by-instruction basis. Execution starts at the current program counter
(PC).
EXAMPLE
>T
Op-86
P-C002 Y-DEFE X-FFFF A-44 B-00 C-00 S-0048
>T2
Op-B7
P-C005 Y-DEFE X-FFFF A-44 B-00 C-00 S-004B
Op-01
P-C006 Y-DEFE X-FFFF A-44 B-00 C-00 S-004B
Dr. Victor Giurgiutiu
Page 38
DESCRIPTION
Single trace
Register contents after
execution.
Multiple trace (2)
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
DEBUGGING TIPS
MICROCONTROLLER PROBLEMS
•
•
•
•
Is the processor plugged into the PC serial port?
Is the processor plugged into the power supply?
Is the power supply turned on?
Is the serial port plugged into the correct connector?
HARDWARE PROBLEMS
•
•
•
•
•
•
•
•
•
•
Does the component have power? - Check all voltages
Are the chips oriented correctly - notch in the correct direction?
Do the chips straddle the gap in the center of the board?
Make sure all chips have power (not just input & output lines).
Verify the direction of diodes and electrolytic capacitors.
Verify the power at intermediate locations - use 5 or 0 volts from the supply instead of chip input to
check various conditions.
Verify that the PC ports are giving the expected output signals.
Verify chip and transistor pins with the pin diagrams.
Are there any "open" lines, no voltage connection instead of zero volts?
Verify resistor codes and capacitor values.
SOFTWARE PROBLEMS
•
•
•
•
•
•
•
•
•
•
•
•
•
Is the correct program currently in memory?
Is the correct starting location being used (G ????).
Verify the program with ASM.
Use trace (T) to step through and verify branches, jumps and data.
Compare memory locations with expected information after the program stops.
Insert SWI at a key location to allow verification of branch, memory and accumulator values.
Do branches and jumps have the correct offsets?
Have RET and RTI commands been reversed somewhere?
For serial communications, has TE or RE been set?
For serial communications, has TDRE or RDRF been reset?
For parallel port C, has 1007 been set for input or output?
Has the interrupt mask been cleared (CLI)?
Has the stack pointer changed substantially?
Use the BUFFALO commands to do step-by-step (Trace, T) and Break-Point (BR) execution of the
program. Press F1 for details of the BUFFALO commands.
Dr. Victor Giurgiutiu
Page 39
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THRSIM11 SIMULATION OF PARALLEL COMMUNICATION
The specific windows that need to be open during the THRSim11 simulation of parallel communication
are:
• Port registers
• Port B pins
• Port C pins
Dr. Victor Giurgiutiu
Page 40
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THE THRSIM11IO BOX
The THRSim11 IO box is use, among others, to perform the simulation of Port B and Port C functions.
Port B, which is only an output port, is simulated as the eight LED’s PB0, PB1, … , PB7. When a
logical 1 signal is sent to a Port B pin, PBx, the corresponding LED lights up (becomes red).
Port C pins (PC0, PC1, … , PC7) can be selected as either input or output using the DDRC register bits
in your program. When selected as input (DDRCx = 0, x = 0, 1, … , 7), the switches are used to send
signals into the MCU along the PCx line. When selected as output (DDRCX = 1), the switches flip up
and down according to the value on that PCx line. (up = 1, down = 0)
Dr. Victor Giurgiutiu
Page 41
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
ASCII AND BCD CODES
Dr. Victor Giurgiutiu
Page 42
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THRSIM11 SIMULATION OF SERIAL COMMUNICATION
The specific windows that need to be open during the THRSim11 simulation of serial communication
are:
• Serial registers
• Serial transmitter
• Serial receiver
Dr. Victor Giurgiutiu
Page 43
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THE THRSIM11 SERIAL TRANSMITTER
The THRSim11 serial transmitter simulates the PC keyboard in the lab. It sends characters to the MCU.
During simulation, with your program running, type a character in the transmitter and press the Send
button. The MCU should receive it and react according to your instructions.
Dr. Victor Giurgiutiu
Page 44
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THE THRSIM11SERIAL RECEIVER
The THRSim11 serial receiver acts like the PC monitor in the lab. It receives signals sent by the MCU.
With your program running, and the serial receiver window open, you should see a character displayed
in the receiver window every time the MCU transmits a character while executing your program.
Dr. Victor Giurgiutiu
Page 45
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THRSIM11 SIMULATION OF TIMER FUNCTIONS
The specific windows that need to be open during the THRSim11 timer functions simulation are:
• Timer registers
• Port A pins
• Number of Clock cycles
Dr. Victor Giurgiutiu
Page 46
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
THRSIM11 SIMULATION OF ANALOG TO DIGITAL CONVERSION
The specific windows that need to be open during the THRSim11 simulation of analog to digital
conversion are:
• AD converter registers
• Sliders E port
Dr. Victor Giurgiutiu
Page 47
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
EE ENGINEERING BASICS
Dr. Victor Giurgiutiu
Page 48
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
BASIC MULTIMETER OPERATION
BASIC MULTIMETER INFORMATION
Multimeter is a measuring instrument. It can be used to measure voltage, current and resistance.
An analog meter (Figure a) moves a needle along a scale. The function of the meter can be changed by
switching the dial. Analog multimeter shown in the figure is cheap but difficult for beginners to read
accurately.
Most modern multimeters are digital. Similar to analog ones, digital multimeter (Figure b) has a dial to
select its function. However, instead of having to interpret the reading of an analog scale, the data is
shown directly in digital format on the LCD display. In addition, the units are also shown.
Multimeter will be used in several labs, and important for checking circuit when doing your final project.
Digital multimeters will be provided by the lab. A check out form must be approved and signed by a TA
or instructor of this class before you can get a multimeter in the lab.
(b)
(a)
BASIC MEASUREMENT PROCEDURES
1. Before using the multimeter, estimate the value you will measure, make sure it is within the
range that the multimeter can measure or withstand.
2. Choose to the function you want to use by switching the dial. Turn on the power.
3. When measuring voltage, connect the BLACK probe (COM) to the ground (0V), and the RED
probe to the nod you want to check. When measuring resistor, first make sure the resistor is not
connected to any other component or power supply, then connect the probes to the two ends of
the resistor.
4. Two alligator clips are supplied with probes. For your safety, alligator clips MUST be used
when measuring any voltage more than 36V. They can also be used to free your hands by
clipping the probes onto the circuit. Put the alligator clips back in the box after each use.
5. Read the data on the LCD display, remember the units.
6. Turn off the power after you finish.
MULTIMETER TROUBLESHOOTING
1.
2.
3.
4.
Is the BLACK probe in the COM plug?
Is the RED probe in the correct plug?
Is the function dial turned to the correct position?
Is the power of the multimeter on?
Dr. Victor Giurgiutiu
Page 49
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
BASIC OSCILLOSCOPE OPERATION
BASIC MEASUREMENT PRINCIPLES
The oscilloscope (O-scope) is a valuable tool for both diagnostic and measurement purposes. It displays
a voltage vs. time plot. The voltage displayed is determined as the difference between the measured
voltage and the reference voltage.
Both the measured and the reference voltage are determined from the probe. Although there are many
types of probes, they all have three basic components: a measured voltage lead, a reference voltage lead,
and a connection to the oscilloscope. To measure a voltage, or potential difference, with the oscilloscope,
one must do three things:
1)
2)
3)
Establish a reference. This is done by attaching the reference lead of the probe to the desired
potential. For our purposes we will always use ground (0V) for our reference.
Measure the voltage. This is done by placing the measuring lead of the probe to the potential to
be measured.
Display the measurement properly and interpret the results.
The first two aspects are relatively straightforward. They involve physical placement of the probe leads.
The third aspect of oscilloscope use is critical; to be a useful tool, the oscilloscope must be configured
such that the user knows the voltage vs. time profile.
Vertical and horizontal
position adjusters
Signal
display
adjusters
Time
scale
Channel 1
Voltage scale
for channel 1
Trigger
Voltage scale
for channel 2
Channel 2
Probe
adjuster
External
trigger
In the EMCH367 lab, you will be using the analog Tektronix 2225 O-scope, which can display 2
channels, as indicated in the above figure. The voltage (vertical) scale for each channel can be set
separately, using the appropriate knobs. You can display the channels separately or together, or perform
basic arithmetic operations on the signals (addition, inversion). The time (horizontal) scale can display
from .05μs to 0.5s per division, with 10 horizontal divisions. Results that the maximum wavelength able
to be displayed is 10x0.5s=5s, corresponding to a minimum frequency of 0.2Hz.
If you have doubts about the proper functioning of one of the O-scope channels or the probes, you can
ask a TA for help, or check yourself, using the following procedure: a) hook up the probe corresponding
Dr. Victor Giurgiutiu
Page 50
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
to the supposedly bad channel to the “Probe adjuster” pin; b) set the timescale to .5ms; c) if the probe
you use is 1X, set the appropriate voltage scale to 0.5 V; if the probe is 10X, set the voltage scale to
50mV; d) set the “Trigger Source” on the tested channel; e) use the vertical and horizontal adjuster to
clearly see the signal on the O-scope display. If the equipment is in good condition, you should see a
square wave with the half-wavelength equal to a horizontal division, and the height equal one vertical
division.
TRIGGER
Most of the measurements made in this course will have fairly long time periods with respect to the
capability of the oscilloscope to measure it, but more importantly, with respect to your eyes' ability to
interpret the plots. In some cases, though, the use of a trigger function of the oscilloscope is very useful.
A trigger is used when the signal to be measured is very rapid, difficult to measure, or occurs
sporadically. In essence, the trigger is a separate probe, which looks for a pulse, or a transition of the
voltage from one state to another. Once the oscilloscope trigger probe detects a pulse, the oscilloscope
knows that the signal of interest is going to follow along the measuring probe. Then, the pulse can be
displayed along with the signal to give a point of reference. You will use the trigger function in Lab 4,
Serial Communications.
OSCILLOSCOPE TROUBLESHOOTING
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
If the oscilloscope image is not what you think it should be, consider the following:
Make sure the oscilloscope power is on.
Make sure that the intensity is not turned all the way down.
Make sure the probe is plugged into the oscilloscope.
Make sure you are measuring the proper voltage (What is the probe touching?).
Make sure you have the proper reference voltage (Where is the reference wire?).
Make sure you are displaying the signal from your probe channel.
Make sure the voltage is set for the proper scale for your probe (most lab probes are 10x).
Make sure the oscilloscope is set to measure a DC voltage.
Use the beam find function to verify that the beam is on the screen. Adjust the horizontal and
vertical position if it is not.
Make sure the calibration knobs are properly set. The knobs should be turned counter clockwise
till they “click”.
If you are using the trigger function, make sure the trigger is properly set.
Adjust the time scale.
Dr. Victor Giurgiutiu
Page 51
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
RESISTORS
CHART TO READ RESISTORS
R = (First Digit)(Second Digit) x (Multiplier) ± (Tolerance)
R = (First Band)(Second Band) x (Third Band) ± (Fourth Band)
st
Color
1 Band
2nd Band
Black
0
0
Brown
1
1
Red
2
2
Orange
3
3
Yellow
4
4
Green
5
5
Blue
6
6
Violet
7
7
Gray
White
8
9
Silver
10%
brown black
red
8
9
Fourth Band Represents Tolerance
Gold
rd
3 Band
1 (100)
10 (101)
100 (102)
1k (103)
10k (104)
100k (105)
1M (106)
10M (107)
100M (108)
--5%
gold
| 1 | 0 | x 100 = 1000 Ω = 1 kΩ ±5%
A quick reference for retrieving the resistance of a particular resistor, based on the color code:
http://www.electrician.com/resist_calc/resist_calc.htm
RESISTORS AVAILABLE IN THE EMCH 367 LAB
10 Ω
22 Ω
47 Ω
56 Ω
100 Ω
200 Ω
220 Ω
470 Ω
1 kΩ
1.8 kΩ 2.2 kΩ 4.7 kΩ 5.6 kΩ 6.8 kΩ 8.2 kΩ 10 kΩ
27 kΩ
56 kΩ
100 kΩ 220 kΩ 470 kΩ 680 kΩ 820 kΩ 1 ΜΩ
A selection of variable resistors (potentiometers or “pots”) is also available.
Dr. Victor Giurgiutiu
Page 52
680 Ω
16 kΩ
4.7 ΜΩ
10 Ω, 5 W
22 kΩ
10 ΜΩ
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
EMITTER-DETECTOR
Dr. Victor Giurgiutiu
Page 53
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
OPEN COLLECTOR COMPARATOR
Dr. Victor Giurgiutiu
Page 54
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
OPEN COLLECTOR BUFFER
Dr. Victor Giurgiutiu
Page 55
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
OP AMP
POWER TRANSISTOR
Dr. Victor Giurgiutiu
Page 56
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
PORT PROTECTION
GENERIC INPUT TO MICROCONTROLLER PORTS
Dr. Victor Giurgiutiu
Page 57
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
PORT A PROTECTION
OPTOISOLATOR (OPEN COLLECTOR)
Dr. Victor Giurgiutiu
Page 58
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
KEYBOARD AND DISPLAY CIRCUITS
Dr. Victor Giurgiutiu
Page 59
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
EMCH367 HARDWARE LIST
Dr. Victor Giurgiutiu
Component
Stock
8 Pin
8 Pin connector
DIP socket 8 PIN
DIP socket 14 PIN
DIP socket 16 PIN
DIP socket 20 PIN
DIP socket 24 PIN
DIP socket 28 PIN
DIP socket 40 PIN
PLCC socket 52 PIN
Socket adaptor 60 PIN
8 Pin connector cover
BNC T Jack-Jack-Jack
BNC Connector
BNC T Jack-plug -Jack
BNC Jack-Jack
BNC terminal
BNC wall outlet
BNC misc.
Crystal (8M)
Fuse (125V, 4A)
HP display IC
Heat sink
Jumper
Led red
Led green
Led yellow
Led 7-segment (common anode)
led 10-segment
Magnetic switch
Micro-phone
Switch NC push button
Switch NO push button
Switch light touch
Switch lever type
Switch SPST DIP
Switch toggle type
SMD-DIP adapter
Terminal Block
10 Ω resistors
50
40
30
20
15
4
20
20
6
15
15
40
2
1
1
7
3
0
1
12
3
2
10
25
300
5
30
30
20
1
1
30
1
8
8
15
10
2
20
100
Page 60
Reorder?
(Y/N)
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
Y
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
22 Ω resistors
47 Ω resistors
56 Ω resistors
100 Ω resistors
150 Ω resistors
200 Ω resistors
220 Ω resistors
470 Ω resistors
680 Ω resistors
5.6KΩ resistors
1.8KΩ resistors
2.2KΩ resistors
2.4KΩ resistors
4.7KΩ resistors
1KΩ resistors
6.8KΩ resistors
8.2KΩ resistors
10KΩ resistors
16KΩ resistors
22KΩ resistors
24KΩ resistors
27KΩ resistors
56KΩ resistors
100KΩ resistors
220KΩ resistors
470KΩ resistors
680KΩ resistors
820KΩ resistors
1MΩ resistors
4.7MΩ resistors
10MΩ resistors
10Ω/5W resistors
POT 0.5K
POT 1K
POT 50K
POT 100K
POT 200K
POT (for lab 250KΩ)
5PF capacitor
10PF capacitor
27PF capacitor
100PF capacitor
1000PF capacitor
0.1 μF capacitor
Dr. Victor Giurgiutiu
Page 61
Course Package.doc
50
50
50
100
100
20
100
100
100
40
30
30
40
100
50
30
40
40
50
40
50
30
40
50
40
40
40
40
80
30
4
20
0
1
4
6
0
13
3
20
50
30
20
30
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
Y
N
N
N
Y
N
N
N
N
N
N
N
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
0.047 μF capacitor
0.68μF capacitor
4.7μF capacitor
22μF capacitor
33μF capacitor
220μF capacitor
0.1μF/50V capacitor
2.1μF capacitor
22PF capacitor
Diodes
LM 431 Adjustable Precision Zener Shunt Regulator
Transistor 2N 2219A
Transistor PN 2222A
TIP 120
TIP 121
TIP 122
TIP 42
TIP 30B
IRF 530
7805 voltage regulator
7812 voltage regulator
7912 voltage regulator
Temperature Sensor
Modular Jack (RJ45)
12-bit A/D converter LTC 1290
INA 118 precision amplifier
7420 Dual 2 input NAND
7430 8 input NAND
7475 Quad Latch
7483 4-bit BIN Adder
7486 Quad 2 input XOR
7490 Decade counter
74125 Quad tri-state buffer
74132 Quad 3 input NAND Schmitt trigger
74136 Quad 2 input XOR OC output
74138 3-8 line decoder
74193 Sync. 4-bit up/down BIN counter
74136 Sync. 4-bin counter
74154 4-16 line decoder
74244 Octal tri-state
74373 latch
LM301 OP-AMP
LM311 Voltage comparator
LM555 timer
Dr. Victor Giurgiutiu
Page 62
Course Package.doc
50
4
10
40
20
10
1
10
5
100
20
5
5
50
20
15
10
10
30
10
10
5
0
10
1
1
10
5
25
10
40
15
8
20
10
0
30
2
20
20
20
0
40
15
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
Y
N
N
N
N
N
N
N
N
N
N
N
N
Y
N
N
N
N
N
Y
N
N
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
LM741 OP-AMP
LM 1458 dual OP-AMP
LM 3914 Dot/Bar graph display driver
ADC0833 serial I/O 8-bit A/D converter
DAC0808 8-bit D/A converter
CD4013 dual D-flip flop
CD4066 Quad bilateral switch
CD 4511 BCD decoder
MC14049 HEX Buffer Inverter
MC1488 Quad line driver
MC1489 Quad line receiver
PS2501 OPTICALLY COUPLED ISOLATORS
MC6810/6811
MC6850
TC9402 voltage-to-frequency (V/F) converter
MAX232
Solid relay
Beaded tie
DC motor plate
Braided wire
Terminals
5 inch bolt
DC-DC converter
Chip extractors
Wire cutters
Soldering irons
Solder suckers
Solder
IC printed circuit boards
Solid, single conductor wire in many different colors
Multi-conductor wire in red/black
Electromagnets/magnet wire
Ribbon cable
MRTl00F connector repair tool
2 pin jumpers
+12V
Battery
+6V
+1.5V
Small Digital Meters
Large digital Meters
Electromagnets & Solenoids
Large
Speaker
Small
Battery holder
Dr. Victor Giurgiutiu
Page 63
Course Package.doc
20
20
10
8
30
4
2
30
5
3
4
60
25
25
5
8
5
50
10
1
40
1
2
1
20
3
1
2
3
1
1
1
1
1
40
1
1
4
10
8
5
3
6
25
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
DC motor (Super Jack)
Fan(with DC motor)
Power adapter
115AC-8.5VDC
115AC-12VDC
Push Button Box (for lab)
Servo Motor
10-Segment led board
Oscilloscope Probes
DC-pump
Light
Large breadboard
Small Breadboard
Robot
Stepper Motor Driver boards (for lab)
Small Analog Meters
Magnetic Sensor
Motion Sensor
Emitter/Detector (Omron)
Pressure sensor
Sensors
Temperature sensor
Emitter detector (amplified)
Emitter detector (Non-amplified)
Thermocouple
EVB Port Cable
Dr. Victor Giurgiutiu
Page 64
Course Package.doc
16
1
2
1
1
2
12
13
10
8
8
24
1
5
15
3
3
3
2
1
9
25
1
12
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
N
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
INTRODUCTION TO FUNCTIONAL MODULES
An essential part of our mechatronics education is the construction of functional modules to help
teaching hands-on skills related to the interfacing of mechanical, electrical, and electronic components
of a Mechatronics system. Non-EE engineering students need hands-on experience to increase their
ability and confidence in tackling electrical and electronics concepts, especially during the realization
phase of a Mechatronics project. To address this need, we started developing a suit of functional
teaching modules.
The modules that have been developed include:
i) voltage divider;
ii) op-amp signal amplifiers;
iii) opto-electronic sensor;
iv) on/off (field-effect MOSFET) power amplifier;
v) linear power amplifier;
vi) pulse-width modulation dc motor drive unit;
vii) stepper motor drive unit;
viii) AC/DC converter;
ix) temperature sensor;
x) humidity sensor;
xi) H-bridge for DC motor (relay and transistor);
xii) dimmer circuit;
xiii) open collector buffer;
xiv) voltage comparator;
xv) limit switch;
xvi) wireless transmitter and receiver;
xvii) ultrasonic sensor.
Accompanying the functional modules are electrical and component schematics, applicable equations,
and a full experimental report containing calibration results. These functional modules are intended as
bolt-on building blocks with clearly defined inputs and outputs, and an explanation of the underlying
operational principles. To achieve this, the functional modules are housed in transparent casings, which
allow the students to see the actual electric/electronic components of the circuitry, and to compare this
image with the intricacy of the circuit diagram. The students are expected to use the functional modules
as a learning tool. After understanding their functionality, they are expected to duplicate the circuitry on
their own breadboards to be incorporated into their Mechatronics class projects, as well as into other
hands-on projects.
ASK YOUR TA ABOUT THE FUNCTIONAL MODULES BINDER. IT WILL BE VERY USEFUL
FOR THE PROJECT.
Dr. Victor Giurgiutiu
Page 65
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
ATTACHMENT 1: EMCH 367 PROJECT PROPOSAL
Team members:
_____________
_____________
_____________
_____________
Project Title:
Project Proposal
1. Proposed idea
2. System overview
3. Program design, with flowcharts
4. Hardware design, with necessary component list and components diagram
Note: Just brief description. Program flowcharts are required. If you need to use some electronic
components, please attach the related diagrams. Example: The LM1458 operational amplifier diagram:
LM1458
B
A
output A
+ 15V
Inverting
input A
output B
Non-inverting
input A
Inverting
input B
- 15V
Dr. Victor Giurgiutiu
Non-inverting
input B
Page 66
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
ATTACHMENT 2: PROJECT REPORT TEMPLATE
University of South Carolina
Department of Mechanical Engineering
EMCH367 – Fundamentals of Microprocessors
Spring 2003 Course Project Report
TA Mentor: _______________________
XXXXXXX TITLE XXXXXXX
by
YYY YYYYYY
ZZZ ZZZZZZ
Date: …………….
Dr. Victor Giurgiutiu
Page 67
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Table of Contents
(Insert Table of Contents auto-generated by Word from the Insert menu)
Dr. Victor Giurgiutiu
Page 68
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Note on using the heading styles in Word
Through out your typing, you should take advantage of using the heading styles in MS
Word. Using heading styles has multiple advantages:
1. It helps you organize your report easily
2. It lets you make an automatic Table of Contents
3. It lets you shift text around using the Outline View
4. Others (can you name more? -- email them to me at [email protected])
You can make a text entry be raised to a certain heading level (Heading 1, or Heading 2,
3 etc.) by selecting the appropriate heading style from the style window (where you
usually see “Normal”). If the heading styles are visible in the styles window pull-down
menu, go to Format/Styles and select the desired heading style from the list. I have
already used heading styles when writing this template. You may add more headings to
the document as needed. DO NOT DELETE THE HEADING ALREADY EXISTING –
THEY ARE REQUIRED.
Note on using the Word picture editor
This is a Word picture
Figure 3 This is a Word picture.
If you have not used other software for producing the drawing, sketches, or circuit
diagrams, use WORD PICTURE EDITOR. To start a Word picture, go the pull down
menu Insert/Object, and select Microsoft Word Picture. You will be opened into a Word
Picture Editor screen. Activate the Drawing toolbar from the View pull down menu (if
not already activated), and use the available drawing tools. YOU WILL HAVE FUN.
When ready, press the Reset Picture Boundary button on the Edit Picture tool bar, and
then press Close.). By done last action: make the picture layout ‘In line with the text’ (By
default, the picture is floating over text). To do so, right click on the picture, choose
Format Object, select the Layout tab, and choose ‘In line with the text’.
To Drawing toolbar has Flowchart symbols. To access them, go to Autoshapes/Flowchart.
Dr. Victor Giurgiutiu
Page 69
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
Note on using pictures created in Excel, MathCad, and other
software packages
When copy and paste from Excel, MathCad, or other software, DO NOT PASTE
DIRECTLY. Rather, use the PASTE SPECIAL under the Edit menu, and select ‘Paste as
picture’. The difference is that if you paste directly, you are going to embed into you
Word file the original Excel, MathCad, etc. file, such that when you double click on the
picture, you will be opened into the original application. You do not need this feature,
and you DO NOT WANT to do it, since your Word file will quickly grow to very large
size. Hence, paste special as a picture. This will keep your file size manageable.
Note on the template
This template is intended for your orientation. You are free to modify and add to it as
needed. However, remember that you are responsible for making a full comprehensive
report.
Dr. Victor Giurgiutiu
Page 70
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
1. EXECUTIVE SUMMARY
(Give a 1-paragraph summary of your report)
2. INTRODUCTION
Introduce the reader to the subject, make him/her familiar to the state of the art in the
subject, identify the target market, discuss the demand for your product, and put forward
your proposed concept.
Background
Needs and Opportunities
Proposed Concept
3. TECHNICAL DESCRIPTION
(In this section, you will transfer all the technical information for the reader to duplicate
your work, if the need arises)
3.1 SYSTEM OVERVIEW
Give a short overview of the system.
Describe expected behavior.
List function the product should fulfil)
Use figure/photos/sketches to bring your point home.
Being an overview (and not the full description), do not exceed 1 page.
3.2 HARDWARE DESIGN
Describe the hardware design of your product.
Include drawings, schematics, sketches, and circuit diagrams, as needed to properly
convey the message and identify each important component.
Describe the function of each component, how it works and what it does.
3.3 SOFTWARE DESIGN
Describe the logic flow (intelligence component) in your product.
Include flowcharts
Include program printout
3.4 ACCEPTANCE TESTS
Describe the tests you have done to prove the product is working.
Include results in table or chart format.
Dr. Victor Giurgiutiu
Page 71
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
4. ECONOMIC ASPECTS
Give a succinct description of the economic aspect related to producing the prototype and
future production. Determine the commercial feasibility of your product.
4.1 PROTOTYPE COSTS
Work out the prototype costs using the Excel spreadsheet below. Introduce your own
estimates of personnel rates and times and of material costs base on your experience with
building the prototype.
PROTOTYPE COSTS
Engineer
Technician
Others
Total Personnel Costs
Materials
Total Direct Costs
Indirect Costs @
Total Prototype Costs
$/hr
50
40
30
hours
10
10
2
Personnel
costs
$
500
$
400
$
60
$
960
$
100
$ 1,060
$
482
$ 1,542
45.50%
4.2 PRODUCTION COSTS, PRODUCTION PRICE, AND RETAIL PRICE.
Work out the production costs and production price using the Excel spreadsheet. Estimate
retail and distribution costs and work out a retail price per item.
PRODUCTION COSTS and FACTORY PRICE per 1000 items
Personnel
$/hr
hours
costs
50
80
$
4,000
Engineer
40
120
$
4,800
Technician
30
20
$
600
Others
Total Personnel Costs
$
9,400
Materials
$ 50,000
Total Direct Costs
$ 59,400
Indirect Costs @
45.50%
$ 27,027
Total Production Costs per 1000 items
$ 86,427
Profit @
7%
$
6,050
$ 92,477
Total Factory Price per 1000 items
Factory Retail Price per item
$
92.48
4.3 COMMERCIAL FEASIBILITY
Based on the cost and price items above, and using data about similar items (either
already on the market or in preparation for the market by the competition), make an
estimate of the commercial feasibility of your product.
Dr. Victor Giurgiutiu
Page 72
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
5. CONCLUSIONS
Write up a succinct wrap up of your project. Highlight achievements and project the
course forward. Insist on the mental image that you want the reader to be left with after
reading your report.
6. REFERENCES
List the references that you used in writing up the report.
1. Engineer's Mini Notebook Series, Radio Shack, Inc.
2. National Semiconductor Databooks
3. Found in the lab, these books contain all the technical specifications of the electronic
devices we will use. They are generally called "The Blue Books."
4. The Engineering Handbook. Richard C. Dorf (Ed), CRC Press, 1995,
ISBN 0-8493-8344-7.
5. Mark’s Standard Handbook of Mechanical Engineers, E. A. Avallone and T.
Baumeister III, 9th Edition, McGraw Hill, 1987.
6. Others
Dr. Victor Giurgiutiu
Page 73
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
ATTACHMENT 3: PRESENTATION TEMPLATE
General Instructions
•You have the liberty to select the background, transition effects, sounds, etc.
•Use the Slide Master view to make settings that apply to the whole document
•Use the following slides as a minimum requirement. Add to them as necessary to carry
your point through effectively.
•Use figures, photos, diagrams liberally. This is a visual show!!! We have both a digital
still camera and a digital video camera for those who wish to use them.
Acknowledgements
• Here is the place to express gratitude for th
help and/or support received from others
Introduction
Outline
• Bullet the main items of your talk
• What?…Describe your product.
• Who?…Identify your target market.
• Why?…Discuss the demand for your
product.
Technical Description (several
slides -- this is the main body)
• How
• Materials Used
• Hardware considerations
– Diagrams, schematics, etc
– Photo of project with callout
• Software Considerations
– Subroutines, Difficult Logic?
Dr. Victor Giurgiutiu
Troubleshooting
• Testing
• Problems encountered
Page 74
8/19/2008
EMCH 367
Microcontrollers in Mechanical Engineering
Course Package.doc
(Continued)
Economic Aspects
• Here you should have charts showing
– prototype costs and price
– production costs and retail price
• Use table format similar to that given to yo
in the Report Template.
Miscellaneous. Info.
• Commercial Feasibility
• Anything else?
Conclusion
• Wrap up your work nicely and leave a goo
feeling about it.
Dr. Victor Giurgiutiu
Page 75
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Examples
EXAMPLES
Examples are mainly intended for the students to get started quickly with the basic concepts,
programming language, and hex/binary conventions. The following examples are available:
Word file
Example_1
Example_2
Example_3
Example_4
Example_5
Example_6
Example_7
Example_8
Example_9
Example_10
Example_delay
Example_sq_wave
Example_buttons_bx
Example_SCI_transm
Example_SCI_recept
Example_IC
Example_OC
Example_RPM_1
Example_RPM_2
Example_Step
Example_Long_Delay
Example_Sort
Example_AD_convert
ASM file(s)
Ex1.asm
Ex2.asm
Ex3.asm
Ex4.asm
Ex5.asm
Ex6.asm
Ex7.asm
Ex8.asm
Ex9.asm
Ex10.asm
Ex_Delay.as
m
Sq_wav1.asm
Buttons_bx.as
m
SCI_transm.a
sm
SCI_recept.as
m
Ex_IC.asm
Ex_OC.asm
Ex_RPM_1.as
m
Ex_RPM_2.as
m
Ex_Step.asm
Ex_Long_Del
ay.asm
Ex_Sort.asm
Ex_AD_1.as
m
Sq_wav1.asm
HEX_BCD.as
m
Ex_AD_2.as
m
Ex_AD_3.asm Ex_AD_4.asm
An overview of the examples is presented next.
Dr. Victor Giurgiutiu
Page 76
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Examples
EXAMPLES OVERVIEW
#
Example_1
Example_2
Example_3
Example_4
Example_5
Example_6
Dr. Victor Giurgiutiu
Concepts
• Familiarize the user with the THRSim11 simulator environment
• Introduce the user to the syntax and concepts of Assembly (.asm) language
• Familiarize the user the way arithmetic operations are handled by the
microcontroller
• Instruct the user to interpret the List (.LST) file.
• Teach the user to perform the simulation and follow the step-by-step results.
• Introduce the LDAA, LDAB and ABA operations
• Introduce inherent mode
• Introduce immediate mode
• Familiarize the user with the THRSim11 simulator environment
• Introduce the user to the syntax and concepts of Assembly (.asm) language
• Familiarize the user the way arithmetic operations are handled by the
microcontroller
• Instruct the user to interpret the List (.LST) file.
• Teach the user to perform the simulation and follow the step-by-step results.
• Introduce ADDA operation
• Review the principles of the decimal numbers, i.e., in the range 0 – 9
• Review the decimal carry concept, i.e., when a result is outside the 0 – 9 range.
• Prepare the ground for hex arithmetic
• Introduce hex numbers and hex symbols, a, b, c, d, e, f.
• Introduce single precision and double precision registers
• Introduce hex arithmetic.
• Review 2-digit decimal arithmetic with carry to prepare the ground for 2-digit hex
arithmetic with carry.
• Introduce hex arithmetic with carry
• Facilitate comparison with the decimal case by using the same numbers as in
Example 5
Page 77
8/19/2008
EMCH 367
Example_7
Example_8
Example_9
Example_10
Example_
delay
Example_
sq_wave
Fundamentals of Microcontrollers
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Dr. Victor Giurgiutiu
Examples
Introduce 2-digit hex arithmetic with carry
Introduce the ‘lost carry’ concept
Introduce unsigned hex overflow
Introduce incrementation (INCA)
Introduce decrementation (DECA)
Review decimal borrow concepts using decrementation
Introduce hex borrow using decrementation
Introduce 2’s complement negative hex numbers as decrementation of zero with
free borrow
Show the decimal equivalent of the 2-digit hex decrementation of zero
Introduce hex subtraction
Introduce hex subtraction with negative results using the free borrow concept.
Show the decimal equivalent of hex subtraction with negative results using free
borrow.
Introduce 8-bit binary numbers
Introduce connection between 8-bit binary numbers and 2-digit hex numbers.
Introduce 8-bit binary arithmetic
Introduce binary 8-bit logic
Introduce masking
Review the use of branching
Illustrate a delay (wait) program
Demonstrate a flowchart and its relation with the program tasks list and program
code
Demonstrate the calculation of clock cycles from the clock cycles of each operation
Demonstrate the calculation of MCU time from the clock cycles
Review the use parallel ports
Illustrate the generation of a square wave using Port B output and a waiting
sequence
Demonstrate the use of a subroutine to shorten the length of a program
Examine the relation between displayed simulation time and clock cycles in
THRSim11 simulator
Page 78
8/19/2008
EMCH 367
Example_
buttons_bx
Example_
SCI_transm
Example_
SCI_recept
Example_IC
Fundamentals of Microcontrollers
•
•
•
•
•
•
Review the use parallel ports
Illustrate the use of Port C for input and output
Introduce the concept of shifting register and memory content
Practice the use of the THRSim11 IO box for input and output
Review the use of serial communication interface (SCI) for transmission
Illustrate the sending of a character through SCI
•
•
•
•
•
•
Review the use of serial communication interface (SCI) for reception
Illustrate the receiving of a character through SCI
Review the use of MCU Timer function as an Input Capture (IC) device
Review the use of the free running clock, TCNT, and it overflow flag, TOF
Review the use of a input capture clock, TIC1, and its event flag, IC1F
Demonstrated how the selection of signal transition to be captured is made (here
rising edge, EDG1A) and that the MCU is only sensitive to that particular
transition.
Show the calculation of actual time in μs from the timer readings, T1, T0, and
overflow count, NOF.
Review the use of MCU Timer function as an Output Compare (OC) device
Review the setting of OMx and OLx bits to select a desired OC event (in this
example, we set OM3=0, OL3=1, to generate a toggle on the OC3 pin)
Review the detection of the TOCx match with TNCT and the corresponding OC
action
Present the correlation between delay, DT, with actual frequency of the square
wave.
Explore the accuracy with which frequency can be adjusted
Explore the determination of low and high bounds on the frequencies that can be
generated with the MCU
Review the use of MCU Timer function as an Input Capture (IC) device
Review the use of the free running clock, TCNT, and it overflow flag, TOF
Review the use of a input capture clock, TIC1, and its event flag, IC1F
Demonstrated how the selection of signal transition to be captured is made (here
rising edge, EDG1B) and that the MCU is only sensitive to that particular
transition.
Introduce the use of soft masks (here, IC1_MSK, TOF_MSK).
Introduce the concept of layered flowcharting of a program: big-picture with
generic descriptions; detailed flowcharts for particular sections of the program.
•
Example_OC
•
•
•
•
•
•
Example_
RPM_1
•
•
•
•
•
•
Dr. Victor Giurgiutiu
Examples
Page 79
8/19/2008
EMCH 367
Example_
RPM_2
Fundamentals of Microcontrollers
•
•
•
•
•
•
•
Example_
Step
•
•
•
•
•
•
Example_
Sort
Example_
Long_Delay
•
•
•
•
•
Example_
AD_convert
•
•
Dr. Victor Giurgiutiu
Examples
Review the used of two time captures to calculate the time duration of an event
Illustrate the use of scaling factors (100s) to deal with numbers that are larger than
the microcontroller word length
Illustrate the handling of overflow counts, with special attention to the situation
when the two time captures are on one side and another of a timer overflow (timechange line)
Introduce the method of calculating multiplication through repeated additions and
decrementation of a counter
Introduce the use of a conversion subroutine to convert from hex to BCD
Illustrate rotation speed calculation from rotation period.
Illustrate the use of scaling factors (100s) to present the result on a display with
limited number of digits.
Review the use and control of stepper motors.
Discuss the stepper motor energizing patterns, 1- and 2-phase energizing types,
full- and half-step motion.
Introduce the concept of creating quasi-continuous motion through a sequence of
steps
Introduce the concept of sequential accessing a finite set of stored patterns through
index addressing with a continuously updating pointer.
Illustrate a method to ‘load’ a single-precision (2-hex) variable into a double
precision (4-hex) register.
Introduce the concept of automatic incrementation/decrementation of the
addressing pointer with a programmable step size
Discuss the reset actions to be taken when the pointer hits the ‘roof’ or ‘floor’.
Review the use of keystroke commands for controlling a process
Introduce the concept of ‘multiple sort’ and its ‘sequential sort’ equivalent
Present a subroutine that can implement a long delay between stepper motor steps
Introduce the concept of how to achieve double precision delays (4-hex) using
single precision (2-hex) variables
Review the use of A/D conversion function of the M68HC11 microcontroller.
Illustrate various modes of performing A/D conversion.
Page 80
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Examples
Page 81
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 1
EXAMPLE 1
OBJECTIVE
This simple example has the following objectives:
• Familiarize the user with the THRSim11 simulator environment
•
Introduce the user to the syntax and concepts of Assembly (.asm) language
•
Familiarize the user the way arithmetic operations are handled by the microcontroller
•
Instruct the user to interpret the List (.LST) file.
•
Teach the user to perform the simulation and follow the step-by-step results.
•
Introduce the LDAA, LDAB and ABA operations
•
Introduce immediate addressing mode
•
Introduce inherent addressing mode
PROGRAM
Ex1.asm program is very simple. It performs the arithmetic operation 3 + 2 = 5 using the ABA operation
in immediate mode. To achieve this, the program does the following operations:
•
Load the number 3 into accA using the opcode mnemonic LDAA with operand #3. The symbol #
signifies that the number 3 is used immediately. For this reason, this mode of operation is called
immediate mode).
•
Load the number 2 into accB using the opcode mnemonic LDAB with operand #2, i.e., using
immediate mode
•
Add the number in accA (i.e., 3) with the number in accB (i.e., 2) using the opcode mnemonic
ABA and no operand. This mode, which uses no operant, is called inherent mode.
The symbolic representation of this process is:
3ÆA
(immediate mode)
2ÆB
(immediate mode)
A + B Æ A (inherent mode)
This signifies that number 3 is loaded into accA, number 2 is loaded into accB, and the content of accA
is added to the content of accB with the result being put back into accA.
EXECUTION
1. Open THRSim11.
2. Maximize THRSim11 window.
3. Close the Commands window.
4. Open file Ex1.asm.
Dr. Victor Giurgiutiu
Page 82
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 1
5. Assemble file by pressing the Assemble button.
During assembly, you must have inserted in the A: floppy disk drive the floppy disk with the file
VAR_DEF.ASM. In this way, the assembler will find the file path A:\VAR_DEF.ASM when
executing the Assembly directive #INCLUDE. Else, you get error.
6. Tile windows by pressing the ‘Tile button’.
7. Set a break point to the line containing the opcode mnemonic SWI.
To do so, select the line, right click, and chose ‘Set Breakpoint’. The line becomes amber.
8. Change to decimal the display mode of registers A, B in the ‘CPU Registers’ window.
achieve this, right click on the line and select ‘Decimal’.
To
9. Put zeros in (i.e. reset) registers D, X, Y
To achieve this, highlight the line, type in the values, and hit Enter. Unless you hit enter, the
value will not take effect. (A and B get automatically reset by resetting D, since A and B are the
two halves of D). Your screen should look like this:
The green highlight in the .LST window indicates which line of program is to be executed next.
The memory address of the highlighted line, as given in the first column, is $c000. This means
that the program counter (PC) at $c000. Indeed, in the CPU registers window, you can see PC
$c000. The PC value indicates the memory address of the instruction to be executed next.
10. Use the ‘Step’ button
to step through the program.
For the Step button to be active, you need to be in the .LST window. Hence, select the .LST
window, if you have not done so already.
Dr. Victor Giurgiutiu
Page 83
8/19/2008
EMCH 367
Press the Step button
Fundamentals of Microcontrollers
Example 1
once. Your screen should look like this:
The green highlight moves to the next line, which starts at address $c001. The program counter
in the CPU registers window is PC $c001.
The line $c001 performs the loading of number 3 into accA. This line has not been executed yet.
It will be executed next when the Step button is pressed.
11. Press the Step button
Dr. Victor Giurgiutiu
again. Your screen should look like this:
Page 84
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 1
The green highlight has moved to the next line, starting at address $c003. It has jumped by 2
counts because the line that has just been executed had to Opcodes (i.e., machine instructions)
in it, 86 and 03. Each Opcode takes up one memory address, hence the program has move
forward by 2 locations. The current value of the program counter is PC $c003, as can be readily
verified in the CPU registers window.
The result of executing the previous instruction is now apparent. The number 3 has been loaded
into accA. You can verify this by noting that, in the CPU registers window, you see A 3.
12. Press the Step button again. The screen looks like this:
The execution of the previous instruction has loaded the number 2 into accB, just as the number
3 was loaded into accA. The result of this operation is apparent in the CPU registers window
where now we can see B 2.
13. Press the Step button again. The screen looks like this:
Dr. Victor Giurgiutiu
Page 85
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 1
The execution of the previous instruction has performed the addition between the contents of
accA (i.e., 3) and the contents of accB (i.e., 2). The result of the operation has been put back
into accA. This means that the arithmetic operation 3 + 2 = 5 has been executed. The result of
the addition is shown in the CPU registers window: the accA has become A 5, as expected.
The green highlight has moved to the next line which starts at memory address $c006. (In the
CPU registers window, the program counter indicates PC $c006.) The move of the program
counter was only by one memory location because the operation ABA just executed does not
have operand (inherent mode), and only requires one Opcode.
The line $c006 contains the opcode mnemonic SWI which signifies the end of the program. You
are done! (Do not press the ‘Step’ again, because it will throw you out of the program area.)
14. To rerun the program, you have to place the program counter again at the beginning of the
program. Select the line $c001, i.e., where the meaningful part of the program starts. Right click
and select ‘Place program counter on …’. The line that was selected becomes green highlighted.
You can now step again through the program and see how it operates. You can also press the
‘Run’ button
, and the program will automatically execute up to the next breakpoint. In our
case, the program will run all the way to the SWI instruction where the breakpoint is placed.
WHAT YOU HAVE LEARNED
In this simple exercise, you have learned quite a few things:
• New words and concepts: Opcode, opcode mnemonic, immediate mode, Assembly language
(.asm), list file (.LST), reset, program counter (PC), break point, registers, .
•
Microprocessor opcode mnemonics LDAA, LDAB, and ABA.
•
Meaning of immediate mode and how to invoke it by using the symbol #
•
Meaning of inherent mode.
•
Symbolic representation of the operations and their meaning
Dr. Victor Giurgiutiu
Page 86
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 1
•
Open and customize THRSim11 environment
•
Assemble an .asm file
•
Interpret an .LST file
•
Tile the THRSim11 windows (remember that the tiling sequence follows the sequence in which
you accessed the files, with the most recently accessed window tiled in the left upper corner!)
•
Put a value in a memory address, e.g. when you put zeros in the registers
•
Set a break point
•
Step through the program simulation and follow the changes taking place in the ‘CPU registers’
window.
•
See how program execution is affecting accA and accB. Identify the results of the calculation, i.e.
3 + 2 = 5 makes accA to take the value A 5.
Dr. Victor Giurgiutiu
Page 87
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 2
EXAMPLE 2
OBJECTIVE
This simple example has the following objectives:
• Familiarize the user with the THRSim11 simulator environment
•
Introduce the user to the syntax and concepts of Assembly (.asm) language
•
Familiarize the user the way arithmetic operations are handled by the microcontroller
•
Instruct the user to interpret the List (.LST) file.
•
Teach the user to perform the simulation and follow the step-by-step results.
•
Introduce ADDA operation
PROGRAM
Ex2.asm program is very simple. It performs the arithmetic operation 3 + 2 = 5 using the ADDA
operation in immediate mode. To achieve this, the program does the following operations:
•
Load the number 3 into accA using the opcode mnemonic LDAA with the operand #3, i.e., using
immediate mode.
•
Add the number in accA (which is 3) with the number 2 using the opcode mnemonic ADDA with
the operand #2. (Note that the immediate mode is again used.)
The symbolic representation of this process is:
3ÆA
(immediate mode)
A+2ÆA
(immediate mode)
This signifies that number 3 is loaded into accA, number 2 is loaded into immediate memory, and the
content of accA is added to of memory with the result being put back into accA.
EXECUTION
1. Open THRSim11.
2. Maximize THRSim11 window.
3. Close the Commands window.
4. Open file Ex2.asm.
5. Assemble file by pressing the Assemble button.
During assembly, you must have inserted in the A: floppy disk drive with the file
VAR_DEF.ASM. In this way, the assembler will find the file path A:\VAR_DEF.ASM when
executing the Assembly directive #INCLUDE. Else, you get error.
Dr. Victor Giurgiutiu
Page 88
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 2
6. Tile windows by pressing the ‘Tile button’.
7. Set a break point to the line containing the opcode mnemonic SWI.
To do so, select the line, right click, and chose ‘Set Breakpoint’. The line becomes amber.
8. Change to decimal the display mode of registers A, B in the ‘CPU Registers’ window. To
achieve this, right click on the line and select ‘Decimal’.
9. Put zeros in (i.e. reset) registers D, X, Y.
To achieve this, highlight the line, type in the values, and hit Enter. Unless you hit enter, the
value will not take effect. (A and B get automatically reset by resetting D, since A and B are the
two halves of D). Your screen should look like this:
The green highlight in the A:\Ex2.LST window indicates which line of program is to be executed
next. The memory address of the highlighted line, as given in the first column, is $c000. This
means that the program counter (PC) at $c000. Indeed, in the CPU registers window, you can
see PC $c000. The PC value indicates the memory address of the instruction to be executed
next.
10. Use the ‘Step’ button
to step through the program.
For the Step button to be active, you need to be in the .LST window. Hence, select the .LST
window, if you have not done so already.
Dr. Victor Giurgiutiu
Page 89
8/19/2008
EMCH 367
Press the Step button
Fundamentals of Microcontrollers
Example 2
once. Your screen should look like this:
The green highlight moves to the next line, which starts at address $c001. The program counter
in the CPU registers window is PC $c001.
The line $c001 performs the loading of number 3 into accA. This line has not been executed yet.
It will be executed next when the Step button is pressed.
11. Press the Step button again. Your screen should look like this:
The green highlight has moved to the next line, starting at address $c003. It has jumped by 2
counts because the line that has just been executed had two Opcodes (i.e., machine
instructions) in it, 86 and 03. Each Opcode takes up one memory address, hence the program
has move forward by 2 locations. The current value of the program counter is PC $c003, as can
be readily verified in the CPU registers window.
The result of executing the previous instruction is now apparent. The number 3 has been loaded
into accA. You can verify this by noting that, in the CPU registers window, you see A 3.
12. Press the Step button again. The screen looks like this:
Dr. Victor Giurgiutiu
Page 90
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 2
The execution of the previous instruction has performed the addition between the contents of
accA (i.e., 3) and the number kept in the immediate memory (i.e., 2). The result of the operation
has been put back into accA. This means that the arithmetic operation 3 + 2 = 5 has been
executed. The result of the addition is shown in the CPU registers window: the accA has
become A 5, as expected.
The green highlight has moved to the next line which starts at memory address $c005. (In the
CPU registers window, the program counter indicates PC $c005.) The line $c005 contains the
opcode mnemonic SWI which signifies the end of the program. You are done! (Do not press the
‘Step’ again, because it will throw you out of the program area.)
13. To rerun the program, you have to place the program counter again at the beginning of the
program. Select the line $c001, i.e., where the meaningful part of the program starts. Right click
and select ‘Place program counter on …’. The line that was selected becomes green highlighted.
You can now step again through the program and see how it operates. You can also press the
‘Run’ button
, and the program will automatically execute up to the next breakpoint. In our
case, the program will run all the way to the SWI instruction where the breakpoint is placed.
WHAT YOU HAVE LEARNED
In this simple exercise, you have learned quite a few things:
• New words and concepts: Opcode, opcode mnemonic, immediate mode, Assembly language
(.asm), list file (.LST), reset, program counter (PC), break point, registers, .
•
Microprocessor opcode mnemonics LDAA and ADDA
•
Meaning of immediate mode and how to invoke it by using the symbol #
•
Symbolic representation of the operations and their meaning
•
Open and customize THRSim11 environment
•
Assemble an .asm file
•
Interpret an .LST file
•
Tile the THRSim11 windows (remember that the tiling sequence follows the sequence in which
you accessed the files, with the most recently accessed window tiled in the left upper corner!)
Dr. Victor Giurgiutiu
Page 91
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 2
•
Put a value in a memory address, e.g. when you put zeros in the registers
•
Set a break point
•
Step through the program simulation and follow the changes taking place in the ‘CPU registers’
window.
•
See how program execution is affecting accA. Identify the results of the calculation, i.e.
3 + 2 = 5 makes accA to show A 5.
Dr. Victor Giurgiutiu
Page 92
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 2
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 93
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 3
EXAMPLE 3
OBJECTIVE
This simple example has the following objectives:
• Review the principles of the decimal numbers, i.e., in the range 0 – 9
•
Review the decimal carry concept, i.e., when a result is outside the 0 – 9 range.
•
Prepare the ground for hex arithmetic
PROGRAM
Ex3.asm program is similar to ex2.asm, but uses numbers that give the result outside the 0 – 9 range. It
performs the arithmetic operation 7 + 6 = 13. To achieve this, the program does the following:
• Load the number 7 into accA using LDAA, i.e.,
7ÆA
•
Load the number 6 into accB using LDAB, i.e.,
•
Add the number in accA (i.e., 7) with the number in accB (i.e., 6) A + B Æ A
6ÆB
A 13
EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open file Ex3.asm.
Assemble file. Tile windows. Set break point at the line containing SWI. Set the display of A, B
registers to ‘Decimal’. Reset registers D, X, Y. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 94
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 3
Use the ‘Step’ button to step through the program. Press the Step button once. The registers do not
change. Press again. Number 7 is loaded into accA. Press again. Number 6 is loaded into accB. Press
again. AccA and AccB are added together. The result, 13, appears in accA. The number 6 is still
preserved in AccB. Your screen should look like this:
WHAT YOU HAVE LEARNED
In this simple exercise, you have prepared the ground for understanding hex arithmetic by reviewing
decimal arithmetic with results outside the range 0 – 9. The things that you have reviewed are:
• In decimal arithmetic, the base of the number system is ten
•
Ten independent symbols exist for representing the first ten numbers in the decimal system: 0, 1,
2, 3, 4, 5, 6, 7, 8, 9. These symbols are called digits.
•
The greatest number that can be represented with a single decimal symbol is nine.
•
Numbers greater than nine are represented with two or more digits. For example, number thirteen
is represented as 13, i.e. with two digits.
•
The symbol furthest to the left is called the most significant digit (MSD). In number 13, the most
significant digit is 1. It signifies the number of tens contained in the number. In our case, we
have only one ten, since 1 x ten = ten
•
The symbol furthest to the right is called the least significant digit (LSD). In number 13, the least
significant digit is 3. It signifies the number of units contained in the number. In our case, we
have three units, since 3 x units = three.
•
The complete number is assembled by adding the contribution of all digits, from LSD through
MSD. In number 13 there are two digits, MSD = 1, LSD = 3. The complete number is 1 x ten + 3
x units = ten + three = thirteen.
•
When the result of an addition is greater than nine, a carry occurs.
•
New words and notations: digits, most significant digit (MSD), least significant digit (LSD),
carry.
Dr. Victor Giurgiutiu
Page 95
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 4
EXAMPLE 4
OBJECTIVE
This simple example has the following objectives:
• Introduce hex numbers and hex symbols, a, b, c, d, e, f.
•
Introduce single precision and double precision registers
•
Introduce hex arithmetic.
PROGRAM
Ex4.asm program is identical to ex3.asm, but uses hex numbers. It performs the arithmetic operation $07
+ $06 = $0d. To achieve this, the program does the following:
• Load the number $07 into accA using LDAA, i.e.,
$07 Æ A
•
Load the number $06 into accB using LDAB, i.e.,
•
Add the number in accA (i.e., $07) with the number in accB (i.e., $06) A + B Æ A
$06 Æ B
A $0d
During this process, the number $07 was incremented six times by one. Sequentially, it went through
$08, $09, $0a, $0b, $0c, and finally, $0d. Hence, to achieve $07 + $06 we can choose two paths:
- Path 1: start with $07 in accA and increment six times using the ADDA opcode.
- Path 2: Start with $07 in accA and $06 in accB and do the addition using ABA.
EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open file Ex4.asm.
Assemble file. Tile the windows. Set break point at the line containing SWI. Set the display of A, B
registers to ‘Hexadecimal’. Reset registers D, X, Y. Your screen should look like this:
Note that, in single-precision 8-bit arithmetic, hex numbers are always represented with two digits, even
if the most significant digit (MSD) is zero. For example, the single-precision accA and accB are
Dr. Victor Giurgiutiu
Page 96
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 4
represented as $00 and $00. In double precision 8-bit arithmetic, hex numbers are always represented
with four digits, even if the more significant ones are zero. For example, double precision accD and
index registers X and Y are all represented as $0000. This convention helps us discern quickly between
the single precision and the double precision registers.
Use the ‘Step’ button to step through the program. Press the Step button once. The registers do not
change. Press again. Your screen should look like this:
During the operation, number 7 has been loaded into accA as $07. Also changed is accD, which results
from concatenation of accA:accB. Since accA is $07 and accB is $00, accD is $0700. This
concatenation process is always done in hex format, and is not apparent when decimal display is used
(check that this is so by looking into Example 1 through Example 3).
From here on, two paths are possible. They will be followed in sequence.
Dr. Victor Giurgiutiu
Page 97
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 4
PATH 1
Step again. AccA has incremented by one from $07 to $08. The screen should look like this:
Continue stepping and watch accA going sequentially through $0b, $0c, $0d. Finally, the screen should
look like this:
Dr. Victor Giurgiutiu
Page 98
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 4
This is result of the addition $07 + $06 = $0d, achieved through successive incrementation.
Dr. Victor Giurgiutiu
Page 99
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 4
PATH 2
The PC is placed at beginning of Path 2. Step once. The accA is reloaded with $07. Your screen looks
like this:
Step again. Your screen looks like this:
During the operation, number 6 has been loaded into accB as $06. Since accA is $07 and accB is $06,
accD is $0706.
Dr. Victor Giurgiutiu
Page 100
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 4
Now, step again to perform the addition $07 + $ 06 = $0d. The screen looks like this:
During the last operation, AccA and AccB have been added together. The result of the operation $07 +
$06 = $0d appears in accA. The number $06 is still preserved in AccB.
WHAT YOU HAVE LEARNED
In this simple exercise, you have understood how hex arithmetic works:
• In hex arithmetic, the base of the number system is sixteen (hexadecimal).
•
Sixteen independent symbols exist for representing the first sixteen numbers in the hex system: 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f.
•
The greatest number that can be represented with a single hex symbol is fifteen.
•
In single-precision 8-bit arithmetic, hex numbers are always represented with two digits, even if
the most significant digit (MSD) is zero. For example, you saw during this exercise how the
single-precision accA and accB took values $07 and $06. Later on, accA became $0d.
•
In double precision 8-bit arithmetic, hex numbers are always represented with four digits, even if
the more significant ones are zero.
•
In hex arithmetic, single-precision numbers can be built into double precision numbers through
concatenation (i.e., by putting them side by side). For example, when accA was $07 and accB
was $06, accD, which is simply accA:accB, was $0706. This was not so in decimal arithmetic
(check that this is so by looking into Example 2 and Example 3).
•
New words: hex arithmetic, hexadecimal, single precision, double precision, 8-bit arithmetic,
concatenation.
Dr. Victor Giurgiutiu
Page 101
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 5
EXAMPLE 5
OBJECTIVE
This simple example has the following objectives:
• Review 2-digit decimal arithmetic with carry to prepare the ground for 2-digit hex arithmetic
with carry.
PROGRAM
Ex5.asm program is similar to ex3.asm, but uses numbers outside the 0 – 9 range. It performs the
arithmetic operation 9 + 8 = 17. To achieve this, the program does the following:
• Load 9 into accA using LDAA, i.e.,
9ÆA
•
Load 8 into accB using LDAB, i.e.,
8ÆB
•
Add accA (i.e., 9) with accB (i.e., 8)
A+BÆA
A 17
EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open file Ex5.asm.
Assemble file. Tile windows. Set break point at the line containing SWI. Set the display of A, B
registers to ‘Decimal’. Reset registers D, X, Y. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 102
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 5
Use the ‘Step’ button to step through the program. Press the Step button once. The registers do not
change. Press again. Number 9 is loaded into accA. Press again. Number 8 is loaded into accB. Press
again. AccA and AccB are added together. The result, 17, appears in accA. The number 8 is still
preserved in AccB. Your screen should look like this:
During the addition 9 + 8 = 17, decimal arithmetic with carry has been performed. The numbers nine
and eight, when added, give the number seventeen, which is greater than nine. Since the greatest number
that can be represented with just one decimal digit is nine, a carry to the next level, tens, had to be
enacted. In words: “nine plus eight makes seven carry one”. In symbols: 9 + 8 = 17.
WHAT YOU HAVE LEARNED
In this simple exercise, you have reviewing decimal arithmetic with carry to prepare the ground for
understanding hex arithmetic with carry. The things that you have reviewed are:
• The greatest number that can be represented with a single decimal digit is nine.
•
Numbers greater than nine are represented with two or more digits. For example, number
seventeen is represented as 17, i.e. with two digits.
•
When the result of adding two decimal numbers is greater than nine, a carry takes place.
•
New words and notations: addition with carry.
Dr. Victor Giurgiutiu
Page 103
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 6
EXAMPLE 6
OBJECTIVE
This simple example has the following objectives:
• Introduce hex arithmetic with carry
•
Facilitate comparison with the decimal case by using the same numbers as in Example 5
PROGRAM
Ex6.asm program is similar to ex5.asm, but uses hex numbers representation. It performs the arithmetic
operation $09 + $08 = $11. To achieve this, the program follows two paths:
Path 1: Load $09 into accA increment eight times.
• During this process, the number $09 is increased by one eight times using the INCA opcode.
Sequentially, it goes $09 Æ $0a Æ $0b Æ $0c Æ $0d Æ $0e Æ $0f Æ $10 Æ $11.
•
After the first six increments, the end of the hex symbols list ( i.e., symbol f) has been reached.
The process is at $0f.
•
The next (seventh) increment is performed with a carry, i.e. a zero is placed in the units
placeholder and a one is carried over into the next placeholder. At this point, the number $10 is
obtained.
•
The remaining and last increment moves the number from $10 to $11 by adding a one to the
units placeholder.
Path 2: Load $09 into accA, $08 into accB and perform the addition A + B Æ A. The result is $09 +
$08 = $11. (You can check this by using a Hex calculator.)
Path 1 is explicit and lets the user understand the carry process. Path 2 is shorter and is usually taken in
programming. Note that the result, $11, is the hex equivalent of the decimal number 17 from Example 5.
Dr. Victor Giurgiutiu
Page 104
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 6
EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open file Ex6.asm.
Assemble file. Tile windows. Set break point at the line containing SWI. Set the display of A, B, and D
registers to ‘Hexadecimal’. Reset registers D, X, Y. Your screen should look like this:
Use the ‘Step’ button to step through the program. Press the Step button once. The registers do not
change.
Dr. Victor Giurgiutiu
Page 105
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 6
Path 1
Step again. The numbers $09 is been loaded into accA. Your screen should look like this:
Step again. AccA has increased by one from $09 to $0a. The screen should look like this:
Dr. Victor Giurgiutiu
Page 106
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 6
Continue stepping and watch accA going sequentially through $0b, $0c, $0d, $0e, $0f. At this point, the
screen should look like this:
Step again. An increment from $0f to $10 takes place. The screen should look like:
Perform the final step and get the desired result at the end of Path 1, A $11.
Path 2: Place PC at $c013 (beginning of Path 2). Step once. The accA is reloaded with $09. Your screen
looks like this:
Dr. Victor Giurgiutiu
Page 107
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 6
Step again to load accB with $08. Now, step again to perform the addition $09 + $ 08 = $11. The result
appears in accA. The screen looks like this:
Dr. Victor Giurgiutiu
Page 108
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 6
WHAT YOU HAVE LEARNED
In this simple example, you have understood hex arithmetic with carry:
1. In Path 1, you saw addition as a repeated incrementation. The number $09 was loaded in accA
and subsequently incremented.
•
After 6 increments, from $09 to $0a, $0b, $0c, $0d, $0d, $0e, and $0f, the hex symbols
were exhausted.
•
The next increment (the seventh) enacted a carry such that the second placeholder (MSD)
was increased from 0 to 1, while the first placeholder (LSD) was reset to 0. At this stage,
the value in accA was $10. (This is by far different from the decimal 10).
•
The next and final increment (the eighth) incremented the LSD and the number in accA
moved from $10 to $11.
2. In Path 2, you saw the direct application of the hex addition using accA and accB, such that $09
+ $08 = $11.
3. You should note that the result $11 is the hex equivalent of the decimal result 17 from Example 5
(recall, 9 + 8 = 17).
4. New words: hex arithmetic with carry, placeholder.
Dr. Victor Giurgiutiu
Page 109
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
EXAMPLE 7
OBJECTIVE
This simple example has the following objectives:
• Introduce 2-digit hex arithmetic with carry
•
Introduce the ‘lost carry’ concept
•
Introduce ‘half carry’ concept
•
Introduce MSB carry
PROGRAM
Ex7.asm program performs the following arithmetic operations
• 15 + 27 = 42 (decimal) using the opcode mnemonics LDAA, LDAB, ABA
•
$0f + $1b = $2a (hex half carry - from bit 3) using the opcode mnemonics LDAA, LDAB, ABA
•
$ff + $01 = $00 (hex MSB carry) using the opcode mnemonics LDAA, ADDA
•
255 + 1 = 0 (decimal equivalent of a hex MSB carry) using the opcode mnemonics LDAA,
ADDA
Note: To facilitate understanding, the same numbers are used in both decimal and the hex cases.
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open file Ex7.asm.
Assemble file. Tile the windows. Set a break point at the line containing SWI. Reset registers D, X, Y.
Your screen should look like this:
Dr. Victor Giurgiutiu
Page 110
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
Use the ‘Step’ button to step through the program. Press the Step button once. The registers do not
change. You get to the beginning of a section in your program.
SECTION: 15 + 27 = 42 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Set the display option of accA and accB to Decimal.
Use the Step button to step through this section of your program. After 2 steps, the screen looks like this:
During the previous 2 operations, the numbers 15 and 27 have been loaded into accA and acc B,
respectively.
Press the step button once. The screen looks like this:
Dr. Victor Giurgiutiu
Page 111
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
Congratulations! The first section in this example has been completed. You have achieved the decimal
addition 15 +27 = 42. AccA shows A 42, which is the expected result.
Note:
• A decimal carry happen during this operation, since, in the LSD, 5 + 7 = 12, ‘keep 2 and carry
1’.
•
In the result, the LSD is 2. This signifies that of the result with carry, which was 12, the least
significant digit, 2, was retained, and the most significant digit was carried in the next higher
position.
•
In the result, the MSD is 4. This signifies that the MSD of the result was obtained through the
addition of the most significant digits of the constituents, 1 and 2, and the carry 1, i.e., 1+2+1 =
4.
SECTION: $0F + $1B = $2A (HEX HALF-CARRY) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex. Your
screen looks like this:
Dr. Victor Giurgiutiu
Page 112
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
Use the Step button to step through this section of your program. After 2 steps, the screen looks like this:
During the previous 2 operations, the numbers $0f and $1b have been loaded into accA and acc B,
respectively.
Press the step button once. The screen looks like this:
Dr. Victor Giurgiutiu
Page 113
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
Congratulations! The second section in this example has been completed. You have achieve the hex
addition $0f + $1b = $2a. AccA shows A $2a, which is the expected result.
Note:
• A hex half carry happen during this operation, since, in the LSD, $f + $b = $1a, ‘keep a and
carry 1’.
•
In the result, the LSD is a. This signifies that of the result with carry, which was $1a, the least
significant digit, a, was retained, and the most significant digit, 1, was carried in the next higher
position.
•
In the result, the MSD is 2. This signifies that the MSD of the result was obtained through the
addition of the most significant digits of the constituents, 0 and 1, and the carry 1, i.e., 0+1+1 =
2.
Note that the decimal equivalent of your result is $1a = 42, i.e., the same as in the previous section.
Dr. Victor Giurgiutiu
Page 114
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
$FF + $01 = $00 (MSB CARRY) USING THE OPCODE MNEMONICS LDAA, ADDA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program. After the first step, your screen looks
like this:
During this operation, the number $ff has been loaded into accA.
Press again the step button. Your screen looks like this:
During this operation, $01 was added to the number $ff existing in accA. If more than two hex digit
could be displayed, the operation would have looked like $0ff + $001 = $100. Alas, the 8-bit
architecture of our microcontroller does not allow for more than two hex digits. Hence, the third digit in
Dr. Victor Giurgiutiu
Page 115
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
the result is lost. (We have just experienced a ‘lost carry’). The result is $00. The event that you have
just witnessed is called hex MSB carry. However, the fact that this event took place has been recorded
by the microcontroller logic by setting the bit 0 in the condition code (CC) register. Before this operation,
the CC register was %1111000; after this operation, the CC register has become %11110101. The bits
that have been set by this operation are:
• C = 1 (bit 0 in CC register), signifying that a MSB carry took place during the operation
•
Z = 1 (bit 2 in CC register), signifying that the result of the operation was zero
Also affected by this operation was the bit N (CC register bit 3) which switched from 1 to 0. The
meaning of this will be explained in a later example, in which negative numbers are studied.
255 + 1 = 0 (DECIMAL EQUIVALENT OF HEX MSB CARRY) USING THE OPCODE MNEMONICS LDAA,
ADDA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to decimal.
After the first step, your screen looks like this:
During this operation, the decimal number 255 has been loaded into accA. (This decimal number is the
decimal equivalent of the hex number $ff used in the previous section.)
Press again the step button. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 116
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
During this operation, 1 was added to the number 255 existing in accA. The result should have been 256.
No decimal carry happened. However, the result is too large to be stored in 2-digit hex format, since 256
= $100. Hence, the third highest digit in the hex representation is lost, and only the last two digits are
retained. The displayed result $00, i.e., 0 in decimal. This proves again that, internally, the MCU works
in hex!
Dr. Victor Giurgiutiu
Page 117
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
WHAT YOU HAVE LEARNED
In this example, you have learned the following:
• In hex arithmetic, the symbol furthest to the left is also called the most significant digit (MSD).
In number $1d, the most significant digit is 1. It signifies the number of sixteens contained in the
number. In our case, we have only one sixteen, since 1 x sixteen = sixteen
•
In hex arithmetic, the symbol furthest to the right is called the least significant digit (LSD). In
number $1d, the least significant digit is d. It signifies the number of units contained in the
number. In our case, we have thirteen units, since the hex number d represents the number
thirteen, and d x units =thirteen.
•
The hex number $1d has the value twenty-nine, since sixteen plus thirteen makes twenty-nine.
•
You have observed a hex MSB carry. In our case, the machine has 2-digit hex precision; hence,
it cannot store numbers with more than two digits. When to the number $ff we added the number
$01, the result should have been $100 (Proof: $0ff + $001 = $100). But our MCU we cannot
store more than 2 hex digits in single precision, hence, the leading 1 is lost (‘lost carry’). The
phenomenon is called MSB carry. (The name MSB signifies most significant bit and it refers to
the binary equivalent of the hex number).
•
You have also observed the decimal representation of a hex MSB carry. This happened when to
the decimal number 255 we added the number 1. The result was 0, instead of 256 as you would
have expected. This illustrates the range limitation of your MCU (8-bit, 2-hex). Also illustrated
is the fact that, internally, MCU works in hex. YOU SHOULD TRAIN YOURSELF TO THINK
IN HEX TO BETTER UNDERSTAND THE WORKING OF THE MCU !
•
New words and notations: most significant digit (MSD), least significant digit (LSD), 8-bit
arithmetic, most significant bit (MSB), addition with carry, hex arithmetic with carry, ‘lost carry’,
hex half carry, MSB carry.
Dr. Victor Giurgiutiu
Page 118
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 7
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 119
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
EXAMPLE 8
OBJECTIVE
This exercise has the following objectives:
• Introduce decrease (SUBA)
•
Review decimal borrow concepts using decrease
•
Introduce hex borrow using decrease
•
Introduce 2’s complement negative hex numbers as decrease of zero with free borrow
•
Show the 2-digit 2's complement negative hex numbers
•
Show the decimal equivalent of the
2-digit 2's complement negative hex numbers
2-digit
hex
decrease
of
zero
and
of
Note: To facilitate understanding, the same numbers are used in both decimal and the hex cases.
PROGRAM
The program ex8.asm performs the following arithmetic operations:
• 7 – 1 = 6 (decimal) using the opcode mnemonics LDAA, SUBA
• $07 - $01 = $06 (hex) using the opcode mnemonics LDAA, SUBA
• 10 - 1 = 9 (decimal) using the opcode mnemonics LDAA, SUBA
• $10 - $01 = $0f (hex) using the opcode mnemonics LDAA, SUBA
• $00 - $01 = $ff (hex) using the opcode mnemonics LDAA, SUBA
• 0 - 1 = 255 (decimal equivalent of 2-digit hex arithmetic) using the opcode mnemonics LDAA,
SUBA
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open ex8.asm.
Assemble, tile the windows, set the breakpoint, and reset the registers. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 120
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Example 8
Page 121
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
SECTION: 7 – 1 = 6 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, SUBA
Set accA display to decimal. Step through section i) of the code. At the end of this section, your screen
looks like this:
During the execution of this section, decimal number 7 was loaded into accA, and decreased by 1 to
become 6. During the decrease, decimal borrow did not need to happen.
Dr. Victor Giurgiutiu
Page 122
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
SECTION: $07 - $01 = $06 (HEX) USING THE OPCODE MNEMONICS LDAA, SUBA
Set accA display to hex. Step through section ii) of the code. At the end of this section, your screen
looks like this:
During the execution of this section, hex number $07 was loaded into accA, and decreased by 1 to
become $06. During the decrease, hex borrow did not need to happen.
Dr. Victor Giurgiutiu
Page 123
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
SECTION: 10 - 1 = 9 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, SUBA
Set accA display to decimal. Step through section iii) of the code. At the end of this section, your screen
looks like this:
During the execution of this section, decimal number 10 was loaded into accA, and decreased by 1 to
become 9. During the decrease, decimal borrow happened because the LSD was 0.
Dr. Victor Giurgiutiu
Page 124
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
SECTION: $10 - $01 = $0F (HEX) USING THE OPCODE MNEMONICS LDAA, SUBA
Set accA display to hex. Step through section vi) of the code. At the end of this section, your screen
looks like this:
During the execution of this section, hex number $10 was loaded into accA, and decreased by 1 to
become $0f. During the decrease, hex borrow happened because the LSD was 0.
Dr. Victor Giurgiutiu
Page 125
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
SECTION: $00 - $01 = $FF (HEX) USING THE OPCODE MNEMONICS LDAA, SUBA
Set accA display to hex. Step through section v) of the code. At the end of this section, your screen
looks like this:
During the execution of this section, hex number $00 was loaded into accA, and decreased by 1 to
become $ff. During the decrease, hex borrow happened because the LSD was 0. Since MSD was also 0,
a ‘free borrow’ beyond the MSD happened. Hence, the result of $00-$01 is the same as the result of
$000+$100-$001=$0ff, i.e. $ff.
Dr. Victor Giurgiutiu
Page 126
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
SECTION: 0 - 1 = 255 (DECIMAL EQUIVALENT OF 8-BIT HEX ARITHMETIC) USING THE OPCODE
MNEMONICS LDAA, SUBA
Set accA display to decimal. Step through section vi) of the code. At the end of this section, your screen
looks like this:
During the execution of this section, decimal number 0 was loaded into accA, and decreased by 1 to
become 255. We notice that the operation is equivalent to 0+256-1=255. This indicates that, although
the operation was displayed in decimal, a hex free borrow actually happened, since 256=$100.
USING CALCULATOR TO OBTAIN HEX NEGATIVE NUMBERS FOR –100
Use your calculator to find the HEX equivalent of negative decimal number –100. Type –100 into your
calculator, and convert to hex. After you have done this, you will see hex number F…FFF9C in your
screen. (The number of F depends on the maximum display length of your calculator.) The last two
digits, 9C, are the hex negative number of –100.
Dr. Victor Giurgiutiu
Page 127
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• In decimal arithmetic, decrease results in the value of the number being reduced by one unit
•
In hex arithmetic, decrease has the same meaning as in decimal arithmetic: the value of the
number is being reduced by one unit
•
For a 2-digit decimal number with the LSD zero, e.g., 10, decrease required a borrow to be
performed from the MSD into the LSD. As a result, we could perform the decrease and the result
was 9. The result showed that, because of the borrow, the MSD decreased from 1 to 0, and the
LSD increase from 0 to 9, i.e., from the bottom of the decimal symbols sequence to the top of the
sequence.
•
For a 2-digit hex number with the LSD zero, e.g., $10, decrease also required a borrow to be
performed from the MSD into the LSD. As a result, we could perform the decrease and the result
was $0f. The result showed that, because of the borrow, the MSD decreased from 1 to 0, and the
LSD increase from 0 to f, i.e., from the bottom of the hex symbols sequence to the top of the
sequence.
•
The difference between 10 (ten) and $10 (hex one-zero = decimal sixteen).
•
For a 2-digit hex number with zero LSD but also zero MSD (i.e., $00), decrease is still possible
using the ‘free-borrow’ concept. The free-borrow concept, which is implemented on most
microcontrollers, allows us to freely borrow a value of one from the next higher digit beyond the
precision of the machine. In other word, if we extend the range to 3 hex digits and write $ff as
$0ff, incrementing by one yields $0ff + $001 = $100. Conversely, decreasing $100 by one yields
$0ff, i.e., $ff. This leads directly to the concept of 2's complement negative numbers
•
2-digit 2's complement negative hex numbers are the numbers that appear to the left of the hex
zero in the following sequence: …, $fd, $fe, $ff, $00, $01, $02, $03, …. We notice that:
•
•
$ff is the negative of $01, and $ff + $01 = $00
•
$fe is the negative of $02, and $fe + $02 = $00
•
$fd is the negative of $03, and $fd + $031 = $00
•
etc.
New words and notations: decrease, free borrow, 2's complement negative numbers.
Dr. Victor Giurgiutiu
Page 128
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 8
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 129
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
EXAMPLE 9
OBJECTIVE
This exercise has the following objectives:
• Introduce hex subtraction
•
Introduce hex subtraction with negative results using the free borrow concept.
•
Show the decimal equivalent of hex subtraction with negative results using free borrow.
Note: To facilitate understanding, the same numbers are used in both decimal and the hex cases.
PROGRAM
The program ex9.asm performs the following arithmetic operations:
I. $0d - $06 = $07 (hex) using the opcode mnemonics LDAA, LDAB, SBA
II. $00 - $05 = $fb (hex) using the opcode mnemonics LDAA, LDAB, SBA
III. 0 - 5 = 251 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
LDAB, SBA
IV. $0e - $3a = $d4 (hex) using the opcode mnemonics LDAA, LDAB, SBA
V. 14 - 58 = 212 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
LDAB, SBA
Dr. Victor Giurgiutiu
Page 130
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open ex9.asm.
Assemble, tile the windows, set the breakpoint, and reset the registers. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 131
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
SECTION: $0D - $06 = $07 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, SBA
Load and assemble ex9.asm. Set accA display to hex. Step through section vii) of the code. At the end of
this section, your screen looks like this:
During the execution of this section, hex number $0d was loaded into accA, hex number $06 was loaded
into accB, and then accB was subtracted from accA. The result of the arithmetic operation remained in
accA. The result was $07. A hex borrow did not happen, since the number in accB was less than the
number in accA, and the LSD of the number in accB was also less than the LSD of the number in accA.
Dr. Victor Giurgiutiu
Page 132
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
SECTION: $00 - $05 = $FB (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, SBA
Set accA accB displays to hex. Step through section viii) of the code. At the end of this section, your
screen looks like this:
During the execution of this section, hex number $00 was loaded into accA, hex number $05 was loaded
into accB, and then accB was subtracted from accA. The result of the arithmetic operation remained in
accA. The result was $fb. This is equivalent to the hex operation $000+$100-$005=$0fb, and indicates
that a hex free borrow happened.
Dr. Victor Giurgiutiu
Page 133
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
SECTION: 0 - 5 = 251 (DECIMAL EQUIVALENT OF 8-BIT HEX ARITHMETIC) USING THE OPCODE
MNEMONICS LDAA, LDAB, SBA
Set accA and accB displays to decimal. Step through section ix) of the code. At the end of this section,
your screen looks like this:
During the execution of this section, decimal number 0 was loaded into accA, and decimal number 5
into accB. Then, accB was subtracted from accA. The result of the subtraction remained in accA. The
result was 251. We notice that the following decimal arithmetic operation happened 0-5=251. This
operation is equivalent to 0+256-1=255. This indicates that, although the operation was displayed in
decimal, a hex free borrow actually happened since 256=$100.
Dr. Victor Giurgiutiu
Page 134
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
SECTION: $0E - $3A = $D4 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, SBA
Set accA accB displays to hex. Step through section x) of the code. At the end of this section, your
screen looks like this:
During the execution of this section, hex number $0e was loaded into accA, hex number $3a was loaded
into accB, and then accB was subtracted from accA. The result of the arithmetic operation remained in
accA. The result was $d4. This is equivalent to the hex operation $00e+$100-$03a=$0d4, and indicates
that a hex free borrow happened.
Dr. Victor Giurgiutiu
Page 135
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
SECTION: 14 - 58 = 212 (DECIMAL EQUIVALENT OF 8-BIT HEX ARITHMETIC) USING THE OPCODE
MNEMONICS LDAA, LDAB, SBA
Set accA and accB displays to decimal. Step through section xi) of the code. At the end of this section,
your screen looks like this:
During the execution of this section, decimal number 14 was loaded into accA, and decimal number 58
into accB. Then, accB was subtracted from accA. The result of the subtraction remained in accA. The
result was 212. We notice that the following decimal arithmetic operation happened 14-58=212. This
operation is equivalent to 14+256-58=212. This indicates that, although the operation was displayed in
decimal, a hex free borrow actually happened since 256=$100.
Dr. Victor Giurgiutiu
Page 136
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 9
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• Subtraction using SBA opcode mnemonic happened as expected, in both decimal and hex
arithmetic, as long as the minuend is greater than the subtrahend (e.g., 13-6=7, $0d-$06=$07).
•
When the minuend is less than the subtrahend, the result of the subtraction operation is
calculated using a free borrow (e.g., $0e-$3a=$00e+$100-$03a=$0d4=$d4).
•
Even if decimal display of numbers is used, the calculations and the free borrow still happen in
hex (e.g., 14-58=14+256-58=212, where 256=$100).
•
New words and notations: subtraction, minuend, subtrahend.
Dr. Victor Giurgiutiu
Page 137
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example 10
EXAMPLE 10
OBJECTIVE
This example has the following objectives:
• Introduce 8-bit binary numbers
•
Introduce connection between 8-bit binary numbers and 2-digit hex numbers.
•
Introduce 8-bit binary arithmetic
•
Introduce the half carry (bit 3 carry) concept
•
Introduce 8-bit binary logic
•
Introduce masking
PROGRAM
Use Ex10.asm code to do the following:
ι)• Construct the numbers zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve,
thirteen, fourteen, fifteen, sixteen, seventeen using the addition command ADDA. Represent these
numbers in decimal, binary, and hex using the display options of accA.
ιι)• 3 + 2 = 5 in binary and hex using LDAA, LDAB, ABA
ιιι)•
13 – 6 =7 in binary and hex using LDAA, LDAB, SBA
ιϖ)•
$0f + $01 = $10 in binary and hex using LDAA, LDAB, ABA (half carry, or
bit-3 carry)
ϖ)•
$10 -$01 = $0f in binary and hex using LDAA, SUBA
ϖι)•
$ff + $01 = $00 in binary and hex using LDAA, ADDA (MSB carry)
ϖιι)•
$00 - $01 = $ff in binary and hex using LDAA, SUBA
ϖιιι)•
1 AND 0 = 0 using LDAA, ANDA
ιξ)•
1 OR 0 = 1 using LDAA, ORAA
ξ)• 1 XOR 0 = 1 using LDAA, EORA
ξι)•
1 OR 1 = 1 using LDAA, ORAA
ξιι)•
1 XOR 1 = 0 using LDAA, EORA
ξιιι)•
%11111111 NAND %00000000 = %11111111 using LDAA, ANDA, COMA
ξιϖ)•
%00000000 NOR %11111111 = %00000000 using LDAA, ORAA, COMA
ξϖ)•
%10101110 AND %00000010 = %00000010 using LDAA, ANDA (masking)
(Note: the NAND and NOR instructions do not exist in the MC6811 instruction set, but can be obtained
by using the COM instruction after the AND and OR instructions.)
Dr. Victor Giurgiutiu
Page 138
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open and assemble
Ex10.asm. Tile the windows, set the breakpoint, and reset the registers. Reset accA and accB by typing
zero into them. Set the display option of accA to binary. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 139
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: REPRESENT NUMBERS ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
ELEVEN, TWELVE, THIRTEEN, FOURTEEN, FIFTEEN, SIXTEEN, SEVENTEEN
IN DECIMAL, BINARY, AND HEX
Use the Step button to step through this section of your program. After first step your screen looks like
this:
During this operation, the number zero has been loaded into accA. Your[VG1] Assembly instruction used
the decimal 1, and the simulator converted it to binary, %00000001, per your display setting. The
number one stored in accA is represented using all the 8 bits, though the seven highest bits (preceding
bits) are zero, i.e., %00000001. This rules always apply when binary numbers are represented in this
simulator.
Change the display option of accA to hex. Your screen will look like this:
Step through the rest of the operations, incrementing each time accA by one. At each step, observe the
binary representation, then switch to hex, then to decimal, and back to binary. When incrementing,
observe how the binary bits either increment from 0 to 1, or increment from 1 to 0 with a binary carry to
the left. When you get to the equivalent of number ten, your binary screen should look like this:
Dr. Victor Giurgiutiu
Page 140
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Change the display option of accA to HEX, your screen looks like this:
Continue with the incrementation process until you reach fifteen. Note that during this process, only the
lower four binary bits and the corresponding hex LSD are being affected. The higher four binary bits
and the hex MSD are not being affected. When you reached fifteen, your binary screen should look like
this:
Dr. Victor Giurgiutiu
Page 141
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Change the display option of accA to HEX, your screen looks like this:
Return to the binary display. Note that all the lower bits (bit 0, bit 1, bit 2, bit 3) have been filled with
1’s, while all the higher bits (bit 4, bit 5, bit 6, bit 7) are still filled with 0’s. You have reached the point
where further incrementation will produce a carry from bit 3 into bit 4. When this happens, the lower bit
will be returned to 0, while a 1 will appear in the least significant position of the upper bits. In hex
Dr. Victor Giurgiutiu
Page 142
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
display, this will correspond to a hex carry from the lower to higher nibble of the hex number, i.e. from
$0f to $10.
Press the step button to effect this incrementation. Your binary screen looks like this:
Change the display of accA to HEX; your screen looks like this:
The decimal equivalent of the number in accA at this point is 16. Further incrementation will again
affect only the lower bits, until a bit 3 carry takes again place.
At the end of this section of your program, the binary screen looks like this:
Dr. Victor Giurgiutiu
Page 143
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Change the display option of accA to HEX, your screen looks like this:
Dr. Victor Giurgiutiu
Page 144
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: PERFORM 3 + 2 = 5 IN BINARY AND HEX USING LDAA, LDAB, ABA
Place PC at the beginning of section ii) in the code. Turn display of accA and accB to binary. Step
through this section of the code until the numbers three and two have been loaded into accA and accB,
respectively. They will show as binary, as illustrated by the screen capture below:
Perform the addition of accB to accA; the result is shown in accA. Observe that a carry from bit 1 into
bit 2 has happened. The screen should look like this:
Dr. Victor Giurgiutiu
Page 145
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Repeat this section with the display of accA and accB turned to hex. Observe that, in hex, no carry is
apparent. The corresponding screen captures are:
Dr. Victor Giurgiutiu
Page 146
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: PERFORM 13 – 6 =7 IN BINARY AND HEX USING LDAA, LDAB, SBA
Place PC at the beginning of section iii) in the code. Turn display of accA and accB to binary. Step
through this section of the code until the two numbers have been loaded into accA and accB,
respectively. The screen looks like this:
Perform the subtraction operation. Note that a borrow was enacted from bit 2 into bit 1 and then from bit
3 into bit 2 to permit the operation to take place. After subtraction, your screen looks like this:
Dr. Victor Giurgiutiu
Page 147
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Repeat this section with the display of accA and accB turned to hex. Observe that, in hex, no borrow is
apparent. The screen corresponding captures are:
Dr. Victor Giurgiutiu
Page 148
8/4/20068/21/20058/19/2005
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 149
Example 10
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: PERFORM $0F + $01 = $10 IN BINARY AND HEX USING LDAA, ADDA (HALF CARRY OR BIT 3
CARRY)
Reset accA and accB. Place PC at the beginning of section iv) in the code. Turn display of accA to
binary. Step through this section of the code until the number $0f has been loaded into accA. The screen
looks like this:
Dr. Victor Giurgiutiu
Page 150
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Perform the incrementation. Note the carry that takes place from bit 3 into bit 4. Your screen looks like
this:
Dr. Victor Giurgiutiu
Page 151
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Repeat this section with the display of accA turned to hex. Observe that, in hex, a carry is also apparent.
The corresponding screen captures are:
Dr. Victor Giurgiutiu
Page 152
8/4/20068/21/20058/19/2005
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 153
Example 10
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: PERFORM $10 -$01 = $0F IN BINARY AND HEX USING LDAA, SUBA
Reset accA and accB. Place PC at the beginning of section v) in the code. Turn display of accA to binary.
Step through this section of the code until the number $10 has been loaded into accA. The screen looks
like this:
Perform the decrementation. Note that a borrow takes place from bit 4 into bit 3. Your screen looks like
this:
Repeat this section with the display of accA turned to hex. Observe that, in hex, a borrow is also
apparent. The corresponding screen captures are:
Dr. Victor Giurgiutiu
Page 154
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: PERFORM $FF + $01 = $00 IN BINARY AND HEX USING LDAA, ADDA (MSB CARRY)
Reset accA and accB. Place PC at the beginning of section vi) in the code. Turn display of accA to
binary. Step through this section of the code until the number $ff has been loaded into accA. The screen
looks like this:
Dr. Victor Giurgiutiu
Page 155
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Perform the increment. Note the lost carry that takes place from bit 7. Your screen looks like this:
Repeat this section with the display of accA turned to hex. Observe that, in hex, a lost carry is also
apparent. The corresponding screen captures are:
Dr. Victor Giurgiutiu
Page 156
8/4/20068/21/20058/19/2005
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 157
Example 10
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: PERFORM $00 - $01 = $FF IN BINARY AND HEX USING LDAA, SUBA
Reset accA and accB. Place PC at the beginning of section vii) in the code. Turn display of accA to
binary. Step through this section of the code until the number $00 has been loaded into accA. The screen
looks like this:
Perform the decrementation. Note the free borrow that takes place from into bit 7. Your screen looks
like this:
Repeat this section with the display of accA turned to hex. Observe that, in hex, a free borrow is also
apparent. The corresponding screen captures are:
Dr. Victor Giurgiutiu
Page 158
8/4/20068/21/20058/19/2005
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 159
Example 10
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: 1 AND 0 = 0 USING LDAA, ANDA
Reset accA and accB. Place PC at the beginning of section viii) in the code. Turn display of accA to
decimal. Step through this section of the code until the number 1 has been loaded into accA. The screen
looks like this:
Step again. The number 1 is AND-ed with 0. The result is 0. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 160
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: 1 OR 0 = 1 USING LDAA, ORAA
Reset accA and accB. Place PC at the beginning of section ix) in the code. Leave display of accA to
decimal. Step through this section of the code until the number 1 has been loaded into accA. The screen
looks like this:
Step again. The number 1 is OR-ed with 0. The result is 1. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 161
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: 1 XOR 0 = 1 USING LDAA, EORA
Place PC at the beginning of section x) in the code. Leave display of accA to decimal. Step through this
section of the code until the number 1 has been loaded into accA. The screen looks like this:
Step again. The number 1 is XOR-ed with 0. The result is 1. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 162
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: 1 OR 1 = 1 USING LDAA, ORAA
Place PC at the beginning of section xi) in the code. Leave display of accA to decimal. Step through this
section of the code until the number 1 has been loaded into accA. The screen looks like this:
Step again. The number 1 is OR-ed with 1. The result is 1. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 163
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: 1 XOR 1 = 0 USING LDAA, EORA
Place PC at the beginning of section xii) in the code. Leave display of accA to decimal. Step through
this section of the code until the number 1 has been loaded into accA. The screen looks like this:
Step again. The number 1 is OR-ed with 1. The result is 0. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 164
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
SECTION: %11111111 NAND %00000000 = %11111111 USING LDAA, ANDA, COMA
Place PC at the beginning of section xiii) in the code. Turn display of accA to binary. Step through this
section of the code until the number %11111111 has been loaded into accA. The screen looks like this:
Step again. The number %11111111 is AND-ed with %00000000. The result is %00000000. Your
screen looks like this:
Dr. Victor Giurgiutiu
Page 165
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
[VG2]
Dr. Victor Giurgiutiu
Page 166
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Step again. We get the Boolean inversion of the result using the COMA (complement of accA) opcode.
The result is now %11111111 (note that COMA inverses all the bits). Your screen looks like this:
SECTION: %00000000 NOR %11111111 = %00000000 USING LDAA, ORAA, COMA
Place PC at the beginning of section xiv) in the code. Reset accA and accB. Turn display of accA to
binary. Step through this section of the code until the number %00000000 has been loaded into accA.
The screen looks like this:
Dr. Victor Giurgiutiu
Page 167
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Step again. The number %00000000 is OR-ed with %11111111. The result is %11111111. Your screen
looks like this:
Dr. Victor Giurgiutiu
Page 168
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Step again. We get the Boolean inversion of the result using the COMA opcode (complement of accA).
The result is now %00000000 (note that COMA inverses all the bits). Your screen looks like this:
SECTION: %10101110 AND %00000010 = %00000010 USING LDAA, ANDA (MASKING)
This section demonstrates how the mask %00000010 selects the second bit (bit 1) of the number
%10101110. Place PC at the beginning of section xv) in the code. Leave display of accA to binary. Step
through this section of the code until the number %10101110 has been loaded into accA. The screen
looks like this:
Dr. Victor Giurgiutiu
Page 169
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Step again. The number %10101110 is AND-ed with %00000010. The result is %00000010. Your
screen looks like this:
Dr. Victor Giurgiutiu
Page 170
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
Notice the effect of the mask. Out of all the bits that were set in accA, only that bit (bit 1) that coincides
with the mask has remained. Mask is useful for checking the status of selected bits (e.g., flags).
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The 8-bit binary numbers
•
The connection between 8-bit binary numbers and 2-digit hex numbers.
•
The 8-bit binary arithmetic
•
The half carry (bit 3 carry) concept
•
The 1-bit and 8-bit binary logic
•
The fact that logic operations are performed bit-by-bit
•
Boolean inversion using the complement opcode (e.g., COMA).
•
Masking, i.e., the selection of bits using masks
•
New words and notations: 8-bit binary arithmetic, 8-bit binary logic; complement opcode;
masking, flags.
Dr. Victor Giurgiutiu
Page 171
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
•
Dr. Victor Giurgiutiu
Page 172
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
(This page is intentionally left blank)
Dr. Victor Giurgiutiu
Page 173
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example 10
ank)
Dr. Victor Giurgiutiu
Page 174
8/4/20068/21/20058/19/2005
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
EXAMPLE DELAY
OBJECTIVE
This example has the following objectives:
• Review the use of branching
•
Illustrate a delay (wait) program
•
Demonstrate a flowchart and its relation with the program tasks list and program code
•
Demonstrate the calculation of clock cycles from the clock cycles of each operation
•
Demonstrate the calculation of MCU time from the clock cycles
PROGRAM
The program does the following:
Code
Flowchart
(i) Define variable DELAY at
$0000
(ii) Load DELAY into accA
Define variables:
DELAY
Æ
$0000
Load DELAY into accA
(iii) Decrement accA
(iv) Branch back to (iii) if the
result is higher than zero
(unsigned >0)
LABEL1
Y
(vi) SWI
Subtract 1 from accA
Brach if higher
than zero
N
SWI
DELAY
RMB
1
LDAA DELAY
LABEL1
BHI
SUBA #1
LABEL1
SWI
CODING
The essential code for this program is shown in the third column above. The program has been coded
into the file Ex_delay.asm using the standard template.
Dr. Victor Giurgiutiu
Page 175
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
EXECUTION
Open THRSim11. Close the Commands window. Open the memory window. Open and assemble
Ex_delay.asm. Tile windows, set breakpoint, and reset registers. Set standard labels (Label/Set Standard
Labels). Remove labels RAM and DATA. Set display of memory DELAY to decimal. Press the RESET
button. Your screen should look like this:
a) Put 5 into variable DELAY: click $ff on line $0000 in the memory list, and type in the value 5 in
the highlighted location. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 176
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
Note “Clock Cycles 2” in the lower right corner. This indicates that 2 clock cycles were expended just to
get the MCU started and reset.
b) Step through the program; after each step, observe the number of cycles taken by each operation.
You will notice that NOP takes 2 cycles, LDAA takes 3, SUBA takes 2, and BHI takes 3. Look
up these opcodes in the Motorola MC68HC11 Programming Reference Guide pocketbook and
verify these numbers in the ‘Cycles’ column of the Instructions table.
c) After each pass through LABEL1, accA is decremented by one. When reaching the branch
instruction BHI, the program branches back to LABEL1 if the result of the decrementation is
still higher than zero. After the first pass, accA was decremented from 5 to 4. The screen looks
like this:
Dr. Victor Giurgiutiu
Page 177
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
Note that clock cycles counter shows 12. This number is made up as follows: 2+2+3+2+3=12. During
this pass, accA was reduced from $05 to $04. These are illustrated in the table below:
Cycles count table, actual and cumulative, opcode by opcode, after pass 1.
AccA start
2
START NOP
2
LDAA DELAY 3
LABEL1 SUBA #1
2
BHI
LABEL1 3
SWI
AccA end
Dr. Victor Giurgiutiu
Pass 1
$05
2
4
7
9
12
$04
Page 178
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
After the second pass, the screen looks like this:
Note that clock cycles counter shows 17. This number is made up as follows: 2+2+3+2(2+3)=17. During
this pass, accA was reduced from $04 to $03. These are illustrated in the table below:
Cycles count table, actual and cumulative, opcode by opcode, after pass 2.
AccA start
START
NOP
LDAA DELAY
LABEL1 SUBA #1
BHI
LABEL1
SWI
AccA end
Dr. Victor Giurgiutiu
2
2
3
2
3
Pass 1
$05
2
4
7
9
12
$04
Pass 2
$04
2
3
14
17
$03
Page 179
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
After the third pass, the screen looks like this:
Note that clock cycles counter shows 22. This number is made up as follows: 2+2+3+3(2+3)=22. During
this pass, accA was reduced from $03 to $02. These are illustrated in the table below:
Cycles count table, actual and cumulative, opcode by opcode, after pass 3.
AccA start
START
NOP
LDAA DELAY
LABEL1 SUBA #1
BHI
LABEL1
SWI
AccA end
Dr. Victor Giurgiutiu
2
2
3
2
3
Pass 1
$05
2
4
7
9
12
$04
Pass 2
$04
2
3
14
17
$03
Page 180
Pass 3
$03
2
3
19
22
$02
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
After the fourth pass, the screen looks like this:
Note that clock cycles counter shows 27. This number is made up as follows: 2+2+3+4(2+3)=27. During
this pass, accA was reduced from $02 to $01. These are illustrated in the table below:
Cycles count table, actual and cumulative, opcode by opcode, after pass 4.
AccA start
START
NOP
LDAA DELAY
LABEL1 SUBA #1
BHI
LABEL1
SWI
AccA end
Dr. Victor Giurgiutiu
2
2
3
2
3
Pass 1
$05
2
4
7
9
12
$04
Pass 2
$04
2
3
14
17
$03
Page 181
Pass 3
$03
2
3
19
22
$02
Pass 4
$02
2
3
24
27
$01
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
After the fifth and final pass, the screen looks like this:
Note that clock cycles counter shows 32. This number is made up as follows:
2+2+3+4(2+3)+2+3=7+5*5=32. During this pass, accA was reduced from $01 to $00. At the branch
point, the loop was exited, and the operation SWI was executed after which the program stopped. These
are illustrated in the table below:
Cycles count table, actual and cumulative, opcode by opcode, after pass 5.
AccA start
START
NOP
LDAA DELAY
LABEL1 SUBA #1
BHI
LABEL1
SWI
AccA end
2
2
3
2
3
Pass 1
$05
2
4
7
9
12
$04
Pass 2
$04
2
3
14
17
$03
Pass 3
$03
2
3
19
22
$02
Pass 4
$02
2
3
24
27
$01
Pass 5
$01
2
3
29
32
$00
The total number of cycles expended during the operation of this program with DELAY=5 was 32. The
number of cycles was calculated with formula: N_cycles=7+DELAY*5=7+5*5=32
a) Each clock cycle takes 1/2MHz=0.5 micro-sec. The total time taken by the MCU to execute this
program can be calculated with the formula D_t=N_cycles*0.5 micro-sec. For DELAY=5,
N_cycles=32, and D_t=16 micro-sec=0.000016 sec. This value is shown in the lower left corner
of the simulator window as ‘Simulated time: 0.000016 sec’. To see it, you may have to expand
the window. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 182
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
b) Reset the simulator. Run the program by pressing the Run button. The program stops when
accA has been reduced to zero. The values shown on the task bar are Simulated time: 0.000016
sec in the lower left corner and Clock Cycles 32 in the lower right corner.
c) Reset the simulator. Put value 10 in DELAY.
d) Predict the number of cycles with the formula N_cycles=7+DELAY*5=7+10*5=57. Calculate
the time D_t=N_cycles*0.5=57*0.5=28.5 micro-sec=0.0000285.
e) Run the program. The screen capture is:
Note that ‘Clock Cycles 57’, while ‘Simulated time: 0.0000285 sec.
Dr. Victor Giurgiutiu
Page 183
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example DELAY
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of variables
•
The use of labels and branching
•
The flowchart and its relation with the program tasks list and program code
•
Calculation of clock cycles from the clock cycles of each operation
•
Calculation of MCU time from the clock cycles knowing that each clock cycle lasts 0.5 microsec
•
How to read clock cycles and simulated time in the simulator window
•
How to write a delay (wait) program
•
New words and notations: variables, labels, branch, clock cycles, MCU time.
Dr. Victor Giurgiutiu
Page 184
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
EXAMPLE SQUARE WAVE
OBJECTIVE
This example has the following objectives:
• Review the use parallel ports
•
Illustrate the generation of a square wave using Port B output and a waiting sequence
•
Demonstrate the use of a subroutine to shorten the length of a program
•
Examine the relation between displayed simulation time and clock cycles in THRSim11 simulator
Figure 1 Square wave schematics showing the half-wave duration, Δt, and the low (L) and high (H)
states.
PROGRAMS
This example uses two programs that produce the same output – the generation of a square wave of
programmable wavelength. The wavelength is programmed using the variable DELAY. The square-wave
electrical signal is output through second pin of Port B, i.e., pin PB1. The difference between the first and
second program consist in the use of a subroutine. The use of a subroutine compresses the code and
shortens the total length of the program.
Dr. Victor Giurgiutiu
Page 185
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
PROGRAM SQ_WAV1
Instructions
Code
Flowchart
DELAY
Define variable DELAY at $0000
Load REGBAS in reg. X
Send low signal
Load %00000000 in accA
Store accA in Port B
Load DELAY into accB
Decrease accB in a loop until zero
Send high signal
Load %00000010 in accA
Store accA in Port B
Define DELAY Æ$0000
Initialize REGBAS in reg X
BEGIN Send low signal
Load %00000000 in accA
Store accA in Port B
Load DELAY into accB
LABEL1 Decrease accB by 1
Loop until zero
Send high signal
Load %00000010 in accA
Store accA in Port B
Load DELAY into accB
Decrease accB in a loop until zero
Branch back to (iii)
Load DELAY into accB
LABEL2 Decrease accB by 1
Loop until zero
SWI
RMB
* Start main program
START
ORG
PROGRAM
LDX
#REGBAS
* Begin typing your code
* Send low signal
BEGIN
LDAA
#%00000000
STAA
PORTB,X
LDAB
DELAY
LABEL1 SUBB
BHI
#1
LABEL1
* Send high signal
LDAA
#%00000010
STAA
PORTB,X
LDAB
SWI
1
LABEL2 SUBB
DELAY
#1
BHI
LABEL2
BRA
BEGIN
SWI
FLOWCHART AND CODE
The program flowchart is show to the right of the program instructions. Note the ‘send low signal’ and
‘send high signal’ blocks. Also note the two wait blocks, one sending the low signal, the other after
sending the high signal. The wait blocks are not detailed, since they have been covered in a previous
example and can be directly cloned from there (the ‘code reuse’ concept).
The essential code for this program is shown to the left of the flowchart. The file Sq_wav1.asm is the
result of incorporating this code in the standard template.
EXECUTION
Open THRSim11. Close the Commands window. Open memory list, port registers, and THRSim11 IO
box. Open and assemble Sq_wav1.asm. Set breakpoint at SWI as an insurance against the program
running wild. Reset the registers. Set standard labels (Label/Set Standard Labels). Set display of accA to
binary. Set display of PORTB to binary. Tile windows. Arrange windows for maximum benefit: memory
$0000 only; registers A through X; sufficient of .asm and .LST windows to show the code. Reset
DELAY, A, B, X. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 186
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
a) Put $04 into variable DELAY. Reset the simulator. The PORTB register is %00000000, and all
the lights in the THRSim11 IO box are off.
b) Note the initialization readings: clock cycles = 2, simulated time = 0.0000010 sec = 1.0 μs. These
values are entered as N_1 and T_1 in the "Initialize" row of Table 1.
c) Make one step through the program. The REGBAS value of $1000 is being loaded into X. This
will assist with accessing the port registers in Extended mode using register X. Your screen
looks like this:
Dr. Victor Giurgiutiu
Page 187
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
d) This is the end of the initialization cycle and the beginning of the low-signal part, L, of the square
wave. Step twice. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 188
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
e) Note the start up readings: clock cycles = 11, simulated time = 0.0000055 sec = 5.5 μs. These
values are entered as N_2 and T_2 in the Initialize row, and as N_1 and T_1 in the first (L) row
of Table 1.
Dr. Victor Giurgiutiu
Page 189
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Table 1
DELAY
State
$04
Initialize
L
H
L
H
L
H
L
H
L
H
L
H
Initialize
L
H
L
H
L
H
L
H
L
H
L
H
$40
f)
Clock cycles
ΔN
N_1 N_2
2
11
9
11
40
29
40
72
32
72 101
29
101 133
32
133 162
29
162 194
32
194 223
29
223 255
32
255 284
29
284 316
32
316 345
29
345 377
32
2
11
9
11 340
329
340 672
332
672 1001
329
1001 1333
332
1333 1662
329
1662 1994
332
1994 2323
329
2323 2655
332
2655 2984
329
2984 3316
332
3316 3645
329
3645 3977
332
T_1
1.0
5.5
20.0
36.0
50.5
66.5
81.0
97.0
111.5
127.5
142.0
158.0
172.5
1.0
5.5
170.0
336.0
500.5
666.5
831.0
997.0
1161.5
1327.5
1492.0
1658.0
1822.5
Time, μs
T_2
5.5
20.0
36.0
50.5
66.5
81.0
97.0
111.5
127.5
142.0
158.0
172.5
188.5
5.5
170.0
336.0
500.5
666.5
831.0
997.0
1161.5
1327.5
1492.0
1658.0
1822.5
1988.5
Example SQUARE WAVE
ΔT ΔN/ΔT ΔT/ΔN
4.5
14.5 2.0
0.5
16.0 2.0
0.5
14.5 2.0
0.5
16.0 2.0
0.5
14.5 2.0
0.5
16.0 2.0
0.5
14.5 2.0
0.5
16.0 2.0
0.5
14.5 2.0
0.5
16.0 2.0
0.5
14.5 2.0
0.5
16.0 2.0
0.5
4.5
164.5 2.0
0.5
166.0 2.0
0.5
164.5 2.0
0.5
166.0 2.0
0.5
164.5 2.0
0.5
166.0 2.0
0.5
164.5 2.0
0.5
166.0 2.0
0.5
164.5 2.0
0.5
166.0 2.0
0.5
164.5 2.0
0.5
166.0 2.0
0.5
Step through the program until PORTB becomes %00000010 and PB1 in THRSim11 IO box
turns on. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 190
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
Note the clock cycles and the simulated time as N_2 = 40 and T_2 = 20.0 the first (L) row of Table 1.
Compute ΔN = 29 and ΔT = 14.5. Also compute ΔN/ΔT = 2.000 and ΔT/ΔN = 0.500. Enter the current
values N_2 = 40 and T_2 = 20.0 as N_1 =40 and T_1 = 20.0 in the first (H) row of Table 1.
g) Step through the program until PORTB becomes again %00000000 and PB1 in THRSim11 IO
box turns off. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 191
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
Note the clock cycles and the simulated time as N_2 = 72 and T_2 = 36.0 in Table 1. Compute ΔN = 32
and ΔT = 16.0. Also compute ΔN/ΔT = 2.000 and ΔT/ΔN = 0.500. Enter the N_2 and T_2 values of this
(H) row as N_1 and T_1 values on the next (L) row.
h) You are now again in a low-signal state. Step through the program until the light PB1 comes on
again. Your screen looks like this
Dr. Victor Giurgiutiu
Page 192
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
Observe the N_2 and T_2 values and compare them with the appropriate values in Table 1.
i)
Repeat this until all the values in the $04 portion of Table 1 have been observed. Note that the
ratios ΔN/ΔT and ΔT/ΔN are consistently 2.000 and 0.500, as theoretically predicted.
j)
Also, note the wavelength of your square wave. The low (L) portion of the signal has 29 cycles,
i.e., 14.5 μs, while the high (H) portion has 32 cycles, i.e., 16.0 μs. The H portion is longer since
in includes an additional operation, BRA, which brings us back to the beginning of the program.
However, at higher wavelength, these differences will fade away. These observations are
important for future use of the MCU as a timing device.
k) Set breakpoints at $c007 and $c011. These points correspond to the moments just after the
sending of %00000000 to PORTB, and the sending of %00000010 to PORTB, respectively.
These breakpoints will allow us to run the program automatically, ensuring that it will stop each
time the signal status is changed.
l)
Reset the MCU. Observe again the clock cycles and the simulated time, and verify that they
correspond to the N_1=2 and T_1=1.0 on row ‘$04 Initialize’ in Table 1.
m) Run to the first breakpoint. Verify N_2=11 and T_2=5.5 in Table 1.
n) Run to the next breakpoint. You have run through the first L lap. Verify N_2=40 and T_2=20.0 on
the corresponding row in Table 1.
o) Run to the next breakpoint. You have run through the first H lap. Verify N_2=72 and T_2=36.0 on
the corresponding row in Table 1.
p) Repeat until you have exhausted the $04 portion of Table 2.
Observe the ratios ΔN/ΔT and ΔT/ΔN Note that the ratios ΔN/ΔT and ΔT/ΔN are consistently 2.000 and
0.500, as theoretically predicted.
Dr. Victor Giurgiutiu
Page 193
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
q) Put $40 into the variable DELAY. Reset the simulator. Repeat the above procedure and verify
the values entered in Table 2 under the $40 section.
Observe the durations of the L and H half-waves of the square wave. They are 164-165 μs and 166 μs,
respectively. The consistency of the L and H parts of signal has greatly improved.
Observe the ratios ΔN/ΔT and ΔT/ΔN Note that the ratios ΔN/ΔT and ΔT/ΔN are consistently 2.000 and
0.500, as theoretically predicted.
PROGRAM SQ_WAV2
Define
variable
DELAY at $0000
DELAY
Define DELAY Æ$0000
Initialize REGBAS in reg X
Load REGBAS in reg. X
Send low signal
Load %00000000 in accA
Store accA in Port B
Jump to subroutine WAIT
BEGIN Send low signal
Load %00000000 in accA
Store accA in Port B
Jump to subroutine
Send high signal
Load %00000010 in accA
Store accA in Port B
Jump to subroutine WAIT
Branch back to (iii)
SWI
Send high signal
Load %00000010 in accA
Store accA in Port B
Jump to subroutine
Subroutine WAIT
(ii)
Load
DELAY
into accB
(iii)
Decrease
DELAY
(iv)
Loop until zero
(v)
Return
from
subroutine
Code
Flowchart
Instructions
(i)
RMB
1
* Start main program
ORG
PROGRAM
START
LDX
#REGBAS
BEGIN
LDAA
#%00000000
STAA
PORTB,X
JSR
SR_WAIT
LDAA
#%00000010
STAA
PORTB,X
JSR
SR_WAIT
BRA
BEGIN
SWI
SR_WAIT
Load DELAY into accB
Decrease accB
Loop until zero
Return from subroutine
SR_WAIT LDAB
DELAY
LABEL1 SUBB
#1
BHI
LABEL1
RTS
SWI
FLOWCHART AND CODE
The program flowchart is show to the left of the program instructions. Note the ‘send low signal’ and
‘send high signal’ blocks. Also, note that the two wait blocks of the program Sq_wav1 have been
replaced by a single subroutine block that is repeatedly called. The essential code for this program is
shown to the left of the flowchart. The file Sq_wav2.asm is the result of incorporating this code in the
standard template.
EXECUTION
Open and assemble Sq_wav2.asm. Set breakpoint at SWI, and reset registers. Set standard labels
(Label/Set Standard Labels). Set display of accA to binary. Set display of PORTB to binary. Tile and
arrange windows for maximum benefit: memory $0000 only; registers A through X; sufficient of .asm
and .LST windows to show the code. Reset DELAY, A, B, X. DO NOT RESET THE SP (stack pointer)
REGISTER, BECAUSE, IF YOU DO SO, ACCESS TO YOUR SUBROUTINE WILL NOT WORK.
Dr. Victor Giurgiutiu
Page 194
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
a) Put $04 into variable DELAY. Reset the simulator. The PORTB register is %00000000, and all
the lights in the THRSim11 IO box are off. Step through the program until you reach subroutine.
Your screen will look like this:
b) Step through the subroutine until you get to RTS and are ready to jump back to the program.
Your screen looks like this:
c) After another step, you are back into the main program:
Dr. Victor Giurgiutiu
Page 195
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
d) As you step further, you observe that the Port B pin 1 is toggled, and the light PB1 in the IO box
comes on. The main program is again ready to jump to the subroutine:
e) Further stepping takes you back into the subroutine, and out again.
f)
Run the program on automatic. You will notice how the subroutine is accessed every time the
PB1 light changes.
g) Put breakpoints at the two JSR lines. Run the program on automatic, and record in Table 2 the
values recorded for DELAY = $04, and for DELAY = $40.
h) Compare the values from Table 2 with those in Table 1. You will notice:
i) For same values of delay (say, DELAY = $04), the duration of the half waves are
different: in Table 2 (20 μs and 21.5 μs) from those in Table 1 (14.5 μs and 16 μs).
This difference is due to the different way in which the two programs were constructed.
Dr. Victor Giurgiutiu
Page 196
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
ii) At low delay values (DELAY = $04), the difference between the durations of the L and
H half waves is significant (7.5%). As the delay increased, this difference fades away.
At DELAY = $40, the difference has come down to 0.9%.
Table 2
DELAY
$04
$40
State
Clock cycles
N_1
N_2
Initialize
2
11
L
11
51
H
51
94
L
94
134
H
134
177
L
177
217
H
217
260
L
260
300
H
300
343
L
343
383
H
383
426
L
426
466
H
466
509
Initialize
2
11
L
11
351
H
351
694
L
694 1034
H
1034 1377
L
1377 1717
H
1717 2060
L
2060 2400
H
2400 2743
L
2743 3083
H
3083 3426
L
3426 3766
H
3766 4109
ΔN
9
40
43
40
43
40
43
40
43
40
43
40
43
9
340
343
340
343
340
343
340
343
340
343
340
343
T_1
1.0
5.5
25.5
47.0
67.0
88.5
108.5
130.0
150.0
171.5
191.5
213.0
233.0
0.0
5.5
175.5
347.0
517.0
688.5
858.5
1030.0
1200.0
1371.5
1541.5
1713.0
1883.0
Time, μs
T_2
5.5
25.5
47.0
67.0
88.5
108.5
130.0
150.0
171.5
191.5
213.0
233.0
254.5
5.5
175.5
347.0
517.0
688.5
858.5
1030.0
1200.0
1371.5
1541.5
1713.0
1883.0
2054.5
ΔT
4.5
20.0
21.5
20.0
21.5
20.0
21.5
20.0
21.5
20.0
21.5
20.0
21.5
5.5
170.0
171.5
170.0
171.5
170.0
171.5
170.0
171.5
170.0
171.5
170.0
171.5
ΔN/ΔT ΔT/ΔN
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
2.000
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
0.500
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of Port B
•
The use of displayed clock cycles and simulated time, and their relative accuracy
•
The fact that the round-off error becomes less severe as the magnitude of the number increases
•
The usefulness of subroutines for shortening programs
•
The use of Port B to generate a square wave
•
New words and notations: subroutine, jump to subroutine (JSR), return from subroutine (RTS),
square wave, wavelength, IO (Input-Output), IO box, accuracy, round-off.
Dr. Victor Giurgiutiu
Page 197
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SQUARE WAVE
(This page is intentionally left blank)
Dr. Victor Giurgiutiu
Page 198
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example BUTTONS BOX
EXAMPLE BUTTONS BOX
OBJECTIVE
This example has the following objectives:
• Review the use of parallel ports
•
Illustrate the use of Port C for input and output
•
Introduce the concept of shifting register and memory content
•
Practice the use of the THRSim11 IO box for input and output
PROGRAMS
This example demonstrates the use of Port B for output and of Port C for both input and output. Port C is
configured to have the even pins PC0, PC2, PC4, PC6 for output. This is achieved using the Data
Direction Register for port C (DDRC). Since the default setting for Port C is input, the pins that have to
be set to output have their image set to 1 in DDRC. In our case, the bits 0, 2, 4, and 6 of DDRC are set to
1. Thus, the Port C pins PC0, PC2, PC4, PC6 become output, while pins PC1, PC3, PC5, PC7 remain
input.
The program loops continuously, reading data from some Port C pins, and sending data back to the other
Port C pins. Simultaneously, the data is also sent to Port B.
PROGRAM BUTTONS_BX
Instructions
Flowchart
Please fill in yourself
Code
START
LDX
#REGBAS
(vi)
Load REGBAS in reg. X
* Begin typing your code
(vii)
Clear port B by storing zero in it
* Clear Port B
Select odd Port C pins for output
(viii) Load %01010101 in accA
(ix)
LDAA
#%00000000
STAA
PORTB,X
* Select PC0, PC2, PC4, PC6 for
output
Store accA to DDRC
Main loop
LDAA
#%01010101
STAA
DDRC,X
(x)
Load Port C to accA
* Main loop
(xi)
Shift accA to the right
BEGIN
(xii)
LDAA
PORTC,X
LSRA
Store accA to Port C and Port B
*
(xiii) Branch back to (v)
(xiv) SWI
STAA
PORTC,X
STAA
PORTB,X
BRA
BEGIN
SWI
FLOWCHART AND CODE
The program flowchart is not provided, since is simpler than in previous examples. The students are
encouraged to use the space provided for filling in their own flowcharts of the program. The essential
code for this program is shown to the right of the flowchart. The file Buttons_bx.asm is the result of
incorporating this code in the standard template.
Dr. Victor Giurgiutiu
Page 199
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example BUTTONS BOX
EXECUTION
Open THRSim11. Close the Commands window. Open port registers, and THRSim11 IO box. Open and
assemble Buttons_bx.asm. Set breakpoint, and reset registers. Set standard labels (Label/Set Standard
Labels). Set display of accA to binary. Set display of PORTB and PORTC to binary. Tile windows.
Arrange windows for maximum benefit. Your screen should look like this:
a) Before you run the program, verify the Port C pins functionality. In the THRSim11 IO box, toggle
up the switch PC3. You will see that the corresponding bit in Port C register, bit 3, becomes 1
immediately. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 200
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example BUTTONS BOX
b) Toggle down the switch PC3 in the IO box.
c) Run the program. The program will loop continuously between label BEGIN and opcode BRA.
d) With the program running, toggle up the switch PC3 in the IO box. Immediately, bit 3 in PORTC
will switch to one. Simultaneously, pin 2 in PORTB will become 1, and the light PB2 in the IO
box will lit. Press the stop button and capture the screen. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 201
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example BUTTONS BOX
e) Try to toggle other PC switches in the IO box. You will notice that now only the odd switches
(PC1, PC3, PC5, PC7) are producing the setting of the corresponding bits in PORTC register.
The other switches (PC0, PC2, PC4, PC6) can be toggled, but with no effect on the PORTC
register. This illustrates how DDRC controls PORTC register.
f)
Restart the program by pressing the Run button. With the program running, try to toggle the
other switches. You will notice that the toggling of the odd switches (PC1, PC3, PC5, PC7) has
the effect of switching on the even Port B lights (PB0, PB2, PB4, PB6). This is the result of the
data from the odd Port C pins is loaded in accA, right shifted, and sent back to Port B.
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of PORTC for input and output
•
The concept of shifting a register
•
The use of the THRSim11 IO box for both input and output
•
New words and expressions: toggle switch; shift a register, shift data.
Dr. Victor Giurgiutiu
Page 202
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI TRANSMISSION
EXAMPLE SCI TRANSMISSION
OBJECTIVE
This example has the following objectives:
• Review the use of serial communication interface (SCI) for transmission
•
Illustrate the sending of a character through SCI
PROGRAM SCI_TRANSMIT
This program is an example of SCI transmission. The character T is being sent to SCDR when TDRE is
set.
Instructions
a)
Load REGBAS in reg. X
b)
Initialize BAUD=9600
c)
Initialize 8-bit word
d)
Initialize TE and RE
e)
Load character 'T' in AccB
f)
Check if TDRE is set
g)
Store accB to SCDR
h)
Branch back to (v)
i)
SWI
Code
Flowchart
START
Initialize REGBAS in reg X
Initialize SCI:
BAUD = 9600
8-bit word
TE=1, RE=1
LABEL2
Load ‘T’ in accB
Check if TDRE is set
LABEL3 Load SCSR into accA
AND with mask %10000000
Loop if zero
LDX
#REGBAS
LDAA
#%00110000
STAA
BAUD,X
LDAA
#%00000000
STAA
SCCR1,X
LDAA
#%00001100
STAA
SCCR2,X
LABEL2 LDAB
#'T'
* Send the character to the terminal
LABEL3 LDAA
SCSR,X
ANDA
#%10000000
BEQ
LABEL3
* You are here when the transmission reg. is
empty
STAB
SCDR,X
BRA
LABEL2
SWI
Store AccB to SCDR
SWI
FLOWCHART AND CODE
The program flowchart is show to the right of the program instructions. Note the initialization block,
which contains reg. X initialization and SCI initialization. After initialization, the character T is loaded
into accB. Then, the status of TDRE (transmission data register empty) flag is checked in a loop. When
TDRE is found set, the loop is exited and the contents of accB is stored in SCDR (serial communication
data register). This operation automatically resets TDRE. Now, the program loops back to the beginning
and tries to send again.
The essential code for the program is shown to the right of the program flowchart. This essential code
was incorporated into the standard asm template to generate the file SCI_transmit.asm.
EXECUTION
Open THRSim11. Close the Commands window. View serial registers. View serial receiver. Open and
assemble SCI_transmit.asm. Set breakpoint at STAB SCDR,X instruction and at SWI. Reset registers.
Set standard labels (Label/Set Standard Labels). Set display of accA to binary. Set display of BAUD,
SCCR1, SCCR2, SCSR to binary. Arrange windows for maximum benefit: Reset, A, B, X. Press the
RESET button. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 203
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI TRANSMISSION
Note that the reset value of SCSR is %11000000, i.e., it has the flags TDRE and TC set. This indicates
that the transmitter is ready to transmit.
a) Press the RUN button. The program should loop on LABEL3 and exit the loop when the
condition TDRE=1 is satisfy. This condition is checked with the mask %10000000. The mask is
applied on the value found in SCSR. When bit 7 in SCSR is set, the mask senses it and the
condition for exiting the loop is satisfied. Since TDRE=1 from the reset, the loop is passed
through and exited.
Dr. Victor Giurgiutiu
Page 204
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI TRANSMISSION
b) When the ‘check TDRE’ loop is exited, the program gets to the line
STAB
SCDR,X
This line is a breakpoint. At this moment, the screen looks like this:
c) Step manually to the next line, which stores accB into SCDR. This store operation automatically
resets TDRE. The screen looks like this:
Dr. Victor Giurgiutiu
Page 205
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI TRANSMISSION
Note that SCSR is %00000000. This proves that TDRE has been reset by the storing to SCDR. Also note
that the value $54 from accB has not yet arrived in SCDR. (The reason for this is that the simulator has
an internal delay when running SCI in manual mode.)
d) Press RUN again. The program loops several times on LABEL3 before exiting. While looping,
you can see SCSR=%00000000, i.e., TDRE=0. When exiting, SCSR=%10000000, i.e.,
TDRE=1. When the program pause, the screen looks like this:
Note that SCSR=%10000000, i.e., TDRE=1. The transmission of the character was done, and SCI
is ready to transmit again.
e) Press RUN again 2 times. Note that the character T has appeared in the serial receiver window.
Your screen capture looks like this:
Dr. Victor Giurgiutiu
Page 206
8/19/2008
EMCH 367
f)
Fundamentals of Microcontrollers
Example SCI TRANSMISSION
Press RUN again. You get an additional character in the serial receiver window. Your screen
capture looks like this:
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of serial communication interface (SCI) for transmission
•
The sending of a character through SCI
•
New words and notations: SCSR, SCDR, TDRE.
Dr. Victor Giurgiutiu
Page 207
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI TRANSMISSION
•
Dr. Victor Giurgiutiu
Page 208
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI RECEPTION
EXAMPLE SCI RECEPTION
OBJECTIVE
This example has the following objectives:
• Review the use of serial communication interface (SCI) for reception
•
Illustrate the receiving of a character through SCI
PROGRAM SCI_RECEPT
This program is an example of SCI reception. The character T is being sent to SCDR when TDRE is set.
Flowchart
Instructions
a)
b)
c)
d)
Load REGBAS in reg. X
Initialize BAUD=9600
Initialize 8-bit word
Initialize TE and RE
Wait for the reception of a keystroke
e)
check if RDRF is set by
loading SCSR into accA and
AND with mask for RDRF,
%00100000
You are here when reception data reg. is full
f)
Load SCDR into accB
g)
Store accB through Port B
h)
Branch back to (e)
i)
SWI
Initialize REGBAS in reg X
Initialize SCI:
BAUD = 9600
8-bit word
TE=1, RE=1
LABEL0
No operation
Check if RDRF is set
LABEL1 Load SCSR into accA
AND with mask %00100000
Loop if zero
Code
START
LDX
LDAA
STAA
LDAA
STAA
LDAA
STAA
LABEL0 NOP
#REGBAS
#%00110000
BAUD,X
#%00000000
SCCR1,X
#%00001100
SCCR2,X
LABEL1 LDAA
ANDA
BEQ
LDAB
STAB
BRA
SWI
SCSR,X
#%00100000
LABEL1
SCDR,X
PORTB,X
LABEL0
Load accB from SCDR
Store accB to Port B
SWI
FLOWCHART AND CODE
The program flowchart is show to the right of the program instructions. Note the initialization block,
which contains reg. X initialization and SCI initialization. After initialization, the status of RDRF
(reception data register full) flag is checked in a loop. When RDRF is set, the loop is exited and the
content of SCDR (serial communication data register) is loaded in accB. This operation automatically
resets RDRF. Now, the program loops back to the beginning and waits for another transmission.
The essential code for the program is shown to the right of the program flowchart. This essential code
was incorporated into the standard asm template to generate the file SCI_recept.asm.
EXECUTION
Open THRSim11. Close the Commands window. View ports registers and serial registers. View serial
transmitter. Open and assemble SCI_recept.asm. Set breakpoint at LDAB SCDR,X and at SWI. Reset
registers. Set standard labels (Label/Set Standard Labels). Set display of BAUD, SCCR1, SCCR2, SCSR
to binary. Set display of accA to binary. Arrange windows for maximum benefit: Reset, A, B, X, PORTB.
Press the RESET button. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 209
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI RECEPTION
a) Press the RUN button. The program should loop on LABEL1 and exit the loop when the
condition RDRF=1 is satisfy. This condition is checked with the mask %00100000. The mask is
applied on the value found in SCSR. When bit 5 in SCSR is set, the mask senses it and the
condition for exiting the loop is satisfied.
b) Type the character T in the serial transmitter window and press Send. The character is sent to
the MCU. The MCU takes a few laps to sense it. When the MCU senses it, the RDRF gets set,
and the ‘check RDRF’ loop is exited.
c) When the ‘check RDRF’ loop is exited, the program gets to the line
LDAB
SCDR,X
This line is a breakpoint. At this moment, the screen looks like this:
Dr. Victor Giurgiutiu
Page 210
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI RECEPTION
Note that that SCSR is %11100000, i.e., the RDRF flag (bit 5 of SCSR) is set. This indicates that the
character was received. (The TDRE and TE flags, i.e., bits 6 and 7, are also set, but this is due to the
reset.) Note also that the ASCII code for the character T, $54 appears in SCDR (serial communication
data register). From SCDR it will be loaded into accB.
d) Step manually to the next line, which loads the data from SCDR into accB. This load operation
automatically resets RDRF. The screen looks like this:
Note that SCSR is %11000000. This proves that RDRF (bit 5) has been reset by the loading from SCDR;
but TDRE and TC remained set, since they are not affected by reception operations.
e) Step again. The content of accB is stored in PORTB. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 211
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SCI RECEPTION
Note that the ASCII code for T, i.e., $54, appears in PORTB.
f)
Switch again to auto run. The program loops now again on LABEL1. Press again the send button
in the serial transmitter. The character T is sent again, and after a few laps the program exits the
loop and gets to the LDAB SCDR,X breakpoint.
g) Run again automatically. Change the character in the serial transmitter to A. You will notice that
the corresponding ASCII code, $41, appear in SCDR, and then, after manual steps, gets loaded
in accB and stored in PORTB.
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of serial communication interface (SCI) for reception
•
The reception of a character through SCI
•
New words and notations: RDRF, ASCII code.
Dr. Victor Giurgiutiu
Page 212
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
EXAMPLE INPUT CAPTURE TIMER FUNCTION
OBJECTIVE
This example has the following objectives:
• Review the use of MCU Timer function as an Input Capture (IC) device
• Review the use of the free running clock, TCNT, and it overflow flag, TOF
• Review the use of a input capture clock, TIC1, and its event flag, IC1F
• Demonstrated how the selection of signal transition to be captured is made (here rising edge,
EDG1A) and that the MCU is only sensitive to that particular transition.
• Show the calculation of actual time in μs from the timer readings, T1, T0, and overflow count,
NOF.
PROGRAM EX_IC
This program is an example of timer input capture. The process is started when a keystroke is received.
Then, the time is measured until a low-high transition is captured on line IC1. In this process, the initial
time, T0, and the capture time, T1, as well as the number of overflows are recorded. After the input
capture, the IC1F flag is reset, the overflow counter is zeroed, and the process is repeated.
FLOWCHART AND CODE
The program flowchart is show to the right of the program instructions. Note the variable definition block
in which T0, T1, and NOF are defined. Next, the initialization block contains reg. X initialization, timer
IC initialization, and SCI initialization. The program loop starts at label BEGIN with the overflow
counter, NOF, being zeroed. First, the RDRF (reception data register full) flag is checked in a loop to
verify if a keystroke has been received. When keystroke was received, the time counter is read and stored
in T0. Then, the programs loops on LABEL1 until and input capture IC1 is recorded. In this loop, TOF is
first check to verify if timer overflow takes place. When timer overflow is detected, the overflow counter,
NOF, is incremented and TOF is reset. Next, IC1F is check to verify if input capture on IC1 took place.
If input capture is not detected, the program returns to LABEL1. When input capture is detected, the
program exits the loop, loads the IC1 timer from TIC1 and stores it in the capture time variable, T1. The
program loops back to the beginning and wait for a new keystroke to restart the process.
The essential code for the program is shown to the right of the program flowchart. This essential code
was incorporated into the standard asm template to generate the file Ex_IC.asm.
Dr. Victor Giurgiutiu
Page 213
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Instructions
i)
ii)
iii)
iv)
v)
vi)
vii)
viii)
ix)
x)
xi)
xii)
xiii)
xiv)
xv)
xvi)
xvii)
xviii)
Define variables:
a. Origin of time, T0 = 2 bytes
b. Capture time, T1 = 2 bytes
c. Overflow counter, NOF1 = 1
byte
Initialize
Initialize index X to REGBAS
Initialize timer IC1 function: set
EDG1A in TCTL2
Initialize SCI
Wait for a keystroke reception
Store initial time
Zero overflow counter NOF1
Reset TOF
Wait for the input capture
Check TOF
Jump if no TOF; else
a. Increment overflow counter
b. Reset TOF
Check IC1F
Loop back
After input capture
Load and store t1
Reset IC1F by writing 1 to it
Loop back to iii) and do it again
Code
Flowchart
Define variables:
• Origin of time, T0 = 2 bytes
• Capture time, T1 = 2 bytes
• Overflow counter, NOF1 = 1 byte
START • Initialize REGBAS in reg X
• Initialize timer IC function:
set EDG1A in TCTL2
• Initialize SCI:
BEGIN NOP
Check if RDRF is set
LABEL0
• Load TCNT into T0
• Zero NOF1
• Reset TOF
LABEL1
N
Check TOF
Y
• Increment NOF1
• Reset TOF
LABEL2
Check IC1F
N
Y
• Load and store measured
time from TIC1 into T1
• Reset IC1F
SWI
Dr. Victor Giurgiutiu
Example INPUT CAPTURE TIMER FUNCTION
Page 214
ORG
T0
RMB
T1
RMB
NOF1
RMB
ORG
START LDX
LDAA
STAA
LDAA
STAA
LDAA
STAA
LDAA
STAA
BEGIN NOP
LABEL0 LDAA
ANDA
BEQ
LDAA
LDD
STD
LDAA
STAA
LDAA
STAA
LABEL1 LDAA
ANDA
BEQ
INC
LDAA
STAA
LABEL2 LDAA
ANDA
BEQ
LDD
STD
LDAA
STAA
BRA
SWI
DATA
2
2
1
PROGRAM
#REGBAS
#%00010000
TCTL2,X
#%00110000
BAUD,X
#%00000000
SCCR1,X
#%00001100
SCCR2,X
SCSR,X
#%00100000
LABEL0
SCDR,X
TCNT,X
T0
#$00
NOF1
#%10000000
TFLG2,X
TFLG2,X
#%10000000
LABEL2
NOF1
#%10000000
TFLG2,X
TFLG1,X
#%00000100
LABEL1
TIC1,X
T1
#%00000100
TFLG1,X
BEGIN
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, timer registers, port A pins,
memory list, serial transmitter. Open and assemble Ex_IC.asm. Set breakpoints at $c01a, $c02e, $c03b,
and at SWI[VG3]. Reset registers and memory. Set standard labels (Label/Set Standard Labels). Set display
of TCTL2, TFLG1, TFLG2 to binary. Arrange windows for maximum benefit: Press the RESET button.
Your screen should look like this:
[VG4]
Dr. Victor Giurgiutiu
Page 215
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
a) Press the RUN button. The program should loop on LABEL0. Type letter T into the serial
transmitter and send. The program should exit the loop and stop at $c01a. At this point your
screen looks like this:
Dr. Victor Giurgiutiu
Page 216
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
b) Step. You will notice that the contents of SCDR ($54, i.e. ASCII for T) has been loaded into accA
c) Step again. The screen looks like this:
You notice that the contents of TCNT (in this case, $101c) has been loaded into accD. (The double
accumulator accD is used, since the time values are in double precision, i.e., require 4 hex digits).
Dr. Victor Giurgiutiu
Page 217
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
d) Step again.
You notice that the content of accD (for me, $101c, but you may get something else!) has been loaded in
memory at location T0. It takes two consecutive memory locations, and is loaded as $10 followed by $1c.
At this stage, The timer count (TNCT) value was captured and stored into T0 as initial time.
a) Check for TOF. Switch display of accA to binary. Step. The value of TFLG2 (%01000000) is
loaded into accA.
b) Step 2 times. The value in accA is AND-ed with the TOF mask (%10000000). Since TOF was
not set, the result is zero and the BEQ operation jumps to LABEL2.
c) Check for IC1F. Step once. The value of TFLG1 (%00000000) is loaded into accA. Step 2 times.
The value in accA is AND-ed with the IC1F mask (%00000100). Since IC1F was not set, the
result is zero and the BEQ operation jumps to LABEL1.
d) You are back at LABEL1. Step through the TOF check and stop when you are at $c035
e) Toggle IC1 pin in Port A pins window from 0 to 1. Notice that, as you do so, bit 2 in TFLG1 gets
also set. This bit is the IC1F bit, and it detects that a transition has taken place on line IC1.
Dr. Victor Giurgiutiu
Page 218
8/19/2008
EMCH 367
f)
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
Step. The value in TFLG1 (%00000100) gets loaded into accA. Step again. AccA is AND-ed with
the IC1F mask (%00000100). The result is (%00000100), i.e., non-zero.
g) Step again. Since the result of the previous operation was non-zero, the BEQ operation does not
branch, and you proceed to line $c03b
h) Change display of accA to hex. Step. The value in TIC1 (for me, $2994, but you may get
something else!) is loaded in accD (The double accumulator accD is needed, since the timer
values are in double precision, i.e., four hex long)
i)
Step again. The value in accD (for me, $2994, but you may have something else!) is stored as
the captured time in T1. Note that two memory location are used, and the storage is done as $29
followed by $94
j)
You will do this now on automatic. Press the Run button. Then, press the send button in the
serial transmitter to start the input-capture process. Your program stops at the breakpoint $c01a.
k) Step. The TCNT value (mine is $cf13, yours may differ!) gets captured in accD.
l)
Step two times. The TCNT value ends up in T0 (in my case, $cf13, yours may differ!).
m) Run. Toggle pin IC1 in port A window. As you toggle from 1 to 0, nothing happens, since you
only set EDG1A=1 in the initialization section. This means that you programmed the MCU to only
recognize raising edges on line IC1, i.e., transitions from 0 to 1.
n) Toggle again, now from 0 to 1. Note that the loop is exited, and the program stops at the
breakpoint $c03b.
o) Run again several times, and consolidate your understanding of the way the program runs. Try
sending different characters, and notice that the program is only sensitive to you sending a
character, but insensitive to what character you sent.
p) When you are content with your understanding, remove all breakpoint but SWI. Set a new
breakpoint at $c043. Run, go through the sending and the toggling, and, after it stops at the
breakpoint, write below the values of T0, T1, NOF:
My results
T0
$49c8
T1
$6227
NOF
Your results
0
Calculate the time taken between your sending of the character (start of the process) and your toggling
of IC1 from low to high (stop of the process).
(Δt)mine = (T1-T0 + $10000*NOF)*0.5 μs = ($6227 - $49c8 + $10000*0)* 0.5 μs = 3119 μs = 3.1 ms
(Δt)yours = (T1-T0 + $10000*NOF)*0.5 μs = ($???? - $???? + $10000*0)* 0.5 μs = ???? μs = ???.? ms
Dr. Victor Giurgiutiu
Page 219
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example INPUT CAPTURE TIMER FUNCTION
q) Try to wait for the NOF to change to 1 before you toggle the IC1 pin. write below the values of
T0, T1, NOF:
My results
T0
$872e
T1
$366e
NOF
Your results
1
(Δt)mine = (T1-T0 + $10000*NOF)*0.5 μs = ($366e - $872e + $10000*1)* 0.5 μs = 55,200 μs = 55.2 ms
(Δt)yours = (T1-T0 + $10000*NOF)*0.5 μs = ($???? - $???? + $10000*1)* 0.5 μs = ????? μs = ???.? ms
Note: The results from u) and t) do not need to agree. They depend on human factor, like when you
decide to toggle the IC1 bit.
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of MCU Timer function as an Input Capture (IC) device
•
The use of the free running clock, TCNT, and it overflow flag, TOF
•
The use of a input capture clock, TIC1, and its event flag, IC1F
•
The selection of signal transition to be captured (here rising edge, EDG1A) and the fact that the
MCU is only sensitive to that particular transition.
•
The calculation of actual time in μs from the timer readings, T1, T0, and overflow count, NOF.
Dr. Victor Giurgiutiu
Page 220
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
EXAMPLE OUTPUT COMPARE TIMER FUNCTION
OBJECTIVE
This example has the following objectives:
• Review the use of MCU Timer function as an Output Compare (OC) device
•
Review the setting of OMx and OLx bits to select a desired OC event (in this example, we set
OM3=0, OL3=1, to generate a toggle on the OC3 pin)
•
Review the detection of the TOCx match with TNCT and the corresponding OC action
•
Present the correlation between delay, DT, with actual frequency of the square wave.
•
Explore the accuracy with which frequency can be adjusted
•
Explore the determination of low and high bounds on the frequencies that can be generated with
the MCU
V
Logical 1, +5 V
L
Logical 0, 0 V
H
L
H
t
Δt
Δt
Δt
Δt
Figure 1 Square wave schematics showing the half-wave duration, Δt, and the low (L) and high (H)
states.
PROGRAM EX_OC
This program is an example of timer output compare. The program runs freely and generates repeated
toggles of the output compare pin OC3 (PA5) at equal intervals that are determined using the delay
variable DT. Thus, a square wave is generated. The program instructions are given in the first column
below.
FLOWCHART AND CODE
The program flowchart is show to the right of the program instructions. Note the variable definition block
in which DT is defined. Next, the initialization block contains reg. X initialization and timer OC
initialization. The program stores the current time (TCNT) plus the delay DT in the OC3 timer TOC3. A
loop is entered in which the OC3 flag, OC3F is checked. When OC3F is set, the loop is exited. The
OC3F is reset, and the value of TOC3 is updated with the current time plus the delay. Then, the program
loops back.
The program loops back to the beginning and waits for a new keystroke to restart the process.
The essential code for the program is shown to the right of the program flowchart. This essential code
was incorporated into the standard asm template to generate the file Ex_OC.asm.
Dr. Victor Giurgiutiu
Page 221
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Instructions
i) * Define variable
•
Half wave duration DT = 2 bytes
ii) Initialize
•
Initialize index X to REGBAS
•
Initialize timer OC3 function:
set to toggle (OM3=0, OL3=1)
iii) Store initial time + DT in TOC3
iv) Wait and loop until OC3F is set;
when OC3F set, proceed
v) Reset OC3F
vi) Update TOC3: add DT to current
time and store in TOC3
vii) Branch back iv)
Example OUTPUT COMPARE TIMER FUNCTION
Flowchart
Define variables:
• Half wave duration DT = 2 bytes
START • Initialize index X to REGBAS
• Initialize timer OC3 function:
set to toggle (OM3=0,
OL3=1)
Store TCNT+DT in TOC3
LABEL1
Check if OC3F is set
Reset OC3F
Store TCNT+DT in TOC3
Code
ORG
DT
RMB
ORG
START LDX
LDAA
STAA
LDD
ADDD
STD
LABEL1 LDAA
ANDA
BEQ
LDAA
STAA
LDD
ADDD
STD
BRA
SWI
DATA
2
PROGRAM
#REGBAS
#%00010000
TCTL1,X
DT
TCNT,X
TOC3,X
TFLG1,X
#%00100000
LABEL1
#%00100000
TFLG1,X
DT
TCNT,X
TOC3,X
LABEL1
SWI
Dr. Victor Giurgiutiu
Page 222
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, timer registers, port A pins,
memory list. Open and assemble Ex_OC.asm. Set breakpoints at $c013 and at SWI. Reset registers and
memory. Set standard labels. Set display of TCTL1, TFLG1 to binary. Arrange windows for maximum
benefit: Press the RESET button. Your screen should look like this:
a) Put $0020 in DT. When doing this, note that DT takes two memory locations, $0000:$0001.
b) Step through your program. Notice how the bit 4 is initialized in TCTL1 (this sets OC3 to toggle).
Dr. Victor Giurgiutiu
Page 223
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
c) Step further. Note that the value in TCNT is added with DT and stored in TOC3. At this point,
your screen looks like this
d) Step further. The program goes through the loop on LABEL1. As long as TCNT is less than
TOC3, the bit OC3F in TFLG1 (bit 5) remains zero, and the program loops.
e) When the value of TCNT exceeds TOC3, the bit OC3F gets set. Simultaneously, the output
compare function is activated. Recall that our program was set to toggle the value in pin OC3
when output compare condition is met. Look in the Port A pins window. Notice that the pin OC3
(PA5) is set. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 224
8/19/2008
EMCH 367
f)
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
At this point, the condition for exiting the loop is met, and, when stepping further, the loop is
exited. Your program gets to $c013. The mask for OC3F is stored in TFLG1 and OC3F gets
reset. Your screen is:
Dr. Victor Giurgiutiu
Page 225
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
g) Step further. The time increment, DT, is added to the current time, TCNT, and stored in TOC3 as
the new time. Your screen is:
h) Step again through your program. Observe that the whole procedure is repeated, only that this
time the toggle was from 1 to 0. This shows that, effectively, a square wave of half wave duration
DT is being generated at pin OC3 (PA5). Next we will verify the length of the half wave in time
units and determine the effective frequency.
i)
Press the Reset button. Press the RUN button. The program should again loop on LABEL1 for a
while, and then exit the loop and stop at $c013. At this point your screen looks like this:
Dr. Victor Giurgiutiu
Page 226
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
Note that the clock cycles are 62 and the simulation time is 31 μs. These values are entered in Table 1.
j)
Run again through the program. At the next breakpoint, your screen looks like this:
Note that the clock cycles are 113 and the simulation time is 56.5 μs. These values are entered again in
Table 1.
Dr. Victor Giurgiutiu
Page 227
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
k) Run further through your program, and after each breakpoint stop, record the clock cycles and
the simulated time in Table 1. Do this until you have completed 6 L-H groups. These correspond
to 6 square waves.
l)
Calculate the half-wave time, Δt, and the equivalent frequency, f=1/2Δt. (When doing this, omit
the first row in your readings.) Note that the time interval oscillates between 25 and 26 μs, while
the frequency oscillates between 20.0 and 19.2 kHz, i.e., 19.9±0.2 kHz, or 19.9±1% kHz. These
oscillations are an indication of the repeatability of your process, and are due to the displayed
simulation time being limited to 1 μs, while one MCU cycle takes 0.5 μs.
m) Calculate the raw frequency corresponding to the delay $0020 using the formula
f raw =
1
Hz . Notice that the raw frequency is 31.25 kHz, while the obtained
2 ⋅ DT ⋅ 0.5μs
frequency is 20 kHz. The difference is a programming overhead due to the extra cycles that are
consumed in the program between two OC events. We expect that this overhead will become
less and less significant as the delay increases, i.e. at lower frequencies.
n) Put the value $0200 in DT. Repeat the procedure above, and enter the clock cycles and simulate
time values in Table 1. Note that the effective frequency oscillated between 1.859 and 1.866
kHz, i.e., 1.8625±0.0035 kHz, or 1.8625±0.2%. The repeatability of our simulation has greatly
improved. Calculate the raw frequency corresponding to the delay $0200 using the formula
f raw =
1
Hz . Notice that the raw frequency is 2.0 kHz, while the effective frequency
2 ⋅ DT ⋅ 0.5μs
is 1.8625 kHz. The difference has reduced considerably, (-6.9% error). This confirms the
hypothesis that the programming overhead due to the extra cycles that are consumed in the
program between two OC events is less significant at higher DT values, i.e. at lower frequencies.
o) Repeat for DT=$2000. For this long delay, the frequency scale is switched from kHz to just Hz. In
just a couple of cycles, you note stable behavior, and perfect frequency accuracy. This is due to
the desired frequency (122 Hz) being much lower than the MCU clock frequency (2 MHz).
For more details of how these errors are generated in the MCU, please see Appendix 4.
Dr. Victor Giurgiutiu
Page 228
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
Table 1
DT
Raw f State
hex
kHz
0020
31.25 L
H
L
H
L
H
L
H
L
H
L
H
kHz
0200
2.0 L
H
L
H
L
H
L
H
L
H
L
H
2000
Hz
122 L
H
L
H
Dr. Victor Giurgiutiu
Clock cycles
T_1
T_2
2
62
62
113
113
164
164
215
215
266
266
317
317
368
368
419
419
470
470
521
521
572
572
623
ΔT
60
51
51
51
51
51
51
51
51
51
51
51
Time, μs
t_1
t_2
1.0
31.0
31.0
56.5
56.5
82.0
82.0
107.5
107.5
133.0
133.0
158.5
158.5
184.0
184.0
209.5
209.5
235.0
235.0
260.5
260.5
286.0
286.0
311.5
Δt
537
537
537
537
537
537
537
537
537
537
537
537
0.0
269.5
538.0
806.5
1075.0
1343.5
1612.0
1880.5
2149.0
2417.5
2686.0
2954.5
269.5
538.0
806.5
1075.0
1343.5
1612.0
1880.5
2149.0
2417.5
2686.0
2954.5
3223.0
270
269
269
269
269
269
269
269
269
269
269
269
19.6
19.6
19.6
19.6
19.6
19.6
19.6
19.6
19.6
19.6
19.6
kHz
1.855
1.862
1.862
1.862
1.862
1.862
1.862
1.862
1.862
1.862
1.862
1.862
2
8216 8214
8216 16430 8214
16430 24644 8214
24644 32858 8214
0.0
4108.0
8215.0
12322.0
4108.0
8215.0
12322.0
16429.0
4108
4107
4107
4107
Hz
122
122
122
122
2
539
1076
1613
2150
2687
3224
3761
4298
4835
5372
5909
539
1076
1613
2150
2687
3224
3761
4298
4835
5372
5909
6446
Page 229
26
26
26
26
26
26
26
26
26
26
26
f=1/2Δt
kHz
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
GENERATING A DESIRED FREQUENCY
We will now practice to obtain a desired frequency (Table 2). We will start with a low frequency, e.g.,
100 Hz, since we have noticed that our square wave generation behaves much better at low frequencies.
Then, we will increase the desired frequency, until a practical limit is obtained.
a) Examine the row 100 Hz in Table 2. Notice that the corresponding half-period is 5000 μs. Hence,
a
raw
estimation
of
the
delay
can
be
calculated
with
the
formula
delay = half-period/0.5, and then converted to hex. The result is entered as
Raw delay in Table 2.
b) Enter the DT = $2710 into the THRSim11, reset, and run. Note that the time of the breakpoint
stop is 5012 μs. Run further, and note the second time as 10024 μs. These values are entered in
Table 2. The resulting half-wave duration is 5012 μs, which corresponds to 99.8 Hz, i.e. a -0.2%
error. We consider this good enough and select to stop here.
c) Try to generate 200 Hz. According to Table 2, the corresponding half-period is
2500 μs, and the raw delay is $1388. Since we know that the MCU adds some extra cycles of its
own, we select to round down the raw delay to the value $1380. Enter this value in the
THRSim11, reset, and run. Record the times after first and second loop. These times are
entered in Table 2 as 2510 μs and 5020 μs, respectively. The corresponding frequency is 199.2
kHz, i.e., -0.4% in error. We improve on this error by making a minor adjustment to the DT from
$1380 to $1370. The value $1370 gives us the desired frequency of 200 Hz exactly.
d) Try to generate 500 Hz. According to Table 2, the corresponding half-period is
1000 μs, and the raw delay is $07D0. Enter this value in the THRSim11, reset, and run. Record
the times after first and second loop, and enter them in Table 2 as
1012 μs and 2023 μs, respectively. The corresponding frequency is 495 kHz, i.e.,
-1.1% in error. We improve on this error by making a minor adjustment to the DT, from $07d0 to
$07c0. The value $07c0 gives us the frequency 499 Hz, which is only –0.3% in error. We select
to stop here.
e) Try to generate 1000 Hz and 2000 Hz. Follow Table 2, for the values of the corresponding halfperiod, raw delay, and actual DT iterations. Notice how accuracy is being improved by small
adjustments in second hex digit of the DT.
f)
Try to generate 5000 Hz. According to Table 2, the corresponding half-period is
100 μs, and the raw delay is $00C8. This is very small delay, and we expect some difficulties!
Enter this value in the THRSim11, reset, and run. Record the times after first and second loop,
and enter them in Table 2 as 112 μs and 223 μs, respectively. The corresponding frequency is
4505 kHz, i.e., -9.9% in error. We try to improve on this error by making minor adjustments to the
DT, from $00c8 to $00c0, and then to $00b8, $00b0, $00b4. However, the accuracy cannot be
reduced below 2%. This indicates that we have reached a limit in our capability to fine-tune the
frequency. This limit is due to the low value of the desired DT. We select to stop here, and
conclude that 5000 Hz (5 kHz) is a practical limit in the square-wave frequency that can be
generated with the MCU within 2% accuracy.
For more details of how these errors are generated in the MCU, please see Appendix 4.
Dr. Victor Giurgiutiu
Page 230
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
Table 2
Desired f Half-period Raw Delay
μs
Hz
hex
100
5000
2710
200
2500
1388
500
1000
07D0
1000
500
03E8
2000
250
01F4
5000
100
00C8
DT
hex
2710
1380
1370
07d0
07c0
03e0
03d0
01f0
01e0
00c8
00c0
00b8
00b0
00b4
t_1
5012
2510
2502
1012
1007
508
503
260
256
112
112
108
103
103
Time, μs
t_2
10024
5020
5002
2023
2010
1015
1002
520
506
223
218
210
200
205
Δt
5012
2510
2500
1011
1003
507
499
260
250
111
106
102
97
102
f=1/Dt
Hz
99.8
199.2
200.0
495
499
986
1002
1923
2000
4505
4717
4902
5155
4902
error %
-0.2%
-0.4%
0.0%
-1.1%
-0.3%
-1.4%
0.2%
-3.8%
0.0%
-9.9%
-5.7%
-2.0%
3.1%
-2.0%
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of MCU Timer function as an Output Compare (OC) device
•
The setting of OMx and OLx bits to select a desired OC event (in this example, we set OM3=0,
OL3=1, to generate a toggle on the OC3 pin)
•
The detection of the TOCx match with TNCT and the corresponding OC action
•
The correlation between delay, DT, with actual frequency of the square wave.
•
The accuracy with which frequency can be adjusted
•
The determination of low and high bounds on the frequencies that can be generated with the
MCU
Dr. Victor Giurgiutiu
Page 231
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example OUTPUT COMPARE TIMER FUNCTION
(This page is intentionally left blank)
Dr. Victor Giurgiutiu
Page 232
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
EXAMPLE RPM_1
OBJECTIVE
This example has the following objectives:
• Review the use of MCU Timer function as an Input Capture (IC) device
• Review the use of the free running clock, TCNT, and it overflow flag, TOF
• Review the use of a input capture clock, TIC1, and its event flag, IC1F
• Demonstrated how the selection of signal transition to be captured is made (here falling edge,
EDG1B) and that the MCU is only sensitive to that particular transition.
• Introduce the use of soft masks (here, IC1_MSK, TOF_MSK).
• Introduce the concept of layered flowcharting of a program: big-picture with generic descriptions;
detailed flowcharts for particular sections of the program.
PROGRAM EX_RPM_1
This program EX_RPM_1 captures the times T1 and T2 required in the tachometer RPM experiment
(Figure 1). In this experiment, a disk with an aperture (hole) drilled into it is attached to the shaft of a DC
motor. The aperture in the disk spins through an infrared emitter-detector sensor. The emitter-detector
sensor sends a High (5V) signal when the aperture in the disk allows the beam of light to pass through.
The output of the emitter-detector sensor is attached to the input capture pin IC1 on Port A. The speed of
the motor is controlled by a potentiometer electronic circuit. The potentiometer is a variable resistor. By
turning the knob of the potentiometer, the speed of the DC motor is varied. T1 is the first time when a
falling edge transition is encountered on pin IC1, while T2 is the second time when a falling edge
transition is encountered on the same pin IC1. This corresponds to the time between two consecutive
passages trough the emitter-detector sensor of the hole in the rotating disk. The difference between T2
and T1, plus the time taken by the overflows, will represent the period of rotation of the disk. Hence,
using EX_RPM_2, one can calculate the rotation speed.
MOSFET
DC
Emitter/Detector
7-Segment Display
Port B
Connection
Lamp Test
555 Timer
Speed-Controlling
Potentiometer
Figure 1 DC Motor tachometer experiment to which the present software example is relevant.
Dr. Victor Giurgiutiu
Page 233
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
FLOWCHART AND CODE
The program flowchart is show below. Two flowchart levels are presented: the big-picture and the details.
The big-picture is used to understand the overall architecture of the program. The details are used to
explain some of the blocks. (Details are given only for those blocks which are somehow new, and have
not been used in previous programs.) This flowchart was use to generate the code file Ex_RPM_1.asm
using the standard asm template.
Big-picture Flowchart
Define variables
Detailed Flowcharts
Define variables:
• Overflow counter, NOF (1 byte)
st
• 1 capture, T1 (2 bytes)
nd
• 2 capture, T2 (2 bytes)
• IC1_MSK=%00000100
• TOF_MSK=%10000000
START • Initialize Y= REGBAS
• Initialize IC1 for falling:
set EDG1B in TCTL2
LABEL0 Reset IC1F
LABEL1
LABEL1 Check first IC1 capture
Check IC1F
N
Y
Reset IC1F
Load and store TIC1 in T1
Clear TOF
Zero overflow counter NOF
LABEL2
Check TOF
N
Y
LABEL2 Check TOF
If TOF is set, increment NOF
and reset TOF
Check second IC1 capture
• Increment NOF
• Reset TOF
LABEL3
Check IC1F
Load and store TIC1 in T2
N
SWI
Dr. Victor Giurgiutiu
Page 234
Y
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, timer registers, port A pins,
memory list. Open and assemble Ex_RPM_1.asm. Set breakpoints at
• $c016 (after first input capture on IC1)
•
$c030 (when an overflow happens)
•
$c03f (after second input capture on IC1)
•
SWI.
Reset registers and memory. Set standard labels (Label/Set Standard Labels). Set display of TCTL2,
TFLG1, TFLG2 to binary. Arrange windows for maximum benefit: Press the RESET button. Your screen
should look like this:
Dr. Victor Giurgiutiu
Page 235
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
a) Toggle pin IC1 to 1. Start the program. The program stays in a loop on LABEL 1 waiting for a
falling edge transition on pin IC1.
b) Toggle pin IC1 to 0. The program stops at the first breakpoint. Notice that IC1F is set in TFLG1
(bit 2). Also notice the value captured in TIC1. This value should be very close to the value in
TCNT (It is not identical, since the program executed a few operations before stopping at the
breakpoint, hence TCNT is slightly more than TIC1.) Your screen looks like this:
Dr. Victor Giurgiutiu
Page 236
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
c) Step through your program until the program counter is on LABEL2. Note that IC1F is cleared.
Then, TIC1 is loaded into D and then stored in T1. Further, TOF is cleared. Finally, NOF is
zeroed. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 237
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
d) Run. The program enters the second loop on LABEL2. You will notice the program jumping over
a section of code to LABEL3 and then back to LABEL2. The section of code that is bypassed
refers to the situation when an overflow takes place. Let the program run until the timer counter,
TCNT, goes over. At this point, the program should stop at the breakpoint $c030. Your screen
looks like this:
Dr. Victor Giurgiutiu
Page 238
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
e) Step through your program up to LABEL3. Notice the overflow counter, NOF, being incremented,
and the overflow flag, TOF, being reset in TFLG2 (bit 7). Your screen looks like this:
Dr. Victor Giurgiutiu
Page 239
8/19/2008
EMCH 367
f)
Fundamentals of Microcontrollers
Example RPM 1
Let the program run. Toggle pin IC1 back to 1. Nothing should happen since only falling edges
should be detected. Toggle IC1 to 0 again. The program should stop at the second breakpoint.
The value of TIC1 should be updated to a new value. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 240
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
g) Step through your program. The new value of TIC1 is loaded and then stored in T2. The program
branches back to the beginning (LABEL0). Your screen looks like this:
After returning to the beginning, the program zeros the NOF counter and goes through the process again.
h) Let the program run again and repeat the steps above until your are satisfied that you
understand the process well.
i)
Run again but, after each breakpoint, simply hit the run button and let the program run until the
next breakpoint. Make sure you understand how the generation of a falling signal on pin IC1 (by
you toggling from 1 to 0) generates an input capture.
j)
Make sure to run the program long enough such that at least one overflow takes place. Observe
how the overflow counter is incremented and the overflow flag is reset.
Dr. Victor Giurgiutiu
Page 241
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 1
k) Synchronize your toggling of pin IC1, such that T1 will be just after an overflow and T2 is several
cycles later, i.e., T1 < T2. In this situation, T1 and T2 are on the same side of the timer overflow
event and the overflow counter, NOF, should be zero. Write down these values in Table 1, Case
1.
l)
Synchronize your toggling of pin IC1, such that T1 will be just before an overflow, while T2 will
happen just after the overflow. In this case, the value of T2 will be less than the value of T1, i.e.,
T2 < T1. Since T1 and T2 are on different sides of the timer overflow event, the overflow counter
should register NOF = 1. Write down the T1 and T2 values in Table 1, Case 2.
Table 1
NOF
Case 1:
Case 2:
T1 <T2 and on the same
side of the timer overflow
event
T2 < T1, but on opposite
sides of the timer overflow
event
T1
T2
$
$
$
$
WHAT YOU HAVE LEARNED
In this example, you have learned:
• Review the use of MCU Timer function as an Input Capture (IC) device
• Review the use of the free running clock, TCNT, and it overflow flag, TOF
• Review the use of a input capture clock, TIC1, and its event flag, IC1F
• Demonstrated how the selection of signal transition to be captured is made (here rising edge,
EDG1B) and that the MCU is only sensitive to that particular transition.
• Introduce the use of soft masks (here, IC1_MSK, TOF_MSK).
• Introduce the concept of layered flowcharting of a program: big-picture with generic descriptions;
detailed flowcharts for particular sections of the program.
Dr. Victor Giurgiutiu
Page 242
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
EXAMPLE RPM_2
OBJECTIVE
This example has the following objectives:
• Review the used of two time captures to calculate the time duration of an event
• Illustrate the use of scaling factors (100s) to deal with numbers that are larger than the
microcontroller word length
• Illustrate the handling of overflow counts, with special attention to the situation when the two
time captures are on one side and another of a timer overflow (time-change line)
• Introduce the method of calculating multiplication through repeated additions and decrementation
of a counter
• Introduce the use of a conversion subroutine to convert from hex to BCD
• Illustrate rotation speed calculation from rotation period.
• Illustrate the use of scaling factors (100s) to present the result on a display with limited number of
digits.
PROGRAM EX_RPM_2
This program calculates the rotation speed N_100 in 100s rpm and converts it to BCD format.
• The program assumes that the times T1 and T2 (in cycles), as well as the number of overflows,
NOF, have been separately captured and are in memory.
•
To preserve sign information during computation, the program works in hundreds of cycles.
Hence, the variables T1_100 and T2_100 are calculated by dividing T1 and T2 by decimal 100.
•
Then, the program calculates the time taken by the overflows, TOVFL. This is performed by
repeated addition of the duration between 2 overflows, $10000/100, and decrementation of NOF
(Note that the duration between two overflows was also divide by decimal 100, since the program
works in hundreds of cycles.)
•
The total time, T_100, is calculated by adding T2_100+TOVFL and then subtracting T1_100.
•
The rotation speed N_100_HEX, is calculated by dividing
2000000*60/100/100 by the total time, T_100. The result is in hex.
•
Finally, the subroutine HEX_BCD is invoked to obtain N_100_BCD, i.e., the rotation speed in
BCD format. Note that the subroutine is stored separately in the used root of the directory of your
floppy disk and is included at assembly time using the directive #INCLUDE
'A:\HEX_BCD.ASM'
the
decimal
number
To run this example, you have to enter some arbitrary values of T1, T2 and NOF in the appropriate
memory locations. Two numerical examples are given next:
Example 1: T2>T1
Data:
NOF=1, T1=$0006, T2=$110c
Results:
T1_100=$0000, T2_100=$002b, TOVFL=$028f, T_100=$02ba, N_100_HEX=$0011,
N_100_BCD=17
The rotation speed is 1700 rpm.
Example 2: T2<T1
This example gives the same time duration as Example1, but the individual times were shifted to straddle
the time-change line.
Dr. Victor Giurgiutiu
Page 243
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
Data:
Results:
NOF=2, T1=$fffd, T2=$1103
T1_100=$028f, T2_100=$002b, TOVFL=$051e, T_100=$02ba, N_100_HEX=$0011,
N_100_BCD=17
The rotation speed is 1700 rpm.
FLOWCHART AND CODE
The program flowchart is show below. Two flowchart levels are presented: the big-picture and the details.
The big-picture is used to understand the overall architecture of the program. The details are used to
explain some of the blocks. (Details are given only for those blocks which are somehow new, and have
not been used in previous programs.) This flowchart was use to generate the code file Ex_RPM_2.asm
using the standard asm template.
Big-picture Flowchart
Detailed Flowcharts
Define variables
START • Divide T1 by 100 and store in T1_100
• Divide T2 by 100 and store in T2_100
•
•
•
•
•
•
•
•
Overflow counter, NOF1 (1 byte)
st
1 capture, T1 (2 bytes)
nd
2 capture, T2 (2 bytes)
T1_100=T1/100 (2 bytes)
T2_100=T2/100 (2 bytes)
T_100=(total time)/100 (2 bytes)
N_100_HEX=N in 100 rpm (hex) (2 bytes)
N_100_BCD=N in 100 rpm (BCD) (1 byte)
•
•
•
•
•
•
Load T1 in accD
Load 100 in X
IDIV
Load T2 in accD
Load 100 in X
IDIV
Load $0000 in accD
Store accD to TOVFL
NOF=0?
Y
Use repeated addition to
calculate TOVFL (time taken by
overflows, in 100s of cycles)
N
LABEL5 • Load TOVFL in accD
•
•
•
•
T_100=TOVFL+T2_100-T1_100
LABEL6
N_100_HEX=2000000*60/100/100/T_100
Convert N_100_HEX to N_100_BCD
Add ($10000)/100
Store accD into TOVFL
Decrement NOF
Branch back if NOF>0
• Load lower part of N_100_HEX in accA
• JSR HEX_BCD
• STAA N_100_BCD
SWI
Please refer to the appendix for the explanation of sub routine HEX_BCD.
Dr. Victor Giurgiutiu
Page 244
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers AND memory list. Open and
assemble Ex_RPM_2.asm. Set breakpoint at SWI. Reset registers and memory. Set standard labels
(Label/Set Standard Labels). Arrange windows for maximum benefit: Press the RESET button. Your
screen should look like this:
EXAMPLE 1
Recall data from Example 1 above: NOF=1, T1=$0006, T2=$110c. Use your pocket hex calculator to
estimate the result to be expected at the end of the program:
T_100 = (NOF*$10000+T2-T1)/100 = ($01*$10000+$110c-$0006)/$64 = $02ba
(1)
N_100_HEX = (2000000*60/100/100/T_100) = $2ee0/$2ba = $0011
(2)
N_100_BCD = 17
(3)
Because the program needs to work with a finite word size, the variables in Equation (1) are first divided
by decimal100, such that Equation (1) is actually treated as:
T_100 = NOF*($10000)/100+T2/100-T1/100
The terms of equation (1) are calculated separately, as TOVFL, T1_100, T2_100. Hence, the following
operations are performed:
T1_100 = T1/100 = $0006/$64 = $0000
(1a)
T2_100 = T2/100 = $110c/$64 = $002b
(1b)
Dr. Victor Giurgiutiu
Page 245
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
TOVFL = NOF*($10000)/100 = $01*$028f = $028f
(1c)
T_100= TOVFL + T2_100 – T1_100 = $028f + $002b - $0000 = $02ba
(1d)
Note that the result of Equation (1d) is the same as that of equation (1). Hence, Equations (2) and (3) still
stand.
These arithmetic operations are illustrated, step-by-step next.
a) Put in memory the data from Example 1 above: NOF=1, T1=$0006, T2=$110c.Your memory list
should look like Table 1. Note the number of bytes (memory locations) that these variables take:
NOF=1 byte, T1=2 bytes, T2=2 bytes (highlighted).
Table 1
Memory list after Example 1 data has been entered
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$01
$00
$06
$11
$0c
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
b) Step through the section of your program that divides the variables T1 and T2 by decimal 100 to
obtain T1_100 and T2_100. Use the hex pocket calculator to verify these results. The memory
list should look like Table 2. Note that T1_100 and T2_100 also take 2 bytes each.
Table 2
Memory list after the calculation of T1_100 and T2_100
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$01
$00
$06
$11
$0c
$00
$00
$00
$2b
$ff
$ff
$ff
$ff
$ff
$ff
$ff
c) Step through the section of your program that calculates TOVFL, the time taken by overflows,
expressed in 100s of cycles. Note that, initially, TOVFL=$0000 is stored. Then, if NOF≠0, the
Dr. Victor Giurgiutiu
Page 246
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
variable TOVFL is increased by ($10000)/100, while the variable NOF is decremented by one.
The process is repeated as long as NOF≥0. At the end of the process, the memory list should
look like Table 3. Note that TOVFL also takes 2 bytes. Also not that, at the end of this process,
NOF = 0.
Table 3
Memory list after the calculation of TOVFL
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$00
$00
$06
$11
$0c
$00
$00
$00
$2b
$02
$8f
$ff
$ff
$ff
$ff
$ff
d) Step through the section of your program that calculates T_100, the total time in 100s of cycles.
Note how the formula
T_100= TOVFL + T2_100 – T1_100 = $028f + $002b - $0000 = $02ba
(1d)
is applied in two steps, first the addition, then the subtraction. At the end of the process, the
memory list should look like Table 4.
Table 4 Memory list after the calculation of T_100
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
Dr. Victor Giurgiutiu
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$01
$00
$06
$11
$0c
$00
$00
$00
$2b
$02
$8f
$02
$ba
$ff
$ff
$ff
Page 247
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
e) Step through the section of your program that calculates the variable N_100_HEX, the hex
speed of rotation, in 100s of rpm. Note that the ‘magic’ number 2000000*60/100/100 is loaded
into accD as $2ee0 and then divided by T_100. At the end of the process, the memory list should
look like Table 5.
Table 5
Memory list after the calculation of N_100_HEX
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
f)
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$01
$00
$06
$11
$0c
$00
$00
$00
$2b
$02
$8f
$02
$ba
$00
$11
$ff
Step through the last section of your program and calculate the variable N_100_BCD, which
represent the decimal expression of the hex speed of rotation, in 100s of rpm. The conversion
from hex to BCD is achieved by invoking the subroutine HEX-BCD. At the end of the process,
the memory list should look like Table 6.
Table 6
Memory list after the calculation of N_100_HEX
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
Dr. Victor Giurgiutiu
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$01
$00
$06
$11
$0c
$00
$00
$00
$2b
$02
$8f
$02
$ba
$00
$11
$17
Page 248
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
EXAMPLE 2
Recall data from Example 2 as listed at the beginning of this document: NOF=2, T1=$fffd, T2=$1103.
Note that this data represents the same time interval as in Example 1, only that a backwards time shift of
9 cycles took place. For this reason, the times T1 and T2 are on different sides of the time-change line.
T1 happens before the time change, T2 happens after. Therefore, between T1 and T2, the time counter
TCNT goes through a timer overflow. Hence, the overflow counter has the value NOF=2, instead of 1 as
in Example 1.
Use your pocket hex calculator to estimate the result to be expected at the end of the program:
T_100 = (NOF*$10000+T2-T1)/100 = ($02*$10000+$1103-$fffd)/$64 = $02ba
(1)
N_100_HEX = (2000000*60/100/100/T_100) = $2ee0/$2ba = $0011
(2)
N_100_BCD = 17
(3)
Because the program needs to work with a finite word size, the variables in Equation (1) are first divided
by decimal100, such that Equation (1) is actually treated as:
T_100 = NOF*($10000)/100+T2/100-T1/100
The terms of equation (1) are calculated separately, as TOVFL, T1_100, T2_100. Hence, the following
operations are performed:
T1_100 = T1/100 = $fffd/$64 = $028f
(1a)
T2_100 = T2/100 = $1103/$64 = $002b
(1b)
TOVFL = NOF*($10000)/100 = $02*$028f = $051e
(1c)
T_100= TOVFL + T2_100 – T1_100 = $051e + $002b - $028f = $02ba
(1d)
Note that the result of Equation (1d) is the same as that of equation (1). Hence, Equations (2) and (3) still
stand.
These arithmetic operations are illustrated, step-by-step, next.
a) Put in memory the data from Example 1 above: NOF=2, T1=$fffd, T2=$1103. Your memory list
should look like Table 7. Note the number of bytes (memory locations) that these variables take:
NOF=1 byte, T1=2 bytes, T2=2 bytes (highlighted).
Table 7
Memory list after Example 2 data has been entered
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
Dr. Victor Giurgiutiu
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$02
$ff
$fd
$11
$03
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
Page 249
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
b) Step through the section of your program that divides the variables T1 and T2 by decimal 100 to
obtain T1_100 and T2_100. Use the hex pocket calculator to verify these results. The memory
list should look like Table 8. Note that T1_100 and T2_100 also take 2 bytes each.
Table 8
Memory list after the calculation of T1_100 and T2_100
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$02
$ff
$fd
$11
$03
$02
$8f
$00
$2b
$ff
$ff
$ff
$ff
$ff
$ff
$ff
c) Step through the section of your program that calculates TOVFL, the time taken by overflows,
expressed in 100s of cycles. Note that, initially, TOVFL=$0000 is stored. Then, if NOF≠0, the
variable TOVFL is increased by ($10000)/100, while the variable NOF is decremented by one.
The process is repeated as long as NOF≥0. At the end of the process, the memory list should
look like Table 9. Note that TOVFL also takes 2 bytes. Also not that, at the end of this process,
NOF = 0.
Table 9
Memory list after the calculation of TOVFL
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$02
$ff
$fd
$11
$03
$02
$8f
$00
$2b
$05
$1e
$ff
$ff
$ff
$ff
$ff
d) Step through the section of your program that calculates T_100, the total time in 100s of cycles.
Note how the formula
T_100= TOVFL + T2_100 – T1_100 = $051e + $002b - $028f = $02ba
(1d)
is applied in two steps, first the addition, then the subtraction. At the end of the process, the
Dr. Victor Giurgiutiu
Page 250
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example RPM 2
value T_100=$02ba is obtained, which is the same as in Example 1. The memory list should
look like Table 10.
Table 10 Memory list after the calculation of T_100
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$02
$ff
$fd
$11
$03
$02
$8f
$00
$2b
$05
$1e
$02
$ba
$ff
$ff
$ff
e) Step through the section of your program that calculates the variable N_100_HEX, the hex
speed of rotation, in 100s of rpm. Note that the ‘magic’ number 2000000*60/100/100 is loaded
into accD as $2ee0 and then divided by T_100. At the end of the process, the value
N_100_HEX=$0011 is obtained, which is the same as in Example 1. The memory list should
look like Table 11.
Table 11 Memory list after the calculation of N_100_HEX
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
f)
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$01
$00
$06
$11
$0c
$00
$00
$00
$2b
$02
$8f
$02
$ba
$00
$11
$ff
Step through the last section of your program and calculate the variable N_100_BCD, which
represent the decimal expression of the hex speed of rotation, in 100s of rpm. The conversion
from hex to BCD is achieved by invoking the subroutine HEX-BCD. At the end of the process,
the value N_100_BCD=17 is obtained, which is the same as in Example 1. The memory list
should look like Table 12.
Table 12 Memory list after the calculation of N_100_HEX
Dr. Victor Giurgiutiu
Page 251
8/19/2008
EMCH 367
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
Fundamentals of Microcontrollers
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
Example RPM 2
$01
$00
$06
$11
$0c
$00
$00
$00
$2b
$02
$8f
$02
$ba
$00
$11
$17
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of two time captures to calculate the time duration of an event
• The use of scaling factors to deal with numbers that are larger than the microcontroller word
length. In the program, the scale factor decimal 100 was used, such that the cycle counts T1 and
T2 were converted to T1_100 and T2_100, which are measured in 100s of cycles.
• The handling of overflow-counts, with special attention to the situation when the two time
captures are on one side and another of a timer overflow (time-change line). In the first numerical
example, T1 and T2 were on the same side of the time-change line. In the second numerical
example, T1 and T2 were on opposite sides of the time-change line (T1 before, T2 after). As a
result, the number of overflows recorded in the second case was greater by 1 than in the first case.
However, with proper handling, the final result of the computation was the same.
• The calculation of multiplication through repeated additions and decrementation of a counter. The
time taken by overflows, TOVFL, was calculated through repeated addition of the length between
two consecutive overflows. Every time an addition was done, the overflow counter, NOF, was
decremented by one. The loop was exited when NOF=0. This method was necessary since the
multiplication opcode MUL available in set does not contain a .
• Introduce the use of a conversion subroutine to convert from hex to BCD
• Illustrate rotation speed calculation from rotation period.
• Illustrate the use of scaling factors (100s) to present the result on a display with limited number of
digits.
Dr. Victor Giurgiutiu
Page 252
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
EXAMPLE STEP
OBJECTIVE
This example has the following objectives:
• Review the use and control of stepper motors.
• Discuss the stepper motor energizing patterns, 1- and 2-phase energizing types, full- and halfstep motion.
• Introduce the concept of creating quasi-continuous motion through a sequence of steps
• Introduce the concept of sequential accessing a finite set of stored patterns through index
addressing with a continuously updating pointer.
• Illustrate a method to ‘load’ a single-precision (2-hex) variable into a double precision (4-hex)
register.
• Introduce the concept of automatic incrementation/decrementation of the addressing pointer with
a programmable step size
• Discuss the reset actions to be taken when the pointer hits the ‘ceiling’ or ‘floor’.
Controller board
Stepper motor
8-pin input
connector
Figure 1 Stepper motor and its controller board. Control signals to the controller board are sent
through the 8-pin input connector.
PROGRAM EX_STEP
This program is to be used for stepper motor control (Figure 1). A stepper motor is controlled by
sending a binary pattern to its controller board. Eight distinct binary patterns are recognized by the
stepper motor controller board in your lab. They are given in Table 1 as sequences S0 – S7. The stepper
motor has four distinct coils, and a 1 in the energizing pattern signifies that the corresponding coil is
Dr. Victor Giurgiutiu
Page 253
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
energized. Note that in the even sequences (S0, S2, S4, S6) only one bit in the energizing pattern is set.
This indicates that only one out of the four stepper-motor coils (1 phase) is energized. On the other hand,
in the odd sequences (S1, S3, S5, S7), two bit are set, i.e., two coils (2 phases) are energized. The
sequences with two coils energized are labeled full step, while those with only one coil energized are
labeled half step.
Table 1
Stepper motor energizing patterns and their 2-hex equivalent value
Sequence
Energizing
pattern
S0
S1
S2
S3
S4
S5
S6
S7
1000
1001
0001
0101
0100
0110
0010
1010
8-bit
2-hex
equivalence
$08
$09
$01
$05
$04
$06
$02
$0A
Phase
energizing
type
1 phase
2 phase
1 phase
2 phase
1 phase
2 phase
1 phase
2 phase
Step type
Half step
Full step
Half step
Full step
Half step
Full step
Half step
Full step
When these patterns are hit in increasing order, one after the other, the motion is called ‘half speed
forward’. If only the odd sequences are hit, i.e., every second pattern is hit, the motion is ‘full speed
forward’. If the patterns are hit in decreasing order, the motion is, respectively, ‘half-speed backward’
and ‘full speed backward’ (Table 2).
Table 2
Stepper motor speed definitions
Full speed forward
Half speed forward
Half-speed backward
Full speed backward
Step
+2
+1
-1
-2
Start
Even pattern
Anywhere
Anywhere
Even pattern
To control a stepper motor, a parallel port is used to send 8-bit pattern to the stepper-motor control board.
Note the pin assignment:
MSB
LSB
I1
I2
I3
I4
N/A
N/A
N/A
N/A
(white)
(green)
(gray)
(yellow)
The program illustrates the sequentially access to memory locations using a memory pointer:
• The memory locations to be accessed have the variable names S0, S1, S2, S3, S4, S5, S6, S7, and
correspond to addresses $0000 through $0007.
•
The memory pointer has the variable name POINTER and is stored at address $0009
•
The memory pointer is used in index Y addressing. The memory pointer is entered in index
register Y, and the offset is taken as zero ($00). Thus, through Y, the pointer controls directly the
address to be accessed.
Dr. Victor Giurgiutiu
Page 254
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
•
The program automatically steps through the set of eight sequences S0—S7 and generates the
next pointer value, by adding the variable STEP. As shown in Table 2, for stepper motor control,
the values of STEP are +/-1 and +/-2. The positive values correspond to forward motion. The
negative values correspond to backward motion. Two’s complement 8-bit signed convention is
used
to
generate
the
negative
values
(-1=$ff, -2=$fe).
•
The program takes care not to send the pointer outside the eight-sequence range. Hence, when
going forward, whenever the highest sequence, S7, is hit (i.e., we hit the ceiling) the programs
resets to pointer to S0 (i.e., to the floor). When going backward, whenever the floor is hit, the
program resets the pointer to the ceiling.
In the initialization phase, the program enters the values of S0 – S7 given in Table 1 in the appropriate
memory locations. Then it sets STEP=$00, and POINTER=$00
When running the program, you have to enter into memory location STEP one of the following options:
STEP=$01 or $02, or $ff or $fe.
FLOWCHART AND CODE
The program flowchart is show below. Two flowchart levels are presented: the big-picture and the
details. The big-picture is used to understand the overall architecture of the program. The details are
used to explain some of the blocks. (Details are given only for those blocks which are somehow new,
and have not been used in previous programs.) Note that the main program is only intended to
demonstrate the use of the subroutine STEP_SR. For this reason, the main program is a mere call to the
STEP_SR subroutine. The essential code for this program is shown to the right of the flowchart. The
essential code was incorporated into the standard template asm to generate the code file Ex_Step.asm.
Dr. Victor Giurgiutiu
Page 255
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Big-picture Flowchart
START
Define variables
•
•
•
•
•
•
•
•
•
•
S0
S1
S2
S3
S4
S5
S6
S7
STEP
POINTER
Initialize
•
•
•
•
•
•
•
•
•
•
•
X=REGBAS
S0=$08
S1=$09
S2=$01
S3=$05
S4=$04
S5=$06
S6=$02
S7=$0a
STEP=$00
POINTER=$00
Call S/R STEP_SR
LABEL0
Flowchart Details
1 byte
1 byte
1 byte
1 byte
1 byte
1 byte
1 byte
1 byte
1 byte
1 byte
BRA
SWI
STEP_SR • Load POINTER to accB
• Add STEP
Y
Below ceiling?
POINTER ≤ 7?
N
Reset to floor
POINTER=0
LABEL3
Y
Above floor?
0 ≥ POINTER?
N
Reset to ceiling
POINTER=7
LABEL4
Store new value of POINTER
Put POINTER into Y
• Load new sequence code into
accA using Y
• Send sequeuce code from
accA to Port B
• Load $0000 into Y
• Add accB to Y (acc B
contains the value of
POINTER)
Example STEP
Code
* Define program variables
ORG
DATA
S0
RMB
1
S1
RMB
1
S2
RMB
1
S3
RMB
1
S4
RMB
1
S5
RMB
1
S6
RMB
1
S7
RMB
1
STEP
RMB
1
POINTER RMB
1
*Main program
ORG
PROGRAM
START LDX
#REGBAS
LDAA
#$08
STAA
S0
LDAA
#$09
STAA
S1
LDAA
#$01
STAA
S2
LDAA
#$05
STAA
S3
LDAA
#$04
STAA
S4
LDAA
#$06
STAA
S5
LDAA
#$02
STAA
S6
LDAA
#$0A
STAA
S7
* Initialize controls
LDAA
#0
STAA
STEP
LDAA
#$00
STAA
POINTER
* Start looping
LABEL0 JSR
STEP_SR
BRA
LABEL0
SWI
* Step subroutine
STEP_SR
LDAB
POINTER
ADDB
STEP
CMPB
#7
BLE
LABEL3
LDAB
#0
LABEL3 CMPB
#0
BGE
LABEL4
LDAB
#7
LABEL4 STAB
POINTER
LDY
#$0000
ABY
LDAA
$00,Y
STAA
PORTB,X
RTS
RTS
Dr. Victor Giurgiutiu
Page 256
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers AND memory list. Open and
assemble Ex_Step.asm. Set breakpoint at SWI. Reset registers. Press the RESET button. Set standard
labels (Label/Set Standard Labels). Set breakpoint at LABEL0 and at SWI. Arrange windows for
maximum benefit: Your screen should look like this:
Dr. Victor Giurgiutiu
Page 257
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
Let the program run to the first breakpoint. Initialization of the memory variables is achieved. Scroll the
screen to have the LABEL0 line at the top. Rearrange the windows slightly to cover only essential code.
Your screen should look like this:
Dr. Victor Giurgiutiu
Page 258
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
CASE ‘SLOW-FORWARD’ (STEP=$01)
a) Put STEP=$01. This should make the program go forward in increments of one (half-speed
forward). Your screen should look like this:
Dr. Victor Giurgiutiu
Page 259
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
b) Step through the program. Notice that the program goes directly to the subroutine STEP_SR.
The following events happen:
•
The current value of the variable POINTER (POINTER=$00) is loaded into accB.
•
The value of variable STEP (STEP=$01) is added to accB. The result is accB = $01
•
The value in accB is compared with the ceiling (i.e., perform accB-$07). The result of the
comparison is a negative number. Hence, the condition code bit N is set (observe N=1 on
the simulator status bar, and bit 3 = 1 in CC register). Your screen looks like this:
Dr. Victor Giurgiutiu
Page 260
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
•
At branch BLE LABEL3, the branch condition is met (since N=1) and the program branches
to LABEL3.
•
The value of accB is now compared with the floor (i.e., perform accB-$00). The result of the
comparison is a $01. Hence, the condition code bit N is clear (observe N=0 on the simulator
status bar, and bit 3 = 0 in CC register). Your screen looks like this:
Dr. Victor Giurgiutiu
Page 261
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
•
At branch BGE LABEL4, the branch condition is met (since N=0) and the program branches
to LABEL4.
•
The value of accB is stored as the new value of POINTER (observe POINTER at memory
location $0009 having the value $01)
•
At this stage, the value of POINTER must be loaded into index register Y. To achieve this,
the value $0000 is loaded in index register Y. Then, the index register Y and the accB
(containing the current value of POINTER) are added. (This convoluted way of doing things
was needed because there is no simple way to load the single precision variable, POINTER,
into the double precision register Y.) Your screen looks like this:
Dr. Victor Giurgiutiu
Page 262
8/19/2008
EMCH 367
•
Fundamentals of Microcontrollers
Example STEP
The value of the memory where the POINTER points to is now loaded into accA. This is
achieved using index addressing with Y as the index register and $00 as the offset (i.e.,
LDAA $00,Y). In our case, POINTER=$01, hence the memory location $0001 is loaded.
This is the step S1, which has the value S1=$09. Hence, you should see the value $09 in
accA (i.e., A $09 in CPU registers). Finally, the pattern S1, which was loaded in accA, is
sent to Port B. This will make the stepper motor go to the position corresponding to pattern
S1. Your program looks like this:
c) Let your program perform another loop and observe that the POINTER and the value in Port B
have reached the next sequence pattern, S2=$01. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 263
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
d) Repeat and observe each loop until the POINTER and the value in Port B have reached the last
sequence pattern, S7=$0a. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 264
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
e) In the next loop, the program should hit the ceiling and return to the floor. Perform this loop
manually, to verify the logic. At the end of the loop, observe that the POINTER and the value in
Port B have come back to the first sequence pattern, S0=$08. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 265
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
CASE ‘FULL-FORWARD’ (STEP=$02)
Press RESET button. Run initialization. Put the value $02 into the variable STEP and $07 into
variable POINTER. Repeat the pattern of observations covered before. You will see that only the
odd patterns (S1, S3, S5, S7) are being hit. According to Table 1, these patterns correspond to 2phase energizing of the stepper motor (full steps). Satisfy yourself that you fully understand the
logic of the program and that you have fully observed how the program is generating a full-speed
forward motion.
CASE ‘HALF-BACKWARD’ (STEP=$FF)
Put the value $ff into the variable STEP and repeat the pattern of observations covered before.
You will see all the patterns (S0--S7) being hit, but in reverse order (S1, S0, S7, S6, S5, S4, S3,
S2, S1 …). Satisfy yourself that you fully understand the logic of the program and that you have
fully observed how the program is generating a half-speed backward motion.
CASE ‘FULL-BACKWARD (STEP=$FE)
Put the value $fe into the variable STEP and repeat the pattern of observations covered before.
You will see that only the odd patterns are being hit, and that they are hit in reverse order (S1, S7,
S5, S3, S1, …). Satisfy yourself that you fully understand the logic of the program and that you
have fully observed how the program is generating a full-speed backward motion.
Dr. Victor Giurgiutiu
Page 266
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use and control of stepper motors.
• The stepper motor energizing patterns, 1- and 2-phase energizing types, full- and half-step
motion. Learn the eight sequences S0—S7, the odd sequences S1, S3, S5, S7 being full steps (2phase), the even sequences S0, S2, S4, S6 being half-steps (1-phase)
• The concept of creating quasi-continuous motion through a sequence of steps.
• The concept of sequential accessing a finite set of stored patterns through index addressing with
a continuously updating pointer. The eight sequences S0—S7, were stored in memory, and the
variable POINTER was used to address them. The POINTER was loaded into index register Y,
and the memory locations containing the sequences S0—S7 were addressed using the index Y
addressing mode.
• A method to ‘load’ a single-precision (2-hex) variable into a double precision (4-hex) register.
This situation was encountered in connection with the use of variable POINTER for index Y
addressing. Since there is no direct way to store a single precision variable into a double
precision register, a convoluted way was used. The double precision register Y was first loaded
with zeros ($0000) and then added with the single precision variable POINTER. Thus, the single
precision variable POINTER ended up being effectively loaded into index register Y.
• The concept of automatic incrementation/decrementation of the addressing pointer with a
programmable step size. The variable STEP was used with values 1, 2, -1, -2. The positive
values generated forward motion at half and full speed; the negative values created backward
motion. Incrementation and decrementation was done in a loop. Whenever the incremented value
hit a value outside the permissible range (0 to 7), reset was implemented. If the ‘ceiling’ was hit
(i.e., a value greater than 7) the reset was to the floor (i.e., to 0). If the ‘floor’ was hit (i.e., less
than 0) the reset was implemented to the ceiling (i.e., to 7).
Dr. Victor Giurgiutiu
Page 267
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example STEP
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 268
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example LONG DELAY
EXAMPLE LONG DELAY
OBJECTIVE
This example has the following objectives:
• Present a subroutine that can implement a long delay between stepper motor steps
• Introduce the concept of how to achieve double precision delays (4-hex) using single precision
(2-hex) variables
PROGRAM EX_LONG_DELAY
This program illustrates the use of subroutine DLAY_SR. This subroutine performs a long delay action
using TOC1. Although the delay is in double precision (4-hex), the controlling variable, DELAY, is
simple precision. This is one of the special features of this subroutine. DELAY controls the higher 2-hex
digits. This is how this works:
• First, clear the OC1F flag, which is bit 7 in TFLG1. When doing this, we use the OR operation in
preserve the other bits in TFLG1.
•
We load DELAY in accA, which is the higher part of accD. Then, we fill accB, i.e., the lower
part of accD, with $00. If DELAY=$XX, then the value in accD is $XX00.
•
Next, add TCNT to accD and store the result in TOC1. This is the new time
•
Step in place until OC1F is set. When the number of cycles $XX00 have elapsed, you are done.
The subroutine return control to the main program.
A stepper motor is controlled by sending binary patterns (step sequences) to its controller board. Eight
distinct binary patterns (S0 – S7) are recognized by the stepper motor controller board in your lab. When
these patterns are hit in increasing order, one after the other, the motion is called ‘half speed forward’. If
only the odd sequences are hit (i.e., every second pattern), the motion is ‘full speed forward’. If the
patterns are hit in decreasing order, the motion is, respectively, ‘half-speed backward’ and ‘full speed
backward’. The corresponding step sizes are, respectively, +1, +2, -1, -2 (Table 1). Using 2’s
complement 8-bit signed numbers convention, these values correspond to the variable STEP taking hex
values $01, $02, $ff, $fe.
Table 1
Stepper motor speed definitions
Half speed forward
Full speed forward’
Half-speed backward
Full speed backward’
Step size
+1
+2
-1
-2
STEP
$01
$02
$ff
$fe
The program is intended for stepper motor control. The stepper-motor speed is controlled through the
delay inserted between steps. A short delay ensures a high speed, while a long delay produces a slow
speed. The shortest delay that can be physically accommodated by the stepper motor dynamics is 5 ms.
For a 2 MHz processor (0.5 μs/cycle), this corresponds to 10,000 ($2710) cycles. The maximum delay is,
obviously, $ffff. Since we use a single precision variable, DELAY, we need to round the numbers $2710
and $ffff to 2 significant hex numbers. We get $2800 and $ff00 (To maintain delay integrity, the first
number was rounded up, the second number was rounded down.) Hence, the single precision variable,
DELAY, can take values between $28 and $ff.
Dr. Victor Giurgiutiu
Page 269
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example LONG DELAY
FLOWCHART AND CODE
The program flowchart is show below. The essential code for this program is shown to the right of the
flowchart. The essential code was incorporated into the standard template asm to generate the code file
Ex_Long_Delay.asm. Please refer to this file for more coding details, and coding style.
Code
Flowchart
Define variables:
• DELAY
1 byte
ORG
RMB
ORG
START
LDX
JSR
SWI
DLAY_SR LDAA
ORAA
STAA
LDAA
LDAB
ADDD
STD
LABEL5 LDAA
ANDA
BEQ
RTS
DELAY
START Initialize: X=REGBAS
Jump to subroutine DELAY_SR
SWI
DLAY SR
START
• Clear OC1F
• Add DELAY to TCNT
and store in TOC1
Step in place until
OC1F is set
DATA
1
PROGRAM
#REGBAS
DLAY_SR
#%10000000
TFLG1,X
TFLG1,X
DELAY
#$00
TCNT,X
TOC1,X
TFLG1,X
#%10000000
LABEL5
RTS
EXECUTION
Open THRSim11. Close the Commands window. Open and assemble Ex_Long_Delay.asm. View CPU
registers, timer registers, memory list for variable DELAY. Arrange windows for maximum benefit.
Reset registers. Set standard labels (Label/Set Standard Labels). Press the RESET button. Set
breakpoints at SWI and RTS. Put $28 in DELAY. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 270
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example LONG DELAY
a) Step through the program. The program should initialize X=$1000, and then turn control to the
subroutine DLAY_SR.
b) Step through the subroutine. Observe how, first, the flag OC1F is reset.
c) Then note that the value of DELAY is loaded in accA (i.e., in higher part of accD), then $00 is
loaded in accB (i.e., the lower part of accD), and finally the value of TCNT is added to accD.
The result is stored in TOC1. Your screen should look like this:
Note that the value of TOC1 is close to $2800.
d) Let the program run. It should loop continuously on LABEL5 while checking for OC1F. When
TCNT goes over the value of TOC1, the flag OC1F (bit 7 in TFLG1) gets set and the code is
ready to return to the main program. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 271
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example LONG DELAY
You are done.
e) Repeat the above procedure for other values in DELAY: $30, $40, $80 and $ff. Make sure that
you understand the way this subroutine works.
WHAT YOU HAVE LEARNED
In this example, you have learned:
• A subroutine that can implement a long delay between stepper motor steps
• How to achieve double precision delays (4-hex) using single precision (2-hex) variables. The
single precision variable DELAY was used. The variable was loaded into the higher part of
double accD. The higher part of accD is accA. Hence, the variable was loaded in accA using
single precision arithmetic. The lower part of the double precision accumulator accD, which is
the single precision accumulator accB, was loaded with $00. Hence, if DELAY=$XX, at the end
of the process accD=$XX00.
Dr. Victor Giurgiutiu
Page 272
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
EXAMPLE SORT
OBJECTIVE
This example has the following objectives:
• Review the use of keystroke commands for controlling a process
• Introduce the concept of ‘multiple sort’ and its ‘sequential sort’ equivalent
PROGRAM EX_SORT
This program can be used for controlling a process through keystroke commands send from the terminal
keyboard. Once the keystroke command is received, it is echoed to the terminal monitor for confirmation.
Then, the keystroke in the command is compared with a set of command options, and action is
appropriately taken. The program recognizes five keystroke commands:
i)
Move forward
>
ii)
Move backward
<
iii) Increase speed (decrease delay)
+
iv) Decrease speed (increase delay)
v)
Stop program
S
The program use is intended for stepper motor control. A stepper motor is controlled by sending binary
patterns (step sequences) to its controller board. Eight distinct binary patterns (S0 – S7) are recognized
by the stepper motor controller board in your lab. When these patterns are hit in increasing order, one
after the other, the motion is called ‘half speed forward’. If only the odd sequences are hit (i.e., every
second pattern), the motion is ‘full speed forward’. If the patterns are hit in decreasing order, the motion
is, respectively, ‘half-speed backward’ and ‘full speed backward’. The corresponding step sizes are,
respectively, +1, +2, -1, -2 (Table 1). Using two’s complement 8-bit signed numbers convention, these
values correspond to the variable STEP taking hex values $01, $02, $ff, $fe.
Table 1
Stepper motor speed definitions
Half speed forward
Full speed forward’
Half-speed backward
Full speed backward’
Step size
+1
+2
-1
-2
STEP
$01
$02
$ff
$fe
The "half-speed" and "full-speed" commands are part of the coarse speed control. Fine speed control
can be attained by modifying the delay inserted between steps. A shorter delay ensures a higher speed,
while a longer delay produces a slower speed. The shortest delay that can be physically accommodated
by the stepper-motor dynamics is 5 ms. For a 2 MHz processor (0.5 μs/cycle), this corresponds to 10,000
($2710) cycles. The maximum delay is, obviously, $ffff. In the program, we use the single precision
variable, DELAY. When two numbers, $2710 and $ffff are rounded to 2 significant hex numbers, one
gets $2800 and $ff00 (To maintain delay integrity, the first number was rounded up, the second number
was rounded down.) Hence, the single precision variable, DELAY, can take values between $28 and $ff.
The following is the ‘big-picture’ of the program:
a) Define control variables: STEP, DELAY
b) Initialize program:
i)
Dr. Victor Giurgiutiu
Initialize X=REGBAS
Page 273
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
ii)
Initialize SCI
iii) Initialize control variables STEP=0, DELAY=$ff
c) Verify if new keystroke command has arrived. If N, jump directly to e)
d) "Echo" the command back to the terminal monitor for confirmation
e) Sort and process the keystroke command. Modify stepper motor controls based on the keystroke
command:
vi) >
STEP=$01
vii) <
STEP=$ff
viii) +
Increase speed (decrease delay, but not below $28)
ix) Decrease speed (increase delay but not above $ff)
x)
S Stop program
f) Loop back to c)
In the initialization phase, the program enters the values of S0 – S7 given in Table 1 in the appropriate
memory locations. Then it sets STEP=$00, and POINTER=$00
FLOWCHART AND CODE
The program flowchart is show below. Two flowchart levels are presented: the big-picture and the details.
The big-picture is used to understand the overall architecture of the program. The details are used to
explain some of the blocks. (Details are given only for those blocks which are somehow new, and have
not been used in previous programs.) The essential code for this program is shown to the right of the
flowchart. The essential code was incorporated into the standard template asm to generate the code file
Ex_Sort.asm. Please refer to this file for more coding details, and coding style.
Dr. Victor Giurgiutiu
Page 274
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Big-picture Flowchart
Example SORT
Code
Flowchart Details
ORG
RMB
RMB
ORG
START
LDX
LDAA
STAA
LDAA
STAA
LDAA
STAA
LDAA
STAA
LDAA
STAA
LABEL0 NOP
LABEL1 LDAA
ANDA
BEQ
LDAB
LABEL2 LDAA
ANDA
BEQ
STAB
CMPB
BEQ
CMPB
BEQ
CMPB
BEQ
CMPB
BEQ
CMPB
BEQ
JMP
FORWD LDAA
CMPA
BGT
INCA
LABL10 STAA
JMP
BACKWD LDAA
CMPA
BLT
DECA
LABL11 STAA
JMP
FASTER LDAA
CMPA
BLS
DECA
LABEL6 STAA
JMP
SLOWER LDAA
CMPA
BHS
INCA
LABEL7 STAA
JMP
STOP
SWI
LABEL9 BRA
STEP
DELAY
• STEP
• DELAY
Define variables
START
•
•
•
•
Initialize
Keystroke?
1 byte
1 byte
X=REGBAS
SCI
STEP=$00
DELAY=$ff
N
Y
Receive and echo keystroke
FORWD
STEP>+1
>
Y
FORWD
Y
N
Increment STEP
N
BACKWD
STEP<-1
<
Y
BACKWD
N
Sort keystroke
Y
N
Decrement STEP
FASTER
DELAY≤$28
+
Y
Y
FASTER
N
Decrement DELAY
N
SLOWER
DELAY≥$ff
-
Y
Y
SLOWER
N
Increment DELAY
N
S
Y
STOP
STOP
SWI
N
Dr. Victor Giurgiutiu
Page 275
DATA
1
1
PROGRAM
#REGBAS
#%00110000
BAUD,X
#%00000000
SCCR1,X
#%00001100
SCCR2,X
#0
STEP
#$ff
DELAY
SCSR,X
#%00100000
LABEL9
SCDR,X
SCSR,X
#%10000000
LABEL2
SCDR,X
#'>'
FORWD
#'<'
BACKWD
#'+'
FASTER
#'-'
SLOWER
#'S'
STOP
LABEL9
STEP
#+1
LABL10
STEP
LABEL9
STEP
#-1
LABL11
STEP
LABEL9
DELAY
#$28
LABEL6
DELAY
LABEL9
DELAY
#$ff
LABEL7
DELAY
LABEL9
LABEL0
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
EXECUTION
Open THRSim11. Close the Commands window. Open and assemble Ex_Sort.asm. View CPU registers,
serial registers SCSR (set to binary) and SCDR, timer registers TCNT through TOC1, memory list for
variables STEP and DELAY, serial transmitter, serial receiver. Arrange windows for maximum benefit.
Reset registers. Set standard labels (Label/Set Standard Labels). Press the RESET button. Your screen
should look like this:
a) Set breakpoints at the following lines:
•
LDAB SCDR,X
•
STAB SCDR,X
•
SWI
b) Step through the program up to LABEL0. The program should initialize X=$1000, SCI control
registers, and STEP=$00, DELAY=$ff.
c) Let the program run. It should loop continuously through the body of the program and back to
LABEL0, etc.
Dr. Victor Giurgiutiu
Page 276
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
CHECK THE KEYSTROKE COMMAND > (FORWARD)
d) Type > in serial transmitter, and send. After some time, you will see the RDRF bit in SCSR (bit 5)
getting set, and your program should stop at the breakpoint. At this point, SCDR-$3e, i.e., ASCII
code for >. Your program looks like this:
e) Run. The program clears the RDRF flag, and stops at the next breakpoint, STAB SCDR,X.
f)
Step through your program. You will see
•
The program enters the sort sequence
•
The program branches to label FORWARD
•
The BGT condition is not satisfied, and the program increments STEP from $00 to $01. You
have set the STEP to the value +1, for ‘slow-forward’
•
The program branches to LABEL9 and then to LABEL0. Your screen looks like this:
Dr. Victor Giurgiutiu
Page 277
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
g) Let your program run. You will see the program looping again in the big loop.
h) Send the character > again. The sequence of events described above repeats itself. At the end
of the process, STEP=2. You have achieved ‘fast-forward’.
i)
Let your program run. You will see the program looping again in the big loop. Send the character
> again and repeat the sequence of events. Observe carefully how the segment FORWD is
executed. You will notice that the condition BGT is now satisfied, and the program branches over
the INCA instruction. Thus, your STEP does no longer increase, and stays at its maximum value,
STEP=$02 (decimal, +2). Your screen looks like this:
Dr. Victor Giurgiutiu
Page 278
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 279
Example SORT
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
CHECK THE KEYSTROKE COMMAND < (BACKWARD)
j)
Run. While the program is looping on LABEL0, type the character < into the serial transmitter,
and send. The program should stop at the first breakpoint. Run again. The program stops at
second breakpoint.
k) Step through the program. The program will go through the sorting sequence and end up at the
BACKWD segment. The BLT condition is not satisfies, and the program decrements STEP from
$02 to $01. You are back to ‘slow-forward’ At the end of this process, your screen looks like this:
Dr. Victor Giurgiutiu
Page 280
8/19/2008
EMCH 367
l)
Fundamentals of Microcontrollers
Example SORT
Repeat and get the variable STEP to get the value STEP=$00. This corresponds to ‘stand still’.
m) Repeat. This time the variable STEP will be decremented to the value STEP=$ff (decimal –1).
This corresponds to ‘slow-backward’.
n) Repeat. This time the variable STEP will be decremented to the value STEP=$fe (decimal –2).
This corresponds to ‘fast-backward’. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 281
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
CHECK THE KEYSTROKE COMMAND +(INCREASE SPEED)
o) We want to test the keystroke command +. This command should produce an increase in speed,
i.e., a decrease in DELAY from $ff to $fe. Run the program. While the program is looping on
LABEL0, type the character. After the breakpoints, you will see your program sorting at the
program segment FASTER. While going through this segment, the condition for BLS is not
satisfied, and program decrements DELAY to the value DELAY=$fe. At the end of the process,
your screen should look like this:
Dr. Victor Giurgiutiu
Page 282
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
p) Repeat two times. The variable DELAY should become DELAY=$fd, then DELAY=$fc. Your
program should look like this:
Dr. Victor Giurgiutiu
Page 283
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
q) Test now the logic at the lower limit of DELAY, i.e., that it does not go below $28. Make
DELAY=$28. Then, run. Send + again. After the second breakpoint, step through it. The program
gets again to the program segment FASTER, but, this time, the condition for BLS is satisfied and
the program branches over the operation DECA. Hence, the variable delay is not decremented
any further. It stays at DELAY=$28. The logic works as expected. Your screen should look like
this:
Dr. Victor Giurgiutiu
Page 284
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
CHECK THE KEYSTROKE COMMAND -(DECREASE SPEED)
r) We want to test the keystroke command -. This command should produce a decrease in speed,
i.e., an increase in DELAY from $28 to $29.Run the program. While the program is looping on
LABEL0, type the character – and send. After the breakpoints, you will see your program sorting
at the program segment SLOWER. While going through this segment, the condition for BHS is
not satisfied, and program increments DELAY from $28 to$29. At the end of the process, your
screen should look like this:
s) Repeat two times. The variable DELAY should become DELAY=$2a, then DELAY=$2b. Your
program should look like this:
Dr. Victor Giurgiutiu
Page 285
8/19/2008
EMCH 367
t)
Fundamentals of Microcontrollers
Example SORT
Test now the logic at upper limit of DELAY, i.e., that it does not go over $ff. Make DELAY=$ff.
Then, run. Send - again. After the second breakpoint, step through it. The program gets again to
the program segment SLOWER, but, this time, the condition for BHS is satisfied and the
program branches over the operation INCA. Hence, the variable delay is not incremented any
further. It stays at DELAY=$ff. The logic works as expected. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 286
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
CHECK THE KEYSTROKE COMMAND S (STOP)
u) We want to test the keystroke command +. This command should produce the program to stop.
Run the program. While the program is looping on LABEL0, type the character S. After the
breakpoints, you will see your program sorting at the program label STOP. The operation at this
label is SWI. Your program successfully stops. (Do not step manually through SWI, since it will
throw you outside the program area, and give a disassemble error.)
FURTHER CHECKS
v) Remove the breakpoint from LDAB SCDR,X and STAB SCDR, X. Leave only the breakpoint at
SWI.
w) Run your program and test the keystroke commands >, <, +, -, S again, until you are satisfied
that you understood how they work.
Dr. Victor Giurgiutiu
Page 287
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example SORT
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of keystroke commands for controlling a process. The following keystroke commands
have been used:
Move forward
>
i)
ii)
Move backward
<
iii) Increase speed (decrease delay)
+
iv) Decrease speed (increase delay)
v)
Stop program
S
• Introduce the concept of ‘multiple sort’ and its ‘sequential sort’ equivalent. The multiple sort was
needed to go to one of the five possible outcomes according to the keystroke value. Since a
multiple sort command is not available in the MCU programming language, an equivalent
‘sequential sort’ was used instead. The sequential sort, checks the keystroke against one
possibility at a time; if a coincidence is found, it branches out. Otherwise. it continues to check.
Dr. Victor Giurgiutiu
Page 288
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
EXAMPLE – A/D CONVERTER
OBJECTIVE
This example will help you learn how to use the M68HC11 microcontroller to collect analog data in
digital form. The following objectives are considered:
• Review the use of A/D conversion function of the M68HC11 microcontroller.
• Illustrate various modes of performing A/D conversion.
This example covers the following topics:
• Single channel, single conversion, MULT=0, SCAN=0;
• Single channel, continuous conversion, MULT =0, SCAN =1;
• Multiple channel, single conversion, MULT =1, SCAN =0;
• Multiple channel, continuous conversion, MULT =1, SCAN =1;
PROGRAM A/D CONVERTER
SINGLE CHANNEL, SINGLE CONVERSION, MULT=0, SCAN=0
In this section, we will study the single-channel single-conversion. The channel selected in this example
will be the pin PE1. The program will do the following
a) Initialize the A/D conversion
b) Set ADCTL to reflect the following control bits:
i)CD=0, CC=0, CB=0, CA=1 to select pin PE1
ii)SCAN=0, i.e., no scanning
iii)MULT=0, i.e., single channel
c) Check if the A/D conversion has finished. The conversion is finished when the flag CCF is set.
d) Load the results from the AD registers ADR1 – ADR4 and store them into memory locations
VAL1 – VAL4.
e) Loop back to b)
FLOWCHART AND CODE
The program flowchart is show below. Two flowchart levels are presented: the big-picture and the
details. The big-picture is used to understand the overall architecture of the program. The details are
used to explain some of the blocks. (Details are given only for those blocks which are somehow new,
and have not been used in previous programs.) The essential code for this program is shown to the right
of the flowchart. The essential code was incorporated into the standard template asm to generate the
code file Ex_AD_1.asm.
Dr. Victor Giurgiutiu
Page 289
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Big-picture Flowchart
Define variables
Initialize
Code
Flowchart Details
•
•
•
•
VAL1
VAL2
VAL3
VAL4
1 byte
1 byte
1 byte
1 byte
• X=REGBAS
• AD converter
• MULT = 0
• SCAN = 0
• CA=1
ADC
Perform A/D
conversion
LABEL1
Y
CCF=0?
N
Store conversion
results
Example A/D CONVERTER
Store
ADR1, ADR2, ADR3, ADR4 to
VAL1, VAL2, VAL3, VAL4
ORG
DATA
VAL1
RMB
1
VAL2
RMB
1
VAL3
RMB
1
VAL4
RMB
1
* Main program
ORG
PROGRAM
START
LDX
#REGBAS
* switch on A/D converter
BSET
OPTION,X,%10000000
* Perform single A/D conversion on PE0,PE1,PE2,PE3
ADC
BSET
ADCTL,X,%00000001; SCAN=0,
.
MULT=0, CA=1
LABEL1 LDAA
ADCTL,X
ANDA #%10000000
BEQ
LABEL1
* Store the four consecutive conversion values
LDAA
ADR1,X
STAA
VAL1
LDAA
ADR2,X
STAA
VAL2
LDAA
ADR3,X
STAA
VAL3
LDAA
ADR4,X
STAA
VAL4
BRA
ADC
ORG
RESET
FDB
START
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, AD converter registers, port E
pins, memory list, Sliders E port. Open and assemble Ex_AD_1.asm. Reset registers and memory. Set
standard labels (Label/Set Standard Labels). Set display of ADCTL and accA to binary. Arrange
windows for maximum benefit: Press the RESET button. Your screen should look like this:
Dr. Victor Giurgiutiu
Page 290
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Step through the program up to LABEL1. The AD conversion control register ADCTL has been set to
perform a single A/D conversion on the pin PE1. Your screen looks like this:
We are now ready to perform the conversions. Set a breakpoint just after exiting the check CCF loop,
i.e., at line $c010. Make the value of PE1 = 1000 mV. Run. The program performs the AD conversion
and exists the loop. The registers ADR1 – ADR4 have the value $33, which is the hex value of
1000*$ff/5000 (check with your hex calculator!). The screen looks like this:
Step through the program until all the four AD registers get transferred into the memory storage
locations VAL1 – VAL4. The screen looks like this:
Dr. Victor Giurgiutiu
Page 291
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Remove the breakpoint from $c010. Enter 1500 mV into PE1. Run. The program will run continuously.
The converted value $4c (1500*$ff/5000=$4c, check with your hex calculator!) appears in the ADR1 –
ADR4 registers and is transferred into VAL1 – VAL4. The screen looks like this:
Put value 2000 mV into PE1. The converted value $66 (2000*$ff/5000=$66, check with your hex
calculator!) appears in ADR1 – ADR4 and then in VAL1 – VAL4. The screen looks like this:
Dr. Victor Giurgiutiu
Page 292
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Put value 2500 mV into PE1. The converted value $80 appears in ADR1 – ADR4 and then in VAL1 –
VAL4 (2500*$ff/5000=$7f with normal 1 bit convention, check with your hex calculator!. But
M68HC11 uses ½ bit accuracy convention, and hence rounds up to $80). The screen looks like this:
Put value 3500 mV into PE1. The converted value $b3 appears in ADR1 – ADR4 and then in VAL1 –
VAL4 (3500*$ff/5000=$b2 with normal 1 bit convention, check with your hex calculator!. But
M68HC11 uses ½ bit accuracy convention, and hence rounds up to $b3). The screen looks like this:
Dr. Victor Giurgiutiu
Page 293
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Put value 5000 mV into PE1. The converted value $ff appears in ADR1 – ADR4 and then in VAL1 –
VAL4 (5000*$ff/5000=$ff, check with your hex calculator!). The screen looks like this:
At the end of this process, you have verified the conversion of six voltage values in the range 0 – 5 V,
and have obtained the results indicated in Table 1.
Dr. Victor Giurgiutiu
Page 294
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Table 1
Voltage at pin PE1 (mV)
1000
1500
2000
2500
3500
5000
1
2
3
4
5
6
AD converted values (Hex)
$33
$4c
$66
$80
$b3
$ff
Let the program run, and move freely the slider bar on PE1. Observe the reaction time of the MCU
simulator, and how the converted values corresponding to the new simulated voltages appear first in the
ADR1 – ADR4 registers, and then into the VAL1 – VAL4 memory locations.
SINGLE CHANNEL, CONTINUOUS CONVERSION, MULT=0, SCAN=1
You will now perform continuous AD conversion in SCAN mode. This mode does not require you to
check the CCF flag. The program flowchart is showed below. Also two flowcharts are presented. The
essential code for this program is shown to the right of the flowchart. The essential code was
incorporated into the standard template asm to generate the code file Ex_AD_2.asm.
Big-picture Flowchart
Define variables
Initialize
Flowchart Details
•
•
•
•
VAL1
VAL2
VAL3
VAL4
1 byte
1 byte
1 byte
1 byte
• X=REGBAS
• AD converter
Perform A/D
conversion
• MULT = 0
• SCAN = 1
• CA=1
Store conversion
results
Store
ADR1, ADR2, ADR3, ADR4 to
VAL1, VAL2, VAL3, VAL4
LABEL2
Code
ORG
DATA
VAL1
RMB
1
VAL2
RMB
1
VAL3
RMB
1
VAL4
RMB
1
* Main program
ORG
PROGRAM
START
LDX
#REGBAS
* switch on A/D converter
BSET
OPTION,X,%10000000
* Perform a single A/D conversion on PE1
ADC
BSET
ADCTL,X,%00100001
SCAN=1, MULT=0, CA=1
* Store the four consecutive conversion values
LABEL2 LDAA
ADR1,X
STAA
VAL1
LDAA
ADR2,X
STAA
VAL2
LDAA
ADR3,X
STAA
VAL3
LDAA
ADR4,X
STAA
VAL4
BRA
LABEL2 ;BACK TO TOP
ORG
FDB
RESET
START
EXECUTION
Open and assemble Ex_AD_2.asm. Reset registers and memory. Set standard labels (Label/Set Standard
Labels). Run the program. Notice that after addressing ADCTL once at the beginning, the program now
loops only for storing the values of ADR1 – ADR4 into memory locations VAL1 – VAL4. Enter 1000
mV in PE1. The value is converted to $33 and stored in memory. The screen looks like this:
Dr. Victor Giurgiutiu
Page 295
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Continue with the other values in Table 1, until you are satisfied with the functioning of the program.
MULTIPLE CHANNEL, SINGLE CONVERSION, MULT=1, SCAN=0
We will now perform AD conversion on multiple channels, single conversion. This mode is selected by
setting MULT=1 and SCAN=0 such that the conversion is performed once.
The program flowchart is shown below. Two flowchart levels are presented: the big-picture and the
details. The essential code for this program is shown to the right of the flowchart. The essential code was
incorporated into the standard template asm to generate the code file Ex_AD_3.asm.
Dr. Victor Giurgiutiu
Page 296
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Big-picture Flowchart
Define variables
Initialize
Code
Flowchart Details
•
•
•
•
VAL1
VAL2
VAL3
VAL4
1 byte
1 byte
1 byte
1 byte
• X=REGBAS
• AD converter
• MULT = 1
• SCAN = 0
• CD,CC = 0
ADC
Perform A/D
conversion
LABEL1
Y
CCF=0?
N
Store conversion
results
Example A/D CONVERTER
Store
ADR1, ADR2, ADR3, ADR4 to
VAL1, VAL2, VAL3, VAL4
ORG
DATA
VAL1
RMB
1
VAL2
RMB
1
VAL3
RMB
1
VAL4
RMB
1
* Main program
ORG
PROGRAM
START
LDX
#REGBAS
* switch on A/D converter
BSET
OPTION,X,%10000000
* Perform a single A/D conversion on PE0, PE1, PE2, PE3
ADC
LDAA
#%00010000 ; SCAN=0, MULT=1
STAA
ADCTL,X
LABEL1 LDAA
ADCTL,X
ANDA #%10000000
BEQ
LABEL1
* Store the four consecutive conversion values
LABEL2 LDAA
ADR1,X
STAA
VAL1
LDAA
ADR2,X
STAA
VAL2
LDAA
ADR3,X
STAA
VAL3
LDAA
ADR4,X
STAA
VAL4
BRA
ADC
;BACK TO TOP
ORG
RESET
FDB
STAR
EXECUTION
Open and assemble Ex_AD_3.asm. Reset registers and memory. Set standard labels (Label/Set Standard
Labels). The screen looks like this:
Dr. Victor Giurgiutiu
Page 297
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Enter 2500 mV in PE0, 1000 mV in PE1, 3500 mV in PE2, 2000 mV in PE3. Run the program. The
converted value $80, $33, $b3, $66 appear in ADR1 – ADR4, and then get stored in memory locations
VAL1 – VAL4. The screen looks like this:
MULTIPLE CHANNEL, CONTINUOUS CONVERSION, MULT=1, SCAN=1
We will now perform AD conversion on multiple channels continuous conversion. This mode is selected
by setting MULT=1 and SCAN=1 such that the conversion is performed continuously.
The program flowchart is shown below. Two flowchart levels are presented: the big-picture and the
details. The essential code for this program is shown to the right of the flowchart. The essential code was
incorporated into the standard template asm to generate the code file Ex_AD_4.asm.
Dr. Victor Giurgiutiu
Page 298
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Big-picture Flowchart
Define variables
Initialize
Perform A/D
conversion
LABEL2
Store conversion
results
Code
Flowchart Details
•
•
•
•
VAL1
VAL2
VAL3
VAL4
Example A/D CONVERTER
1 byte
1 byte
1 byte
1 byte
• X=REGBAS
• AD converter
• MULT = 1
• SCAN = 1
• CD, CC = 0
Store
ADR1, ADR2, ADR3, ADR4 to
VAL1, VAL2, VAL3, VAL4
ORG
DATA
VAL1
RMB
1
VAL2
RMB
1
VAL3
RMB
1
VAL4
RMB
1
* Main program
ORG
PROGRAM
START
LDX
#REGBAS
* switch on A/D converter
BSET
OPTION,X,%10000000
* Perform a single A/D conversion on PE1
ADC
LDAA
#%00110000 ; SCAN=1, MULT=1
STAA
ADCTL,X
* Store the four consecutive conversion values
LABEL2 LDAA
ADR1,X
STAA
VAL1
LDAA
ADR2,X
STAA
VAL2
LDAA
ADR3,X
STAA
VAL3
LDAA
ADR4,X
STAA
VAL4
BRA
LABEL2 ;BACK TO TOP
ORG
FDB
RESET
START
EXECUTION
Open and assemble Ex_AD_4.asm. Reset registers and memory. Set standard labels (Label/Set Standard
Labels). Run the program. Notice that after addressing ADCTL once at the beginning, the program now
loops only for storing the values of ADR1 – ADR4 into memory locations VAL1 – VAL4. Enter 2500
mV in PE0, 1000 mV in PE1, 3500 mV in PE2, 2000 mV in PE3. The converted value $80, $33, $b3,
$66 appear in ADR1 – ADR4, and then get stored in memory locations VAL1 – VAL4. The screen
looks like this:
Dr. Victor Giurgiutiu
Page 299
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Example A/D CONVERTER
Repeat the process with other values in the four PE1 – PE4 pins. Obtain voltage values by moving the
sliding controls on these pins up and down and observing the converted values being appearing in the
ADR1 – ADR4 registers, and then into the VAL1 – VAL4 memory locations.
WHAT YOU HAVE LEARNED
In this exercise, you have:
• Review the use of A/D conversion function of the M68HC11 microcontroller.
• Illustrated 3 modes of performing A/D conversion:
¾ Single channel single conversion
¾ Single channel continuous conversion
¾ Multiple channel single conversion
¾ Multiple channel continuous conversion
Dr. Victor Giurgiutiu
Page 300
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Homework Assignments
HOMEWORK ASSIGNMENTS
Hmwk1
basic operations
Hmwk2
hex operations
Hmwk3
Programs\SR
Hmwk4a
Parallel com
Hmwk4b
Serial com
Hmwk5
Timer functions
Hmwk6
Digital Tachometer
Hmwk7
Step, sort, delay
Hmwk8
AD conversion
Homework consists of a series of exercises that can be performed individually on the THRSim11
simulator. The exercises introduce the student gradually to basic concepts, programming language, and
hex/binary conventions, branching and logic flow, intermediate level programming, MCU main
functions (Parallel ports, serial communication, timer functions, AD conversion), and advanced
programming. By doing the homework, the students build up his programming and code creation skills.
Homework assignments are shown in the table below:
Exercise 1
Exercise 2
Exercise 3-7
Exercise 8-9
Exercise 10
Ex_delay
Ex_sq_wave
Ex_buttons_bx
Ex_Serial
Ex _Timer
Ex_DC_motor_RPM
Ex_Stepper_motor
Ex_AD_converter
Dr. Victor Giurgiutiu
X
X
X
X
X
X
X
X
X
X
X
X
X
Page 301
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Homework Assignments
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 302
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 1
EXERCISE 1
GENERAL NOTE
• Before starting this exercise, read Example 1 and work through it using the THRSim11 simulator.
•
Then, read this exercise. You will notice that the present exercise is practically identical with
Example 1, only that is uses different numbers.
•
'Save As' this Word file in the personalized format indicated in the course pack.
•
To complete the exercise, you will have to make it look like Example 1 by doing the following:
•
Type in text
•
Insert screen/window captures from the THRSim11 simulator.
OBJECTIVE
This simple exercise has the following objectives:
• Familiarize the user with the THRSim11 simulator environment
•
Introduce the user to the syntax and concepts of Assembly (.asm) language
•
Familiarize the user the way arithmetic operations are handled by the microcontroller
•
Instruct the user to interpret the List (.LST) file.
•
Teach the user to perform the simulation and follow the step-by-step results.
•
Introduce the LDAA, LDAB, ABA operations
•
Introduce the immediate and inherent modes
PROGRAM
You have to write a .asm program that will perform the arithmetic operation 4 + 5 = 9 using the opcode
mnemonics LDAA, LDAB, ABA.
Insert here the symbolic representation of the process: 5 points
Explain what the symbolic representation means: 5 points
CODING AND EXECUTION
Open THRSim11
Maximize THRSim11 window
Close the Commands window
Open the template.asm file and save it with the personalized name LASTNAME_Firstname_Ex1 (Please
respect the upper and lower conventions.).
Type your program in the .asm window after the line saying *Begin typing your code.
Follow Example 1 to assemble your file, tile the windows, set the breakpoint, and reset the registers.
Paste your screen capture below. 10 points
Insert below text to answer the questions:
Dr. Victor Giurgiutiu
Page 303
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
•
What is the meaning of the green highlight? 4 points
•
What is the meaning of the amber highlight? 4 points
•
At what memory address is the program counter placed? 4 points
Exercise 1
Use the Step button to step through the program.
first step
Explain:
• What happened to the green highlight 4 points
•
What is the value of the program counter 4 points
•
What is the program going to do next 4 points
second step.
Explain:
• What is the result of executing the previous instruction 4 points
•
What is the value of the program counter 4 points
•
What has changed in the CPU registers 4 points
•
What is the program going to do next 4 points
third step.
Explain:
• What is the result of executing the previous instruction 4 points
•
What is the value of the program counter 4 points
•
What has changed in the CPU registers 4 points
•
What is the program going to do next 4 points
fourth step.
Explain:
• What is the result of executing the previous instruction 4 points
•
What is the value of the program counter 4 points
•
What has changed in the CPU registers 4 points
•
What is the program going to do next 4 points
Place the program counter at the beginning of your part of the program.
Run the program again step-by-step. What have you noticed? 4 points
Run the program on automatic using the button ‘Run’. What have you noticed? 4 points
Dr. Victor Giurgiutiu
Page 304
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 1
WHAT YOU HAVE LEARNED
In this simple exercise, you have learned quite a few things:
• Symbolic representation of the operations and their meaning
•
Writing an Assembly language code
•
Microprocessor opcode mnemonics LDAA, LDAB, ABA.
•
Immediate mode and how to invoke it by using the symbol #
•
Inherent mode
•
Open and customize THRSim11 environment
•
Assemble an .asm file
•
Tile the THRSim11 windows (remember that the tiling sequence follows the sequence in which
you accessed the files, with the most recently accessed window tiled in the left upper corner!)
•
Put a value in a memory address, e.g. when you put zeros in the registers
•
Set a break point
•
Interpret an .LST file
•
Step through the program simulation and follow the changes taking place in the ‘CPU registers’
window.
•
See how program execution is affecting accA and accB. Identify the results of the calculation, i.e.
4 + 5 = 9 makes accA to take the value A $09.
New words and concepts: Opcode, opcode mnemonic, immediate mode, Assembly language (.asm), list
file (.LST), reset, program counter (PC), break point, registers,
Dr. Victor Giurgiutiu
Page 305
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Exercise 1
Page 306
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 2
EXERCISE 2
GENERAL NOTE
• Before starting this exercise, read Example 2 and work through it using the THRSim11 simulator.
•
Then, read this exercise. You will notice that the present exercise is practically identical with
Example 2, only that is uses different numbers.
•
'Save As' this Word file in the personalized format indicated in the course pack.
•
To complete the exercise, you will have to make it look like Example 2 by doing the following:
•
Type in text
•
Insert screen/window captures from the THRSim11 simulator.
OBJECTIVE
This simple exercise has the following objectives:
• Familiarize the user with the THRSim11 simulator environment
•
Introduce the user to the syntax and concepts of Assembly (.asm) language
•
Familiarize the user the way arithmetic operations are handled by the microcontroller
•
Instruct the user to interpret the List (.LST) file.
•
Teach the user to perform the simulation and follow the step-by-step results.
•
Introduce the LDAA, ADDA operations
•
Introduce the immediate mode
PROGRAM
You have to write a .asm program that will perform the arithmetic operation 4 + 5 = 9 using the opcode
mnemonics LDAA, ADDA.
Insert here the symbolic representation of the process: 7 points
Explain what the symbolic representation means: 7 points
CODING AND EXECUTION
Open THRSim11
Maximize THRSim11 window
Close the Commands window
Open the template.asm file and save it with the personalized name LASTNAME_Firstname_Ex2 (Please
respect the upper and lower conventions.).
Type your program in the .asm window after the line saying *Begin typing your code.
Follow Example 2 to assemble your file, tile the windows, set the breakpoint, and reset the registers.
Paste your screen capture below. 8 points
Insert below text to answer the questions:
Dr. Victor Giurgiutiu
Page 307
8/19/2008
EMCH 367
•
Fundamentals of Microcontrollers
Exercise 2
At what memory address is the program counter placed? 6 points
Use the Step button to step through the program.
first step
Explain:
• What is the value of the program counter 6 points
•
What is the program going to do next 6 points
second step.
Explain:
• What is the result of executing the previous instruction 6 points
•
What is the value of the program counter 6 points
•
What has changed in the CPU registers 6 points
•
What is the program going to do next 6 points
third step.
Explain:
• What is the result of executing the previous instruction 6 points
•
What is the value of the program counter 6 points
•
What has changed in the CPU registers 6 points
•
What is the program going to do next 6 points
Place the program counter at the beginning of your part of the program. Reset accumulator A and B.
Run the program again step-by-step. What have you noticed? 6 points
Run the program on automatic using the button ‘Run’. What have you noticed? 6 points
Dr. Victor Giurgiutiu
Page 308
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 2
WHAT YOU HAVE LEARNED
In this simple exercise, you have learned quite a few things:
• Symbolic representation of the operations and their meaning
•
Writing an Assembly language code
•
Microprocessor opcode mnemonics LDAA, ADDA.
•
Immediate mode and how to invoke it by using the symbol #
•
Inherent mode
•
Open and customize THRSim11 environment
•
Assemble an .asm file
•
Tile the THRSim11 windows (remember that the tiling sequence follows the sequence in which
you accessed the files, with the most recently accessed window tiled in the left upper corner!)
•
Put a value in a memory address, e.g. when you put zeros in the registers
•
Set a break point
•
Interpret an .LST file
•
Step through the program simulation and follow the changes taking place in the ‘CPU registers’
window.
•
See how program execution is affecting accA and accB. Identify the results of the calculation, i.e.
4 + 5 = 9 makes accA to take the value A $09.
•
New words and concepts: Opcode, opcode mnemonic, immediate mode, Assembly language
(.asm), list file (.LST), reset, program counter (PC), break point, registers, .
Dr. Victor Giurgiutiu
Page 309
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 2
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 310
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 3-7
EXERCISE 3-7
GENERAL NOTE
• Before starting this exercise, read Examples 3, 4, 5, 6, 7 and work through them using the
THRSim11 simulator.
•
Then, read this exercise. You will notice that the present exercise is practically identical with these
examples, only that is uses different numbers.
•
'Save As' this Word file in the personalized format indicated in the course pack.
•
To complete the exercise, you will have to do the following:
•
Type in text
The exercise has 6 sections. Do them in sequence.
OBJECTIVE
This exercise has the following objectives:
• Review decimal numbers and decimal symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
•
Review the decimal carry concept, i.e., when a result is outside the 0 – 9 range
•
Review 2-digit decimal arithmetic with carry
•
Prepare the ground for hex arithmetic
•
Introduce hex numbers and hex symbols: a, b, c, d, e, f
•
Introduce2-digit hex arithmetic
•
Introduce 2-digit hex carry as a repeated incrementation
•
Introduce 2-digit hex arithmetic with carry
•
Introduce the ‘lost carry’ concept
•
Introduce MSB carry
•
Introduce single precision and double precision register concepts
Note: To facilitate understanding, the same numbers are used in both decimal and the hex cases.
Dr. Victor Giurgiutiu
Page 311
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 3-7
PROGRAM
You have to write .asm code to perform the arithmetic operations listed below:
• 8 + 7 = 15 (decimal) using the opcode mnemonics LDAA, LDAB, ABA
• $08 + $07 = $0f (hex) using the opcode mnemonics LDAA, LDAB, ABA
• 9 + 9 = 18 (decimal) using the opcode mnemonics LDAA, LDAB, ABA
• $09 + $09 = $12 (hex half carry) using the opcode mnemonics LDAA, ADDA
• $09 + $09 = $12 (hex) using the opcode mnemonics LDAA, LDAB, ABA
• 12 + 29 = 41 (decimal) using the opcode mnemonics LDAA, LDAB, ABA
• $0c + $1d = $29 (hex) using the opcode mnemonics LDAA, LDAB, ABA
• $ff + $01 = $00 (MSB carry) using the opcode mnemonics LDAA, ADDA
• 255 + 1 = 0 (decimal equivalent of a MSB carry) using the opcode mnemonics LDAA, ADDA
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window.
Open the template.asm file and save it with the personalized name LASTNAME_Firstname_Ex3-7
(Please respect the upper and lower conventions.).
Type your program in the .asm window after the line saying *Begin typing your code.
Assemble your file, tile the windows, set the breakpoint, and reset the registers.
Paste the screen capture here. 1 point(s)
SECTION: 8 + 7 = 15 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to Decimal.
Use the Step button to step through this section of your program.
Explain:
• Which are the MSD and the LSD in the result 15? What do they represent? 3 point(s)
•
What is a decimal carry 2 point(s)
•
Did a decimal carry happen or not? Why? 3 point(s)
SECTION: $08 + $07 = $0F (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• How many digits are used to represent the number eight in hex on the simulator? Why? 3 point(s)
•
What is the meaning of concatenation? 2 point(s)
Dr. Victor Giurgiutiu
Page 312
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 3-7
•
Which registers are concatenated and what is the result of the concatenation? 2 point(s)
•
What was the content of accD after you loaded $08 in accA? Why? 3 point(s)
•
What was the content of accD after you loaded $08 in accA and $07 in accB? Why?
2 point(s)
•
What is a hex carry 2 point(s)
•
Did a hex carry happen or not? Why? 2 point(s)
SECTION: 9 + 9 = 18 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to Decimal.
Use the Step button to step through this section of your program.
Explain:
• What is a decimal carry 2 point(s)
•
Did a decimal carry happen or not? Why? 2 point(s)
SECTION: $09 + $09 = $12 (HEX) USING THE OPCODE MNEMONICS LDAA, ADDA,
Part I: start with $09 in accA and increment by 1 using the ADDA opcode
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program until the first has been executed.
Use the Step button to step further through this section of your program until accA has reached the value
$0f.
Use the Step button to do an additional step through this section of your program. AccA should change
to $10.
Use the Step button to do further step through this section of your program until the operation $09 + $09
= $12 using is completed.
Explain:
• Did a hex carry happen or not? Why? 3 point(s)
•
After how many executions has the carry happen? 2 point(s)
•
What was the value of accA before the hex carry? 2 point(s)
•
What was the value of accA after the hex carry? 2 point(s)
•
What was the final value of accA? 2 point(s)
SECTION: $09 + $09 = $12 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Part II: start with $09 in accA and $09 in accB. Do the addition using the ABA opcode
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• Did a hex carry happen or not? Why? 3 point(s)
•
What is the hex result of your operation? 2 point(s)
Dr. Victor Giurgiutiu
Page 313
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
•
What is the MSD of the result? What does is signify? 3 point(s)
•
What is the LSD of the result? What does it signify? 3 point(s)
•
What is the decimal equivalent of the result? 3 point(s)
Exercises 3-7
SECTION: 12 + 29 = 41 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to Decimal.
Use the Step button to step through this section of your program.
Explain:
• Did a decimal carry happen or not? Why? 3 point(s)
•
What is the LSD in the result? 2 point(s)
•
What is the MSD in the result? 2 point(s)
SECTION: $0C + $1D = $29 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, ABA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• Did a hex carry happen or not? Why? 2 point(s)
•
What is the hex result of your operation? 2 point(s)
•
What is the LSD of the result? What does it signify? 3 point(s)
•
What is the MSD of the result? What does is signify? 3 point(s)
•
What is the decimal equivalent of the result? 3 point(s)
$FF + $01 = $00 (HEX) USING THE OPCODE MNEMONICS LDAA, ADDA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• What is the result of your operation? 2 point(s)
•
Did a hex carry happen or not? Why? 2 point(s)
•
What type of carry was this? 2 point(s)
•
What is the name of the event that happened? 2 point(s)
•
How do you explain what happened? 3 point(s)
255 + 1 = 0 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, ADDA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to decimal.
Use the Step button to step through this section of your program.
Explain:
• What is the result of your operation? 3 point(s)
•
Did a decimal carry happen or not? Why? 3 point(s)
•
Did a hex carry happen or not? Why? 3 point(s)
Dr. Victor Giurgiutiu
Page 314
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
•
What type of carry was this? 3 point(s)
•
How do you explain what happened? 3 point(s)
Dr. Victor Giurgiutiu
Page 315
Exercises 3-7
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 3-7
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• In decimal arithmetic, the base of the number system is ten. Ten independent symbols exist for
representing the first ten numbers in the decimal system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. These symbols
are called digits.
•
The greatest decimal number that can be represented with a single decimal symbol is nine.
•
Decimal numbers greater than nine are represented with two or more digits. For example,
number fifteen is represented as 15, i.e. with two digits.
•
When the result of adding two decimal numbers is greater than nine, a carry takes place.
•
The symbol furthest to the left is called the most significant digit (MSD). In number 15, the most
significant digit is 1. It signifies the number of tens contained in the number. In our case, we
have only one ten, since 1 x ten = ten
•
The symbol furthest to the right is called the least significant digit (LSD). In number 15, the least
significant digit is 5. It signifies the number of units contained in the number. In our case, we
have five units, since 5 x units = five.
•
A complete number is assembled by adding the contribution of all digits, from LSD through
MSD. In number 15 there are two digits, LSD = 5, MSD = 1. The complete number is 1 x ten + 5
x units = ten + five = fifteen.
•
In decimal arithmetic, when the result of an addition is greater than nine, a carry occurs.
•
In hex arithmetic, the base of the number system is sixteen (hexadecimal). Sixteen independent
symbols exist for representing the first sixteen numbers in the hex system: 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, a, b, c, d, e, f.
•
The greatest hex number that can be represented with a single hex symbol is fifteen.
•
In single-precision 8-bit arithmetic, hex numbers are always represented with two digits, even if
the most significant digit (MSD) is zero. For example, during this exercise, the single-precision
accA and accB took values $08 and $07. After addition, accA became $0f.
•
In double precision 8-bit arithmetic, hex numbers are always represented with four digits, even if
the more significant ones are zero.
•
In hex arithmetic, single-precision numbers can be built into double precision numbers through
concatenation (i.e., by putting them side by side). For example, when accA was $08 and accB
was $07, accD, which is simply accA:accB, was $0807. This was not so in decimal arithmetic
(check this out by looking into the part of your program performing the decimal addition 8 + 7,
with accA, accB and accD set to decimal display).
•
In hex arithmetic, the symbol furthest to the left is also called the most significant digit (MSD).
In number $1d, the most significant digit is 1. It signifies the number of sixteens contained in the
number. In our case, we have only one sixteen, since 1 x sixteen = sixteen
•
In hex arithmetic, the symbol furthest to the right is called the least significant digit (LSD). In
number $1d, the least significant digit is d. It signifies the number of units contained in the
Dr. Victor Giurgiutiu
Page 316
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 3-7
number. In our case, we have thirteen units, since the hex number d represents the number
thirteen, and d x units =thirteen.
•
The hex number $1d has the value twenty-nine, since sixteen plus thirteen makes twenty-nine.
•
Addition can be viewed as a repeated incrementation. The number $09 was loaded in accA and
subsequently incremented nine times.
•
After the first six increments, from $09 to $0a, $0b, $0c, $0d, $0d, $0e, and $0f, the hex
symbols in the MSD were exhausted.
•
The next increment (the seventh) enacted a carry such that the MSD was increased from
0 to 1, while the first placeholder (LSD) was reset to 0. At this stage, the value in accA
was $10. (This is by far different from the decimal 10).
•
The next and final increment (the eighth) incremented the LSD and the number in accA
moved from $10 to $11.
•
You saw the direct application of the hex addition using accA and accB, such that $09 + $08 =
$12.
•
You should note that the result $12 is the hex equivalent of the decimal result 18 (recall, 9 + 8 =
17).
•
You have observed an MSB carry. In our case, the machine has 2-digit hex precision, hence it
cannot store numbers with more than two digits. However, if to the number $ff we add $01, the
result should be $100 (Proof: $0ff + $001 = $100). Since we cannot store more than 2 hex digits,
the leading 1 is lost (‘lost carry’). The phenomenon is called MSB carry where MSB refers to the
most significant bit from binary representation.
•
New words and notations: digits, most significant digit (MSD), least significant digit (LSD), hex
arithmetic, hexadecimal, single precision, double precision, 8-bit arithmetic, concatenation,
addition with carry, hex arithmetic with carry, increment, placeholder, ‘lost carry’, most
significant bit (MSB), MSB carry.
Dr. Victor Giurgiutiu
Page 317
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 8-9
EXERCISE 8-9
GENERAL NOTE
• Before starting this exercise, read Examples 8, 9 and work through them using the THRSim11
simulator.
•
Then, read this exercise. You will notice that the present exercise is practically identical with these
examples, only that is uses different numbers, at times.
•
'Save As' this Word file in the personalized format indicated in the course pack.
•
To complete the exercise, you will have to do the following:
•
Type in text
•
Insert screen/window captures from the THRSim11 simulator.
The exercise has 11 sections. Do them in sequence.
OBJECTIVE
This exercise has the following objectives:
• Review decrementation
•
Review decimal borrow concepts using decrementation
•
Introduce hex borrow using decrementation
•
Introduce 2’s complement negative hex numbers as decrementation of zero with free borrow
•
Show the decimal equivalent of the 8-bit decrementation of zero
•
Introduce hex subtraction as a repeated decrementation
•
Introduce hex subtraction with negative results using the free borrow concept.
•
Show the decimal equivalent of hex subtraction with negative results using free borrow.
Note: To facilitate understanding, the same numbers are used in both decimal and the hex cases.
PROGRAM
You have to write .asm code to perform the arithmetic operations listed below:
• 8 – 1 = 7 (decimal) using the opcode mnemonics LDAA, SUBA
•
$08 - $01 = $07 (hex) using the opcode mnemonics LDAA, SUBA
•
20 – 1 = 19 (decimal) using the opcode mnemonics LDAA, SUBA
•
$20 - $01 = $1f (hex) using the opcode mnemonics LDAA, SUBA
•
$00 - $01 = $ff (hex) using the opcode mnemonics LDAA, SUBA
•
0 - 1 = 255 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
SUBA
•
$0f - $07 = $08 (hex) using the opcode mnemonics LDAA, LDAB, SBA
•
$00 - $07 = $f9 (hex) using the opcode mnemonics LDAA, LDAB, SBA
Dr. Victor Giurgiutiu
Page 318
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 8-9
•
0 - 7 = 249 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
LDAB, SBA
•
$0f - $2b = $e4 (hex) using the opcode mnemonics LDAA, LDAB, SBA
•
15 - 43 = 228 (decimal equivalent of 8-bit hex arithmetic) using the opcode mnemonics LDAA,
LDAB, SBA
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window.
Open the template.asm file and save it with the personalized name LASTNAME_Firstname_Ex8-9
(Please respect the upper and lower conventions.).
Type your program in the .asm window after the line saying *Begin typing your code.
Assemble your file, tile the windows, set the breakpoint, and reset the registers.
Paste your screen capture below. 4 point(s)
SECTION: 8 - 1 = 7 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, SUBA
Reset accA and accB by typing zero into them. Set the display option of accA to decimal.
Use the Step button to step through this section of your program. When the operation has been
completed, capture your screen.
Paste the screen capture here. 4 point(s)
Explain:
• What is a decimal borrow? 4 point(s)
•
Did a decimal borrow happen or not? Why? 4 point(s)
SECTION: $08 - $01 = $07 (HEX) USING THE OPCODE MNEMONICS LDAA, SUBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• What is a hex borrow? 4 point(s)
•
Did a hex borrow happen or not? Why? 4 point(s)
SECTION: 20 - 1 = 19 (DECIMAL) USING THE OPCODE MNEMONICS LDAA, SUBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to decimal.
Use the Step button to step through this section of your program.
Explain:
Dr. Victor Giurgiutiu
Page 319
8/19/2008
EMCH 367
•
Fundamentals of Microcontrollers
Exercises 8-9
Did a decimal borrow happen or not? Why? 4 point(s)
SECTION: $20 - $01 = $1F (HEX) USING THE OPCODE MNEMONICS LDAA, SUBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• What is a hex borrow? 4 point(s)
•
Did a hex borrow happen or not? Why? 4 point(s)
•
Do the operations 20 – 1 and $20 - $01 give the same result or not? Why? 4 point(s)
SECTION: $00 - $01 = $FF (HEX) USING THE OPCODE MNEMONICS LDAA, SUBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• Did a hex borrow happen or not? Why? 4 point(s)
SECTION: 0 - 1 = 255 (DECIMAL EQUIVALENT OF 8-BIT HEX ARITHMETIC) USING THE OPCODE
MNEMONICS LDAA, SUBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to decimal.
Use the Step button to step through this section of your program.
Explain:
• Did a borrow happen or not? Why? 4 point(s)
•
What type of borrow happened? 4 point(s)
•
Why did you get the answer 255? 4 point(s)
SECTION: $0F - $07 = $08 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, SBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• Did a hex borrow happen or not? 4 point(s)
•
What type of borrow was it? 4 point(s)
Dr. Victor Giurgiutiu
Page 320
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 8-9
SECTION: $00 - $07 = $F9 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, SBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• Did a hex borrow happen or not? 4 point(s)
•
What type of borrow was it? 4 point(s)
SECTION: 0 - 7 = 249 (DECIMAL EQUIVALENT OF 8-BIT HEX ARITHMETIC) USING THE OPCODE
MNEMONICS LDAA, LDAB, SBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to decimal.
Use the Step button to step through this section of your program.
Explain:
• Why did you get the answer 249? 6 point(s)
SECTION: $0F - $2B = $E4 (HEX) USING THE OPCODE MNEMONICS LDAA, LDAB, SBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to hex.
Use the Step button to step through this section of your program.
Explain:
• Did a hex borrow happen or not? 4 point(s)
•
What type of borrow was it? 4 point(s)
SECTION: 15 - 43 = 228 (DECIMAL EQUIVALENT OF 8-BIT HEX ARITHMETIC) USING THE OPCODE
MNEMONICS LDAA, LDAB, SBA
Reset accA and accB by typing zero into them. Set the display option of accA and accB to decimal.
Use the Step button to step through this section of your program.
Explain:
• Why did you get the answer 228? 6 point(s)
USE CALCULATOR TO OBTAIN HEX NEGATIVE NUMBERS OF –56 AND –120
Insert your answers here:
-56: _________;
-120: ____________ 8 point(s)
Dr. Victor Giurgiutiu
Page 321
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercises 8-9
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• In decimal arithmetic, decrementation results in the value of the number being reduced by one
unit
•
In hex arithmetic, decrementation has the same meaning as in decimal arithmetic: the value of
the number is being reduced by one unit
•
For a 2-digit decimal number with the LSD zero, e.g., 20, decrementation required a borrow to
be performed from the MSD into the LSD. As a result, we could perform the decrementation and
the result was 19. The result showed that, because of the borrow, the MSD decreased from 2 to 1,
and the LSD increase from 0 to 9, i.e., from the bottom of the decimal symbols sequence to the
top of the sequence.
•
For a 2-digit hex number with the LSD zero, e.g., $20, decrementation also required a borrow to
be performed from the MSD into the LSD. As a result, we could perform the decrementation and
the result was $1f. The result showed that, because of the borrow, the MSD decreased from 2 to
1, and the LSD increase from 0 to f, i.e., from the bottom of the hex symbols sequence to the top
of the sequence.
•
Note the difference between 20 (twenty) and $20 (hex two-zero = decimal thirty-two).
•
For a 2-digit hex number with zero LSD but also zero MSD, decrementation is still possible
within the ‘free-borrow’ concept. The free-borrow concept, which is implemented on most
microcontrollers, allows to freely borrow a one from the next higher digit beyond the precision
of the machine.
•
In our case, the machine has 2-digit hex precision, hence the next higher digit beyond the
machine precision is a third digit. In other word, if we extend the range to 3 hex digits and write
$ff as $0ff, incrementing by one yield $0ff + $001 = $100. Conversely, decrementing $100 by
one yields $0ff, i.e., $ff.
•
Subtraction using SBA opcode mnemonic happened as expected, in both decimal and hex
arithmetic, as long as the minuend is greater than the subtrahend (e.g., 15-7=8, $0f-$07=$08).
•
When the minuend is less than the subtrahend, the result of the subtraction operation is
calculated using a free borrow (e.g., $0f-$2b=$00f+$100-$02b=$0e4=$e4).
•
Even if decimal display of numbers is used, the calculations and the free borrow still happen in
hex (e.g., 15-43=15+256-43=228, where 256=$100).
•
New words and notations: free borrow, minuend, subtrahend.
Dr. Victor Giurgiutiu
Page 322
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 323
Exercises 8-9
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 10
EXERCISE 10
GENERAL NOTE
• Before starting this exercise, read Example 10 and work through it using the THRSim11 simulator.
•
Then, read this exercise. You will notice that the present exercise is practically identical with this
example, only that is uses different numbers, at times.
•
'Save As' this Word file in the personalized format indicated in the course pack.
•
To complete the exercise, you will have to do the following:
•
Type in text
•
Insert screen/window captures from the THRSim11 simulator.
The exercise has 15 sections. Do them in sequence.
OBJECTIVE
This exercise has the following objectives:
• Introduce 8-bit binary numbers
•
Introduce connection between 8-bit binary numbers and 2-digit hex numbers.
•
Introduce 8-bit binary arithmetic
•
Introduce binary 8-bit logic
PROGRAM
You have to write .asm code to do the following:
i) Represent numbers one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen,
fourteen, fifteen, sixteen, seventeen in decimal, binary, and hex
ii) Perform 5 + 4 = 9 in binary and hex using LDAA, LDAB, ABA
iii) Perform 15 – 7 = 8 in binary and hex using LDAA, LDAB, SBA
iv) Perform $1f + $01 = $ in binary and hex using LDAA, ADDA (bit 3 carry)
v) Perform $20 -$01 = $ in binary and hex using LDAA, SUBA
vi) Perform $ff + $01 = $ in binary and hex using LDAA, ADDA (MSB carry)
vii) Perform $00 - $01 = $ in binary and hex using LDAA, SUBA
viii) 0 AND 1 =
using LDAA, ANDA
ix) 0 OR 1 =
using LDAA, ORAA
x) 0 XOR 1 =
using LDAA, EORA
xi) 1 OR 1 =
using LDAA, ORAA
xii) 1 XOR 1 =
using LDAA, EORA
xiii) %00000000 NAND %11111111 = %
using LDAA, ANDA, COMA
xiv) %11111111 NOR %00000000 = %
using LDAA, ORAA, COMA
Dr. Victor Giurgiutiu
Page 324
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
xv) %10101110 AND %00001000 = %
Exercise 10
using LDAA, ANDA (masking)
(Note: the NAND and NOR instructions do not exist in the MC6811 instruction set, but can be obtained
by using the COM instruction after the AND and OR instructions.)
CODING AND EXECUTION
Open THRSim11. Maximize THRSim11 window. Close the Commands window. Open the
template.asm file and save it with the personalized name LASTNAME_Firstname_Ex10 (Please respect
the upper and lower conventions.). Type your program in the .asm window after the line saying *Begin
typing your code. Assemble your file, tile the windows, set the breakpoint, and reset the registers.
SECTION: REPRESENT NUMBERS ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
ELEVEN, TWELVE, THIRTEEN, FOURTEEN, FIFTEEN, SIXTEEN, SEVENTEEN IN DECIMAL, BINARY, AND HEX
Reset accA. Place PC at the beginning of section i) of your code. Set display of accA to binary.
Perform first step.
Explain what happened during this operation. 3 point(s)
Change the display option of accA to hex.
Explain what happened. 3 point(s)
Change the display option of accA to decimal.
Explain what happened. 3 point(s)
Perform the rest of the steps.
Step through the rest of the operations, incrementing each time accA by one. At each step, observe the
binary representation, then switch to hex, then to decimal, and back to binary. When incrementing,
observe how the binary bits either increment from 0 to 1, or increment from 1 to 0 with a binary carry to
the left. While binary numbers experience a carry at each step, the decimal and hex numbers do not.
Watch out for decimal and hex carries! You will only need to capture and paste below those
situations when a decimal or a hex carry happened.
Paste here your screen capture when a decimal carry happened. 5 point(s)
Type in the binary and hex equivalents of the number in
accA:_________________________________________3 point(s)
Explain what happened. 2 point(s)
Paste here your screen capture when a hex carry happened. 5 point(s)
Type in the binary and decimal equivalents of the number in accA:
_____________________________________ 2 point(s)
Explain what happened. 2 point(s)
Dr. Victor Giurgiutiu
Page 325
8/19/2008
EMCH 367
SECTION: PERFORM 5 + 4 =
Fundamentals of Microcontrollers
Exercise 10
IN BINARY AND HEX USING LDAA, LDAB, ABA
Perform the operation.
5 + 4 =_____________ 3 point(s)
Type in the binary and hex equivalents of the results:
%________________________________$_________ 2 point(s)
SECTION: PERFORM 15 – 7 =
IN BINARY AND HEX USING LDAA, LDAB, SBA
Perform the operation.
15 – 7 =_____________3 point(s)
Type in the binary and hex equivalents of the results:
%________________________________$_________ 2 point(s)
SECTION: PERFORM $1F + $01 = $
IN BINARY AND HEX USING LDAA, ADDA (BIT 3 CARRY)
Fill in the blank with the result evaluated by hand.
$1f + $01 = $_______3 point(s)
Perform the operation in the THRSIM11 simulator. Type in the binary and hex equivalents of the results:
%________________________________2 point(s)
$_________ 2 point(s)
SECTION: PERFORM $20 -$01 = $
IN BINARY AND HEX USING LDAA, SUBA
Fill in the blank with the result evaluated by hand.
$20 -$01 = $________3 point(s)
Perform the operation in the THRSIM11 simulator. Type in the binary and hex equivalents of the results:
%________________________________2 point(s)
$_________ 2 point(s)
SECTION: PERFORM $FF + $01 = $
IN BINARY AND HEX USING LDAA, ADDA (MSB CARRY)
Fill in the blank with the result evaluated by hand.
$ff + $01 = $_______3 point(s)
Perform the operation in the THRSIM11 simulator. Type in the binary and hex equivalents of the results:
%______________________________________2 point(s)
$_________ 2 point(s)
SECTION: PERFORM $00 - $01 = $
Dr. Victor Giurgiutiu
IN BINARY AND HEX USING LDAA, SUBA
Page 326
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise 10
Fill in the blank with the result evaluated by hand.
$00 - $01 = $_______3 point(s)
Perform the operation in the THRSIM11 simulator. Type in the binary and hex equivalents of the results:
%______________________________________2 point(s)
$_________ 2 point(s)
SECTION: 0 AND 1 =
USING LDAA, ANDA
Fill in the blank with the result evaluated by hand.
0 AND 1 = _________4 point(s)
Perform the operation in the THRSIM11 simulator.
SECTION: 0 OR 1 =
USING LDAA, ORAA
Fill in the blank with the result evaluated by hand.
0 OR 1 =___________4 point(s)
Perform the operation in the THRSIM11 simulator.
SECTION: 0 XOR 1 =
USING LDAA, EORA
Fill in the blank with the result evaluated by hand.
0 XOR 1 =__________4 point(s)
Perform the operation in the THRSIM11 simulator.
SECTION: 1 OR 1 =
USING LDAA, ORAA
Fill in the blank with the result evaluated by hand.
1 OR 1 =__________4 point(s)
Perform the operation in the THRSIM11 simulator.
SECTION: 1 XOR 1 =
USING LDAA, EORA
Fill in the blank with the result evaluated by hand.
1 XOR 1 =__________4 point(s)
Perform the operation in the THRSIM11 simulator.
SECTION: %00000000 NAND %11111111 = %
USING LDAA, ANDA, COMA
Fill in the blank with the result evaluated by hand.
%00000000 NAND %11111111 = %____________________4 point(s)
Perform the operation in the THRSIM11 simulator.
Dr. Victor Giurgiutiu
Page 327
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
SECTION: %11111111 NOR %00000000 = %
Exercise 10
USING LDAA, ORAA, COMA
Fill in the blank with the result evaluated by hand.
%11111111 NOR %00000000 = %____________________4 point(s)
Perform the operation in the THRSIM11 simulator.
SECTION: %10101110 AND %00001000 = %
USING LDAA, ANDA (MASKING)
Fill in the blank with the result evaluated by hand.
%10101110 AND %00001000 = %____________________4 point(s)
Perform the operation in the THRSIM11 simulator.
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• The 8-bit binary numbers
•
The connection between 8-bit binary numbers and 2-digit hex numbers.
•
The 8-bit binary arithmetic
•
The 1-bit and 8-bit binary logic
•
The fact that logic operations are performed bit-by-bit
•
Boolean inversion using the complement opcode (e.g., COMA).
•
Masking, i.e., the selection of bits using masks
•
New words and notations: 8-bit binary arithmetic, 8-bit binary logic; complement opcode;
masking, flags.
Dr. Victor Giurgiutiu
Page 328
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 329
Exercise 10
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DELAY
EXERCISE DELAY
OBJECTIVE
This exercise has the following objectives:
• Review the use of branching
•
Illustrate a delay (wait) program
•
Demonstrate a flowchart and its relation with the program tasks list and program code
•
Demonstrate the calculation of clock cycles from the clock cycles of each operation
•
Demonstrate the calculation of MCU time from the clock cycles
PROGRAM
The program does the following:
(i) Define variable DELAY at
$0000
(ii) Load DELAY into accB
(iii) Decrease accB by 1
(iv) Branch back to (iii) if the
result is higher than zero
(unsigned >0)
(vi) SWI
Flowchart 5 point(s)
Code 4 point(s)
FLOWCHART
Draw a flowchart for the program in the space provided above.
CODING
Type the essential code for this program in the space provided above. Code the program in to the
personalized file LASTNAME_Firstname_delay.asm using the standard template.
EXECUTION
Open THRSim11. Close the Commands window. Open the memory window. Open and assemble
LASTNAME_Firstname_delay.asm. Tile windows, set breakpoint, and reset registers. Set standard
labels (Label/Set Standard Labels). Set display of memory DELAY to decimal. Optimize the look of
your screen.
x) Put 3 into variable DELAY by modifying it’s corresponding value in the memory list.
Insert your screen: 1 point(s)
Note the value of “Clock Cycles”. .
Dr. Victor Giurgiutiu
Page 330
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DELAY
y) Step to the subroutine and after each step observe the number of cycles taken by each
operation. Enter these values in Table 1. Look up the opcodes in the Motorola
MC68HC11 Programming Reference Guide pocketbook and verify the numbers in
the ‘Cycles’ column of the Instructions table with the numbers that you entered in
Table 1. Put a check mark here ____ when you did so. Did it agree? ___Y;
____N
1 point(s)
z) After each pass through LABEL1, accB is decremented by one. When reaching the
branch instruction BHI, the program branches back to LABEL1 if the result of the
decrementation is still higher than zero. After the first pass, accB was decremented
from 3 to 2. The screen looks like this: (Insert your screen) 1 point(s)
Note that clock cycles counter shows 12. This number is made up as follows: 2+2+3+2+3=12. During
this pass, accB was decremented from $03 to $02. These are illustrated in the table below:
Table 11 Cycles count table, actual and cumulative, opcode by opcode, after pass 1.
NOP
????
????
??????
????
BHI
????
SWI
AccB end
cumulative
Actual
cumulative
Actual
cumulative
2
Actual
cumulative
2
cumulative
Actual
AccB start
Actual
Pass 1
$03
START
$02
After the second pass, paste your screen below: 1 point(s)
Note that value of the clock cycles counter. Explain how is this number made up.
Fill in the entries for Pass 1 and 2 in the table below. 28 point(s)
Table 2
Cycles count table, actual and cumulative, opcode by opcode, after pass 2.
Pass 1
Pass 2
AccB start
START
NOP
????
LABEL1 ????
BHI
Dr. Victor Giurgiutiu
????
????
Page 331
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DELAY
SWI
AccB end
Repeat for the other passes, until the program exits the loop and reaches SWI. Each time:
Paste your screen at the end of the pass. 1 point(s)
Paste an updated table 28 point(s)
Explain what happens 4 point(s)
Derive a formula for calculating the number of cycles. Write the formula below 8 point(s)
N_cycles=??+DELAY*?? =
a) Reset the simulator. Run the program by pressing the Run button. The program stops when accB
has been reduced to zero. Record the values shown on the task bar:
Simulated time = ________ sec = _______ micro-sec 2 point(s)
Clock Cycles = ________
2 point(s)
b) Reset the simulator. Put value 20 in DELAY.
c) Predict the number of cycles with your formula N_cycles=??+DELAY*??=?+???*??=???
2 point(s).
Calculate the time D_t=N_cycles*0.5=??*0.5=??? micro-sec=???????? sec.
2 point(s)
d) Run the program. Insert screen capture when it stops: 1 point(s)
e) Record the values shown on the task bar:
Simulated time = ________ sec = _______ micro-sec 3 point(s)
Clock Cycles = ________
3 point(s)
Do these values agree with your predictions? ___Y ____N 3 point(s)
Dr. Victor Giurgiutiu
Page 332
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DELAY
WHAT YOU HAVE LEARNED
In this example, you have learned:
• The use of variables
•
The use of labels and branching
•
The flowchart and its relation with the program tasks list and program code
•
Calculation of clock cycles from the clock cycles of each operation
•
Calculation of MCU time from the clock cycles knowing that each clock cycle lasts 0.5 microsec
•
How to read clock cycles and simulated time in the simulator window
•
How to write a delay (wait) program
•
New words and notations: variables, labels, branch, clock cycles, MCU time.
Dr. Victor Giurgiutiu
Page 333
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SQUARE WAVE
EXERCISE SQUARE WAVE
OBJECTIVE
This exercise has the following objectives:
• Review the use parallel ports
•
Illustrate the generation of a square wave using Port B output and a waiting sequence
•
Demonstrate the use of a subroutine to shorten the length of a program
•
Examine the relation between displayed simulation time and clock cycles in THRSim11 simulator
PROGRAMS
This exercise uses two programs that produce the same output – the generation of a square wave of
programmable wavelength. The wavelength is programmed using the variable DELAY. The square-wave
electrical signal is output through first pin of Port B, i.e., pin PB0. The difference between the first and
second program consist in the use of a subroutine. The use of a subroutine compresses the code and
shortens the total length of the program.
PROGRAM SQ_WAV1
Instructions
Flowchart 6 point(s)
Code 6 point(s)
Define variable DELAY at $0000
Load REGBAS in reg. X
Send low signal through PB0
Load %00000000 in accA
Store accA in Port B
Load DELAY into accB
Decrease accB in a loop until zero
Send high signal through PB0
Load %???????? in accA
Store accA in Port B
Load DELAY into accB
Decrease accB in a loop until zero
Branch back to (iii)
SWI
FLOWCHART
Draw a flowchart for the program in the space provided.
CODING
Type the essential code for this program in the space provided above. Code the program in the
THRSim11 using the standard template and save it in the personalized file
LASTNAME_Firstname_Sq_wav1.asm. Store it on floppy disk.
Dr. Victor Giurgiutiu
Page 334
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SQUARE WAVE
EXECUTION
Open THRSim11. Close the Commands window. Open memory list, port registers, and THRSim11 IO
box. Open and assemble your LASTNAME_Firstname_Sq_wav1.asm. Set breakpoint at SWI, and reset
registers. Set standard labels (Label/Set Standard Labels). Set display of accA to binary. Set display of
PORTB to binary. Tile windows. Arrange windows for maximum benefit: Reset DELAY. Paste your
screen below: 1 point(s)
Table 1
Time, ⎠ s
DELAY
State
Clock cycles
T_1
T_2
⎠N
⎠ T ⎠ N⎠/ T ⎠ T⎠/ N
N_1 N_2
$03
Initialize
2
11
1.0
5.5
9
4.5
L
0.5
11
40
29
5.5
20.0 14.5 2.0
H
0.5
40
72
32
20.0
36.0 16.0 2.0
L
0.5
72 101
29
36.0
50.5 14.5 2.0
H
0.5
101 133
32
50.5
66.5 16.0 2.0
L
0.5
133 162
29
66.5
81.0 14.5 2.0
H
2.0
0.5
162 194
32
81.0
97.0 16.0
$30
Initialize
2
11
1.0
5.5
9
4.5
L
0.5
11 340
329
5.5 170.0 164.5 2.0
H
0.5
340 672
332 170.0 336.0 166.0 2.0
L
0.5
672 1001
329 336.0 500.5 164.5 2.0
H
0.5
1001 1333
332 500.5 666.5 166.0 2.0
L
0.5
1333 1662
329 666.5 831.0 164.5 2.0
H
2.0
0.5
1662 1994
332 831.0 997.0 166.0
Note: (i) The numbers in the table are not real. You need to substitute them with your actual numbers.
(ii) This is an Excel table, and it has formulae in it. You only need to fill in the N_1 and T_1
values on the Initialize row, and the N_2 and T_2 values in all the rows.
a) Put $03 into variable DELAY. Reset the simulator.
The PORTB register is %???????? 1 point(s)
The lights in the THRSim11 IO box are ____off ____on ? 2 point(s)
b) Record the initialization readings:
Clock cycles = _____ 3 point(s)
Simulated time = ___________ sec = ___ μs.
3 point(s)
c) Make one step through the program. Explain what happens: _____ 3 point(s)
d) Step through the program until PORTB has been loaded with %00000000. Record the start up
readings:
Dr. Victor Giurgiutiu
Page 335
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SQUARE WAVE
Clock cycles = _____ 2 point(s)
Simulated time = ___________ sec = ___ μs.
2 point(s)
Enter these values as N_2 and T_2 in the Initialize row, and as N_1 and T_1 in the first (L) row of
Table 1..
e) Step through the program until PORTB gets set. The value is %__________1 point(s)
The light PB___1 point(s) in THRSim11 IO box turns on. Paste your screen: 1 point(s)
Record the clock cycles and the simulated time as N_2 = ___ and T_2 = ____ and enter these values in
Table 1. 4 point(s)
(You should notice that Table 1, which is in Excel, automatically puts these values also as N_1 and T_1
on the next row.)
Compute:
ΔN = ___
2 point(s)
ΔT = ____
2 point(s)
ΔN/ΔT = ____
2 point(s)
ΔT/ΔN = _____.
2 point(s)
f)
Step through the program until PORTB becomes again %00000000 and PB0 in THRSim11 IO
box turns off. 1 point(s)
Record the clock cycles and the simulated time as N_2 and T_2 in Table 1. Observe ΔN, ΔT, ΔN/ΔT,
ΔT/ΔN.
g) You are now again in a low-signal state. Step through the program until the light PB? comes on
again. 1 point(s)
Record N_2 and T_2 and enter them into Table 1.
h) Repeat this until all the rows in Table 1 have been observed and recorded. Check if the ratios
ΔN/ΔT and ΔT/ΔN are consistently 2.000 and 0.500, as theoretically predicted. ___Y ____N 1
point(s) ?
i)
Also, record the half-wave durations of your square wave.
The low (L) portion of the signal has:
______ cycles
2 point(s)
_____ μs,
1 point(s)
The high (H) portion has:
Dr. Victor Giurgiutiu
______cycles,
2 point(s)
_______ μs.
1 point(s)
Page 336
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SQUARE WAVE
Explain what happens: 2 point(s)
What is this observation is important for ________________________ 2 point(s)
j)
Set breakpoints in the program at the following instances:
•
When the low signal is being loaded
•
When the high signal is being loaded
What do these points correspond to: 2 point(s)
What will these breakpoints allow us to do: 2 point(s)
k) Reset the MCU. Record again the clock cycles and simulated time, and verify that they
correspond to the N_1 and T_1 on row ‘$03 Initialize’ in Table 1.
l)
Run to the first breakpoint. Verify that N_2 and T_2 are the same as before. Do they agree?
___Y ____N. 1 point(s)
m) Run to the next breakpoint. You have run through the first L lap. Enter N_2 and T_2 in Table 2
and verify that they are the same with those entered in Table 1. Do they agree? ___Y ____N. 1
point(s)
n) Run to the next breakpoint. You have run through the first H lap. Verify that N_2 and T_2 are the
same as before. Do they agree? ___Y ____N. 1 point(s)
o) Repeat until you have exhausted the $03 portion of Table 2.
Observe the ratios ΔN/ΔT and ΔT/ΔN. Compare with the theoretical values:
ΔN/ΔTtheory = ????? 1 point(s)
ΔT/ΔNtheory = ???? 1 point(s)
p) Put $30 into the variable DELAY. Reset the simulator. Repeat the above procedure. Observe
and enter the values of N-2 and T_2 in Table 1, under the $30 section.
Observe the wavelengths of the L and H parts of the square wave. They are ____ μs and ____ μs,
respectively.2 point(s)
Calculate the durations of the L and H half-waves for short delay ($03) and long delay ($30):
Short delay: ΔTL = ____ μs, ΔTH = ____ μs, difference = % 2 point(s)
Long delay: ΔTL = ____ μs, ΔTH = ____ μs, difference = % 2 point(s)
Observe the ratios ΔN/ΔT and ΔT/ΔN. Are there any deviations from the theoretical values: ___Y ____N.
1 point(s)
Dr. Victor Giurgiutiu
Page 337
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SQUARE WAVE
Program SQ_WAV2
Instructions
Flowchart 6 point(s)
Code 6 point(s)
I
i)
Define variable DELAY at
$0000
Load REGBAS in reg. X
Send low signal
Load %00000000 in accA
Store accA in Port B
Jump to subroutine WAIT
Send high signal
Load %???????? in accA
Store accA in Port B
Jump to subroutine WAIT
Branch back to (iii)
SWI
ii)
Subroutine WAIT
??????
FLOWCHART
Draw a flowchart for the program in the space provided above.
CODING
Type the essential code for this program in the space provided above. Code the program in the
THRSim11 using the standard template and save it in the personalized file
LASTNAME_Firstname_Sq_wav2.asm. Store it on floppy disk.
EXECUTION
Open THRSim11. Close the Commands window. Open memory list, port registers, and THRSim11 IO
box. Open and assemble your LASTNAME_Firstname_Sq_wav1.asm. Set breakpoint, and reset registers.
Set standard labels (Label/Set Standard Labels). Set display of accA to binary. Set display of PORTB to
binary. Tile windows. Arrange windows for maximum benefit: Reset DELAY, A, B, X.
DO NOT RESET THE SP (stack pointer) REGISTER, BECAUSE, IF YOU DO SO, ACCESS TO
YOUR SUBROUTINE WILL NOT WORK.
i)
Put $03 into variable DELAY. Reset the simulator. The PORTB register is %00000000, and all the
lights in the THRSim11 IO box are off. Step through the program until you jump to subroutine.
j)
Step through the subroutine until you get to RTS and are ready to jump back to the program.
k) After another step, you are back into the main program.
l)
As you step further, you observe that the Port B pin 0 is toggled, and the light PB0 in the IO box
comes on. The main program is again ready to jump to the subroutine.
m) Further stepping takes you again inside the subroutine, and out again.
n) Run the program on automatic. You will notice how the subroutine is accessed every time the PB0
light changes.
Dr. Victor Giurgiutiu
Page 338
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SQUARE WAVE
o) Put breakpoints at the two JSR lines. Run the program on automatic, and record in Table 2 the
values recorded for DELAY = $03, and for DELAY = $30. Compare these values with those in Table
1. 5 point(s)
Table 2
DELAY
State
$03
Initialize
L
H
L
H
L
H
Initialize
L
H
L
H
L
H
$30
Clock cycles
N_1
N_2
2
11
11
51
51
94
94
134
134
177
177
217
217
260
2
11
11
351
351
694
694 1034
1034 1377
1377 1717
1717 2060
N
9
40
43
40
43
40
43
9
340
343
340
343
340
343
Time, s
T_1
T_2
1.0
5.5
5.5
25.5
25.5
47.0
47.0
67.0
67.0
88.5
88.5 108.5
108.5 130.0
0.0
5.5
5.5 175.5
175.5 347.0
347.0 517.0
517.0 688.5
688.5 858.5
858.5 1030.0
T
4.5
20.0
21.5
20.0
21.5
20.0
21.5
5.5
170.0
171.5
170.0
171.5
170.0
171.5
N ⌠T
T ⌠N
2.000
2.000
2.000
2.000
2.000
2.000
0.500
0.500
0.500
0.500
0.500
0.500
2.000
2.000
2.000
2.000
2.000
2.000
0.500
0.500
0.500
0.500
0.500
0.500
Note: (i) The numbers in the table are not real. You need to substitute them with your actual numbers.
(ii) This is an Excel table, and it has formulae in it. You only need to fill in the N_1 and T_1
values on the Initialize row, and the N_2 and T_2 values in all the rows.
p) Compare the values from Table 2 with those in Table 1. Discuss what you notice:
i) For same delay values, the difference between the results of Table 2 and Table 1
consists of: … 5 point(s)
ii) In Table 2, the difference between the durations of the L and H half waves for short
delays and for long delay is explained as follows: … 5 point(s)
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• The use of Port B
•
The use of displayed clock cycles and simulated time, to track the duration of Low and High
signal half waves in a square wave
•
The usefulness of subroutines for shortening programs
•
The use of Port B to generate a square wave
•
New words and notations: subroutine, jump to subroutine, return from subroutine, square wave,
wavelength.
Dr. Victor Giurgiutiu
Page 339
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise BUTTONS BOX
EXERCISE BUTTONS BOX
GOALS AND OBJECTIVES
The goal of this exercise is to review the use of the parallel ports as an input/output (I/O) device.
Registers that control the parallel ports will be explored. A 4-button 4-LED box will be used as a
communications link. This exercise has the following objectives:
• Review the use of parallel ports
•
Illustrate the use of Port C for input and output
•
Introduce the concept of shifting register and memory content
•
Practice the use of the THRSim11 IO box for input and output
BASIC CONCEPTS
a)
Define in your own words a PARALLEL port. 6 point(s)
b)
How many parallel ports are on the M68HC11 ? _______________________6 point(s)
c)
What are they called? ____________________________________________6 point(s)
d)
What is the difference between them? _______________________________6 point(s)
e)
What are the memory locations that are used by each of them? ___________________
______________________________________________________________6 point(s)
f)
What is DDRC called and how does it work? __________________________________
______________________________________________________________6 point(s)
g)
If you place $fa in DDRC at address $1007 and then load $cf into PORTC at address $1003, what
will the output of parallel Port C be? Fill the result into the table. 12 point(s)
DDRC
pins
Value
Port C
pins
Value
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
PC7
PC6
PC5
PC4
PC3
PC2
PC1
PC0
PROGRAM BUTTONS_BX
This program demonstrates the use of Port B for output and of Port C for both input and output. Port C is
configured to have the pins PC1, PC3, PC5, PC7 for output. This is achieved using the Data Direction
Register for port C (DDRC). Since the default setting for Port C is input, the pins that have to be set to
output have their image set to 1 in DDRC. In our case, the bits ?, ?, ?, and ? of DDRC are set to 1. Thus,
the Port C pins PC1, PC3, PC5, PC7 become output, while pins PC0, PC2, PC4, PC6 remain input.
Dr. Victor Giurgiutiu
Page 340
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise BUTTONS BOX
The program loops continuously, reading data from the some Port C pins, and sending data back to the
other Port C pins. Simultaneously, the data is also sent to Port B.
Instructions
a)
Load REGBAS in reg. X
b)
Clear port B by storing zero
in it
Flowchart 17 point(s)
Code 17 point(s)
Select ??? Port C pins for output
c)
Load %???????? in accB
d)
Store accB to DDRC
e)
Load Port C to accB
Main loop
f)
Shift accB to the left
g)
Store accB to Port C
h)
Store accB to Port B
i)
Branch back to (v)
j)
SWI
FLOWCHART
Draw a flowchart for the program in the space provided above.
CODING
Use the flowchart to code your program in the simulator. Write or paste your coded program in the space
provided. Code the program in to the personalized file LASTNAME_Firstname_Buttons_bx.asm using
the standard template.
EXECUTION
Open THRSim11. Close the Commands window. Open port registers and THRSim11 IO box. Open your
program. Before assembling your program, disactivate the “Store accB to Port C” instruction by putting *
at its beginning (see the code in Example Button Box). Set breakpoint, and reset registers. Set standard
labels (Label/Set Standard Labels). Set display of accB to binary. Set display of PORTB and PORTC to
binary. Tile windows. Arrange windows for maximum benefit. Paste your screen below:
a) Before you run the program, verify the Port C pins functionality. In the THRSim11 IO box, toggle
up the switch PC2. You will see that the corresponding bit in Port C register, bit ?, becomes 1
immediately. Paste your screen below: 3 point(s)
b) Toggle down the switch PC2 in the IO box.
c) Run the program. The program will loop continuously between label ?????? and opcode
??????. 6 point(s)
d) With the program running, toggle up the switch PC2 in the IO box. Immediately, bit ? (3
point(s))in PORTC will switch to one. Simultaneously, pin ? in PORTB will become 1, and the
Dr. Victor Giurgiutiu
Page 341
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise BUTTONS BOX
light PB? (3 point(s)) in the IO box will lit. Press the stop button and capture the screen. Paste
your screen below: 3 pointa(s)
e) Try to toggle other PC switches in the IO box. You will notice that now only the even switches
(PC0, PC2, PC4, PC6) are producing the setting of the corresponding bits in PORTC register.
The odd switches (PC?, PC?, PC?, PC?) can be toggled, but with no effect on the PORTC
register. This illustrates how DDRC controls PORTC register.
f)
Restart the program by pressing the Run button. With the program running, try to toggle the
other switches. You will notice that the toggling of the even switches (PC?, PC?, PC?, PC?) has
the effect of switching on the odd Port B lights (PB?, PB?, PB?, PB?). This is the result of the
data from the odd Port C pins is loaded in accB, left shifted, and sent back to Port B.
g) Finally, re-activate the line “store accB to Port C” by removing the *. This makes your program
ready to be used in Lab2.
WHAT YOU HAVE LEARNED
In this exercise, you have learned:
• The use of PORTC for input and output
•
The concept of shifting a register
•
The use of the THRSim11 IO box for both input and output
•
New words and expressions: toggle switch; shift a register, shift data.
Dr. Victor Giurgiutiu
Page 342
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise BUTTONS BOX
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 343
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SERIAL COMMUNICATION
EXERCISE -- SERIAL COMMUNICATION
OBJECTIVE
The objective of this homework is to learn how to use the serial communication port of the M68HC11:
• Basic concepts of serial communications are reviewed.
•
The BAUD rate and other aspects of the serial communications interface (SCI) are investigated.
•
The registers used to transmit and receive serial communications data are examined
•
The TDRE and RDRF flags used to identify whether or not serial communications data has been
transmitted or received are used
•
The concept of echo is developed
BASIC CONCEPTS
1)
Describe in your own words, using formulae or diagrams, as needed:
a) Baud Rate: 2 point(s)
b) Start Bit: 2 point(s)
c) Stop Bit: 2 point(s)
d) ASCII Code: 2 point(s)
e) BCD code 2 point(s)
2)
Using the chart in the back of M68HC11 Quick Reference Manual, write the ASCII code in hex
and in 8-bit binary for the following characters: 16 point(s)
Character
a
&
P
6
3)
ASCII
$61
Binary
01100001
Character
DEL
D
#
x
ASCII
Binary
Convert the following decimal numbers into BCD and hex formats: 16 point(s)
Number
80
08
65
84
Dr. Victor Giurgiutiu
BCD
1000 0000
Hex
$50
Binary
%01010000
Page 344
Number
32
78
89
00
BCD
Hex
Binary
8/19/2008
EMCH 367
4)
Fundamentals of Microcontrollers
Exercise SERIAL COMMUNICATION
Consider the character 'Q' being transmitted through serial communication. Sketch and label the
ten bits that make up this communication (the serial-data word). 3 point(s)
Label
Value
5)
Name and briefly describe the five Serial Communications Interface (SCI) registers. 8 point(s)
6)
Briefly describe the functions of the RE and TE bits in the SCI. 2 point(s)
7)
The following questions refer to RDRF:
a) Describe in your own words the function of RDRF 2 point(s)
b) In what register is it located? 2 point(s)
c) How does one write a program to check the status of RDRF? 2 point(s)
d) How is RDRF cleared? 2 point(s)
The following questions are related to TDRE:
8)
a) Describe in your own words the function of TDRE. 2 point(s)
b) In what register is it located? 2 point(s)
c) How does one write a program to check the status of TDRE? 2 point(s)
d) How is TDRE cleared? 2 point(s)
PROGRAM ECHO
Note: This program is based on the examples SCI_recept and SCI_transm. In fact, it can be assembled
from these two examples. Before performing the present programming, review, duplicate, and operate
the coding in examples SCI_recept and SCI_transm.
• The program ECHO will continuously check if the MCU has received the transmission signal
from the terminal keyboard here simulated by the serial transmitter.
•
When keyboard transmission is received, the binary pattern of the character’s ACII code will be
sent to Port B for display. This way, you will check that the bit pattern corresponds to that from
the ASCII table.
Dr. Victor Giurgiutiu
Page 345
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SERIAL COMMUNICATION
•
Then, the character is transmitted back to the terminal to be displayed on the monitor screen here
simulated by the serial receiver.
•
To achieve synchronization with lab equipment during future use of this program in the lab, a
sync pulse (low-high-low) is generated in Port C just before the serial transmission.
INSTRUCTIONS
i.
viii.
ix.
Set the BAUD register to 9600 and the SCCR1 to 8 bits. (This step is not necessary
when connecting to the microcontroller through MiniIDE, but it must be included in order
to run this program on the simulator.)
Initialize the serial communication interface (SCI) for reception and transmission
Initialize all Port C pins for output
Branch in place until the reception data register is full (i.e., branch back if RDRF is not
set). This checks if the SCI transmission has been received.
Continue when the SCI transmission has been received
Load the key code into AccB and send it out through PORTB. This will be shown on the
IOBox LED display.
Branch in place until the transmission register is empty (i.e., branch back if TDRE is not
set). This checks if the transmission can take place.
Send out a low-high-low pulse through PORTC.
Send back the character (echo) through SCI.
x.
Loop continuously from (vii)
ii.
iii.
iv.
v.
vi.
vii.
FLOWCHART
Draw a flowchart for the program in the space provided.
CODING
Use the flowchart to code your program in the simulator using the standard template.. Save the program
in the personalized file name LASTNAME_Firstname_Echo.asm. Write or paste your coded program in
the space provided.
Flowchart 11 point(s)
Dr. Victor Giurgiutiu
Code 10 point(s)
Page 346
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise SERIAL COMMUNICATION
EXECUTION
Open THRSim11. Close the Commands window. View ports registers and serial registers. View serial
transmitter and receiver. View IO box. Open and assemble your program. Set breakpoints as follows:
• After RDRF has been detected and its loop exited
•
After TDRE has been detected and its loop exited
•
At SWI
Reset registers. Set standard labels (Label/Set Standard Labels). Set display of BAUD, SCCR1, SCCR2,
SCSR to binary. Set display of accA to binary. Set display of ports B and C to binary. Arrange windows
for maximum benefit: Reset, A, B, X, PORTB, PORTC. Press the RESET button. Paste your screen: 1
point(s)
a) Fill in the ASCII codes for each key listed in Table 1. 7 point(s)
Table 1
Key
Q
ASCII code
51
IO box
MSBÆLS
8- LED pattern B01010001
Equivalent Hex
$51
values
Agreement (Y/N)
Y
2
5
B
b) Run your program in the simulator. The program should be looping at the beginning showing
that it is waiting on a keystroke.
c) Once the program is running, enter the letter Q into the serial transmitter window and click Send.
This means that the letter Q is being sent to the microcontroller. After a few moments, the letter
Q should begin appearing in the serial receiver window. This means that the microcontroller has
sent the letter Q back to the terminal.
*You should see the ASCII code for the character Q represented by the red lights in the IO box
and by the values in the Port B pins window.
*You can also detect a “flicker” of the Port C switches in the IO box and a “flicker” of the
values in the Port C pins window as the program sends out the High-Low-High pulse each time
the character is transmitted.
Repeat with the other keys mentioned in Table 1 and check that your program runs successfully.
If you do not get the desired results, debug your program. If you cannot solve the problems,
please contact your TA.
Dr. Victor Giurgiutiu
Page 347
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise TIMER FUNCTIONS
EXERCISE TIMER FUNCTIONS
GOALS AND OBJECTIVES
This exercise will practice the MC6811 functions for time measurements. Input capture (IC) and output
compare (OC) functions will be reviewed and applied to measure a bolt drop and to generate a square
wave.
Part I will review the groundwork. Part II will perform time measurements on a dropping bolt using
input capture (IC) timer functions. Part III will generate a square wave using output compare (OC) timer
functions.`
PART I -- BASIC CONCEPTS
1)
How long are the timer registers? ____________ bits; __________hex digits 2 point(s)
2)
How many memory locations are needed to store one timer information? ___________ 1 point(s)
3)
How are the timer flags reset (cleared)? _____________________________________2 point(s)
4)
Describe the free-running time counter (TCNT) concept: 2 point(s)
Answer:
a) What is the reset value of TCNT? __________ 1 point(s)
b) Can the free-running counter be stopped while MCU is on: ____Y ______N 1 point(s)
c) How long does a count last? ______ μs 1 point(s)
d) How many bits are in TCNT? _________1 point(s)
e) What is the greatest hex number that can appear in TCNT? ___________ 1 point(s)
f) What happens after TCNT has reached its maximum value?____________________________
___________________________________________________________________2 point(s)
g) What is the maximum time duration that TNCT can measure between two consecutive overflows?
___________ μs = ___________ ms. 2 point(s)
h) What is the name and the function of TOF? Name: _____________ Function: __________
___________________________________________________________________3 point(s)
i) Where is TOF located? __________________________1 point(s)
j) What is the mask for TOF? %_____________________1 point(s)
5)
Input Capture Function
a) Describe the Input Capture (IC) concept: __________________________________________
__________________________________________________________________2 point(s)
b) How many IC registers are there and what are their names? ___________________3 point(s)
c) What happens with the IC registers at MCU reset? __________________________1 point(s)
d) Can you change the value in an IC register? ____Y _________N 1 point(s)
e) Where are the input capture flags (ICxF) located? __________________________1 point(s)
Dr. Victor Giurgiutiu
Page 348
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise TIMER FUNCTIONS
f) When do the input capture flags (ICxF) get set? ___________________________________
_________________________________________________________________1 point(s)
g) What are the masks for the input capture flags? Fill in the table: 3 point(s)
IC1F
IC2F
IC3F
%
%
%
h) What is the name of EDGxB and EDGxA bits ? _____________________1 point(s)
i) Where are EDGxB and EDGxA bits located? _______________________1 point(s)
j) What function do EDGxB and EDGxA perform? _____________________1 point(s)
6)
Output Compare Function
k) Describe the output compare concept: ____________________________2 point(s)
l) How many OC registers are there and what are their names?
___________________________________________________________5 point(s)
m) What happens with the OC registers at MCU reset? _________________________1 point(s)
n) Where are the output compare flags (OCxF) located? _______________________1 point(s)
o) When do the output compare flags (OCxF) get set? _________________________1 point(s)
p) Can you change the value in an OC register? ___________Y _________N
1 point(s)
q) Where are the OMx, OLx bits located? ___________________________________1 point(s)
r) What do the OMx, OLx bits do? _________________________________________1 point(s)
s) What are the masks for output compare flags (OCxF)? Fill the table below: 5 point(s)
OC1F
OC2F
OC3F
OC4F
OC5F
Dr. Victor Giurgiutiu
%
%
%
%
%
Page 349
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise TIMER FUNCTIONS
PART II: INPUT CAPTURE – BOLT DROP EXPERIMENT TIMER PROGRAM
Note: This program is based on the example Ex_IC and
Figure 1 Bolt drop experimental setup
previous examples regarding the use of Port B and of SCI.
Before performing the present program, review, run, and
thoroughly understand the coding in example Ex_IC.
MC6811 will be used in an experiment to measure travel
times. A 1.5-in bolt will be held by an electromagnet at the
top of a drop shaft. The electromagnet is connected to the
MCU. This magnet is controlled by any of the 8 pins on
PORTB. It is turned on by sending 5V through parallel
PORTB. When a keystroke occurs, the MCU commands
the electromagnet to release the bolt. Simultaneously, the
time origin, T0, is recorded. The bolt travels down the shaft.
After falling a specified distance (L = 48.75-in), the bolt
crosses an infrared emitter-detector sensor and interrupts its
beam causing its output voltage to fall from high (+5V) to
low (~0V). When the bolt exits the emitter detector sensor,
its output voltage comes back up to high (+5V). The output
from the emitter-detector sensor is wired into the input
capture pins IC1 and IC2 of the MCU. You will program
the microprocessor to perform the following functions:
(a) Control the electromagnet
Electromagnet
Drop shaft
Electronics
(b) Take the initial time when the process starts
(c) Measure the time when the free-falling bolt reaches
the emitter-detector
(d) Measure the time the bolt passes through the
emitter-detector
7)
Emitter-detector
sensor
Using basic Physics -- Mechanics, calculate the theoretical time for the bolt to drop (time or
arrival), t1, the theoretical instantaneous velocity of the bolt when entering the emitter-detector
sensor, v1, the theoretical time of exit, t2, and the time it takes the bolt to completely pass through
the emitter-detector, Δt. Show your work below: 5 point(s)
t1 = _________ ms, v1 = ________ in/s,
Dr. Victor Giurgiutiu
t2 = ________ ms,
Page 350
Δt = ________ ms
8/19/2008
EMCH 367
8)
Fundamentals of Microcontrollers
Exercise TIMER FUNCTIONS
You are looking for two separate types of signal transition from the emitter-detector. Based on the
description above:
a) What is the type of the first transition observed on the emitter detector sensor (i.e., when the bolt
enters the emitter detector sensor)? _____________ (1 point(s)) Sketch the signal below
(1 point(s)). This transition will be attached to IC1. What values do you attach to EDG1B and
EDG1A? Enter the answer in the table below. (1 point(s))
EDG1B
EDG1A
b) What is the type of the second transition observed on the emitter detector sensor (i.e., when the bolt
exits the emitter detector sensor)? _____________ (1 point(s)) Sketch the signal below
(1 point(s)). This transition will be attached to IC2. What values do you attach to EDG2B and
EDG2A? Enter the answer in the table below. (1 point(s))
EDG2B
EDG2A
Where are IC1 and IC2 located (port and pin)? Enter your answer here: ________________(2 point(s))
9)
Draw a flowchart (draw it on the next page) to do the following:
i)
Set up the following variable names and locations
• TIME0 @ $0000 & $0001
• TIME1 @ $0002 & $0003
• TIME2 @ $0004 & $0005
• NOF1 @ $0006
• NOF2 @ $0007
ii)
Set the EDGA and EDGB bits of the TCTL2 register for the signal transitions that you
expect to see on IC1 and IC2 as discussed above.
iii)
Turn the electromagnet on. This magnet is controlled by any of the 8 pins on PORTB. It
is turned on by sending 5V through all the pins of the parallel PORTB. (Subsequently, it
is turned off by sending 0V through PORTB.)
iv)
Wait for a key to be pressed.
v)
When a key is pressed, have the electromagnet turn off and store the value of the timer
counter (TCNT) in TIME0.
vi)
Keep track of the time it takes for the bolt to fall from the magnet until it enters the beam
of the emitter-detector sensor. Keep track of the number of timer overflows that occur
until the first input capture occurs by incrementing NOF1 and NOF2.
vii)
Store the value of the timer counter TIC1 when the bolt enters the emitter-detector sensor
into TIME1.
viii) Store the value of the timer counter TIC2 when the bolt leaves the emitter-detector sensor
into TIME2. Keep track of the number of timer overflows that occur until the second
input capture occurs by incrementing NOF2.
Dr. Victor Giurgiutiu
Page 351
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
ix)
Exercise TIMER FUNCTIONS
End Program.
FLOWCHART
Below, draw a flowchart for your program.5 point(s)
CODING
Use the flowchart to code your program in the simulator using the standard template. Save the program
in the personalized file name LASTNAME_Firstname_Drop.asm. Write or paste your coded program
below. 5 point(s)
EXECUTION
Open THRSim11. Close the Commands window. View ports registers and serial registers, serial
transmitter, serial receiver, IO box, Port A pins, timer registers, memory locations$0000-$0007. Set
display of TCTL2, TFLG1, TFLG2 to binary. Arrange windows for maximum benefit: Open and
assemble your program. Reset. Set standard labels. Set breakpoints as follows:
• Just after the bolt has been released
•
Just after the first input capture
•
Just after the second input capture
•
At SWI
i)
Toggle the value of Pin PA2/IC1 from "0" to "1" by double clicking on it. This simulates the
signal that the Input capture registers are from the emitter detector sensor.
ii)
Run your program in the simulator. The program should be looping at the beginning showing that
it is waiting on the keystroke. You should also notice the value of Port B in the I/O box. The red
lights should be on, ensuring that of the electromagnet is on.
iii)
Once the program is running, enter character S into the serial transmitter window and click Send.
The keystroke detection loop should be exited, and your program should stop at the first
breakpoint.
iv)
Step through the program. Port B lights should turn off and the value of the TCNT should be
stored in TIME0.
v)
Run. The program should then begin the loop looking for the first input capture, while also
verifying for timer overflows and incrementing NOF1 when they occur. Let this part of the
program run for a while. Watch as the TCNT changes from $ffff to $0000. This should cause your
program to increment your timer overflow counters NOF1 and NOF2.
vi)
Trigger the first input capture by toggling the value of Pin PA2/IC1 in the Port A Pins window
from "1" to "0" (double clicking on it). The MCU should see this as the awaited transition on IC1,
and the flag IC1F flag should get set. The first input capture loop should be exited, and your
program should stop at the breakpoint.
Dr. Victor Giurgiutiu
Page 352
8/19/2008
EMCH 367
vii)
Fundamentals of Microcontrollers
Exercise TIMER FUNCTIONS
Step through the program. Observe the value of TIC1 be stored in TIME1.
viii) Run again. Your program should loop looking for the second input capture, while also verifying
for timer overflows and incrementing NOF2 when they occur.
ix)
Trigger the second input capture by changing the value of Pin PA1/IC2 in the port A Pins window
from "0" to "1". This should cause the second input capture loop to be exited and the program to
stop at the next break point.
x)
Step through the program and watch the value of TIC2 being stored in TIME2. Your program
should terminate.
xi)
Reset and run your program again. This time, after each stop at the breakpoint, simply press the
run button and let it go on. Verify that your program runs well. Do any corrections necessary.
PART III: OUTPUT COMPARE – SQUARE WAVE GENERATION
Note: This program is based on the example Ex_OC. Before performing the present program, review,
run, and thoroughly understand the coding in examples Ex_OC.
You want to generate a square wave using the MCU output compare timer function OC5. The half
wavelength duration, in machine cycles, should be stored in the double-precision variable DT. The Low
and High states of the square wave will be created by toggling the OC5 pin at DT intervals.
a) Indicate the Port and Pin value where OC5 is located ________________________2 point(s)
b) Indicate the values of OM5 and OL5 that will ensure toggle: OM5___ OL5 ____
2 point(s)
c) Draw a flow chart (draw it on the next page) to perform the following:
i)
Set the OM5 and OL5 pins of the TCTL1 to toggle
ii)
Add DT to TCNT and store it in TOC5
iii)
Loop until successful output compare happens on OC5
iv)
Add DT to TCNT and store it in TOC5
v)
Loop back.
vi)
Branch back to iii).
FLOWCHART
5 point(s)
CODING
Use the flowchart to code your program in the simulator using the standard template. Save the program
in the personalized file name LASTNAME_Firstname_OC_sqwav.asm. Write or paste your coded
program below. 5 point(s)
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, timer registers, port A pins,
memory list. Open and assemble your program. Set breakpoints at
Dr. Victor Giurgiutiu
Page 353
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
•
Just after output compare happens
•
At SWI
Exercise TIMER FUNCTIONS
Reset registers and memory. Set standard labels. Set display of TCTL1, TFLG1 to binary. Arrange
windows for maximum benefit: Press the RESET button.
a) Run your program and verify it in a manner similar to Ex_OC and verify that it works as
expected
b) Use the calculation patterns of Ex_OC to complete the information in Table 1. Insert your
calculations below. 13 point(s)
Hex Number
Half wavelength
duration (μs)
Frequency (Hz)
T = Theory;
Dr. Victor Giurgiutiu
$0100
$1000
$8000
$a000
$ffff
$
$
T
E
T
250
E
1500
E = Experiment.
Page 354
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise TIMER FUNCTIONS
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 355
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
EXERCISE DC MOTOR TACHOMETER
GOALS AND OBJECTIVES
The objectives of this exercise are:
•
•
•
•
•
•
•
•
•
•
•
To verify the student’s understanding of DC motor functionality
To develop a DC motor tachometer (RPM counter) program to be used in the lab
Review the use of MCU Timer functions (free running clock, TCNT, overflow flag, TOF, input
capture clock, TIC1, and its event flag, IC1F, the selection of signal transition to be captured
(here rising edge, EDG1B) and that the MCU is only sensitive to that particular transition.
Introduce the use of soft masks (here, IC1_MSK, TOF_MSK).
Introduce the concept of layered flowcharting of a program: big-picture with generic
descriptions; detailed flowcharts for particular sections of the program.
Review the use of two time captures to calculate the time duration of an event
Illustrate the use of scaling factors (100s) to deal with numbers that are larger than the
microcontroller word length
Introduce the method of calculating multiplication through repeated additions and
decrementation of a counter
Introduce the use of a conversion subroutine to convert from hex to BCD
Illustrate rotation speed calculation using the recorded period of rotation
Illustrate the use of scaling factors (100s) to present the result on a display with limited number
of digits.
PART I – THEORY OF DC MOTORS (30%)
1)
List all the types of electric motors that you know. Give a one-sentence description of each type. 4
point(s)
2)
Draw a 2-view schematic sketch of a direct current (DC) motor. Identify torque (T), speed (ω,
internal resistance (R), back emf (E), and applied voltage (V). 2 point(s)
3)
Write the relationship between back emf and speed. Sketch this relationship in ω-E coordinates.
2 point(s)
Dr. Victor Giurgiutiu
Page 356
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
4)
Write the relationship between torque and current. Sketch this relationship in I-T coordinates
2 point(s)
5)
Write the expression for heat power that needs to be dissipated from a running DC motor.
max
Assuming the maximum power dissipation is Pdiss
, express the maximum current, Imax, and the
maximum torque, Tmax. 3 point(s)
6)
Write the electrical model of a DC motor. 2 point(s)
a) Derive the expression of speed at a given torque, T 2 point(s)
b) Derive the expression for the no-load speed, ω0. This is the maximum speed that the motor can
run at. 2 point(s)
c) Derive the expression for the zero-speed torque, T0, at a given supply voltage, V. This is the
start-up torque. 2 point(s)
PART II – DC MOTOR TACHOMETER PROGRAM (70%)
Note: This program is based on two examples: Example_RPM_1 and Example_RPM_2. Before
performing the present program, review, run, and thoroughly understand the coding in these examples.
The program that you will construct will be used in Lab 4: DC motor tachometer RPM experiment
(Figure 1). In this experiment, a disk with an aperture (hole) drilled into it is attached to the shaft of a
DC motor. The aperture in the disk spins through an infrared emitter-detector sensor. The emitter-
Dr. Victor Giurgiutiu
Page 357
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
detector sensor sends a High (5V) signal when the aperture in the disk allows the beam of light to pass
through. The output of the emitter-detector sensor is attached to the input capture pin IC1 on Port A.
The speed of the motor is controlled by a potentiometer and to an electronic circuit. The potentiometer is
a variable resistor. By turning the knob of the potentiometer, the speed of the DC motor is varied.
T1 is the first time when a falling edge transition is encountered on pin IC1, while T2 is the second time
when a falling edge transition is encountered on the same pin IC1. This corresponds to the time between
two consecutive passages trough the emitter-detector sensor of the hole in the rotating disk. The
difference between T2 and T1, plus the time taken by the overflows, will represent the period of rotation
of the disk. Hence, one can calculate the rotation speed.
MOSFET
DC
Emitter/Detector
7-Segment Display
Port B
Connection
Lamp Test
555 Timer
Speed-Controlling
Potentiometer
.
Figure 1 DC Motor tachometer experiment to which the present software example is relevant.
7)
Table
Calculate the time between two consecutive passes of the hole through the emitter detector (period
of rotation, τ, in ms, and T in cycles) for various frequencies of rotation (Hz). Show your work
below. Enter the results in the Table below. 9 point(s)
Calculation of period of rotations for various rotation speeds
Assumed speed,
N (rpm)
8,000
6,000
4,000
2,000
1,000
800
Dr. Victor Giurgiutiu
Frequency of
rotation, f (Hz)
Period of rotation
T (MCU cycles)
τ (ms)
Page 358
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
THE PROGRAM INSTRUCTIONS
i.
Use the microcontroller input-capture functions to capture the times, T1 and T2, and the
number of overflows, NOF, corresponding to two consecutive passes of the aperture through
the emitter-detector sensor.
ii.
Use decimal 100 to scale down T1 and T2, and obtain the scaled values T1_100 and T2_100,
i.e. the time values in 100’s of cycles.
iii.
Calculate the time taken by overflows, TOVFL, in 100’s of cycles
iv.
Calculate the total time, T_100, in 100’s of cycles
v.
Use T_100 to calculate N_100_hex, the rotation speed in 100’s RPM
vi.
Convert the hex number N_100_hex to 2-digit BCD representation using subroutine
HEX_BCD. Store the 2-digit BCD representation to N_100_BCD
vii.
Output the N_100_BCD to port B to be routed to a 2 digit 7-segment LED display. This display
will show the rotation speed in 100s RPM.
FLOWCHART
Draw, below, a flowchart for your program. 6 point(s)
CODING
Use the flowchart to code your program in the simulator using the standard template. Save the program
in the personalized file name LASTNAME_Firstname_RPM.asm. Write or paste your coded program
below. 5 point(s)
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, timer registers, port A pins,
memory list. Open and assemble your program. Set breakpoints at
• After first input capture on IC1
•
When an overflow happens
•
After second input capture on IC1
•
SWI
Reset registers and memory. Set standard labels. Set display of TCTL2, TFLG1, TFLG2 to binary.
Arrange windows for maximum benefit: Press the RESET button. Paste your screen below: 1 point(s)
a) Toggle pin IC1 to 1. Start the program. The program should stay in a loop waiting for a falling
edge transition on pin IC1.
b) Toggle pin IC1 to 0. The program should stop at the first breakpoint. Notice that IC1F is set in
TFLG1 (bit 2). Also notice the value captured in TIC1. This value should be very close to the
Dr. Victor Giurgiutiu
Page 359
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
value in TCNT (It is not identical, since the program executed a few operations before stopping
at the breakpoint, hence TCNT is slightly more than TIC1.)
c) Step through your program until IC1F is cleared, TIC1 is loaded into D and then stored in T1,
TOF is cleared, and NOF is zeroed.
d) Run. The program enters the second IC1 capture loop. Let the program run until the timer
counter, TCNT, goes through an overflow. At this point, the program should stop at a
breakpoint.
e) Step through your program and notice the overflow counter, NOF, being incremented, and the
overflow flag, TOF, being reset.
f)
Let the program run. Toggle pin IC1 back to 1. Nothing should happen since only falling edges
should be detected. Toggle IC1 to 0 again. The program should stop at the second IC1 capture
breakpoint. The value of TIC1 should be updated to a new value.
g) Step through your program. The new value of TIC1 is loaded and then stored in T2. The
program branches back to the beginning (LABEL0).
After returning to the beginning, the program zeros the NOF counter and goes through the process again.
h) Let the program run again and repeat the steps above until you are satisfied that your program
runs well.
i)
Run again but, after each breakpoint, simply hit the run button and let the program run until the
next breakpoint. Make sure you verify that the generation of a falling edge signal on pin IC1 (by
you toggling from 1 to 0) generates an input capture.
j)
Make sure to run the program long enough such that at least one overflow takes place. Observe
how the overflow counter is incremented and the overflow flag is reset.
k) Synchronize your toggling of pin IC1, such that T1 will be just after an overflow, and T2 several
cycles later. In this situation, T1 and T2 are on the same side of the overflow (same side of the
time-change line) and the overflow counter, NOF, should be zero. Write down these values in
the table below, Case 1. 3 point(s)
l)
Synchronize your toggling of pin IC1, such that T1 will be just before an overflow, while T2 will
happen after the overflow. Write down these values in the table below, Case 2. 3 point(s)
NOF
Case 1:
Case 2:
T1 <T2 and on the same side of the timer overflow
event
T2 < T1, but on opposite sides of the timer overflow
event
T1
T2
$
$
$
$
VERIFICATION OF CASE 1 OF EXAMPLE_RPM_2
Recall data from Case 1 of Example_RPM_2: NOF=1, T1=$0006, T2=$110c. Use your pocket hex
calculator to estimate the results to be expected at the end of the program: 6 point(s)
T_100 = (NOF*$10000+T2-T1)/100 = ($01*$10000+$110c-$0006)/$64 = $_______
(1)
N_100_HEX = (2000000*60/100/100/T_100) = $2ee0/$2ba = $_______
(2)
N_100_BCD =_______
(3)
Dr. Victor Giurgiutiu
Page 360
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
Because the program needs to work with a finite word size, the variables in Equation (1) are first divided
by decimal100, such that Equation (1) is actually treated as:
T_100 = NOF*($10000)/100+T2/100-T1/100
The terms of equation (1) are calculated separately, as TOVFL, T1_100, T2_100. Hence, the following
operations are performed: 4 point(s)
T1_100 = T1/100 = $0006/$64 = $_______
(1a)
T2_100 = T2/100 = $110c/$64 = $_______
(1b)
TOVFL = NOF*($10000)/100 = $01*$028f = $_______
(1c)
T_100= TOVFL + T2_100 – T1_100 = $028f + $002b - $0000 = $_______
(1d)
Note that the result of Equation (1d) is the same as that of equation (1). Hence, Equations (2) and (3)
still stand.
Next, verify these arithmetic operations step-by-step:
a) Put Case 1 data in memory: NOF=1, T1=$0006, T2=$110c. Table 1 reflects your memory list.
Fill in the missing values (marked by ??). 5 point(s)
Table 1
Memory list after Case 1 data has been entered
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$??
$??
$??
$??
$??
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
b) Step through the section of your program that divides the variables T1 and T2 by decimal 100
to obtain T1_100 and T2_100. Use the hex pocket calculator to verify these results
T1_100=____________________2 point(s)
T2_100=____________________2 point(s)
c) Step through the section of your program that calculates TOVFL, the time taken by overflows,
expressed in 100s of cycles.
TOVFL=_____________________ 2 point(s)
d) Step through the section of your program that calculates T_100, the total time in 100s of cycles.
Note how the formula
T_100= TOVFL + T2_100 – T1_100
(1d)
is applied in two steps, first the addition, then the subtraction.
Dr. Victor Giurgiutiu
Page 361
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
T_100=_____________________2 point(s)
e) Step through the section of your program that calculates the variable N_100_HEX, the hex
speed of rotation, in 100s of rpm. Note that the ‘magic’ number ???????*??/???/??? is loaded
into accD as $???? and then divided by T_100. At the end of the process, the value
N_100_HEX=$???? is obtained.
N_100_HEX=________________ 2 point(s)
f)
Table 2
Step through the last section of your program and calculate the variable N_100_BCD, which
represent the decimal expression of the hex speed of rotation, in 100s of rpm. The conversion
from hex to BCD is achieved by invoking the subroutine HEX-BCD. Fill in the missing values
(marked by ??). 1 point(s)
Memory list after the calculation of N_100_HEX
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
VERIFICATION OF CASE 2 OF EXAMPLE_RPM_2
Recall data from Case 2 of Example_RPM_2: NOF=2, T1=$fffd, T2=$1103. Note that this data
represents the same time interval as in Case 1, only that a backwards time shift of 9 cycles took place.
For this reason, the times T1 and T2 are on different sides of the time-change line. T1 happens before
the time change, T2 happens after. Therefore, between T1 and T2, the time counter TCNT goes through
a timer overflow. Hence, the overflow counter has the value NOF=2, instead of 1 as in Case 1.
Use your pocket hex calculator to estimate the result to be expected at the end of the program:
6 point(s)
T_100 = (NOF*$10000+T2-T1)/100 = ($02*$10000+$1103-$fffd)/$64 = $______
(1)
N_100_HEX = (2000000*60/100/100/T_100) = $2ee0/$2ba = $______
(2)
N_100_BCD = ______
(3)
Because the program needs to work with a finite word size, the variables in Equation (1) are first divided
by decimal100, such that Equation (1) is actually treated as:
T_100 = NOF*($10000)/100+T2/100-T1/100
Dr. Victor Giurgiutiu
Page 362
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
The terms of equation (1) are calculated separately, as TOVFL, T1_100, T2_100. Hence, the following
operations are performed: 4 point(s)
T1_100 = T1/100 = $fffd/$64 = $______
(1a)
T2_100 = T2/100 = $1103/$64 = $______
(1b)
TOVFL = NOF*($10000)/100 = $02*$028f = $______
(1c)
T_100= TOVFL + T2_100 – T1_100 = $051e + $002b - $028f = $______
(1d)
Note that the result of Equation (1d) is the same as that of equation (1). Hence, Equations (2) and (3)
still stand.
Next, verify these arithmetic operations step-by-step:
g) Put Case 2 data in memory: NOF=2, T1=$fffd, T2=$1103. Table 3 reflects your memory list. Fill
in the missing values (marked by ??). 5 point(s)
Table 3
Memory list after Case 2 data has been entered
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$??
$??
$??
$??
$??
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
$ff
h) Step through the section of your program that divides the variables T1 and T2 by decimal 100
to obtain T1_100 and T2_100. Use the hex pocket calculator to verify these results.
T1_100=___________________ 2point(s)
T2_100=___________________ 2point(s)
i)
Step through the section of your program that calculates TOVFL, the time taken by overflows,
expressed in 100s of cycles. Note that, initially,
TOVFL=___________________ 2 point(s)
j)
Step through the section of your program that calculates T_100, the total time in 100s of cycles.
Note how the formula
T_100= TOVFL + T2_100 – T1_100
(1d)
is applied in two steps, first the addition, then the subtraction. At the end of the process, the
same T_100 value as in Case 1 should be obtained.
T100=____________________2 point(s)
Dr. Victor Giurgiutiu
Page 363
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
k) Step through the section of your program that calculates the variable N_100_HEX, the hex
speed of rotation, in 100s of rpm. Note that the ‘magic’ number ???????*??/???/??? is loaded
into accD as $???? and then divided by T_100. At the end of the process, the value
N_100_HEX=$???? is obtained, which is the same as in Case 1.
N_100_HEX=______________ 2 point(s)
l)
Step through the last section of your program and calculate the variable N_100_BCD, which
represent the decimal expression of the hex speed of rotation, in 100s of rpm. The conversion
from hex to BCD is achieved by invoking the subroutine HEX-BCD. At the end of the process,
the same N_100_BCD value as in Case 1 should be obtained. Fill in the missing values
(marked by ??). 1 point(s)
Table 4
Memory list after the calculation of N_100_BCD
NOF
T1
T2
T1_100
T2_100
TOVFL
T_100
N_100_HEX
N_100_BCD
$0000
$0001
$0002
$0003
$0004
$0005
$0006
$0007
$0008
$0009
$000a
$000b
$000c
$000d
$000e
$000f
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
$??
WHAT YOU HAVE LEARNED
In this exercise, you have:
•
•
•
•
•
•
•
•
•
•
Consolidated your understanding of DC motor functionality
Developed a DC motor tachometer (RPM counter) program to be used in the lab
Reviewed the use of MCU Timer functions (free running clock, TCNT, overflow flag, TOF, input
capture clock, TIC1, and its event flag, IC1F, the selection of signal transition to be captured
(here rising edge, EDG1B) and that the MCU is only sensitive to that particular transition.
Started to use soft masks (here, IC1_MSK, TOF_MSK).
Been introduced to the concept of layered flowcharting of a program: big-picture with generic
descriptions; detailed flowcharts for particular sections of the program.
Reviewed the used of two time captures to calculate the time duration of an event
Used scaling factors (100s) to deal with numbers that are larger than the microcontroller word
length
Used a method of calculating multiplication through repeated additions and decrementation of a
counter
Used of a conversion subroutine to convert from hex to BCD
Performed rotation speed calculation using the recorded period of rotation
Dr. Victor Giurgiutiu
Page 364
8/19/2008
EMCH 367
•
Fundamentals of Microcontrollers
Exercise DC MOTOR TACHOMETER
Used of scaling factors (100s) to present the result on a display with limited number of digits.
Dr. Victor Giurgiutiu
Page 365
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise STEPPER MOTOR
EXERCISE – STEPPER MOTOR
OBJECTIVE
This exercise will help you learn how to control a stepper motor through keyboard using the serial
communication and parallel ports of the M68HC11: The following objectives are considered:
• Review the use and control of stepper motors.
• Discuss the stepper motor energizing patterns, 1- and 2-phase energizing types, full- and halfstep motion.
• Introduce the concept of creating quasi-continuous motion through a sequence of steps
• Introduce the concept of sequential accessing a finite set of stored patterns through index
addressing with a continuously updating pointer.
• Illustrate a method to ‘load’ a single-precision (2-hex) variable into a double precision (4-hex)
register.
• Introduce the concept of automatic incrementation/decrementation of the addressing pointer with
a programmable step size
• Discuss the reset actions to be taken when the pointer hits the ‘roof’ or ‘floor’.
• Review the use of keystroke commands for controlling a process
• Introduce the concept of ‘multiple sort’ and its ‘sequential sort’ equivalent
• Use a subroutine that can implement a long delay between stepper motor steps
• Introduce the concept of how to achieve double precision delays (4-hex) using single precision
(2-hex) variables
BASIC CONCEPTS
1) Using a stepper motor involves "stepping" through a series of control signals. For the stepper motor
configuration discussed in class, show the 2-hex numbers corresponding to full-step and half-step
operation during a complete revolution. 42 point(s)
Full-step operation
Step
Sequence
number
1
S1
2
3
4≡0
Half-step operation
Number
Sequence
2-hex of excited
coils
Step number
number
½
S0
$09
2
1
S1
1½
2
2½
3
3½
4≡0
2-hex
number
$08
$09
Number
of excited
coils
1
2
2) How does the step pattern differ for a rotation in the opposite direction from that in question 1?
4 point(s)
Dr. Victor Giurgiutiu
Page 366
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise STEPPER MOTOR
3) If a half step pattern is used, the number of steps per rotation is doubled. This technique decreases
the "holding power" of the motor. Explain why. 6 point(s)
4) Describe the difference between unipolar and bipolar connection of stepper motor coils. 6 point(s)
5) The stepper motors used in this lab are low speed devices. The maximum effective rotation speed is
approximately 200 steps/sec. This physical condition necessitates a wait loop between each step. It is
suggested that you use wait loop to let the stepper motor perform the command before sending to it
another command. A timer offset could be used and altered to meet the changing speed requirements
of the program. Considering the speed of the microprocessor, what is the smallest wait loop that
could be used? Enter your answer here: _________________________6 point(s)
PROGRAM STEPPER MOTOR
Note: This program will be based on the examples Step, Sort, and Long Delay. In fact, it can be
assembled from these two examples. Before performing the present programming, review, duplicate,
and operate the example codes Ex_Step.asm, Ex_Sort_asm, and Ex_Long_Delay.
This program should make the stepper motor run forward and backward, at half speed and full speed,
according to control keystrokes send through the keyboard and echoed on the screen. The "half-speed"
and "full-speed" commands are part of the coarse speed control. Fine speed control (increase speed,
decrease speed) should be attained by modifying the delay inserted between steps. The program should
recognize five keystroke commands:
i)
Move forward
>
ii)
Move backward
<
iii)
Increase speed (decrease delay)
+
iv)
Decrease speed (increase delay)
v)
Stop program
S
This program will take a little more thought. The programming will need to be done at several layers of
complexity, using program segments and subroutines from the examples Step, Sort, and Long Delay and
from previous examples. The following is the ‘big-picture’ of your program:
Dr. Victor Giurgiutiu
Page 367
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise STEPPER MOTOR
a) Define variables: patterns S0, S1, S2, S3, S4, S5, S6, S7; variables STEP, POINTER, DELAY
b) Initialize program:
Initialize X=REGBAS
i)
ii)
Initialize SCI
iii) Initialize stepper motor sequence S0—S7;
iv) Initialize control variables STEP=0, POINTER=$00, DELAY=$ff
c) Verify if new keystroke command has arrived. If N, jump directly to f)
d) "Echo" the command back to the terminal monitor for confirmation
e) Sort and process the keystroke command. Modify stepper motor controls based on the keystroke
command.
f) Perform delay
g) Perform step:
i)
Calculate pointer
ii)
Access next step pattern
iii)
Send step pattern to the stepper motor through Port B
h) Loop back to c)
FLOWCHART
Draw a flowchart for the program. Use a layered flowchart approach. Use subroutines to perform
delay and to perform step. It is up to you to go with your layered flowcharting as detailed as needed
for successful programming. Insert the flowchart below. 15 point(s)
CODING
Use the flowchart to code your program in the simulator using the standard template. Save the program
in the personalized file name LASTNAME_Firstname_Stepper_Motor.asm. Write or paste your coded
program below. 15 point(s)
EXECUTION
Open THRSim11. Close the Commands window. View CPU registers, PORTB register, serial register
SCSR (display binary), serial transmitter, serial receiver, active memory. Open and assemble your
program. Set standard labels. Set breakpoints as follows:
• Just before the program checks for SCI reception
•
After SCI reception
•
After SCI transmission
•
At beginning of delay subroutine
•
At beginning of step subroutine
•
At SWI
Arrange windows for maximum benefit. Press the RESET button.
Dr. Victor Giurgiutiu
Page 368
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise STEPPER MOTOR
a) Run your program to the first breakpoint. The program should go through initialization and give
values to the variables S0—S7, STEP, POINTER, DELAY. Paste your screen. 3 point(s).
b) Run further. The program should be looping at the beginning and wait for a keystroke.
c) Enter the character > into the serial transmitter window and Send. After a few moments, the
character should be received and the program should stop at the breakpoint. Paste your screen
below. 3 point(s)
d) Run further. The program should be waiting for SCI transmission to happen. After a few
moments it should stop.
e) Step through the program
f) Repeat with the other control keys and check that your program runs successfully. If you do not
get the desired results, debug your program.
WHAT YOU HAVE LEARNED
In this exercise, you have:
• Reviewed the use and control of stepper motors.
• Discussed the stepper motor energizing patterns, 1- and 2-phase energizing types, full- and halfstep motion.
• Introduced the concept of creating quasi-continuous motion through a sequence of steps
• Introduced the concept of sequential accessing a finite set of stored patterns through index
addressing with a continuously updating pointer.
• Illustrated a method to ‘load’ a single-precision (2-hex) variable into a double precision (4-hex)
register.
• Introduced the concept of automatic incrementation/decrementation of the addressing pointer
with a programmable step size
• Discussed the reset actions to be taken when the pointer hits the ‘roof’ or ‘floor’.
• Reviewed the use of keystroke commands for controlling a process
• Introduced the concept of ‘multiple sort’ and its ‘sequential sort’ equivalent
• Used a subroutine that can implement a long delay between stepper motor steps
• Introduced the concept of how to achieve double precision delays (4-hex) using single precision
(2-hex) variables
Dr. Victor Giurgiutiu
Page 369
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise A/D CONVERTER
EXERCISE – A/D CONVERTER
OBJECTIVE
This exercise will help you learn how to use the M68HC11 microcontroller to collect analog data in
digital format. The following objectives are considered:
• Review the use of A/D conversion function of the M68HC11 microcontroller.
• Illustrate the use of A/D conversion to convert an analog voltage signal on a designated channel
(Port E pin) into four sequential digital values
• Demonstrate how to calculate an average of four values and send it to Port B for display
BASIC CONCEPTS
1) Explain what register must be set, and to what bit pattern, in order to activate (turn on) the AD
converter of M68HC11 microcontroller during the initialization segment of your program. 6 point(s)
2) Identify and write below the bit pattern setting of the A/D conversion control register ADCTL to
achieve a one-time conversion of the input signal on channels PE3 6 point(s)
ADCTL = %????????
3) Identify and write below the bit pattern setting of the A/D conversion control register ADCTL to
achieve continuous conversion of an the input signal on channels PE3 6 point(s)
ADCTL = %????????
4) Identify and write below the bit pattern setting of the A/D conversion control register ADCTL to
achieve a one-time conversion of input signals on channels PE4 – PE7 6 point(s)
ADCTL = %????????
5) Identify and write below the bit pattern setting of the A/D conversion control register ADCTL to
achieve continuous conversion of input signals on channels PE0 – PE3 6 point(s)
ADCTL = %????????
6) Fill Table 1 with the predicted AD conversion values for each voltage value. 18 point(s)
Table 1
1
2
3
4
5
6
Voltage at pin PE4 (mV)
750
1600
2200
3000
4000
5000
James Kendall
AD converted values (Hex)
$26
$??
$??
$??
$??
$??
Page 370
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise A/D CONVERTER
PROGRAM A/D CONVERTER
Note: This program will be based on the Example A/D converter. Before performing the present
programming, review, operate, and duplicate the example codes Ex_AD_1.asm, Ex_AD_2.asm,
Ex_AD_3.asm and Ex_AD_4.asm. However, only one of these four example codes is needed to
complete the program for this exercise (Choose wisely!).
PROGRAM DESCRIPTION
This program should make the MCU perform continuous A/D conversion on pin PE4, store the
conversion results in double precision variables VAL1 – VAL4, average some of the values VAL1 –
VAL4, and send out the averaged result through port B. The averaging is done by sequentially adding
the values VAL1 – VAL4 into accD and then dividing by 4 using the inherent operation IDIV. Because
IDIV utilizes register X, you will have to use register Y for indexed addressing in your program. Also,
note that, in this program, VAL1 – VAL4 are double precision, while in the Example A/D converter
they were single precision. You need to have VAL1 – VAL4 as double precision variables in order to
properly perform the sequential addition in accD.
The following steps should be considered in your program:
a) Define program variables, double precision VAL1 – VAL4
b) Initialize index register Y to REGBAS
c) Activate (turn-on) A/D converter function of the MCU
d) Set A/D control register ADCTL to perform continuous conversion on channel PE4
e) Zero accD
f) Load and store the converted values from ADR1 – ADR4 to VAL1 – VAL4. Perform these
operations using the appropriate accumulator such that at the end of the process the single
precision values existing in ADR1 – ADR4 get properly stored in the double precision variables
VAL1 – VAL4 (Hint: recall that accD = accA:accB).
g) Sequentially add VAL1 through VAL2 into accD.
h) Store the number 2 into register X (this is the denominator
i) Perform the division operation IDIV.
j) Send result of division through Port B for display
k) Loop back to e)
FLOWCHART
Draw a flowchart for the program. Use a layered flowchart approach. It is up to you to go with your
layered flowcharting as detailed as needed for successful programming. Insert the flowchart below.
15 point(s)
CODING
Use the flowchart to code your program in the simulator using the standard template. Save the program
in the personalized file name LASTNAME_Firstname_AD.asm. Write or paste your coded program
below. 17 point(s)
James Kendall
Page 371
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise A/D CONVERTER
EXECUTION
Open THRSim11. Close the Commands window. Activate your program. View CPU registers, Port E
pins, AD converter registers, Port B register, memory list, Sliders E port. View ADCTL as binary. Open
and assemble your program. Set standard labels. Set breakpoints at SWI. Arrange windows for
maximum benefit. Press the RESET button. Paste your screen: 2 point(s)
g) Enter the value 750 mV in PE4. Look up the expected value after conversion in Table 1. The
expected value is ______?????? 6 point(s)
h) Let your program run. The program should go through initialization and perform an AD
conversion giving values in registers ADR1 – ADR4. Stop program and paste your screen.
2 point(s)
i) Set breakpoint at the line performing ‘zero accD’.
j) Reset. Fill VAL1 – VAL 4, and PORTB with $ff. Let run to the breakpoint
k) Step through the program. The following should happen:
a. Values from registers ADR1 – ADR4 should be loaded into the lower part of accD and
then stored in the double precision values VAL1 – VAL4. Paste your screen below when
this has happened just for ADR1: 2 point(s)
b.The values in VAL1 – VAL4 should be sequentially added into accD and then divided by
X. Paste your screen below when this has happened for VAL1 and VAL2: 2 point(s)
c. The division by number 4 is performed. Paste your screen below when this has happened:
2 point(s)
d.The division result, i.e., the average value, is stored in Port B. Paste your screen below
when this has happened: 2 point(s)
l) Repeat with the other voltage values indicated in Table 1. Paste your screen below at the end of
each cycle: 2 point(s)
m) Clear the breakpoint at ‘zero accD’ and let your program run freely. Move the PE4 sliders up and
down and watch the value in Port B change accordingly.
WHAT YOU HAVE LEARNED
In this exercise, you have:
• Reviewed the use of A/D conversion function of the M68HC11 microcontroller.
• Used of A/D conversion to continuously convert an analog voltage signal on Port E pin PE4
• Stored the four sequential digital values resulting from conversion as double precision values
VAL1 – VAL4
• Calculated the average of the four values using sequential addition into accD and IDIV division
by the number 4 loaded in register X.
• Sent the double precision content of register X to Port B for display as a single precision number.
James Kendall
Page 372
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Exercise A/D CONVERTER
(This page is left intentionally blank)
James Kendall
Page 373
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Labs
LABS
The labs focus on hands-on experience with the microcontroller unit (MCU) and ancillary hardware.
Programming for the labs can be effectively achieved by using the code, programs, and subroutines
developed during the homework assignments.
Lab 1
Hmwk1
Hmwk2
Hmwk3 – Ex10
Hmwk3 – Ex_Delay
Hmwk4
Hmwk5
Hmwk6
Hmwk7
Hmwk8
Lab 2
Lab 3
Lab 4
Lab 5
X
X
X
X
X
X
X
X
X
The labs are given next
Dr. Victor Giurgiutiu
Page 374
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Labs
Lab Handout
NO food and NO drinks !!!
Door code: 41325
Color code of wires on breadboard:
Green: +15V
Black: 0V
Red: +5V
White: -15V
Yellow: signal
MINIIDE INSTRUCTIONS
1. Open miniIDE by double clicking the miniIDE icon on the desktop;
2. Connect the EVB to the host computer by 1) clicking the
icon and 2) pressing the reset button
with the pencil. If a welcome message is shown on the screen, the EVB is connected, if not, call help
to your TA.
3. Open an .ASM code file in your floppy disk. If needed, modify the codes and save. Hint: put star *
mark at the beginning of the last two lines (after the command SWI) to comment these two lines. i.e.
SWI
*
ORG
$FFFE ; reset vector
*
FDB
START ; set to start of program
4. Compile the program by clicking the
icon;
5. Type “LOAD T” in the terminal (bottom) window and press “ENTER” key;
Then click the download icon
. (Now the compiled program is downloaded into the
microcontroller’s RAM.)
6. Use command RM to check the registers, and reset them if needed. Make sure the PC (Program
Counter ) points to the starting address of your programs, i.e. PC is C000).
7. Type in “T” to run the program step by step.
8. Or, type in “GO C000” in the terminal window to run the program automatically.
Dr. Victor Giurgiutiu
Page 375
8/19/2008
EMCH 367
Type in
Fundamentals of Microcontrollers
Labs
How to use the ‘RM’ command:
>RM <enter>
PC – xxxx
Y – xxxx
X – xxxx
A – xxxx
PC – C000
Y – 0000
•
Use the “space” key to get to the next register
•
Use the “enter” key to get out of the setup
How to use the ‘MM’ command:
MM (MEMORY MODIFY) command will allow you to change the value at specific memory locations.
Type in the memory address after the MM command.
Here is an example:
MM 0000
How to use the ‘MD’ command:
MM (MEMORY DISPLAY) command will allow you to view the value at specific memory locations.
Type in the memory address after the MM command.
Here is an example:
MD 0000
Dr. Victor Giurgiutiu
Page 376
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Labs
Some of the frequently used BUFFALO commands are listed alphabetically in the Table below.
COMMAND
DESCRIPTION
HELP
Display monitor commands
ASM [<addr>]
Assembler/disassembler
BF <address1> <address2> <data>
Block fill memory with data
BR [-][<addr>]
Set up breakpoint
CALL [<address>]
Execute subroutine
Execute program
GO [<address>]
Memory Display
MD [<address1> [<address2>]]
Memory Modify
MM [<address>]
MOVE <address1> <address2>
Move memory to new location
[<destination>]
OFFSET [-]<arg>
Offset for download
Register Modify
RM [p, y, x, a, b, c, s]
Trace $1~$ff instructions
T [<n>]
RD
Register Display
miniIDE Program Interface
menu
toolbar
Editor Window
( Your .asm file here )
Output Window
( Your compile information, errors, etc. )
Terminal Window
BUFFALO 2.5
> ( type your BUFFALO command here )
Dr. Victor Giurgiutiu
Page 377
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Labs
Attention:
•
Have your .asm files ready before you come to the LAB
•
You need to print out the lab report before you come to the LAB. You will finish it when you are
doing the LAB and hand in the report right after the lab.
•
You need to keep this handout at hand as reference for Labs.
•
CLEAN UP your mess, put everything back in order and turn off the oscilloscope before you
leave.
Dr. Victor Giurgiutiu
Page 378
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Labs
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 379
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 1
LAB 1 - BASIC PROGRAMMING
OBJECTIVE
The objective of this lab is to develop basic programming skills in direct contact with the Motorola
68HC11 microcontroller unit (MCU).
PREREQUISITES
Floppy disk with the asm codes
Hard copy (printout) of Hmwk1 Hmwk2, Hmwk 3. When printing, use the 'pages per sheet'
option in the lower right corner of the print dialog-box with settings of 4 or 2 (depending on your
eyesight) to save paper. (We may want to experiment a little with this before printing the full
document.)
PROCEDURE
The students will utilize the asm code developed with the THRSim11 simulator for Hmwk1 and Hmwk2.
The students will go through their Hmwk1 and Hmwk2 step by step and will find how the MCU
responds to their instruction. The lab is divided into sections. After completing each section, the student
will ask the TA to check the student’s work and make a check mark on that section.
The asm code is compiled and downloaded into the MCU through the MiniIDE terminal emulator
software. The same software allows to correct/modify/re-save the code as the need arises. When using
the MiniIDE, the following procedure is used to 'activate' your program in the MCU:
a) Verify that the power supply is active, and that the MCU is connected to the power supply
b) Open the MiniIDE program
c) Connect it to the processor using the menu item ‘Terminal connect/disconnect’ button.
d) Open your asm program from the floppy disk
e) Compile your asm program
f) Type “LOAD T” in the terminal window and press enter. Download the S19 code of your
program to the MCU using the 'Download' button
g) Type the BUFFALO command RM in the command window. Verify that the program counter
(PC) is set to the value $C000. If not, set it to $C000.
h) Reset accA and accB by typing 0 at the command prompt
j) To step through the program, use the BUFFALO command T
k) To run the program, use the BUFFALO command G, with the starting PC (e.g., $C000)
Hmwk 1 -- Exercise 1
Activate your LASTNAME_Firstname_Ex1.asm file.
Step through the program and compare what you see happening in PC, accA, accB with your predictions
from Exercise 1.
When satisfied with your results, call your TA and demonstrate.
TA checkmark ________
Hmwk 1 -- Exercise 2
Activate your LASTNAME_Firstname_Ex2.asm file.
Step through the program and compare what you see happening in PC, accA, accB with your predictions
from Exercise 2.
When satisfied with your results, call your TA and demonstrate.
TA
checkmark ________
Hmwk 2 -- Exercise 3-7
Activate your LASTNAME_Firstname_Ex3-7.asm file. Step through the program and compare what
you see happening in PC, accA, accB with your predictions from Exercise 3-7.
Dr. Victor Giurgiutiu
Page 380
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 1
Note that when decimal numbers are specified in the asm code, their hex equivalent are actually loaded.
Verify the conversion with your pocket calculator. When satisfied with your results, call your TA and
demonstrate.
8+7=15
TA checkmark ________
$08+$07=$0f
TA checkmark ________
9+9=18
TA checkmark ________
$09+$09=$12
TA checkmark ________
12+29=41
TA checkmark ________
$0c+$1d=$29
TA checkmark ________
$ff+$01=$00
TA checkmark ________
255+1=0
TA checkmark ________
Hmwk 2 -- Exercise 8-9
Activate your LASTNAME_Firstname_Ex8-9.asm file.
Step through the program and compare what you see happening in PC, accA, accB with your
predictions from Exercise 3-7.
Note that when decimal numbers are specified in the asm code, their hex equivalent are actually
loaded.
When satisfied with your results, call your TA and demonstrate.
8-1=7
TA checkmark ________
$08-$01=$07
TA checkmark ________
20-1=19
TA checkmark ________
$20-$01=$1f
TA checkmark ________
$00-$01=$ff
TA checkmark ________
0-1=255
TA checkmark ________
$0f-$07=$08
TA checkmark ________
$00-$07=$f9
TA checkmark ________
0-7=249
TA checkmark ________
$0f-$2b=$e4
TA checkmark ________
15-43=228
TA checkmark ________
Hmwk 3 -- Exercise 10
Activate your LASTNAME_Firstname_Ex10.asm file.
Step through the program and compare what you see happening in PC, accA, accB with your
predictions from Exercise 3-7.
Note that when decimal numbers are specified in the asm code, their hex equivalent are actually
loaded.
When satisfied with your results, call your TA and demonstrate.
i) one through seventeen
TA checkmark ________
ii) 5+4=9
TA checkmark ________
iii) 15-7=8
TA checkmark ________
iv) $1f+$01=$
TA checkmark ________
v) $20-$01=$
TA checkmark ________
vi) $ff+$01=$
TA checkmark ________
vii) $00-$01=$
TA checkmark ________
viii)
0 AND 1 =
TA checkmark ________
ix) 0 OR 1 =
TA checkmark ________
x) 0 XOR 1 =
TA checkmark ________
xi) 1 OR 1 =
TA checkmark ________
xii) 1 XOR 1 =
TA checkmark ________
xiii)
%00000000 NAND %11111111 = %
TA checkmark ________
Dr. Victor Giurgiutiu
Page 381
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
xiv)
%11111111 NOR %00000000 = %
xv) %10101110 AND %00001000 = %
Dr. Victor Giurgiutiu
Page 382
Lab 1
TA checkmark ________
TA checkmark ________
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 1
(This page is intentionally left blank)
Dr. Victor Giurgiutiu
Page 383
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 2
LAB 2 – PARALLEL AND SERIAL COMMUNICATION
OBJECTIVE
The objectives of this lab are to review the parallel and serial communication in the MC68HC11
microcontroller. The objective of this laboratory experiment is to learn how to use the serial
communication port of the M68HC11. Basic concepts of serial communications will be reviewed. The
registers used to transmit and receive serial communications data and the RDRF and TDRE flags used to
identify whether or not serial communications data has been received or sent will be examined. The
BAUD rate and other aspects of the serial communications interface (SCI) will be investigated..
• Review the use parallel ports
•
Illustrate the generation of a square wave using Port B output and a waiting sequence
•
Illustrate the use of Port C for input and output using a 4-button 4-LED box
•
Examine the relation between time and clock cycles
•
Review the use of serial communications
•
Investigate BAUD rate, ASCII code, 10-bit serial communication
•
Develop and practice the concept of echo
•
Measure serial communications signals, including the start bit, ASCII code, and the stop bit,
using the oscilloscope with an external trigger generated by MCU
PREREQUISITES
Floppy disk with the asm codes for the programs:
• LASTNAME_Firstname_Buttons_bx.asm
•
LASTNAME_Firstname_Sq_wav1.asm
•
LASTNAME_Firstname_Sq_wav2.asm
•
LASTNAME_Firstname_Echo.asm
Hard copy (printout) of Hmwk4a and Hmwk 4b. When printing, use the 'pages per sheet' option
in the lower right corner of the print dialog-box with settings of 4 or 2 (depending on your
eyesight) to save paper. (We may want to experiment a little with this before printing the full
document.)
PROCEDURE
The students will utilize the asm code developed with the THRSim11 simulator for Hmwk4a and
Hmwk4b. The students will go through their Hmwk4a and Hmwk4b step by step and will verify that the
MCU responds to instructions as expected.
The lab is divided into sections. After completing each section, the student will ask the TA to check the
student’s work and make a check mark on that section.
The asm code is activated into the MCU following the standard procedure learned in Lab 1.
Dr. Victor Giurgiutiu
Page 384
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 2
WARM UP EXERCISES
1)
Connect the oscilloscope Channel 1 through a hook probe to Port B Pin0 using a male connector.
Set the oscilloscope Channel 1 to DC, 5V/div, and zero vertically in mid screen. Use the MM
command to put $01 into PORTB, i.e., in the MCU address $1004. The oscilloscope signal
should jump to 5 V. Put again $00 in PORTB. The oscilloscope signal should jump to 0 V. Do
you observe this? ___ Y ___ N
2)
Assume $A5 is loaded into PORTB at address $1004. What will be the output of parallel port B?
Predict the results in the table below. Label which pin is the MSB.
Port B
PB7
PB6
PB5
PB4
PB3
PB2
PB1
PB0
pins
Value
Use the MM command to put $A5 into PORTB, i.e., in the MCU address $1004. Verify the output of
parallel port B with the oscilloscope and the 8-LED display. Check the voltages on all of the pins of
parallel port B (PB0 - PB7) with the oscilloscope. Then check them with the 8-LED display. Write down
your observations.
PB0:
V PB1:
V PB2:
V PB3:
V
PB4:
V PB5:
V PB6:
V PB7:
V
When satisfied with your results, call your TA and demonstrate.
TA checkmark ________
3)
If you place $fa in DDRC at address $1007 and then load $c8 into PORTC at address $1003,
what will be the output of parallel port C? Enter your prediction in the table below.
DDRC pins
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Value
Port C pins
PC7
PC6
PC5
PC4
PC3
PC2
PC1
PC0
Value
Load $fa in DDRC at address $1007 and then load $C8 into PORTC at address $1003. Verify the output
of parallel port C. Check the voltages on all of the PC0 - PC7 pins of parallel port C with the
oscilloscope probe. Then check them with the 8-LED display. Write down your observations.
PC0:
V PC1:
V PC2:
V PC3:
V
PC4:
V PC5:
V PC6:
V PC7:
V
When satisfied with your results, call your TA and demonstrate.
TA checkmark ________
Dr. Victor Giurgiutiu
Page 385
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 2
SQUARE WAVE
Use the code LASTNAME_Firstname_Sq_wav2.asm generated in Hmwk4a.
The parallel port B is used to generate a square wave. A square wave is a signal that is high for a
specified period of time, then low for a specified period of time. In this case, the high state will be +5V,
and the low state will be 0V. Your target is to generate a square wave signal with the period of time for
each state (half-wavelength) approx. 100 μs. The square wave signal generated by your MCU will be
measured on the oscilloscope screen and compared with your predictions.
Your code should make the MCU send out a low signal for a specified time, then a high signal for the
same time. After sending out a high signal and then a low signal, it will repeat the process. The duration
of the high and low states is specified using the variable DELAY. The variable DELAY is used in a wait
subroutine. The MCU is a very fast device. Our M68HC11 has an 8 MHz crystal, which generates a 2
MHz clock speed. Compute and answer the following questions:
a) What is the shortest duration of time that the oscilloscope can measure per division? Look up
on the oscilloscope panel and enter your answer here: ___________________________
b) What is the duration of an M68HC11 machine cycle? Calculate your answer using the
M68HC11 clock speed of 2 MHz and enter your answer here: ________________________
Activate the code LASTNAME_Firstname_Sq_wav2.asm. According to your Example Square wave,
when value $40 is entered in DELAY (The address of DELAY is 0000; Buffalo command MM 0000 is
used to change the value of DELAY), the length of your half-wave, Δt, should be 165 μs. Hook the
oscilloscope probe to the pin corresponding to your coding, and verify that what you see on the
oscilloscope screen meets with your predictions. (Adjust the time/div button to see the square wave
properly…). Write here the half-wavelength value read on the oscilloscope screen ______ μs.
Change DELAY to the other values given in the table below, and run your program again. Enter the Δt
(μsec) predicted by you using the simulator (see Hmwk4a) and the values read on the oscilloscope
screen.
DELAY
Δt (μsec)
Measured by simulator
Δt (μsec)
Measured on
oscilloscope
Col 3
Error, %
(col 2 – col 3)/col 3
Col 1
Col 2
Col 4
$10
$__
100
100
0%
$40
165/166
165
0.3%
$A0
$FF
Try to adjust the value of DELAY to have the half-wave last 100 μs. With just a few trials, you should
be able to find the right value of DELAY to achieve this. The value you found is: DELAY =
$_________ Enter the value in the table.
When satisfied with your results, call your TA and demonstrate.
TA checkmark ________
Dr. Victor Giurgiutiu
Page 386
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 2
BUTTONS BOX
You are given a box (see Figure) with four buttons and four LED’s (light emitting diodes). When
pressed, the buttons (B0, B1, B2, B3) produce either +5 Volt (Normally Open = N.O. type buttons) or 0
Volt (Normally Closed = N.C. type buttons). The buttons are connected (through a port protection card)
to the even port C pins PC0, PC2, PC4, and PC6. The LED’s are connected to the odd port C pins PC1,
PC3, PC5, and PC7.
Port C
B0
5V
PC7
LED’s
PC1
PC3 PC5
5V
Buttons
PC0 PC2 PC4
PC6
5V
W ires:
Green=Gnd
Red = +5 V
Port C connection
5V
L0
B1
L1
B2
PC0
PC1
PC2
PC3
PC4
L2
B3
PC5
PC6
L3
PC7
Figure 4
The 4-Button 4-LED Box: (a) photo; (b) diagram
Attach the box to the microprocessor through a port protection card. Be careful that you connect the
MSB of the button box to the MSB of the microprocessor. Activate your
LASTNAME_Firstname_Buttons_bx.asm program. Press buttons and see how the corresponding LED
is lighting up. When satisfied with your results, call your TA and demonstrate.
TA checkmark ________
Dr. Victor Giurgiutiu
Page 387
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 2
SERIAL COMMUNICATION ECHO
You wish to create a program that will receive a keystroke from the terminal keyboard, and echo the
same keystroke, continuously, to the terminal screen. The program will also let you see the binary
pattern of keystrokes sent from the computer to the MCU. To achieve this, you will continuously check
if the MCU has received, via SCI reception, a keystroke from the computer keyboard. When a key has
been pressed, you will send out its ASCII value through the parallel port B, and back through the SCI
transmission. A LED board, affixed to the parallel port B, will display the bit pattern of the ASCII value.
This way, you check that the bit pattern corresponds to the ASCII table.
Serial cable
Wire connected to TXD
pin PD1
Figure 2
Dr. Victor Giurgiutiu
Connection diagram of serial communication
Page 388
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 2
You will also monitor the communication by tapping the serial communications signal and displaying it
on the oscilloscope screen. You will be able to see the complete 10-bit pattern, and the time duration of
the communication. This exercise is based on Hmwk4b, Serial communication.
a) Fill in the ASCII codes for each key listed in Table #1.
b) Connect the LED board to port B. Attach a probe from channel 2 to parallel port C. Attach
another probe from O-scope channel 1 to the leading out wire (serial communication TXD pin
PD1). Set the O-scope trigger to channel 2, Set display to “Both”.
c) Activate your code LASTNAME_Firstname_Echo.asm. in the MCU and run it. Press key "Q"
on the keyboard. The character should appear on the screen continuously, while its ASCII code
is sent out through the parallel port B and displayed on the LED board. Read the bit pattern
displayed on the LED board and enter it in Table #1. Write the equivalent Hex number and
compare the ASCII code.
d) Manipulate the time (horizontal) scale, amplitude (vertical) scale, and the trigger level, until you
see both the triggering pulse and the serial communications transmission. Identify the start bit,
the ASCII code for the character being transmitted, and the stop bit on the oscilloscope screen.
Compare the ASCII code listed in M68HC11 Quick Reference Manual to the one displayed on
the oscilloscope. Enter your answer in Table 1.
e) Use the oscilloscope to calculate the BAUD rate of the MCU
Duration of signal Δt = ________ ms; Number of bits read in the signal N = ________;
Calculated BAUD rate = # of bits/duration = N /Δt =____________bits/sec
f) Repeat for keys 0, 3, 8, D.
g) Sketch below the 10-bit pattern observed on the oscilloscope screen for character Q.
Dr. Victor Giurgiutiu
Page 389
8/19/2008
EMCH 367
TABLE 1
Key
ASCII code
Fundamentals of Microcontrollers
Q
0
3
8
Lab 2
D
51
LED
MSBÆLSB
8-bit pattern
Equivalent
Hex values
O-scope
8-bit pattern*
Equivalent
Hex values
* This should be the 8-bit character as you see it on the O-scope screen.
When satisfied with your results, call your TA and demonstrate.
TA checkmark ________
Dr. Victor Giurgiutiu
Page 390
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Page 391
Lab 3
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 3
LAB 3 – TIMER FUNCTIONS: BOLT DROP AND SQUARE WAVE
OBJECTIVE
This lab will use MC6811 to perform time measurements. Part I will perform time measurements on a
dropping bolt using input capture (IC) timer functions. Part II will generate a square wave using output
compare (OC) timer functions.
PREREQUISITES
Floppy disk with the asm codes for the programs:
• LASTNAME_Firstname_Drop.asm
•
LASTNAME_Firstname_OC_sqwav.asm
Hard copy (printout) of Hmwk5 – Timer functions. When printing, use the 'pages per sheet'
option in the lower right corner of the print dialog-box with settings of 4 or 2 (depending on your
eyesight) to save paper. (We may want to experiment a little with this before printing the full
document.)
PROCEDURE
The students will utilize the asm code developed with the THRSim11 simulator for Hmwk5. The
students will go through the printout of Hmwk5 step by step and will verify that the MCU responds to
instructions as expected.
The lab is divided into sections. After completing each section, the student will ask the TA to check the
student’s work and make a check mark on that section.
The asm code is activated into the MCU following the standard procedure learned in Lab 1.
Dr. Victor Giurgiutiu
Page 392
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 3
PART I – BOLT DROP EXPERIMENT (50%)
Note: This part uses the timer program
LASTNAME_Firstname_Drop.asm developed in the Figure 1 Bolt drop experimental setup
section “Input capture – bolt drop experiment” of
Hmwk5.
Electromagnet
MC6811 will be used in an experiment to measure
travel times. A 1.5-in bolt will be held by an
electromagnet at the top of a drop shaft. The
electromagnet is connected to the MCU. . This
Drop shaft
magnet is controlled by any of the 8 pins on PORTB.
It is turned on by sending 5V through parallel PORTB.
When a keystroke occurs, the MCU commands the
electromagnet to release the bolt. Simultaneously, the
time origin, T0, is recorded. The bolt travels down the
Electronics
shaft. After falling a specified distance (L = 48.75-in),
the bolt crosses an infrared emitter-detector sensor
and interrupts its beam causing its output voltage to
fall from high (+5V) to low (~0V). When the bolt
exits the emitter detector sensor, its output voltage
comes back up to high (+5V). The output from the
emitter-detector sensor is wired into the input capture
pins IC1 and IC2 of the MCU. You will program the
microcontroller to perform the following functions: (a)
control the electromagnet, (b) take the initial time
when the process starts, (c) measure the time required
for the free-falling bolt to reach the emitter-detector;
(d) measure the time required for the bolt to pass
through the emitter-detector.
Emitter-detector
sensor
WIRING DIAGRAM
Wire
Green wire:
Red wire
Black wire
White wire:
Yellow wire
with 2 prongs:
Dr. Victor Giurgiutiu
Connection
+15V
+5V
Ground
To parallel port B pin controlling the
magnet
Signal wire to the input capture pins IC1
and IC2
Page 393
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 3
BOLT DROP CIRCUIT DIAGRAM
+5V
1KΩ
E+
+15V
+D
1KΩ
+5V
Electromagnet
+5V
+5V
1KΩ
IRF510
R250
Port A pin 1
Port A pin 2
470KΩ
3
76
Port B pins
10Ω
1KΩ
1
-
+
Comparator
LM2901 12
PRE-TEST PROCEDURE
Before starting your test, perform the following pre-test procedure to verify that your experimental setup is performing correctly:
i)
Check the correct wiring of the bolt drop set up:
Wire
Green wire:
Red wire
Black wire
White wire:
Yellow wire
with 2 prongs:
Connection
+15V
+5V
Ground
To parallel port B pin controlling the
magnet
Signal wire to the input capture pins IC1
and IC2
Check mark
TA checkmark ________
ii)
Take the white wire out of the Port B connection (if connected). Check the
electromagnet holding action upon the bolt by applying 5V to the white wire. The bolt
should hold. Then, check the release action by applying 0 V. [Note that 0 V is different
from “no-voltage” (floating wire). A floating wire may not release the bolt] The bolt
should drop.
iii)
Connect O-scope Ch.1 to the signal wire (yellow). Set Trigger Mode to Auto and
Horizontal to 0.2 sec/div. You will see a spot traveling across the screen at 5V level. (If
Dr. Victor Giurgiutiu
Page 394
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 3
the spot is too bright, adjust Brightness Intensity). By hand, introduce the bolt in the
emitter-detector zone at the lower end of the tube and watch the signal go to 0V on the
O-scope screen. Extract the bolt and watch the signal go back to 5V. Now, let the bolt
drop through the tube and watch the fast 5V/0V/5V transition (spot flicker) on the
screen.
iv)
Connect the white wire to port B. Manually, send a 5V voltage through port B (i.e.,
store $ff into Port B at memory location $1004) and verify that the electromagnet holds
the bolt. Now, send a 0V through port B (store $00 into Port B at memory location
$1004) and observe the electromagnet releasing the bolt. Watch the 5V/0V/5V
transition on the screen as the dropping bolt passes the emitter-detector sensor.
v)
Where are IC1 and IC2 located (port and pin)? Enter your answer here:
_____________________ Draw a sketch of the pin assignments in the space below
vi)
Connect the signal wire (yellow) to IC1 and IC2 pins.
TA checkmark ________
TEST PROCEDURE
i) Put the bolt into the electromagnet hold position
ii) Activate the program LASTNAME_Firstname_Drop.asm.
iii) Press any key. The bolt should drop and the program should stop when the bolt exits the tube.
iv) Read the memory locations for T0, T1, T2, NOF1, NOF2. Record the readings in the table.
v) Perform all the 6 trials and enter the appropriate values in the table.
TA checkmark ________
vi) Start manual calculations by completing the formulae below:
Time of entry: t1 = [T1+NOF1*($__________)-T0] cycles * (_____________ s/cycle)
Time of exit: t2 = [T2+NOF2*($__________)-T0] cycles * (_____________ s/cycle)
Time for bolt to pass: Δt = t2 – t1
Velocity: v = L/Δt = _____/Δt (in/s)
Error: ε = (theoretical – measured)/theoretical *100%
TA checkmark ________
Then, calculate t1, t2, Δt, v in the table.
vii) Use the formulae to calculate the measured time of entry in each trial
viii) Calculate the average measured time of entry, t1, and its deviation.
ix) Use the formulae to calculate the measured time of exit in each trial
x) Calculate the average measured time of exit, t2, and its deviation.
xi) Use the measured time of entry and time of exit in each trial to calculate the measured time
taken by the bolt to pass through.
xii) Calculate the average measured time of passing, Δt, and its deviation.
Dr. Victor Giurgiutiu
Page 395
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 3
xiii) Use the appropriate formula to calculate the bolt velocity using the measured time of passing
and its deviation.
xiv) Use the formulae to calculate the measured time required for the bolt to pass in each trial
Trial
1
2
3
T0
T1
T2
NOF1
NOF2
T1+NOF1*$10000-T0
Measured time of entry (ms)
Average measured time of entry, t1 (ms)
Theoretical time of entry (ms) and error (%)
t1 _____ ms
εt = ____%
t1,theory = ________ ms,
T2+NOF2*($__________)-T0
Measured time of exit (ms)
Average measured time of exit, t2 (ms)
t2 _____ ms
Measured time for bolt to pass through
emitter-detector (ms)
Average Δt (ms)
Δt _____ ms
Average measured velocity v (in/s)
v ____ in/s
Theoretical velocity (in/s) and error (%)
vtheory = ________ in/s,
εv = ____%
xv)Compare the experimental results with the theoretical results calculated in Ex_Timer and discuss
any discrepancies. Comment upon the error of your measurements, and discuss possible
sources of errors. Enter your answers in the space below.
TA checkmark ________
Dr. Victor Giurgiutiu
Page 396
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 3
PART II – SQUARE WAVE GENERATION WITH TIMER FUNCTIONS (50%)
In this part of the lab, you will generate a square wave with the microcontroller. In Lab 2, you generated
a square wave through a parallel port pin using a wait loop. Here, you will generate a square using the
output compare timer function of the microcontroller. The square wave will be generated at the port A
pin OC5.
WIRING DIAGRAM
Fill in the space at the end of the next sentence. The port A location of pin OC5 is at pin PA___.
Connect the oscilloscope Channel 1 probe to this pin.
TA checkmark ________
TEST PROCEDURE
1. Using the results derived in Hmwk5, fill in the missing information in the first two rows of the table
below.
2. Connect the OC5 pin of port A to the oscilloscope Channel 1.
3. Activate the program LASTNAME_Firstname_OC_sqwav.asm
4. Put the value DT=$0100 and run your program(Buffalo command MD 0000 to display the memory
area, MM ADDRESS to modify the values of variables)
5. Watch the signal on screen and measure the half wavelength duration of the square wave, in μs.
Enter the value in the table below
6. Compute the corresponding ‘measured frequency’
TA checkmark ________
7. Calculate the absolute and relative errors
8. Repeat for the other values in the table
Desired frequency
(Hz)
Calculated DT
$0100
$8000
$ffff
250
1500
$
$
Measured half
wavelength duration
(μs)
Measured Frequency
(Hz)
Absolute error (Hz)
Relative error (%)
TA checkmark ________
Dr. Victor Giurgiutiu
Page 397
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 4
LAB 4 – DC MOTOR TACHOMETER
OBJECTIVE
The objectives of this laboratory are:
(a) To understand the functioning of a DC motor
(b) To test the DC motor tachometer program developed in Hmwk6.
PREREQUISITES
Floppy disk with the asm codes for the program:
• LASTNAME_Firstname_RPM.asm
Hard copy (printout) of Hmwk6 – Digital tachometer. When printing, use the 'pages per sheet'
option in the lower right corner of the print dialog-box with settings of 4 or 2 (depending on your
eyesight) to save paper. You may want to experiment a little with this before printing the full
document.
PROCEDURE
The students will utilize the asm code developed with the THRSim11 simulator for Hmwk6. The
students will go through the printout of Hmwk6 step by step and will verify that the MCU responds to
instructions as expected.
The lab is divided into sections. After completing each section, the student will ask the TA to check the
student’s work and make a check mark on that section.
The asm code is activated into the MCU following the standard procedure learned in Lab 1.
EXPERIMENTAL SETUP
The experimental setup for this experiment consists of a DC electric motor, a speed-control
potentiometer and its electronics, an emitter-detector sensor, a disk with an aperture (hole) attached to
the DC motor shaft, and a pair of 7-LED displays connected through appropriate electronics to a 8-pin
Port B connector. The aperture in the disk spins through the infrared emitter-detector sensor. The
emitter-detector sensor sends a High (5V) signal when the aperture in the disk allows the beam of light
to pass through. The emitter-detector sensor output wire is attached to the input capture pin IC1 on Port
A.
The speed of the motor is controlled by a potentiometer and an electronic timer circuit. The
potentiometer is a variable resistor. By varying the angular position of the potentiometer (turning the
knob), one varies the timer’s capacitor’s charge and discharge path resistance, which, in turn, varies the
duty cycle supplied to the DC motor. As the duty cycle to the DC motor is varied, the power delivered
and speed also vary.
Dr. Victor Giurgiutiu
Page 398
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 4
WIRING DIAGRAM
Wire
Red wire
Black wire
Yellow wire
Connection
+5 V
0 V (Ground)
Signal wire to input capture pin IC1
MOSFET
DC
Transmissive
Photomicrosensor
(Emitter/Detector)
7-Segment
Display
Port B
Connection
Lamp Test
Figure 1 DC Motor tachometer experiment to which the present software example is relevant.
CIRCUIT DIAGRAM
Dr. Victor Giurgiutiu
555 Timer
Page 399
Speed-Controlling
Potentiometer
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 4
PRE-TEST PROCEDURE
Before starting your test, perform the following pre-test procedure to verify that your experimental setup is performing correctly:
1)
Check the correct wiring of the DC motor set up:
Wire
Red wire
Black wire
Yellow wire
2)
Connection
+5 V
0 V (Ground)
Signal wire to the input capture pins IC1
Check mark
Press the small black “Lamp Test” button on the DC motor board. Do all the LEDs light up,
displaying the number 88? Y ___ N ____. Connect port B to the 2-digit 7-LED display. Send $99
through port B. Does the display indicate correctly? Y ___ N ____. Repeat with $66. Try other
base-10 numbers. Does the display correctly indicate all these numbers? If not, contact your TA.
TA checkmark ________
PART I –DC MOTOR SPEED-VOLTAGE CHARACTERISTIC (30%)
3)
Disconnected the motor from the circuit and measure its internal resistance, R = _________ Ω.
(You may want to borrow a digital multimeter from your TA for this measurement).
4)
Connect the circuit to the power supply terminals. Attach the voltmeter probes to the DC motor
terminals.
5)
Connect the oscilloscope Ch. 1 probe to the sensor output wire (yellow) of the circuit board. Set
the oscilloscope trigger mode to Auto, source to Ch. 1, and coupling to DC.
6)
By rotating the knob of the potentiometer, modify the duty cycle of voltage delivered to the DC
motor to increase and decrease the motor speed. Find the voltage value for the fastest speed (fullspeed). Enter this value in the table. Then find other values until you have matched all these
descriptors: full-speed, ¾-speed, ½-speed, ¼-speed, very slow, and stopped.
7)
Run the DC motor at full speed. Examine the signal on screen. Modify the sec/div setting until the
signal best fits the screen and can be measured. Measure the period of rotation, τ and enter your
result in Table 1. Repeat for the other speed settings in the table.
8)
Calculate the angular frequency, ω, motor constant, K, and the measured rotation speed based on
the measured period of rotation. Enter the values in Table 1.
Dr. Victor Giurgiutiu
Page 400
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 4
Table 1
Period of
Speed Voltage
rotation, τ
description (V)
(ms)
Rotation
speed, ω
(rad/s)
RPM
Motor
constant, K
Full-speed
¾-speed
½-speed
¼-speed
Very slow
Stopped
Average motor
constant, Kav
PART II – DC MOTOR TACHOMETER (70%)
The program LASTNAME_Firstname_RPM.asm developed in Hmwk6 will be used to measure and
display the rotation speed using the microcontroller input capture function IC1. Recall from Hmwk6 that
T1 is the first time when a falling edge transition is encountered on pin IC1, while T2 is the second time
when a falling edge transition is encountered on the same pin IC1. This corresponds to the time between
two consecutive passages trough the emitter-detector sensor of the hole in the rotating disk. The
difference between T2 and T1, plus the time taken by the overflows, will represent the period of rotation
of the disk. Hence, one can calculate the rotation speed and display it. Since the experimental setup has
only two 7-LED displays, the rotation speed will be displayed in 100s RPM.
1)
Activate the program LASTNAME_Firstname_RPM.asm and let it run
TA checkmark ________
2)
Read the displayed rotational speed and enter the values in the table.
3)
Calculate the error between the displayed value and the calculated value rotation speed value. In
this calculation, take the rotation speed resulting from oscilloscope measurements as the standard.
4)
Calculate the average motor constant and enter its value in the table.
5)
Repeat for the other voltage settings.
TA checkmark ________
TA checkmark ________
Dr. Victor Giurgiutiu
Page 401
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 4
Error in rotation speed
measurement (%)
Displayed speed
(x100 RPM)
Measured speed
(RPM)
Period of rotation, τ
(ms)
Voltage (V)
Speed description
Table 2
Full-speed
¾-speed
½-speed
¼-speed
Very slow
Stopped
Dr. Victor Giurgiutiu
Page 402
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 4
(This page is left intentionally blank)
Dr. Victor Giurgiutiu
Page 403
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Lab 5
LAB 5 STEPPER MOTOR AND A/D CONVERSION
OBJECTIVE
The objective of this laboratory is to introduce the student to the use of:
1. Stepper motors under microprocessor control
2. A/D conversion with the 68HC11 microcontroller
The physical principles and the programming features of these devices will be studied and applied.
PART I – STEPPER MOTORS
PREREQUISITES
Floppy disk with the asm codes for the programs:
• LASTNAME_Firstname_Stepper_Motor.asm
Hard copy (printout) of Hmwk7 – Stepper Motor. When printing, use the 'pages per sheet' option
in the lower right corner of the print dialog-box with settings of 4 or 2 (depending on your
eyesight) to save paper. (We may want to experiment a little with this before printing the full
document.)
PROCEDURE
The students will utilize the asm code developed with the THRSim11 simulator for Hmwk 7 and Hmwk
8. The students will go through the printout of Hmwk7 step by step and will verify that the MCU
responds to instructions as expected.
The lab is divided into sections. After completing each section, the student will ask the TA to check the
student’s work and make a check mark on that section.
The asm code is activated into the MCU following the standard procedure learned in Lab 1.
EXPERIMENTAL SETUP
The experimental setup for this experiment consists of a stepper motor (Figure 1) and its controller
board (Figure 2). The stepper motor controller board is connected to the MCU port B. The MCU
generates a sequence of binary patterns that are used by the controller board to energize the stepper
motor coils and generate motion.
Controller board
Stepper motor
8-pin input
connector
Dr. Victor Giurgiutiu
Page 404
8/19/2008
Fundamentals of Microcontrollers
EMCH 367
Lab 5
Figure 1 Stepper motor and its controller board. Control signals to the controller board are sent
through the 8-pin input connector.
CIRCUIT DIAGRAM
BLACK
RED
Figure 2 Circuit diagram of the stepper motor controller board
WIRING DIAGRAM
Wire
Green wire:
Red wire
Black wire
Connection
+15 V
+5 V
0 V (Ground)
The 8-pin input connector on the controller board is connected to MCU Port B. Make sure to respect the
MSB convention.
PRE-TEST PROCEDURE
Before starting your test, perform the following pre-test procedure to verify that your experimental setup is performing correctly:
1. Check the correct wiring of the stepper motor controller board and input/output connectors:
Dr. Victor Giurgiutiu
Page 405
8/19/2008
Fundamentals of Microcontrollers
EMCH 367
Wire
Green wire:
Red wire
Black wire
Input connector
Output connector
Connection
+15 V
+5 V
0 V (Ground)
Port B
Stepper motor connector
Lab 5
Check mark
2. Test hardware:
Use a removable marker to make two alignment marks, one on the stator, the other on the rotor of the
stepper motor. Energize and establish communication.
Manually send the 2-hex numbers corresponding to the four full-step sequences of Table 1 to the parallel
port B. Use a pencil to mark the position of your marking after each block of four full-step sequences
has been entered. Fill in the answers below:
Estimate the angle of rotation after one complete block of four full-step sequences= ______________
Count the number of blocks of four full-step sequences needed to achieve a complete rotation = _____
Calculate the angle of rotation corresponding to one full step: _______
Deduce the angle of rotation corresponding to a half step: __________
Table 1
Stepper motor energizing patterns and their 2-hex equivalent value
Sequence
Energizing
pattern
S0
S1
S2
S3
S4
S5
S6
S7
1000
1001
0001
0101
0100
0110
0010
1010
8-bit
2-hex
equivalence
$08
$09
$01
$05
$04
$06
$02
$0A
Phase
energizing
type
1 phase
2 phase
1 phase
2 phase
1 phase
2 phase
1 phase
2 phase
Step type
Half step
Full step
Half step
Full step
Half step
Full step
Half step
Full step
STEPPER MOTOR CONTROL PROGRAM
Run the program of homework 7 using the commands >, <, +, -, S: Verify that it can be controlled to do
forward and backward motion, slower and faster. Verify that it stops.
i)Move forward
>
Check mark
ii)Move backward
<
Check mark
iii)Increase speed (decrease delay)
+
Check mark
iv)Decrease speed (increase delay)
-
Check mark
v)Stop program
S
Check mark
Dr. Victor Giurgiutiu
Page 406
8/19/2008
Fundamentals of Microcontrollers
EMCH 367
Lab 5
When satisfied with the program operation, show it to your TA.
TA checkmark ________
PART II – A/D CONVERSION
PREREQUISITES
Floppy disk with the asm codes for the program:
• LASTNAME_Firstname_AD.asm
Hard copy (printout) of Hmwk8 – A/D Conversion. When printing, use the 'pages per sheet'
option in the lower right corner of the print dialog-box with settings of 4 or 2 (depending on your
eyesight) to save paper. (We may want to experiment a little with this before printing the full
document.)
PROCEDURE
The students will utilize the asm code developed with the THRSim11 simulator for Hmwk8. The
students will go through the printout of Hmwk8 step by step and will verify that the MCU responds to
instructions as expected.
The lab is divided into sections. After completing each section, the student will ask the TA to check the
student’s work and make a check mark on that section.
The asm code is activated into the MCU following the standard procedure learned in Lab 1.
EXPERIMENTAL SETUP
+5 V
Power
Supply
Variable
Potentiometer
Port E
Protection Card
MCU
Port E pin
PE4
Multimeter
MCU
Port B
8-LED
Display
Figure 3 AD conversion experiment: block diagram
The analog-to-digital (AD) converter function of the M68HC11 microprocessor will be used to record,
as eight-bit digital data, the analog signals developed by a variable potentiometer and sent to the MCU
through port E pin PE4.
The experimental setup (Figure 3) consists of a variable potentiometer, port E protection card,
multimeter, the MCU port E, the MCU port B, and an 8-LED display. The potentiometer generates an
adjustable voltage (analog signal) in the range 0 – 5 V. The analog signal is through the port E
protection card to the MCU port E. The multimeter records the value (mV) of the analog signal that
enters the MCU. Inside the MCU, the analog signal is converted to 8-bit digital. Conversion is effected
continuously, in a round-robin fashion and stored internally in four variables (VAL1 – VAL4). The
average of these four values is calculated by software and output through MCU port B for digital display
on the 8-LED display.
Dr. Victor Giurgiutiu
Page 407
8/19/2008
Fundamentals of Microcontrollers
EMCH 367
Lab 5
WIRING DIAGRAM
Wire
Red wire
Black wire
Yellow wire
Connection
+5 V
0 V (Ground)
Potentiometer variable output (0 – 5 V)
EQUIPMENT LIST
• +5V power supply
•
variable potentiometer
•
8-LED display
•
multi-meter
PRE-TEST PROCEDURE
Before starting your test, perform the following pre-test procedure to verify that your experimental setup is performing correctly:
1. Check the correct wiring of the potentiometer, port E protection card, port E pin PE4:
Wire
Red wire
Black wire
Port E protection
card and port E
Input connector
Multimeter
Output connector
Connection
+5 V
0 V (Ground)
MSB alignment
Check mark
Port E protection card pin PE4
Probe to PE4
8-LED display MSB alignment
2. Connect multimeter to yellow wire. Adjust the potentiometer and verify that voltages in the
range 0 – 5 V can be generated.
3. Set potentiometer to generate approx. 750 mV. Check with the multimeter probe that the
generated voltage passes through the port E protection card and arrives at actual port E pin PE4.
AD CONVERTION TEST PROCEDURE
When you are satisfied that the hardware works satisfactorily, proceed with the actual AD conversion
experiment. Table 2 list six target voltage values. With your program running, do the following for each
target voltage:
1. Reading with the multimeter, adjust the potentiometer to within the target value, and, when the
reading is steady, record it in the ‘Actual’ column of Table 2.
2. Calculate the predicted value resulting from AD conversion. Perform the calculation in hex, then
convert to binary. Enter the values in the corresponding column under the heading ‘Predicted’.
3. Call TA to verify.
4. Proceed to the next target voltage.
Dr. Victor Giurgiutiu
Page 408
8/19/2008
Fundamentals of Microcontrollers
EMCH 367
Lab 5
Table 2
#
1
2
3
4
5
6
Voltage at pin PE4 (mV)
Target
Actual
750
1600
2200
3000
4000
5000
Dr. Victor Giurgiutiu
Digital values from AD conversion
Predicted
Displayed
Hex
Binary
$
%
%
$
%
%
$
%
%
$
%
%
$
%
%
$
%
%
Page 409
TA check
mark
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 1
APPENDIX 1 HEX_BCD
This subroutine will convert the HEX number in the ACCA register to BCD number. After this
subroutine is performed, the converted BCD number is stored in the ACCA register for future use.
* HEX_BCD subroutine
* This S/R converts from Hex to BCD the number in accA
HEX_BCD PSHX
; save X in the stack
PSHB
; save B in the stack
TAB
; transfer info from A into low D
CLRA
; clear A
LDX
#10
; load 10 into X
IDIV
; divide info by 10. Quotient ends
; in X, reminder stays in low D
TBA
; transfer reminder (1st decimal
; digit) from low D into A
PSHA
; save 1st digit in the stack
XGDX
; exchange D and X. Quotient
; (i.e., 2nd digit) is now in low D
; i.e, in B
PULA
; retrieve A from the stack.
; 1st digit is now in A
LSLB
; shift B to the left 4 times to get
LSLB
; 2nd digit to the left of B
LSLB
;
LSLB
;
ABA
; add A and B, results stays in A
; now we have both digits in A,
; in the proper order.
PULB
; retrieve original B from stack
PULX
; retrieve original X from stack
RTS
; return
Dr. Victor Giurgiutiu
Page 410
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 1
(This page is intentionally left blank)
Dr. Victor Giurgiutiu
Page 411
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 2
APPENDIX 2 HOW TO SOLDER
Soldering is defined as "the joining of metals by a fusion of alloys which have relatively low melting
points". In other words, you use a metal that has a low melting point to adhere the surfaces to be
soldered together. Soldering is more like gluing with molten metal than anything else. Soldering is also a
must have skill for all sorts of electrical and electronics work. It is also a skill that must be taught
correctly and developed with practice.
This document attempts to teach soldering through a few simple steps. Tips and tricks are also provided
at the end.
HOW TO SOLDER
Step 1: Equipment
Soldering requires two main things: a soldering iron and solder. Soldering irons are the heat source used
to melt solder. Irons of the 15W to 30W range are good for most electronics/printed circuit board work.
Anything higher in wattage and you risk damaging either the component or the board. Note that you
should not use so-called soldering guns. These are very high wattage and generate most of their heat by
passing an electrical current through a wire. Because of this, the wire carries a stray voltage that could
damage circuits and components. The choice of solder is also important. One of the things to remember
is to never use acid core solder. Acid core solder will corrode component leads, board traces and form
conductive paths between components. The best solder for electronics work is a thin rosin core solder. I
prefer a thickness of 0.75mm, but other thicknesses will also work. Just remember not to get anything
too thick.
Remember that when soldering, the rosin in the solder releases fumes. These fumes are harmful to your
eyes and lungs. Therefore, always work in a well ventilated area. Hot solder is also dangerous. Be sure
not to let is splash around because it will burn you almost instantly. Eye protection is also advised.
Step 2: Surface Preparation:
A clean surface is very important if you want a strong, low resistance joint. All surfaces to be soldered
should be cleaned with steel wool and some sort of solvent. Laquer thinner works well. Some people
like to use sand paper, but I think that it is all too easy to sand right through circuit board traces, so steel
wool is my preference. Don't neglect to clean component leads, as they may have a built up of glue from
packaging and rust from improper storage.
Step 3: Component Placement
After the component and board have been cleaned, you are ready to place the component on the board.
Bend the leads as necessary and insert the component through the proper holes on the board. To hold the
part in place while you are soldering, you may want to bend the leads on the bottom of the board at a 45
degree angle. Once you are sure that the component is properly placed, you can more on to the next step.
Dr. Victor Giurgiutiu
Page 412
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 2
Step 4: Apply Heat
Apply a very small amount of solder to the tip of the iron. This helps conduct the heat to the component
and board, but it is not the solder that will make up the joint. Now you are ready to actually heat the
component and board. Lay the iron tip so that it rests against both the component lead and the board.
Normally, it takes one or two seconds to heat the component up enough to solder, but larger components
and larger soldering pads on the board can increase the time.
Step 5: Apply Solder And Remove Heat
Once the component lead and solder pad has heated up, you are ready to apply solder. Touch the tip of
the strand of solder to the component lead and solder pad, but not the tip of the iron. If everything is hot
enough, the solder should flow freely around the lead and pad. Once the surface of the pad is completely
coated, you can stop adding solder and remove the soldering iron (in that order). Don't move the joint
for a few seconds to allow the solder to cool. If you do move the joint, you will get what's called a "cold
joint". This will be discussed shortly.
Dr. Victor Giurgiutiu
Page 413
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 2
Step 6: Cleanup
After you have made all the solder joints, you may wish to clean with steel wool or solvent to remove all
the left over rosin. You may also wish to coat the bottom of the board with laquer. This will prevent
oxidation and keep it nice and shiny.
COLD SOLDER JOINTS
A cold joint is a joint in which the solder does not make good contact with the component lead or
printed circuit board pad. Cold joints occur when the component lead or solder pad moves before the
solder is completely cooled. Cold joints make a really bad electrical connection and can prevent your
circuit from working.
Cold joints can be recognized by a characteristic grainy, dull gray colour, and can be easily fixed. This is
done by first removing the old solder with a desoldering tool or simply by heating it up and flicking it
off with the iron. Once the old solder is off, you can resolder the joint, making sure to keep it still as it
cools.
TIPS AND TRICKS
Soldering is something that needs to be practiced. These tips should help you become successful so you
can stop practicing and get down to some serious building.
Dr. Victor Giurgiutiu
Page 414
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 2
1. Use heatsinks. Heatsinks are a must for the leads of sensitive components such as ICs and
transistors. If you don't have a clip on heatsink, then a pair of pliers is a good substitute.
2. Keep the iron tip clean. A clean iron tip means better heat conduction and a better joint. Use a
wet sponge to clean the tip between joints.
3. Double check joints. It is a good idea to check all solder joints with an ohm meter after they are
cooled. If the joint measures any more than a few tenths of an ohm, then it may be a good idea to
resolder it.
4. Use the proper iron. Remember that bigger joints will take longer to heat up with an 30W iron
than with a 150W iron. While 30W is good for printed circuit boards and the like, higher
wattages are great when soldering to a heavy metal chassis.
Solder small parts first. Solder resistors, jumper leads, diodes and any other small parts before you
solder larger parts like capacitors and transistors. This makes assembly much easier.
Dr. Victor Giurgiutiu
Page 415
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Appendix 3
APPENDIX 3 FLOW CHART TEMPLATE
BASIC FLOWCHART COMPONENTS
The development of complex programs may be facilitated with the use of simple flowcharts
constructed using the following basic components. Additional logic components may also be
employed.
Flowchart symbol
Definition
Logic connectors
Action symbol
Logic symbols
Label symbol
Software interrupt symbol
EXAMPLE FLOWCHART – DELAY PROGRAM
Here is an example of a simple flowchart and how it may be used to facilitate the development of
a simple program:
(i) Define variable DELAY at $0000
(ii) Load DELAY into accA
Code
Flowchart
DELAY RMB 1
(iii) Decrement accA
(iv) Branch back to (iii) if the result is higher
than zero (unsigned >0)
LDAA DELAY
LABEL1
BHI
(vi) SWI
Dr. Victor Giurgiutiu
SUBA #1
LABEL1
SWI
Page 416
8/19/2008
EMCH 367
Dr. Victor Giurgiutiu
Fundamentals of Microcontrollers
Appendix 3
Page 417
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Course Package.doc 4
APPENDIX 4 EXPLANATION OF EXAMPLE OUTPUT COMPAE TIMER
FUNCTION
#INCLUDE
'C:\Temp\VAR_DEF.ASM'
• Define program variables
•
ORG DATA
DT
RMB 2
; Half wave duration
* Start main program
ORG PROGRAM
START
LDX #REGBAS
LDAA #%00010000 ;
*mask for OM3=0, OL3=1
STAA TCTL1,X
;
*set OC3 to toggle
LDD DT
*store TCNT+DT in TOC3
ADDD TCNT,X
STD TOC3,X
*Main loop
LABEL1
LDAA TFLG1,X
*check OC3F
ANDA #%00100000
*mask for OC3F
BEQ LABEL1
*loop back
*We are here when output compare happens
LDAA #%00100000
*reset OC3F
STAA TFLG1,X
LDD DT
*add DT to TCNT
ADDD TCNT,X
STD TOC3,X
*store new time in TOC3
BRA LABEL1
*back to the top
SWI
The output at OC3 will toggle when TCNT=OC3, and the corresponding bit in TFLG1 will also
be set. If we count the cycles of every instruction, we can draw the table as shown below:
4
9(cycles)
2
3
2
4
24(cycles)
4
6
LDAA
TFLG1,X
ANDA
#%00100000
BEQ
LABEL1
LDAA
#%00100000
STAA
TFLG1,X
LDD DT
ADDD
TCNT,X
5
STD
TOC3,X
3
BRA
LABEL
If we set a breakpoint at LDAA #%00100000, just after the checking TFLG loop is done, we may
want to know the relationship between the value of DT and ∆T. Let’s assume we start our
calculating from the breakpoint; what we want to know is how many clock cycles the program
will run till next breakpoint for a DT.
Dr. Victor Giurgiutiu
Page 418
8/19/2008
EMCH 367
Fundamentals of Microcontrollers
Course Package.doc 4
Let’s assume that before the instruction ADDD TCNT,X is performed, the value of TCNT is
TCNT1; we run the program step by step and can find that after the instruction: STD TOC3,X.
The value of TOC3 is TCNT1+4+DT, while the current value of TCNT is TCNT1+11, the
program will keep running until TCNT reaches the value of TOC3, i.e. TCNT1+4+DT. So, when
the checking procedure begins, the difference between TCNT and TOC3 Is: DT-10.
The next work is to find how many checking loops the program will need to detect if TCNT
reaches TOC3.The checking procedure occupies 9 clock cycles, so we assume:
DT-10 = a*9+b;
if b > 4, that means the toggle happens after the instruction LDAA TFLG1,X, so an additional loop is
needed for the program to detect that the TFLG has been set.
if b <=4, the program can detect the TFLG immediately so that no additional loops is needed.
After we know how many loops are needed, the total cycles between breakpoints will be:
9*(number of loops)+24.
So we can write the equations below:
∆T=9*(a+2)+24 if b>4;
or
∆T=9*(a+1)+24 if b<=4.
Let’s take DT=$0020 as one example,
DT-10= 32-10 =22, 22= 2*9 +4, a=2, b=4<=4, so
∆T=9*(a+1) +24=9*(2+1)+24=51.
Dr. Victor Giurgiutiu
Page 419
8/19/2008