2000_TI_MSP430_Application_Reports 2000 TI MSP430 Application Reports

User Manual: 2000_TI_MSP430_Application_Reports

Open the PDF directly: View PDF PDF.
Page Count: 1095

Download2000_TI_MSP430_Application_Reports 2000 TI MSP430 Application Reports
Open PDF In BrowserView PDF
l!} TEXAS

INSTRUMENTS

MSP430 Fal11ily

Mixed-Signal Microcontrollers

2000

2000

Analog and Mixed-Signal

IMPORTANT NOTICE
Texas Instruments and its subsidiaries (TI) reseNe the right to make changes to their products or to discontinue
any product or seNice without notice, and advise customers to obtain the latest version of relevant information
to verify, before placing orders, that information being relied on is current and complete. All products are sold
subject to the terms and conditions of sale supplied at the time of order acknowledgement, including those
pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semiconductor products to the specifications applicable at the time of sale in
accordance with TI's standard warranty. Testing and other quality control techniques are utilized to the extent
TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily
performed, except those mandated by government requirements.
CERTAIN APPLICATIONS USING SEMICONDUCTOR PRODUCTS MAY INVOLVE POTENTIAL RISKS OF
DEATH, PERSONAL INJURY, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE (''CRITICAL
APPLICATIONS"). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, AUTHORIZED, OR
WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT DEVICES OR SYSTEMS OR OTHER
CRITICAL APPLICATIONS. INCLUSION OF TI PRODUCTS IN SUCH APPLICATIONS IS UNDERSTOOD TO
BE FULLY AT THE CUSTOMER'S RISK.
In order to minimize risks associated with the customer's applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assistance or customer product design. TI does not warrant or represent
that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other
intellectual property right of TI covering or relating to any combination, machine, or process in which such
semiconductor products or seNices might be or are used. TI's publication of information regarding any third
party's products or seNices does not constitute Tl's approval, warranty or endorsement thereof.

Copyright © 2000, Texas Instruments Incorporated

MSP430 Family
Mixed-Signal Microcontroller
Application Reports
Author: Lutz Bieri

Literature Number: SLAA024
January 2000

~TEXAS

INSTRUMENTS

IMPORTANT NOTICE
Texas Instruments and its subsidiaries (TIl reserve the right to make changes to their products or to discontinue
any product or service without notice, and advise customers to obtain the latest version of relevant information
to verify, before placing orders, that information being relied on is curient and complete. All products are sold
subject to the terms and conditions of sale supplied at the time of order acknowledgement, including those
pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semiconductor products to the specHlcations applicable at the time of sale in
accordance with Tl's standard warranty. Testing and other quality control techniques are utilized to the extent
TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily
performed, except those mandated by government requirements.
CERTAIN APPLICATIONS USING SEMICONDUCTOR PRODUCTS MAY.lNVOLVE POTENTIAL RISKS OF
DEATH, PERSONAL INJURY, OR ·SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE ("CRITICAL
APPLICATIONS,,). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, AUTHORIZED, OR
WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT DEVICES OR SYSTEMS OR OTHER
CRITICAL APPLICATIONS. INCLUSION OF TI PRODUCTS IN SUCH APPLICATIONS IS UNDERSTOOD TO
BE FULLY AT THE CUSTOMER'S RISK.
In order to minimize risks associated with the customer's applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assistance or customer product design. TI does not warrant or represent
that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other
intellectual property right of TI covering or relating to any combination, machine, or process in which such
semiconductor products or services might be or are used. Tl's publication of information regarding any third
party's products or services does not constitute Tl'sapproval, warranty or endorsement thereof.

Copyright © 2000, Texas Instruments Incorporated

Preface

Read This First
How to Use This Manual
This document contains the following chapters:

o

Chapter 1 - MSP430 Microcontroller Family: Introduction to the MSP430
family, advantages of the MSP430 concept, and operating modes

o
o
o
o
o
o
o
o

Chapter 2 - MSP430 14-Bit Analog-To-Digital Converter:
Chapter 3 - MSP430 Hardware Applications:
Chapter 4 - MSP430 Application Examples:
Chapter 5 - Software Applications:
Chapter 6 - On-Chip Peripherals:
Chapter 7 - Hints and Recommendations:
Chapter 8 - Architecture and Instruction Set:
Chapter 9 - CPU Registers:

iii

iv

_..

lit 1

,tilt

tiUt 8' 1

Contents
--

MSP430 Mlcrocontroller Family. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 1-1
1.1
1.2
1 .3
1.4

1.5

1.6

2

Introduction. . . . .. . . .. .. . . . . . . . . .. . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . .. 1-2
Related Documents .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 1-3
Notation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 1-3
MSP430 Family ............................................................ 1-4
1.4.1
MSP430C31 x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 1-5
1.4.2 MSP430C32x ....................................................... 1-6
1.4.3 MSP430C33x ..................................................... " 1-6
Advantages of the MSP430 Concept .......................................... 1-8
1.5.1
RISC Architecture Without RISC Disadvantages. . . . . . . . . . . . . . . . . . . . . . . .. 1-8
1.5.2 Real-Time Capability With Ultra-Low Power Consumption ................ 1-8
1.5.3 Digitally Controlled Oscillator Stability .................................. 1-9
1.5.4 Stack Processing Capability .......................................... 1-9
MSP430 Application Operating Modes ....................................... 1-10
1.6.1
Active Mode ....................................................... 1-10
1.6.2 Low Power Mode 3 (LPM3) .......................................... 1-10
1.6.3 Low Power Mode 4 (LPM4) .......................................... 1-13

Analog-Te-Digital Converters ..................................................... 2-1
Architecture and Function of the MSP430 14-Blt ADC .............................. 2-3
A table of contents for this application report is found starting on page . . . . . . . . . .. 2-5

Application Basics for the MSP430 14-Blt ADC ................................... 2-41
A table of contents for this application report is found starting on page . . . . . . . . .. 2-43

Additive Improvement of the MSP430 14-Blt ADC Characteristic ................... 2-83
A table of contents for this application report is found starting on page : . . . . . . . .. 2-85

Linear Improvement of the MSP430 14-Blt ADC Characteristic ............•....... 2·113
A table of contents for this application report is found starting on page . . . . . . . .. 2-115

Nonlinear Improvement of the MSP430 14-Blt ADC Characteristic . ................ 2-143
A table o.f contents for this application report is found starting on page . . . . . . . .. 2-145

Using the MSP430 Universal Timer/Port Module as an Analog-te-Dlgltal Converter . 2-175
A table of contents for this application report is found starting on page . . . . . . . .. 2-177

v

Contents

3

Hardware Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3·1
3.1
I/O Port Usage ............................................................. 3-2
3.1 .1 General Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3-2
3.1.2 Zero Crossing Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3-6
3.1 .3 Output Buffering ................... '.' .............................. :. 3-8
3.1.4 Uniliersal Timer/Port I/Os ....... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3-9
3.1.5 110 Used for Fast Serial Transfers .................................... 3-11
3.2
Storage of Calibration Constants ............................................ 3-14
3.2.1
Extemal EPROM for Calibration Constants ............................ 3-14
3.2.2 Intemal RAM for Calibration Constants ................................ 3-16
3.3
M-Bus Connection ......................................................... 3-17
12C Bus Connection ........................................................ 3-18
3.4
3.5
Hardware Optimization ..................................................... 3-25
3.5.1
Use of Unused Analog Inputs ........................................ 3-25
3.5.2 Use of Unused Segment Lines for Digital Outputs ...................... 3-28
3.6
Digital-ta-Analog Converters ................................................ 3-30
3.6.1
Rl2R Method .............................. ,....................... 3-30
3.6.2 Weighted Resistors Methap .......................................... 3-31
3.6.3 Digital-to-Analog Converters Connected Via the 12C Bus ................ 3-32
3.6.4 PWM DAC With the Universal Timer/Port Module . . . . . . . . . . . . . . . . . . . . . .. 3-33
3.6.5. PWM DAC With the Timer_A ............................•..........•• 3-42
3.7
Connection of Large Extemal Memories ....................................... 3-45
3.8
Power Supplies for MSP430 Systems ........................................ 3-52
3.8.1
Battery-Power Systems ............................................. 3-52
3.8.2 Accumulator-Driven Systems .........•...................•.......... 3-54
3.8.3 AC-Drlven Systems .•. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . •. 3-56
3.8.4 Supply From Other System DC Voltages .............................. 3-68
3.8.5 Supply From the M Bus ............................................. 3-71
3.8.6 Supply Via a Fiber-Optic Cable ....................................... 3-73

4

Application Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4·1
4.1
Electricity Meters .....•...•.............•......•........................... , 4-2
4.1.1
Overview .............................................••...•...... " 4-2
4.1.2 The Measurement Principle . . . . . . . . . . • . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . •. 4-3
4.1.3 The Analog-to-Digital Converter of the MSP430C32x . . . . • . . . . . . . . . . . . . .. 4-11
4.1 .4 Analog Interfaces to the MSP430 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-18
4.1.5 Single-Phase Electricity Meters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-30
4.1.6 Dual-Phase Electricity Meters ........•.•............................. 4-35
4.1.7 Three-Phase Electricity Meters . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . • . . . . . . .. 4-39
4.1.8 Measurement of Voltage, Current. Apparent Power. and Reactive Power .. 4-49
4.1.9 Calculation of the System Current Consumption .................•...... 4-50
4.1 .10 System Components ....•••.......................•••..•.... ; . . . . . .. 4-52
4.1.11 Electricity Meter With an Extemal ADC ...•............................ 4-56
4.1 .12 Error 'Simulation for an MSP430C32x-Based Electricity Meter ............ 4-58

vi

Contents

4.2
4.3
4.4
4.5
4.6
4.7

4.8

4.9

4.10

4.11

5

Gas Meter ................................................................ 4-64
Water Flow Meter .......................................................... 4-69
Heat Allocation Counter .................................................... 4-70
Heat Volume Counter ...................................................... 4-72
Battery Charge Meter .............................................'......... 4-75
Connection of Sensors ..................................................... 4-77
4.7.1
Sensor Connection and Linearization ..........•...................... 4-77
4.7.2 Connection of Special Sensors ....................................... 4-82
RF Readout ......................................'. . . . . . . . . . . . . . . . . . . . . . . .. 4-87
4.8.1
MSP430 Electricity Meter ......... , .............................. , , .. 4-87
4.8,2 MSP430 Electricity Meter With Front End ...... , .... , ... , , , , , ... , .... '. 4-88
4.8.3 MSP430 Ferraris-Wheel Electricity Meter With RF Readout .............. 4-90
4.8.4 RF-Interface Module ............. , .................................. 4-91
4.8.5 Protocol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-92
4.8.6 RF Readout With Other Metering Applications. . . . . . . . . . . . . . . . . . . . . . . . .. 4-93
Ultra-Low-Power Design With the MSP430 Family ............................. 4-94
4.9.1 The Ultra Low Power Concept of the MSP430 ....... , . . . . . . . . . . . . . . . . .. 4-94
4.9.2 Current Consumption and Battery Life. . . .. . . . .. . .. . . .. . . . . . .. . . . . . . . .. 4:-96
4.9.3 Minimization of the System Consumption ....................... ,...... 4-98
4.9.4 Correct Termination of Unused Terminals (3xx Family) ................. 4-102
Other MSP430 Applications . . . .. . . . .. . . . . . .. . . . . . . . . . . . . . . . . .. . . . . . .. . . . ... 4-104
4.10.1 Controller for a Heating Installation .................................. 4-104
4.10.2 Pocket Scale .............................................. , ....... 4-107
4.10.3 Remote Control Applications ........................................ 4-108
4.10.4 Sub-Controller for a TV Set ....................... :................. 4-110
4.10.5 Sub-Controller of a Personal Computer.. . . . . . . . . . . . . . . . .. . . .. . .. . . ... 4-112
4.10.6 Subcontroller of a FAX Device. . .. .. . . . .. . . . . .. . .. . . . . . . . . . .. . . . .. ... 4-114
Digital Motor Control ...................................................... 4-115
4.11.1 Introduction ............. , .... , .................................... 4-115
4.11.2 Digital Motor Control With Pulse Width Modulation (PWM) .............. 4-119
4.11 .3 Digital Motor Control With TRIACs .. .. .. . .. .. . . . .. .. .. .. .. .. .. .. .. ... 4-138
4.11.4 Motor Measurements .............................................. 4-145
4.11.5 Conclusion ....................................................... 4-150

Softwa'ra Applications •...•••••••.•••••..••••••.••••..••••••.•..•.......•••.••••. 5-1
5.1

Integer Calculation Subroutines .............................................. 5-2
5.1.1
Unsigned Multiplication 16 x 16-Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-2
5.1.2 Signed Multiplication 16 x 16-Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-7
5.1.3 Unsigned Multiplication 8 x 8-Bits . . . . . .. . . . . . . . .. . . . .. . . . .. . . . .. . . . ... 5-11
5.1.4 Signed Multiplication 8 x 8-Bits ....................................... 5-13
5.1.5 Unsigned Division 32/16-Bits .. . . . .. . . .. . . . . . . . . .. .. .. . .. .. .. . . . . . . . .. 5-16
5.1 .6 Signed Division 32116-Bits ...... .. . .. .. . .. .. .. .. .. .. .. .. .. .. .. . .. . ... 5-17
5.1.7 Shift Routines ...................................................... 5-19
5.1.8 Square Root Routines. . . . . . .. .. . .. . . . . . .. . . .. . . . . . .. . .. .. . . . .. . . .. .. 5-20
Contents

vii

Contents

5.2

5.3

5.4

5.5

5.6

5.7

6

On-Chip Peripherals ............................................................. 8-1
6.1

viii

5.1.9 Signed and Unsigned 32-Bit Compares ............................... 5-25
5.1.10 Random Number Generation .......... '.............................. 5-26
5.1.11 Rules for the Integer Subroutines ..................................... 5-29
Table Processing .......................................................... 5-32
5.2.1 Two Dimensional Tables ............................................. 5-34
5.2.2 Three-Dimensional Tables ................ .. .. . .. . . . .. . . . . . .. . . .. . ... 5-41
Signal Averaging and Noise Cancellation .......................•..•.......... 5-45
5.3.1
Oversampling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . .. 5-45
5.3.2 COntinuous Averaging ............................................... 5-46
5.3.3 Weighted Summation .... ;.......................................... 5-48
5.3.4 Wave Digital Filtering ............................................... 5-49
5.3.5 Rejection of Extremes .....•......................................... 5-50
5.3.6 Synchronization of the Measurement to Hum. . . . . . . . . . . .. . . . . . . . . . . • . .. 5-52
Real-Time Applications ..................... ,'............................... 5-55
5.4.1 Active Mode ......................................................• 5-55
5.4.2 Normal Mode is Low-Power Mode 3 (LPM3) ............. ;............. 5-55
5.4.3 Normal Mode is Low-Power Mode 4 (LPM4) ........................... 5-55
5.4.4 Recommendations for Real-Time Applications. . • . . . . . . . . . . . . . . . . . . . . . .. 5-56
General Purpose Subroutines ............................................... 5-57
5.5.1
Initialization .......................................... : ............. 5-57
5.5.2 RAM clearing Routine ............................................... 5-58
5.5.3 Binary to BCD Conversion ........................................... 5-58
5.5.4 BCD to Binary. . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-60
5.5.5 Keyboard Scan .................................•................... 5-61
5.5.6 Temperature Calculations for Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-63
5.5.7 Data Security Applications ........................................... 5-70
5.5.8 Status/Input Matrix .................................................. 5-78
The Floating-Point Package ............................ : . . . . . . . . . . . . . . . . . . .. 5-83
5.6.1 General. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-83
5.6.2 Common Conventions .............................................. 5-84
5.6.3 The Basic Arithmetic Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-86
5.6.4 Calling Conventions for the Comparison .. .. . . . . . .. .. . .. .. . . . .. . . .. . ... 5-95
5.6.5 Internal Data Representation .. .. . .. .. .. . .. .. .. .. .. . .. . .. .. .. . .. . .. ... 5-96
5.6.6 Execution Cycles ...................... .. .. .. . .. . .. .. . . . .. .. .. .. . ... 5-98
5.6.7 Conversion Routines ..............•................................. 5-99
5.6.8 Memory Requirements of the Floating Point Pa~ge .................. 5-111
5.6.9 Inclusion of the Floating-Point Package into the Customer Software . . .. .. 5-111
5.6.10 Software Examples ................................................ 5-113
Battery Check and Power Fail Detection ..................................... 5-164
5.7.1 Battery Check .........•••..................•...................... 5-164
5.7.2 Power Fail Detection ............................................... 5-175
5.7.3 ·Conclusion ....................................................... 5-188
The Basic Timer . . . . . . . . . . . . . . . . . • . • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6·2

Contents

6.2

6.3

6.4

6.5

6.6

6.7

6.1.1
Change Of the Basic Timer Frequency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-4
6.1.2 Elimination of Crystal Tolerance Error .................................. 6-5
6.1.3 Clock Subroutines ................................................... 6-9
6.1.4 The Basic Timer Used as a 16-BltTlmer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-11
The Watchdog Timer ....................................................... 6-13
6.2.1 Supervision of One Task With the Watchdog ........................... 6-13
6.2.2 Supervision of Multiple Tasks With the Watchdog ...................•... 6-13
The Timer_A .............................................................. 6-18
6.3.1
Introduction ........................................................ 6-18
6.3.2 Timer_A Hardware ................................................. 6-23
6.3.3 Timer Modes ........ '............................................... 6-47
6.3.4 The Timer_A Interrupt Logic ......................................... 6-60
6.3.5 The Output Units ................•.................................. 6-62
6.3.6 Limitations of the Timer_A ........................................... 6-73
6.3.7 Miscellaneous ...................................................... 6-77
6.3.8 Software Examples for the Continuous Mode .......................... 6-77
6.3.9 Software Examples for the Up Mode ................................. 6-136
6.3.10 Software Examples for the Up/Down Mode ........................... 6-180
The Hardware Multiplier ................................................... 6-222
6.4.1
Function ofthe Hardware Multiplier .................................. 6-222
6.4.2 Multiplication Modes ............................................... 6-227
6.4.3 Programming the Hardware Multiplier ................................ 6-230
6.4.4 Software Applications .............................................. 6-240
The System Clock Generator.. . . . . . .. .. . . . . . . . . . . . . .. . . .. . . . . . . . . . . . . . .. ... 6-256
6.5.1
Initialization . . . .. . . . .. . . . .. . . . . . .. . . . . . . . . . . . . . . .. . . . . . .. . . . . . . . . .. 6-256
6.5.2 Entering of Low Power Mode 3 ..................................... , 6-257
6.5.3 Wake-Up From Interrupts in Low Power Mode 3 ....................... 6-257
6.5.4 Adaptation ofthe DCO Tap during Calculations . . . . . . . . . . . . . . . . . . . . . . .. 6-257
6.5.5 Wake-Up from Interrupts in Low Power Mode 4 . . . . . . . . . . . . . . . . . . . . . . .. 6-258
6.5.6 Change of the System Frequency ................................... 6-259
6.5.7 The Modulation Bit M .............................................. 6-260
6.5.8 Use Without Crystal ................................................ 6-261
6.5.9 High System Frequencies Together With the 14-bit ADC ................ 6-261
6.5.10 Dependencies of the System Clock Generator ........................ 6-261
6.5.11 Short Time Accuracy of the System Clock Generator .. . . . . . . . . . . . . . . . .. 6-262
6.5.12 The Oscillator Fault Interrupt Flag ..•.....................•.......... 6-265
6.5.13 Conclusion .................•..................................... 6-266
The RESET Function ..................................................... 6-267
6.6.1
Description of the MSP430 RESET Function .......................... 6-267
6.6.2 RESET With the Internal Hardware, Including the Watchdog ............ 6-271
6.6.3 Reliable RESET With Slowly Rising Power Supplies ................... 6-272
6.6.4 Conclusion ........................................................ 6-280
The Universal Timer/Port Module ........................................... 6-281
6.7.1
Universal Timer/Port Used as an Analog-ta-Digital Converter. . . . . . . . . . .. 6-282
Contents

ix

Contents

6.8
6.9

6.10

6.11

6.7.2 Universal Timer/Port Used as a Timer ........ .. .. .. .. .. .. .. .. .. .. ....
The Crystal Buffer Output • . . . . . . • • . . . . . . . • . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . ..
The USART Module .......................................................
6.9.1
Introduction... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . ..
6.9.2 Baud Rate Generation .............................................
6.9.3 Software Routines . . .. . . .. . . . . . .. . . . . . . . . .. . . . .. . . . .. . .. . . . . . .. . ...
The 8-Bit Interval Timer/Counter ............................................
6.10.1 Introduction .......................................................
6.10.2 Function of the UART Hardware ........................... : .........
6.10.3 The Baud Rate Generation and Correction ............... ". . . . . . . .. . . ..
6.10.4 Software Routines ........... " . . .. . . .. . . . .. .. . . . .. . .. .. . . . .. . . . . ...
The Comparator_A .......................................................
6.11.1 Definitions Used With the Application Examples .......................
6.11.2 Fast Comparator Input Check .................................. " .. ..
6.11.3 Voltage Measurement . .. . . . .. .. . .. .. . . . .. .. . . . . . . . . . . . . . . . .. . . . . ...

6-282
6-285
6-288
6-289
6-294
6-301
6-318
6-318
6-322
6-330
6-336
6-358
6-359
6-361
6-363

7

Hints and Recommendations ••.. . • • • • • . . . . • . . . . . • . . . . . . • • . . • • • . . • . . . . • • . . . . . • • . .• 7·1
7.1
Hints and R~ommendations ................................................. 7-2
7.2
Design Checklist .................................... " ....................... 7-8
7.3
Most Frequent Software Errors ............................................... 7-9
7.4
Most Frequent Hardware Errors ............................................. 7-13
7.5
Checklist for Problems ...... ~ .............................................. 7-14
7.5.1
Hardware Related Problems ......................................... 7-14
7.5.2 Software Related Problems .......................................... 7·14
7.6
Run .Time Estimation .... . . . . . . . . . . . . . . • • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 7·15

8

Architecture and Instruction Set ................... .. • • • • • • . . .. • • • .. . • • . • . • .. • • • •• 8-1
8.1
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 8-2
8.2
Reasons for the Popularity of the MSP430 ..................................... 8-3
8.2.1
Orthogonality. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 8-3
8.2.2 Addressing Modes.. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. . .. .. .. .. .. . ... 8-4
8.2.3 RISC Architecture Without RISC Disadvantages. . . . . . . . . . . . . . . . . . . . . . . .. 8-7
8.2.4 Constant Generator ................................... :. . . .. . . .. .. . .. 8-8
8.2.5 Status Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 8-8
8.2.6 Stack Processing.. • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . .. 8-9
8.2.7 Usability of the Jumps ...................................•............ 8-9
8.2.8 Byte and Word Processor ...... ,..................................... 8-9
8.2.9 High Register Count ..................... ; .......................... 8·10
8.2.10 Emulation of Non-Implemented Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . .. 8-11
8.2.11 No Paging ......•...................•.............................. 8-11
8.3
Effects and Advantages of the MSP430 Architecture ........................... 8-12
8.3.1
Less Program Space ................................................ 8-12
8.3.2 Shorter Programs .................................................. 8-12
8.3.3 Reduced Development Time ......................................... 8-12

x

Contents

8.4

8.5

8.6

9

8.3.4 Effective Code Without Compressing ..................................
8.3.5 Optimum C Code ....... " ...........................................
The MSP430 Instruction Set ................................................
8.4.1 Implemented Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
8.4.2 Emulated Instructions ...............................................
Benefits ..................................................................
8.5.1
High Processing Speed .............................................
8.5.2 Small CPU Area . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
8.5.3 High ROM Efficiency ................................................
8.5.4 Easy Software Development .........................................
8.5.5 Usability on into the Future ..........................................
8.5.6 Flexibility of the Architecture .........................................
8.5.7 Usable for Modern Programming Techniques ..........................
Conclusion .......................................................•........

8-12
8-13
8-14
8-14
8-16
8-17
8-17
8-18
8-18
8-18
8-18
8-19
8-19
8-19

CPU Registers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 9-1
9.1
CPU Registers ............................................................. 9-2
9.1.1 The Program Counter PC . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . .. . .. . . . . . .. 9-2
9.1.2 Stack Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 9-2
9.1.3 Byte and Word Handling. . . . .. . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . .. 9-3
9.1.4 Constant Generator. . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . .. . . . . . .. 9-4
9.1.5 Addressing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 9-5
9.1.6 Program Flow Control.. . .. . . .. .. .. .. .. . .. .. .. . .. .. .. .. . .. .. . .. .. . . ... 9-7
9.2
Special Coding Techniques ................................................. 9-11
9.2.1 Conditional Assembly ............................................... 9-11
9.2.2 Position Independent Code .......................................... 9-12
9.2.3 Reentrant Code .................................................... 9-15
9.2.4 Recursive Code .................................................... 9-16
9.2.5 Flag Replacement by Status Usage ................................... 9-16
9.2.6 Argument Transfer With Subroutine Calls ....................... : . . . . .. 9-18
8.2.7 Interrupt Vectors in RAM ............................................ 9-22
8.3
Instruction Execution Cycles ................................................ 9-24
8.3.1
Double Operand Instructions .. .. . . . .. .. .. .. .. . .. . .. . .. . .. .. .. .. .. .... 9-24
8.3.2 Single Operand Instructions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 9-24
8.3.3 Jump Instructions. . . . . .. .... . . . . . . . .. . . . . . . . . . . .. . . . . . . . .. . . . . . .. . ... 9-25
8.3.4 Interrupt Timing .................................................... 9-25

Contents

xi

Figures
1-1
1-2
1-3

MSI:'430C31x Block Diagram ................................................... 1-5
MSP430C32x Block Diagram ................................................... 1-6
MSP430C33x Block Diagram ...............•................•.................. 1-7

3-1
3-2
3-3
3-4
3-5
3-6
3-7

MSP430 Input for Zero-Crossing ...........•...... , ............................. 3-6
Timing for the Zero Crossing ..................................•................ 3-7
Output Buffering .............................................................. 3-9
The I/O Section of the Universal Timer/Port" Module .............................. 3-10
Connections for Fast Serial Transfer ............................................ 3-13
External EPROM Connections ................................................. 3-15
TSS121 Connections to the MSP430 ........................................... 3-17
12C Bus Connections ......................................................... 3-18
Unused ADC Inputs Used as Outputs ....•...................................... 3-27
RI2R Method for Digital-to-Analog Conversion ................................... 3-31
Weighted Resistors Method for Digital-ta-Analog Conversion ...................... 3-32
12C-Bus for Digital-ta-Analog Converter Connection .............................. 3-33
PWM for the DAC ... . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3-34
PWM Timing by the Universal Timer/Port Module and Basic Timer .................. 3-35
PWM for DAC ............................................................... 3-39
PWM Timing by Universal Timer/Port Module and Basic Timer ..................... 3-40
PWM Generation With Continuous Mode ........................................ 3-43
PWM Generation With Up Mode ............................................... 3-44
PWM Generation With Up-Down Mode ......................................... 3-45
External Memory Control With MSP430 Ports .................................... 3-46
External Memory Control With Shift Registers .................................... 3-47
EEPROM Control With Direct Addressing by I/O Ports ............................ 3-48
Addressing of 1-MB RAM With the MSP430C33x ................................ 3-49
Addressing of 1-MB RAM With the MSP430C31x ................................ 3-51
Battery-Power MSP430C32x System ........................................... 3-53
Battery-Power MSP430C31x System ........................................... 3-54
Accumulator-Driven MSP430 System With Battery Management ................... 3-56
Voltages and Timing for the Half-Wave Rectification .............................. 3-57
Half-Wave Rectification With 1 Voltage and a Zener Diode ........................ 3-59
Half-Wave Rectification With One Voltage and a Voltage Regulator ................. 3-60
Half-Wave Rectification With Two Voltages and Two Voltage Regulators ............ 3-61
Voltages and Timing for Full-Wave Rectification .................................. 3-61
Full Wave Rectification for one Voltage With a Voltage Regulator . . . . . . . . . . . . . . . . . .. 3-62

3-8
3-9
3-10
3-11
3-12
3-13
3-14
3-15
3-16
3-17
3-18
3-19
3-20
3-21
3-22
3-23
3-24
3-25
3-26
3-27
3-28
3-29
3-30
3-31
3-32
3-33
xii

F'/(/ures

3-34
3-35
3-36
3-37
3-38
3-39
3-40
3-41
3-42

Full-Wave Rectification for Two Voltages With Voltage Regulators ..................
Simple Capacitor Power Supply for a Single Voltage . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
Capacitor Power Supply for a Single Voltage ....................................
Split Capacitor Power Supply for Two Voltages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
Split Capacitor Power Supply for Two Voltages With Discrete Components ..........
Simple Power Supply from Other DC Voltages ...................................
Power Supply from other DC Voltages With a Voltage Regulator ...................
Supply from the M Bus ........................................................
Supply via Fiber-Optic Cable ..................................................

4-1
4-2
4-3

Two Measurement Methods for Electronic Electricity Meters ........................ 4-2
Timing for the Reduced Scan Principle (Single Phase) ............................. 4-3
Reduced Scan Measurement Principle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-4
Allocation of the ADC Range .................................................. 4-11
Explanation of ADC Deviation (2nd Column of Table 4-5) ......................... 4-12
Use of the Actual ADC Characteristic for Corrections (8 Subranges Used) ........ . .. 4-16
MSP430 14-Bit ADC Grounding ................................................ 4-19
Split Power Supply for Level Shifting ............................................ 4-21
Virtual Ground IC for Level Shifting .... . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . .. 4-22
Resistor Interface Without Current Source ....................................... 4-23
Resistor Interface With Current Source ......................................... 4-24
Current Measurement ........................................................ 4-26
Current Measurement With a Ferrite Core ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-28
Voltage Measurement ........................................................ 4-29
Single-Phase Electricity Meter With Shunt Resistor ...... . . . . . . . . . . . . . . . . . . . . . . . .. 4-32
Single-Phase Electricity Meter With Current Transformer and RF Readout . . . . . . . . . .. 4-33
Timing for the Reduced Scan Principle (Dual-Phase Meter) . . . . . . . . . . . . . . . . . . . . . . .. 4-35
Dual-Phase Electricity Meter With Current Transformers and Virtual Ground ......... 4-36
Dual-Phase Electricity Meter With Current Transformers and Software Offset4 ......... 38
Normal liming for the Reduced Scan Principle (Three-Phase Meters) ............... 4-40
Evenly Spaced Timing for the Reduced Scan Principle (Three-Phase Meters) ........ 4-40
Three-Phase Electricity Meter With Ferrite Cores and Software Offset .............. 4-42
Electricity Meter With Current Transformers and Split Power Supply ................ 4-44
Timing for the Reduced Scan Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-46
Electricity Meter With an External 16-Bit ADC .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-57
Allocation ofthe ADC Range .................................................. 4-62
Explanation of the ADC Deviation .............................................. 4-63
Gas Meter With MSP430C32x ................................................. 4-65
Gas Meter With MSP430C31x ................................................. 4-66
MSP430C336 Gas Meter ..................................................... 4-67
Electronic Water Flow Meter ................................................... 4-69
Electronic Heat Allocation Meter With MSP430C32x .............................. 4-70
Electronic Heat Allocation Meter With MSP430C31x .............................. 4-71
Heat Volume Counter MSP430C32x ............................................ 4-72

4-4
4-5
4-6
4-7

4-8
4-9
4-10
4-11
4-12
4-13
4-14
4-15
4-16
4-17
4-18
4-19
4-20
4-21
4-22
4-23
4-24
4-25
4-26
4-27
4-28
4-29
4-30
4-31
4-32
4-33
4-34

Contents

3-63
3-65
3-66
3-66
3-67
3-69
3-70
3-72
3-75

xlii

Figures

4-35
4-36
4-37
4-38
4-39
4-40
4-41
4-42
4-43
4-44
4-45
4-46
4-47
4-48
4-49
4-50
4-51
4-52
4-53
4-54
4-55
4-56
4-57
4-58
4-59
4-60
4-61
4-62
4-63
4-64
4-65
4-66
4-67
4-68
4-69
4-70
4-71
4-72
4-73
4-74
4-75
4-76
4-77
4-78
xiv

Heat Volume Counter With 4-Wire-Circuitry MSP430C32x ......................... 4-73
Heat Volume Counter With 16 Bits Resolution MSP430C32x ....................... 4-74
Battery Charge Meter MSP430C32x ............................................ 4-76
Resistive Sensors Connected to MSP430C32x .................................. 4-77
Measurement With Reference Resistors ........................................ 4~79
Connection of Bridge Assemblies .............................................. 4-79
Simplified ADC Characteristic .................................................. 4-81
Fixing of Bridge Assemblies Into One ADC Range. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-82
Gas Sensor Connection to the MSP430C32x .................................... 4-83
Connection of Digital Sensors (Thermometer) ................................... 4-84
Connection of Sensors With Frequency Output Respective Time Output ............ 4-85
Revolution Counter With a Digital Hall Sensor ................................... 4-86
Measurement of the Magnetic Flux With an Analog Hall Sensor ............. , . . . . .. 4-86
MSP430C32x EE Meter With RF Readout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-88
MSP430 EE Meter With RF Readout ........................................... 4-89
MSP430 With a Ferraris-Wheel Meter and RF Readout ........................... 4-90
RF-Interface Module .......................................................... 4-91
RF-Modulation Modes ........................................................ 4-92
M-BUS Long Frame Format ................................................... 4-93
Sequence of Data Transmission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-93
Conventional Solution for a Battery-Driven System ............................... 4-95
Solution With MSP430 for a Battery-Driven System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-95
Approximated Characteristics for the Low Power-Supply Currents .................. 4-96
Current Consumption Characteristic ............................................ 4-97
Connection of Keys to Inputs ................................................. 4-100
Turnoff of External Circuits ................................................... 4-101
Intelligent Heating Installation Control With the MSP430 .......................... 4-106
Heating Installation Controller for a Single-Family Home ......................... 4-107
Simple Battery Driven Scale .................................................. 4-108
Remote Control Transmitter for Security Applications ............................ 4-109
Remote Control Transmitter for AudioNideo .................................... 4-110
Remote Control Receiver With the MSP430 .................................... 4-110
MSP430 in a TV Set. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-111
MSP430 in an AC-Powered Personal Computer ................................. 4-112
MSP430 in a Battery-Powered Personal Computer With Battery Management ...... 4-113
MSP430-Controlled FAX Device .............................................. 4-114
Block Diagram of the UTPM (16-Bit Timer Mode) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 4-118
Low-Frequency PWM-Timing Generated With the Universal Timer/Port Module ..... 4-118
Low Frequency PWM Timing by Universal Timer/Port Module and Basic Timer ...... 4-119
Transistor Output Stage Allowing Both Directions of Rotation ..................... 4-121
Control for Two MOSFET Output Stages ....................................... 4-122
PWM Motor Control With a MOSFET H-Bridge .................................. 4-125
PWM Motor Control for Brushless DC Motor .................................... 4-127
Integrated PWM Motor Control With Static Rotation Direction ..................... 4-128

Figures

4-79
4-80
4-81
4-82
4-83
4-84
4-85
4-86
4-87
4-88
4-89
4-90
4-91
4-92

Integrated PWM Motor Control With Dynamic Rotation Direction ..................
PWM Motors Control for High Motor Voltages ...................................
PWMOutputs for Different Phase Voltages .....................................
PWM Motors Control for High Motor Voltages ...................................
Minimum System and Maximum System Using the MSP430 Family ...............
TRIAC Control for AC Motors and DC Motors ...................................
Positive and Negative TRIAC Gate ContrOl .....................................
Static and Dynamic TRIAC Gate Control .......................................
Nonregulated Voltage for the TRIAC Control ................................ : ...
Minimum System and Maximum System With the MSP430 Family ................
Overcurrent Detection With Single and Multiple Thresholds .......................
Motor Voltage Measurement and Current Measurement . . . . . . . . . . . . . . . . . . . . . . . . ..
Support Functions for the TRIAC Control .......................................
Change of the Direction of Rotation for a Universal Motor ........................

5-1
5-2

16 x 16 Bit Multiplication - Register Use ......................................... 5-3
8 x 8 Bit Multiplication - Register use ........................... .. .. . .. .. .. .. ... 5-12
Unsigned Division - Register Use .............................................. 5-16
Signed Division - Register Use ................................................ 5-18
Data Arrangement in Tables ................................................... 5-32
Two-dimensional Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 5-35
Algorithm for Two-Dimensional Tables .......................................... 5-36
Table Configuration for Signed X and Y ......................................... 5-40
Algorithm for a Three-Dimensional Table ........................................ 5-42
Frequency Response of the Continuous Averaging Filter .......................... 5-47
Reduction of Hum by Synchronizing to the AC Frequency. Single Measurement . . . . .. 5-52
Reduction of Hum by Synchronizing to the AC Frequency. Differential Measurement .. 5-53
Keyboard Connection to MSP430 .............................................. 5-61
Connection of Different Input Signals ........................................... 5-62
Nonlinear Function K f{N) ................................................... 5-63
DES Encryption Subroutine .................................... ; .............. 5-71
Biphase Space Code ......................................................... 5-75
Matrix for Few Valid Combinations ............................................. 5-78
Stack Allocation for .FLOAT and .DOUBLE Formats .............................. 5-93
Floating Point Formats for the MSP430 FPP . . . . . . . . . . . . . . . .. . . . . . .. .. . .. .. .. . ... 5-96
Signed Binary Input Buffer Format 16 Bits ...................................... 5-100
Unsigned Binary Input Buffer Format 16 Bits .................................... 5-101
Signed Binary Input Buffer Format 32 Bits ...................................... 5-101
Unsigned Binary Input Buffer Format 32 Bits .................................... 5-101
Binary Number Format 48 Bit .............................................. ' " 5-102
Binary Number Format 48 Bit ................................................. 5-102
BCD Buffer Format .......................................................... 5-103
Binary Number Format ....................................................... 5-104
Function f{x) ................................................................. 5-125

5-3
5-4
5-5
5-6
5-7
5-8
5-9
5-10
5-11
5-12
5-13
5-14
5-15
5-16
5-17
5-18
5-19
5-20
5-21
5-22
5-23
5-24
5-25
5-26
5-27
5-28
5-29

4-129
4-131
4-134
4-135
4-137
4-139
4-140
4-141
4-143
4-145
4-147
4-148
4-149
4-150

=

Contents

xv

Figures

5-30 Complex Number on TOS and In Memory (.FLOAT Format) ......................
5-31
Connection of the Voltage Reference ...................................•......
5-32 Battery Check With an External Comparator ...•....•...........................
5-33 Discharge Curves for the Battery Check With the Universal Timer/Port Module . . . . ..
5-34 Battery Check With the Universal Timer/Port Module ............................
5-35 Power Fail Detection by Observation of the Charge Capacitor ....................
5-36 Voltages for the Power-Fail Detection by Observation of the Charge Capacitor ......
5-37 Power-Fail Detection by Observation of the Charge Capacitor ....................
5-38 'Power-Fail Detection With the Watchdog .......................................
5-39 Voltages for the Power-Fail Detection With the Watchdog ........................
5-40 Power-Fail Detection With a Supply Voltage Supervisor ..........................
Voltages for the. Power-Fail Detection With a Supply Supervisor ..................
5-41
6-1
6-2
6-3
6-4
6-5
6-6
6-7

6-8
6-9
6-10
6-11
6-12
6-13
6-14
6-15
6-16
6-17
6-18
6-19
6-20
6-21
6-22
6-23
6-24
6-25
6-26
6-27
6-28
6-29
6-30
6-31

xvi

5-132
5-165
5-170
5-173
5-174
5-177
5-177
5-178
5-181
5-182
5-185
5-186

Crystal Calibration ............................................................ 6-6
Crystal Frequency Deviation With Temperature ................................... 6-7
The Hardware of the 16-Bit TimecA (Simplified MSP430x33x Configuration) ........ 6-19
The Timer Register Block ............................................•........ 6-25
Timer Control Register (TACTL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-26
. Timer Vector Register (TAIV) .................................................. 6-31
Simplified Logic of the Timer Interrupt Vector Register ............................ 6-34
Capture/Compare BLock 1 .................................................... 6-35
The Capture/Compare Registers CCRx ......................................... 6-35
Function of the Capture/Compare Registers (CCRx) .............................. 6-37
Timer Control Registers (CCTLx) ............................................... 6-38
Two Different Timings Generated With the Continuous Mode ...................... 6-48
Three Different Asymmetric PWM Timings Generated With the Up Mode ............ 6-52
Two Different Symmetric PWM Timings Generated With the Up/Down Mode .......... 6-55
Unsafe Output Mode Changes ................................................. 6-63
Simplified Logic of the Output Units ............................................. 6-64
Connection of the Port3 Terminals to the Timer_A (MSP430C33x Configuration) ..... 6-66
PWM Generation in the Continuous Mode (CCR1 only controls TA1) ................ 6-68
PWM Generation in the Continuous Mode (CCRO and CCR1 control TA1) ........... 6-69
PWM Signals at TAx in the Up Mode (CCRO contains 4) .......................... 6-71
PWM Signals at Pin TAx With the Up/Down Mode (CCRO contains 3) ............... 6-73
Five independent Timings Generated in the Continuous Mode ..................... 6-82
DTMF Filters and Mixer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-87
TRIAC Control With Timer_A .................................................. 6-95
Static and Dynamic TRIAC Gate Control ........................................ 6-96
Mixture of Capture Mode and Compare Mode With the Continuous Mode ..•....... 6-103
Compare Mode With Timer Values greater than 16 Bit (shown for CCR1) ........... 6-108
Capture Mode With Timer Values greater than 16 Bit (shown for CCR3) ..... . . . . . .. 6-109
Five Different Timings Extending the Normal Timer_A Range ..................... 6-110
MSP430 Operation Without Crystal ............................................ 6-116
RF Interface Module Connection to the MSP430 ................................ 6-121

Rgures

6-32

6-33
6-34
6-35
6-36
6-37
6-38
6-39
6-40
6-41
6-42
6-43
6-44
6-45
6-46
6-47
6-48
6-49
6-50
6-51
6-52
6-53
6-54
6-55
6-56
6-57
6-58
6-59
6-60
6-61
6-62
6-63
6-84
6-65
6-66
6-67
6-68
6-69
6-70
6-71
6-72
6-73
6-74
6-75

RF Modulation Modes ....................................................... 6-122
Amplitude Modulation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-123
Biphase Code Modulation ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-126
Biphase Space Modulation ................................................... 6-130
Real Time Clock Application of the Timer_A .................................... 6-132
Three Different Asymmetric PWM-Timings Generated With the Up Mode ........... 6-147
Digital-to-Analog Conversion ....................................•............ 6-151
TRIAC Control With TimecA ................................................. 6-158
Signals for the TRIAC Gate Control With Up Mode .............................. 6-159
RF Modulation Modes ....................................................... 6-166
Capture Mode With the Up Mode (shown for CCR1) ............................. 6-173
PWM Generation and Capturing With the Up Mode .............................. 6-175
PWM Signals at Pin TAx for the Current MSP430C33x Version .................... 6-184
PWM Signals at Terminal TAx for the Improved MSP430C11 x Version ............. 6-185
PWM Outputs for Different Phase Voltages ..................................... 6-195
PWM Motors Control for High Motor Voltages ................................... 6-196
Symmetric PWM Timings Generated With the Up/Down Mode .................... 6-197
TRIAC Control and 3-Phase Control With the Timer_A ........................... 6-202
Signals for the TRIAC Gate Control With Up/Down Mode ......................... 6-203
Biphase Code Modulation With the Up/Down Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-211
Capturing With the Up/Down Mode .... . . . . . . . . . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . .. 6-213
Capture Mode With the Up/Down Mode (Capture/Compare BlOck 3) ............... 6-214
PWM Generation and Capturing With the Up/Down Mode ........................ 6-216
Block Diagram of the MSP430 16 Y 16-Bit Hardware Multiplier .................... 6-223
The Internal Connection of the MSP430 16 x 16-Bit Hardware Multiplier ............ a.:224
40 Y40-Bit Unsigned Multiplication MPYU40 .................................... 6-241
32 Y32-Bit Signed Multiplication MPYS32 ...................................... 6-243
Finite Impulse Response Filter ............................................... 6-247
Storage for the Finite Impulse Response Filter .................................. 6-248
RAM and ROM Allocation for the Fast Fourier Transformation Algorithm ........... 6-251
Control of the DCO by the System Clock Frequency Integrator . . . . . . . . . . . . . . . . . . . .6-262
Switching of The DCO Taps Dependent on NDCOmod ........................... 6-263
Simplified MSP430 RESET Circuitry ........................................... 6-267
Generation of RESET-Signals for External Peripherals ........................... 6-271
Battery-Powered System With RESET Switch .................................. 6-273
Simple RESET Circuit With a PNP Transistor ................................... 6-273
RESET Circuit With a Comparator and a Reference Diode ....................... 6-274
RESET Circuit With a Schmitt Trigger and a Reference Diode .................... 6-275
RESET Generation With a Comparator ........................................ 6-277
Power Fail Detection With a Supply Voltage Supervisor .......................... 6-277
System Voltages With a Power Supply Supervisor ............................... 6-278
Power Supply From Other DC Voltages With a Voltage Regulator/Supervisor ....... 6-279
Block Diagram of the Universal Timer/Port Module .............................. 6-282
Block Diagram of the Universal Timer/Port Module (16-Bit Timer Mode) ............ 6-283
Contents

xvii

Rgures

6-76
6-77
6-78
6-79
6-80
6-81
6-82
6-83
6-84
6-85
6-86
6-87
6-88
6-89
6-90
6-91
6-92
6-93
6-94
6-95
6-96
6-97
6-98
6-99

Low Frequency PWM Timing Generated With the Universal Timer/Port Module .....
Two MSP430s Running From the Same Crystal .................................
The Crystal Buffer OUtput Used for a DC/DC Converter ..........................
The MSP430 Family USART Hardware ........................................
The USART Switched to the UART Mode ......................................
The RS232 Format (Levels at the MSP430) ....................................
The RS232 Format (Levels on the Transmission Line) ...........................
USART Control Registers Used for the UART Mode .............................
The Baud Rate Generator ....................................................
Baud Rate Correction Function ...............................................
MSP430 8-Blt Interval Timer/Counter ModUle Hardware ..........................
RS232 Format (Levels at the MSP430) ........................................
The RS232 Format (Levels on the Transmission Line) ...........................
UART Hardware Registers ...................................................
The 8-Bit Timer/Counter Transmit Mode. . . . . .. . . .. . . . .. . .. .. . . . . . . . . . . .. . . .. . ..
Interrupt Timing for the Transmit Mode .........................................
The 8-Bit Timer/Counter In Receive Mode ......................................
Interrupt Timing for the Receive Mode .........................................
Baud Rate Correction ..................................................... '"
Transmitted Data Format .....................................................
Received Data Format .......................................................
Comparator_A Hardware .....................................................
Fast Comparator Input Check Circuitry .........................................
Voltage Measurement ......................................... , .............

8-1
8-2

Orthogonal Architecture (Double Operand Instructions) ............................ 8-3
Non-Orthogonal Architecture (Dual Operand Instructions) .......................... 8-4
Addressing Modes ............................................................. 8-4
Word and Byte Addresses of the MSP430 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 8-10
Register Set of the MSP430 .....................•............................. 8-10

8-3
8--4

8-5
9-1
9-2

9-3
9-4

9-5

xvIII

6-284
6-285
6-287
6-289
6-290
6-293
6-293
6-294
6-295
6-297
6-319
6-321
6-322
6-323
6-324
6-326
6-327
6-329
6-333
6-338
6-339
6-358
6-361
6-363

Word and Byte Configuration ................................................... 9-4
Argument Allocation on the Stack .............................................. 9-20
Argument and Result Allocation on the Stack .................................... 9-21
Execution Cycles for Double Operand Instructions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 9-24
Execution Cycles for Single Operand Instructions ................................ 9-25

Tables
1-1
1-2
1-3

MSP430 Sub-Families Hardware Features ....................................... 1-4
System Status During LPM3 ................................................... 1-11
System During LPM4 .... : .................................................... 1-14

3-1
3-2
3-3
3-4

3-6

II00PortO Registers ............................................................ 3-2
II00PortO Hardware Addresses ................................. :............... 3-3
Timer_A IIO-Port Selection .................................................... 3-4
LCD and Output Configuration ................................................. 3-28
Resolution of the PWM-DAC .............................. '. . . . . . . . . . . . . . . . . . .. 3-33
Register Values for the PWM-DAC ............................................. 3-34

4-1
4-2
4-3
4-4
4-5
4-6
4-7
4-8
4-9
4-10
4-11
4-12
4-13
4-14
4-15

Errors Dependent on the Sampling Frequency .................................... 4-8
Errors dependent on the AC Frequency Deviation ................................. 4-9
Errors dependent on the Interrupt Latency Time .................................. 4-10
Errors dependent on Overvoltage and Overcurrent ............................... 4-11
Errors With one Current Range and Single Calibration Range. . . . . . . . . . . . . . . . . . . . .. 4-14
Errors With One Current Range and Two Calibration Ranges ...................... 4-15
Errors in Dependence on Current. Voltage and Phase Angle . . . . . . . . . . . . . . . . . . . . . .. 4-16
Typical Values for a Single-Phase Meter ........................................ 4-34
Typical Values for a Dual-Phase Meter . .. .. . . . .. .. . .. . . .. . . . .. .. .. .. . .. . . . .. . . .. 4-39
Typical Values for a Three-Phase Meter ......................................... 4-45
Current Consumption ofthe System Components ................................ 4-51
System Current Consumption for Six Proposals .................................. 4-52
Termination of Unused Terminals .............................................. 4-103
Peripherals of the MSP430 Sub-Families ....................................... 4-116
Capabilities of the MSP430 Sub-Families ...................................... 4-150

5-1
5-2
5-3
5-4
5-5
5-6
5-7
5-8
5-9
5-10
5-11

Examples for the Virtual Decimal Point.. . . . . . . . . .. . . . . . .. . . .. . . .. .. . . .. . . . . . . . .. 5-30
Rules for the Virtual Decimal Point ............................................. 5-30 '
Sample Weight ..........•................................................... 5-48
Basic Timer Frequencies for Hum Suppression .................................. 5-53
Basic Timer Frequencies for Hum Suppression .................................. 5-54
Error Indication Table ....................... . . . . . . . . . . . . . . .. .. . . .. . . . . . . .. . . .. 5-93
Comparison Results .......•.•................................................ 5-95
CPU Cycles needed for Calculations ........................................... 5-99
Execution Cycles olthe Conversion Routines .. .. .. . .. .. .. .. . .. .. .. . .. .. .. . .. ... 5-111
Memory Requirements Without Hardware Multiplier ............................. 5-111
Memory Requirements With Hardware Multiplier ................................ 5-111

3-5

Contents

xix

.

Tables

5-12
5-13
5-14
5-15
5-16
5-17
5-18

Relative Errors of the Square Root Function ....................................
Relative Errors of the Cubic Root Function .....................................
Errors of the Trigonometric Functions .........................................
Errors of the Hyperbolic Functions.. . .. . . .. . . . . . .. .. . . . . . . .. . . . .. . . .. . . . .. . .. ..
Relative Errors of the Natural Logarithm Function ...............................
Errors of the Exponential Function .............................................
Relative Errors of the Power Function.. . . . . . .. . . .. . . . .. . .. .. .. .. . .. .. . . . . . .. ...

6-1
6-2
6-3
6-4

Basic Timer Interrupt Frequencies ............................................... 6-2
Crystal Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-5
Timer_A Registers ............................................................ 6-24
Mode Control Bits ....... . . . . . .. . . . . . . . .. . . • . . . . . . . . . . . . . . . . . . . . . .. . . . .. . . . ... 6-28
Input Divider Control Bits ...................................................... 6-29
Input Selection Bits (MSP430x33x - Source Depends on MSP430 Type) ........... 6-30
Timer Vector Register Contents ................................................ 6-31
Output Modes of the Output Units .............................................. 6-42
Capture/Compare Input Selection Bits (MSP430x33x) ............................ 6-44
Capture Mode Selection Bits .................................................. 6-45
Combinations of TimecA Modes ............................................... 6-59
TimecA Interrupt Priorities ......................•............................. 6-61
Output Modes of the Output Units .............................................. 6-62
TimecA IIO-Port Selection ...•................................................ 6-65
Short Description ofthe Five Independent Timings ............................... 6-81
DTMF Frequency Pairs ....................................................... 6-86
Errors of the DTMF Frequencies Caused by the MCLK ........................... 6-87
Short Description of the Capture and Compare Mix . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-103
Short Description of the Capture and Compare Mix .. . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-110
Interrupt Overhead for the Three Different Update Methods. . . . . . . . . . . . . . . . . . . . . .. 6-144
Output Voltages for Unsigned PWM ........................................... 6-145
Output Voltages for Signed PWM ............................................. 6-146
Short Description of the Capture and PWM Mix ................................. 6-174
Interrupt Overhead for the Four Different Update Metho.ds . . . . . . . . . . . . . . . . . . . . . . .. 6-193
Output Voltages for Unsigned PWM ........................................... 6-194
Output Voltages for Signed PWM ............................................. 6-195
Results With the Unsigned Multiply Mode ...................................... 6-228
Results With the Signed Multiply Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-228
Results With the Unsigned Multiply-and-Accumulate Mode ....................... 6-229
CPU Cycles Needed for the Different Multiplication Modes ....................... 6-237
CPU Cycles Needed for the FPP Multiplication (FLT_MUL) ....................... 6-239
System Clock Generator Error . . . • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-264
Baud Rate Register UBR Content (MCLK =1,048 MHz) . . . . . . . . . . . . . . . . . . . . . . . . .. 6-299
Baud Rate Registers UBR Content (ACLK = 32,768 Hz) ......................... 6-300
UART Hardware Registers ................................................... 6-322
Baud Rate Register TCDAT Contents (MCLK = 1,048 MHz) ......•........ , ...... 6-335

6-5
6-6
6-7
6-8
6-9
6-10
6-11
6-12
6-13
6-14
6-15
6-16
6-17
6-18
6-19
6-20
6-21
6-22
6-23
6-24
6-25
6-26
6-27
6-28
6-29
6-30
6-31
6-32
6-33
6-34
6-35
6-36
xx

5-114
5-117
5-139
5-139
5-152
5-157
5-161

Tables

6-37

Baud Rate Register TCDAT Contents (ACLK =32,768 Hz) ....................... 6-335

8-1

Constants implemented in the Constant Generator ................................ 8-8

9-1
9-2
9-3

Constant Generator ........................................................... 9-5
Addressing Modes ............................................................ 9-5
Jump Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... 9-9

Contents

xxi

Examples
1-1
1-2

Interrupt Handling I ........................................................... 1-11
Interrupt Handling II .......................................................... 1-12

3-1
3-2
3-3
3-4

Using Timer_A in the MSP430C33x System ...................................... 3-4
MSP430C33x System uses the USART Hardware for SCI (UART) .................. 3-4
The I/O-ports PO.O to PO.3 are used for Input Only
3-5
All Six Ports are Used as Outputs ..•...................................•....... 3-11
External EEPROM Connections ................................................ 3-15
AO - A4 are used as ADC Inputs and A5 - A7 as Digital Inputs . . . . . . . . . . . . . . . . . . . .. 3-25
Controlling Two Inputs as Outputs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3-27
SO to S13 Drive a 4-MUX LCD ..........................•...................... 3-29
PWM DAC With Timer/Port Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 3-34
PWM Outputs With 7-Bit Resolution ............................................ 3-38
External Memory Connected tothe Outputs ..................................... 3-46

3-5
3-6
3-7
3-8
3-9
3-10
3-11
6-1
6-2

6-3
6-4
6-5

6-6
6-7

6-8
6-9
6-10
6-11
6-12
6-13
6-14
6-15
6-16
6-17
6-18
6-19
6-20
6-21
6-22
xxii

Basic Timer Control ........................................................... 6-2
Basic Timer Interrupt Handler . . . . .. . .. . . .. . .. .. . . . . . . . . . . . . .. . . . . . . . . . . .. .. . .. .. 6-4
Quadratic Crystal Temperature Deviation Compensation ........................... 6-7
Watchdog Supervision of Three Functions ............ :. .. . . . . . . . . . . . . . . .. . . .. . .. 6-13
Timer Register Low Byte ....................................................... 6-24
The Timer_A Control Register TACTL ........................................... 6-27
Timer Overflow Interrupt Enable Bit TAlE ....................................... 6-28
Timer Clear Bit CLR .............................. , .......................... 6-28
Mode Control Bits ............................................................ 6-29
Input Divider Control Bits ...................................................... 6-29
Input Selection Bits . . . . . . . . . . . .. .. . .. .. . . . . . . . . . . .. . . .. . . . . . . . . .. . . . .. . . . . .. .. 6-30
Capture/Compare Interrupt Flag CCIFG ............................. , .......... 6-39
Capture Overflow Flag COV.................................................. 6-39
Output Bit OUT............................................................. 6-40
Capture/Compare Input Bit CCI ............................................... 6-40
Capture/Compare Interrupt Enable Bit CCIE .................................... 6-41
Capture/Compare Select Bit CAP ............................................. 6-42
Synchronized Capture/Compare Input SCCI .................................... 6-43
Synchronization of Capture Signal Bit SCS ..................................... 6-44
Capture Mode Selection ...................................................... 6-45
Continuous Mode ............................................................ 6-49
Three Diffe~ent Asymmetric PWM Timings Generated With the Up Mode ............ 6-53

Examples

6-23
6-24
6-25
6-26
6-27
6-28
6-29
6-30
6-31
6-32
6-33
6-34
6-35
6-36
6-37
6-38
6-39
6-40
6-41
6-42
6-43
6-44
6-45
6-46
6-47
6-48
6-49
6-50
6-51
6-52
6-53
6-54
6-55
6-56
6-57
6-58
6-59
6-60
6-61
6-62
6-63
6-64
6-65
6-66

Two Different Symmetric PWM limings Generated With the Up/Down Mode ... . . . . .. 6-56
The Stop Mode .............................................................. 6-58
limer_A Vectors ............................................................. 6-61
Safe Output Mode Changes ................................................... 6-63
Port3 Output Control ......................................................... 6-66
PWM near 0% and 100% ..................................................... 6-69
Pulse Width Modulation in the Up/Down Mode ................................... 6-72
Five independent limlngs Generated in the Continuous Mode ..................... 6-82
DTMF Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-88
DTMF Software - Faster ................... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-91
TRIAC Control ............... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 6-97
Mixed Capture and Compare Modes. . . . . . . . . . .. . . . . . . . . . . . . . . . . . .. . . . . . . . . . . .. 6-104
Extending the Normallimer_A Range ......................................... 6-111
Operation Without Crystal .................................................... 6-117
Amplitude Modulation Methods ............................................... 6-123
Biphase Code Modulation .................................................... 6-126
Biphase'Space Modulation ................ _.... _. _........................... 6-130
Real Time Clock Application of the limer_A .................................... 6-132
Prescaling Factor of 2 ....................................................... 6-138
Generation ofTwo PWM Output Signals ....................................... 6-146
Digital-ta-Analog Conversion ................................................. 6-152
Static TRIAC Control ........................................................ 6-159
RF Modulation Modes ....................................................... 6-167
PWM Generation and Capturing With the Up Mode ............................'.. 6-175
Macro Code ................................................................ 6-186
PWM Outputs for Different Phase Voltages . . . . .. . . . . . . . .. . .. . .. . . .. . . .. .. . .. ... 6-195
Symmetric PWM limings Generated With the Up/Down Mode .................... 6-197
Static TRIAC Control Software ................................................ 6-203
Timer_A Used for PWM Generation and Capturing .............................. 6-216
Multiply Unsigned ........................................................... 6-225
64-Bit Result ............................................................... 6-226
Division by Multiplication ..................................................... 6-239
32 x 32-bit Multiplication and MAC Functions ................................... 6-243
Value Correction ............................................................ 6-245
RESET Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . .. 6-276
4800 Baud from 32 kHz Crystal ............................................... 6-295
2400 Baud From 32 kHz ACLK ............................................... 6-297
Full Duplex Modem .......................................................... 6-301
Full Duplex UART ........................................................... 6-304
Full Duplex UART With Interrupt .... '.......................................... 6-308
Baud Rate Generation ....................................................... 6-330
2400 Baud From ACLK ...................................................... 6-332
Half Duplex UART With Interrupt .............................................. 6-336
Half duplex UART With Interrupt .............................................. 6-348
Contents

xxiii

xxiv

Chapter 1

MSP430 Microcontroller Family

1-1

Introduction

1.1 Introduction
The MSP430 is a 16-bit microcontroller that has a number of special features
not commonly available with other microcontrollers:

o

Complete system on-a-chip - includes LCD control, ADC, 1/0 ports,
ROM, RAM, basic timer, watchdog timer, UART, etc.

o
o

Extremely low power consumption - only 4.2 nW per instruction, typical

o
o
o
o
o
o

RISC structure - 27 core instructions

o

High speed - 300 ns per instruction @ 3.3 MHz clock, In register and register addressing mode

Orthogonal architecture (any instruction with any addressing mode)
Seven addressing modes for the source operand
Four addressing modes for the destination operand
Constant generator for the most often used constants (-1, 0, 1, 2, 4, 8)
Only one external crystal required - a frequency locked loop (FLL) oscillator derives all internal clocks
Full real-time capability - stable, nominal system clock frequency is available after only six clocks when the MSP430 is restored from low-power
mode (LPM) 3; - no waiting for the main crystal to begin oscillation and
stabilize

The 27 core instructions combined with these special features make it easy
to program the MSP430 in assembler or in C, and provide exceptional flexibility
and functionality. For example, even with a relatively low instruction count of
27, the MSP430 is capable of emulating almost the complete instruction set
ofthe legendary DEC PDP-11.
Note:

The software examples provided In this document have been tested for func-

,tionality and may be used freely for system development.
.

1-2

Related Documents
iii

•

1.2 Related Documents
The following documents are recommended for MSP430 reference:

o

The MSP430 Architecture User's Guide and Module Library (Tlliterature
number SLAUE1 OB) contains a detailed hardware description.

o

The MSP430 Software User's Guide (Tlliterature number SLAUE11) contilins further information regarding the instruction set, plus other more
common software information.

1.3 Notation
The following abbreviations and special notations are used:
.and.

Logical AND function

.not.

Logical Inversion

.or.

Logical OR function

.xor.

Logical Excluslve-OR function

[ns1

Square brackets contain the unit for a value (here nanoseconds)
Auxiliary clock (output of the 32-kHz oscillator)

ACLK
ACTL.1

Bit 1 (value 21) of the register ACTL

ADC

Analog-to-digital converter

AGND

Ground connection for the ADC; Vss (MSP430x31 x) or AVss
(MSP43Ox32x)
Normal program
Binary coded decimal (numbers 0 to 9 coded binary with 4 bits)

Background
BCD
CPU

Central processing unit

DCO

Digitally controlled oscillator

(dst)

Destination (location receiving write dala)

Foreground
I/O

Interrupt driven software parts (interrupt handlers)
Input and output Port

LCD

Liquid crystal display

LSB

Least significant bit (or byte)

MCLK

Master clock (output of the-FLL oscillator) for the CPU

MSB
PC

Program counter (RO of register set)

Most Significant bit (or byte)

R111R2

Resistor R1 is connected in parallel with resistor R2

R41R3

32-bit number. MSBs in CPU register R4, LSBs in R3

RAM

Random access memory (data memory)

MSP430 Microcontroller Family

1-3

MSP4~O Family

ROM
SP

Read only memory (program memory)
Stack pointer (R1 of register set)
Source (location supplying read data)
Top of stack (data word the Stack Pointer SP points to)

(sre)

TOS

NOTES:lf no units are defined for equations, the following standard units are used: Vott, Ampere, Farad, seconds and Ohm.

1.4 MSP430 Family
The MSP430 family currently consists of three subfamilies:

o
o
o

MSP430C31x·
MSP430C32x
MSP430C33x

All three are described in detail in the MSP430 Family Architecture User's
Guide and Module Ubrary. The hardware features of the different devices are
shown in Table 1, Figure 1, Figure 2, and Figure 3.

Table 1-1. MSP430 Sub-Families Hardware Features
Hardware Item
14-bttADC
16-bit timer A
Basic timer
FLL oscillator
HW/SWUART
HW-multiplier
I/O ports with interrupt
I/O ports without interrupt
LCD segment lines
Package
Universal timer/port module
USART (SCI or SPI)
Watchdog timer

MSP430C31x
No
No

MSP430C32x

MSP430C33x

Yes
Yes
Yes
No

Yes
No
Yes
Yes
Yes
No

No
Yes
Yes
Yes
Yes

8
0
23
56SS0P
Yes
No
Yes

8
0
21
64QFP
Yes
No
Yes

Yes
24
16
30
100QFP
Yes
Yes
Yes

NOTE: Examples and explanations In thiS document are applicable for all MSP430 devices, unless otherwise noted.

1-4

MSP430 Family

1.4.1

MSP430C31 X
XIN

XOUT

XBUF

Vcc

Vss

po.o

RSTINMI

PO.7

..-L----l....,--t-----L.-....J--...1-------------r-'-----'...,--,
2141eJ16 KB
ROM
8116 KB OTP
'C':ROM
'P':OTP

TOI - t - - - - - - - ,

128/25eJ512
RAM

Power-on-

8 bit Tlmerl
Counter
TXO
Serial Protocol
Support

Reset

SRAM

AXO

1/0 Port
BI/Os,AIIWIth
Interr. Cap.

3 Int. Vectors

TOO~-----~

MAS, 16 Bit

CPU

Test

Incl. 16 Reg.

JTAG

MAB,4BH

MCB
MOB,16Bit

TMS-t-----~

TCK

4--------'

I
I
I
I
I
I

Com (h'l
Ssg 0-18, 22, 23 26
S"ll27

1581t

6

~----------------------TP.O-S
CIN

A13

R23

Figure 1-1. MSP430C31x Block Diagram

MSP430 Microcontrol/er Family

1-5

MSP~30 Family,

1.4.2

MSP43OC32x

r-- XIN

XOUT

XBUF

Vee

"ss

RSTJNMI

po.o

PO.7

--t-----L-~-~------------- ~

~•• ~

II

16 kB OTP

'C': ROM
TOI

_
."
RAM
SRAM

I .~I
~.

COunte,

1)(0

Serial Protocol
Support

'P': OTP

~-

8 vo., An WIth
Inter'. Cap.

RXO

31nt. Vectors

TDO+----.....
MAB,16B~

CPU

Tea1

Incl. 16 Reg.

JTAG

MAB,4B~

MCB

1----1
MOB,16B~

TMS+----.....
TCK

4--------'

I
I
I
I
I
IL.. _ _ _ _ _ _ _ _ _ _ _

Com 11-3
SegG-19
Seg20

6
SVCC

Ao-6

RI

Figure 1-2. MSP430C32x Block Diagram
1.4.3 MSP43OC33x

1-6

TP.O-O
CIN

R33

R23
R03
R13

~
s:::
~

....I

~

~
~

XIN

XBUF

vCCl

VCC2

vSSl

vSS2

RSTINMI

P4.0

P4.7

P2.x

P1.x

P3.0

P3.7

PO.O

PO.7

--t--~-_~--L--L-_L--

~

8

I I:~I I

r---

T

~

to
0~
CJ
iii'

XOUT

24kBROM
32 kB ROM
32kB

p:..:~nl

-...,

I I I oo~
VOPM
lx1l~itaI

2x1lI/OsAil
Interr. Cap.

VOPM

VOPM

lx1l Digital

8VOs.AIIWith
Inteff. Cap.

VOs

3 Int. vectors

2 Int. Vectors

TDI

TOO

TIrnerA

!Q

iti
:3

~

J!
~
~

!:l

~

:::g

...ar

~

3

~

~

TMS
TCK

I
I
I
I
I
I

MPVS

timer

MAC
16x16Bit
8x8Bit

l5B~

CMPI
TAO.a-<;

SiMa I

~-----------------------~~------

6

--------;-r-t-f-

TP.Q-5

CIN

R031 R23
R13

R33

~
~

~
~
3

~

Advantages of the MSP430 Conce~t

1.5 Advantages of the MSP430 Concept
The MSP430 concept differs considerably from other microcontrollers and offers some significant advantages over more traditional designs.

1.5.1

RISC Architecture Without RISC Disadvantages
Typical RISC architectures show their highest performance in calculation- intensive applications In which several registers are loaded with input data, all
calculations are made within the registers, and the results are stored back into
RAM. Memory accesses (iJsing addressing modes) are necessary only for the
LOAD instructions at the beginning and the STORE instructions at the end of
the calculations. The MSP430 can be programmed for such operation, for example, performing a pure calculation task in the floating point without any 1/0
accesses.
Pure RISC architectures have some disadvantages when running real-time
applications that require frequent 1/0 accesses, however. Time is lost whenever an operand is fetched and loaded from RAM, modified, and then stored back
into RAM.
The MSP430 architecture was designed to include the best of both worlds, taking advantage of RISC features for fast and efficient calculations, and addressing modes for real-time requirements:

o

The RiSe architecture provides a limited number of powerful instructions,
numerous registers, and single-cycle execution times.

o

The more traditional microcomputer features provide addressing modes
for al/ instructions. This functionality is further enhanced with 100% orthogonality, allowing any instruction to be used with any addressing mode.

1.5.2 Real·Time Capability With Ultra-Low Power Consumption
The design of the MSP430 was driven by the need to provide full real-time capability while still exhibiting extremely low power consumption. Average power
consumption is reduced to the minimum by running the CPU and certain other
functions of the MSP430 only when it Is necessary. The rest of the time (the
majority of the time), power is conserved by keeping only selected low-power
peripheral functions active.
But to have a true real-time capability, the device must be able to shift from a
low-power mode with the CPU off to a fully active mode with the CPU and all
other device functions operating nominally in a very short time. This was accomplished primarily with the design of the system clock:
1-8

Advantages of the MSP430 Concept

o

No second high frequency crystal is used - inherent delays can range
from 20 ms to 200 ms until oscillator stability is reached

o

Instead, a sophisticated FLL system clock generator is used - generator
output frequency (MCLK) reaches the nominal frequency within 8 cycles
after activation from low power mode 3 (LPM3) or sleep mode

This design provides real-time capability almost immediately after the device
comes out of a LPM - as if the CPU is always active. Only two additional
MCLK cycles (2 ~ @ fe = 1 MHz) are necessary to get the device from LPM3
to the first instruction of the interrupt handler.

1.5.3 Digitally Controlled Oscillator Stability
The digitally controlled oscillator (DCO) is voltage and temperature dependent, which does not mean that its frequency is not stable. During the active
mode, the integral error is corrected to approximately zero every 30.5 J.I.S • This
is accomplished by switching between two different DCO frequencies. One
frequency is higher than the programmed MCLK frequency and the other Is
lower, causing the errors to essentially cancel-out. The two DCO frequencies
are interlaced as much as possible to provide the smallest possible errCir at any
given time. See System Clock Generator for more information.

1.5.4 Stack ProceSSing Capability
The MSP430 is a true stack processor, with most of the seven addressing
modes implemented for the stack pointer (SP) as well as the other CPU registers (PC and R4 through R15). The capabilities of the stack include:

o

Free access to all items on the stack - not only to the top of the stack
(TOS)

o

Ability to modify subroutine and interrupt return addresses located on the
stack

o

Ability to modify the stored status register of interrupt returns located on
the stack

o

No special stack instructions - all of the implemented instructions may
be used for the stack and the stack pointer

o
o

Byte and word capability for the stack
Free mix of subroutine and interrupt handling - as long as no stack modification (PUSH, POP, etc.) is made, no errors can occur

For more information concerning the stack, see Appendix A.
MSP430 Microcontroller Family

1-9

MSP430 Application Operating Modes

1.6 MSP430 Application Operating Modes
MSP430 applications fall into two main classes, depending on the power supply:

o

AC power-driven applications such as electricity meters and AC-powered
controllers. In these applications, the microcontroller needs to be active
at all times. The low current consumption of the MSP430 when active
(900 JJA @ 5 V & fc =1 MHz) puts it well within the typical low-power category now (currently < 40 mAl and in the future as tolerable current consumption diminishes.

o

Battery-powered applications such as gas meters, water flow meters, heat
volume counters, data loggers, and other controller and remote metering
tasks. For these applications, power consumption is the key issue since
operation from a single battery for 10 years or longer is often required. The
average current drawn by the MSP430 needs to be in the range of the self
discharge current of the battery, approximately 1 JJA to 3 JJA.

MSP430 has six operating modes, each with different power requirements.
Three of these modes are important for battery-powered applications:

1.6.1

o
o

Active mode - CPU and other device functions run all the time

o

Low power mode 4 (LPM4) -'the mode typically used during storage. This
mode is also called off mode

Low power mode 3 (LPM3) - the normal mode for most applications during 99% to 99.9% of the time. This mode is also called done mode or sleep
mode

Active Mode
Active mode is used for calculations, decision-making, 110 functions, and other
activities that require the capabilities of an operating CPU. All of the peripheral
functions may be used, provided that they are enabled. The examples shown
in this document use the active mode.

1.6.2

Low Power Mode 3 (LPM3)
LPM3 is the most important mode for battery-powered applications. The CPU
is disabled, but enabled peripherals stay active. The basic timer provides a
precise time base. When enabled, interrupts restore the CPU, switch on
MCLK, and start normal operation. Table 1-2 lists the status of the MSP430
system when in LPM3.

1-10

MSP430 Application Operating Modes

Table 1-2. System Status During LPM3
Active

Not Active

RAM

CPU

ACLK
32768 Hz oscillator
LCD driver (if enabled)

MCLK
Disabled peripherals
Disabled interrupts

Basic timer (if enabled)

FLL

I/O ports
8-bittimer
Enabled peripherals
Universal timer/port
RESET logiC

LPM3 is activated by the following code:
; Definitions for the Operating Modes
GIE
CPUOFF
OSCOFF
SCGO
SCGl
HOLD
CNTCL

.EQU
.EQU
.EQU
.EQU
.EQU
.EQU
.EQU

nOah
OlOh
020h
040h
OaOh
080h
OOah

General Interrupt enable in SR
CPU off bit in SR
Oscillator off bit in SR
System Clock Generator Bit 0
System Clock Generator Bit 1
1: Hold Watchdog
Watchdog Reset Bit

Enter LPM3, enable interrupts. The Watchdog
must be held if the ACLK is used for timing
MOV
BIS

#05AOOh+HOLD+CNTCL,&WDTCTL
#CPUOFF+GIE+SCG1+SCGO,SR

Define WD
Enter LPM3

After the completion of the interrupt routine the software returns to the instruction that set the CPUof! bit. The normal wake-up from LPM3 comes from the
baSic timer, programmed to wake the CPU at regular intervals (ranging from
0.5 Hz to 64 Hz, or more often) to maintain a software timer. This software timer
controls all necessary system activities.

Example 1-1. Interrupt Handling I
The MSP430 system runs normally in LPM3. The enabled interrupt of the basic
timer wakes the system once every second. After one minute, measurements
are made and then the system returns to LPM3.

MSP430 Microcontroller Family

1-11

MSP430 Application Operating Modes

; Interrupt handler for Basic Timer: Wake-up with 1Hz
BT_HANMOV
#05AOOh+CNTCL,&WDTCTL
INC. B SECCNT
CMP.B #60,SECCNT
JHS
MIN1
RETI

Reset watchdog
Counter for seconds +1
1 minute elapsed?
Yes, do necessary tasks
No return to LPM3

One minute elapsed: Return is removed from stack, a branch to
the necessary tasks is made. There it is decided how to proceed
MIN1

INC
CLR
ADD
BR

MINCNT
SECCNT
#4,SP
#TASK

TASK

Minute counter +1
o -> SECCNT
House keeping: SR, PC off Stack
; Do tasks

; Start of necessary tasks

All measurements and calculations are made: Return to LPM3
MOV
BIS

#05AOOh+HOLD+CNTCL, &WDTCTL; Hold WD
#CPUOFF+GIE+SCGO+SCG1,SR
Enter LPM3

LPM3 is the lowest current consumption mode that still allows the use of a realtime clock. The basic timer can interrupt the LPM3 at relatively long time intervals (up to 2 seconds) and update the real-time clock. If the status register is
not changed during the interrupt routines, the RETI instruction returns to the
instruction that set the CPUoff bit (and placed the CPU in LPM3). The program
counter points to the next instruction, which is not executed unless the interrupt
routine resets the CPUoff bit during its run.
If the MSP430 is awakened from LPM3, two additional clock cycles are needed
to load the PC with the interrupt vector address and start the interrupt handler
(8 clocks compared to 6 when in the active mode).

Example 1-2. Interrupt Handling 1/
The MSP430 system runs normally in LPM3. The enabled interrupt of the basic
timer wakes the system once every second. After one minute. measurements
are made and then the system returns to LPM3. The branch to the task is made
by resetting the CPUoff bit inside the interrupt routine.
Interrupt handler for Basic Timer: Wake-up with 1 Hz

1-12

MSP430 Application Operating Mod~s

BT_HANMOV
#05AOOh+CNTCL,&WDTCTL
INC.B SECCNT
CMP.B #60,SECCNT
JHS
MINI
RETI

Reset watchdog
counter for seconds +1
1 minute over?
-Yes, do necessary tasks
No return to LPM3

One minute elapsed: CPUoff is reset, the program continues
after the instruction that set the CPUoff bit (label TASK)
MINl

CLR
INC
BIC

SECCNT
MINCNT
#CPUOFF+SCGl+SCGO,O(SP)

°

-> SECCNT
Minute counter + 1
; Reset CPUoff-bit to

continue

RETI

at label TASK

Background part: Return to LPM3
DONE

MOV
BIS

#05AOOh+HOLD+CNTCL, &WDTCTL; Hold WD
#CPUOFF+GIE+SCGO+SCGl,SR
Enter LPM3

Program continues here if CPUoff bit was reset inside of the
Basic Timer Handler.
TASK
JMP

DONE

Tasks made every minute
Back to LPM3

Note:

The two 8-bit counters of the universal timer/port may also be used during
LPM3. If a counter Is incremented by an external signal (inputs CIN, CMPI,
or TPIN.5) from OFFh to Oh, then the appropriate RCxFG-flag is set. If interrupt is enabled, the CPU wakes up.

1.6.3

Low Power Mode 4 (LPM4)
Low power mode 4 (LPM4) is used ifthe absolute lowest supply current is necessary or if no timing is needed or desired (no change of the RAM content is
allowed). This is normally the case for storage preceding or following the calibration process. Table 3 lists the status ofthe MSP430 system when in LPM4.

MSP430Microcontrol/erFamlly

1-13

M~P430 Application Operating Mod"es "

Table 1-3. System During LPM4
Active
RAM
1/0 ports
Enabled interrupts
Universal timer/port (external
clock)
RESET logic

Not Active
CPU
MCLK
ACLK
FLL
Disabled peripherals
Disabled interrupts
Watchdog
Timers

Once the MSP430 is waked from LPM4, the software has to decide if it is necessary to either enter LPM4 again (if the wake-up was caused by EMI, for example), or to enter one of the other operating modes. To ensure the correct
decision is made, a code can be placed on a port that can be checked by the
MSP430 software. Then, the active mode is entered only if this code is present.
The start-up frequency of the DCO is approximately 500 kHz and may last up
to 4 seconds until a stable MCLK frequency is reached. To enter the LPM4 the
following code is necessary:
Enter LPM4, enable GIE
BIS

#CPUOFF+OSCOFF+GIE+SCGl+SCGO,SR

The exit from LPM4 is principally the same as described for LPM3. Interrupt
handler software has to determine if the CPU stays active or if a return to a lowpower mode is necessary.
When entering the LPM4 the information in control registers SCFIO and SCFI1
of the system clock frequency integrator (SCFI) remains stored. If at this time
the ambienttemperature Is high, SCFI1 contains a relatively high value to compensate the negative temperature coefficient of the DCO. If the LPM4 is later
exited and the ambient temperature is very low, it is possible that the resulting
DCO frequency, based on the value In SCFI1, will be outside of the oscillator
range. It is therefore a good programming practice to set the SCFI control register to a low value before entering LPM4.
Enter LPM4, enable GIE
CLRC
RRC
BIS

1-14

&SCFIl
#CPUOFF+OSCOFF+GIE+SCGl+SCGO,SR

Ensure t~at new MSB is 0
Use halved tap number
Enter LPM4

MSP430 Application Operating Modes

Note:
The two 8-bit counters of the universal timer/port may also be used during
LPM4. If a counter is incremented by an external signal (inputs CIN, CMP,
or TPIN.5) from OFFh to Oh, then the appropriate RCxFG-flag is set. If interrupt is enabled, the CPU wakes up.

MSP430 Microcontroller Family

1-15

1-16

Chapter 2

Analog-to-Digital Converters

2-1

2-2

Architecture and Function of the
MSP430 14-Bit ADC
Lutz Bieri

~1ExAs

INSTRUMENTS
2-3

IMPORTANT NOTICE
Texas Instruments and its subsidiaries (TI) reserve the rlghtto make changes to their products orto discontinue
any product or service without notice, and advise customers to obtain the latest version of relevant information
to verify, before placing orders, that information being relied on is current and complete. All products are sold
subject to the terms and conditions of sale supplied at the time of order acknowledgement, including those
pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semicond~ctor products to the specifications applicable at the time of sale in
accordance with Tl's standard warranty. Testing and other quality control techniques are utilized to the extent
TI deems necessary to support this warranty. Specific testing of all parameters of each device Is not necessarily
performed, except those mandated by government requirements.
CERTAIN APPLICATIONS USING SEMICONDUCTOR PRODUCTS MAY INVOLVE POTENTIAL RISKS OF
DEATH, PERSONAL INJURY, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE (,'CRITICAL
APPLICATIONS"). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, AUTHORIZED, OR
WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT DEVICES OR SYSTEMS OR OTHER
CRITICAL APPLICATIONS. INCLUSION OF TI PRODUCTS IN SUCH APPLICATIONS IS UNDERSTOOD TO
BE FULLY AT THE CUSTOMER'S RISK.
In order to minimize risks associated with the customer's applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assistance or customer product deSign. TI does not warrant or represent
that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other
intellectual property right of TI covering or relating to any combination, machine, or process in which such
semiconductor products or services might be or are useq. Tl's publication of information regarding any third
party's products or services does not constitute Tl's approval, warranty or endorsement thereof.

Copyright © 2000, Texas Instruments Incorporated

Contents
Introduction ................................................................................. 2-8
1.1 Characteristics of the 14-Bit ADC ........................................................ 2-10
2 ADC Function and Modes ................................................................... 2-11
2.1 Function of the ADC ................................................................... 2-12
2.1.1 ADC Timing Restrictions ........................................................ 2-13
2.1.2 Sample and Hold .............................................................. 2-14
2.1.3 Absolute and Relative Measurements ............................................ 2-15
2.2 Using the ADC In 14-Bit Mode ........................................................... 2-16
2.2.1 Timing ........................................................................ 2-17
2.2.2 Software Example ................................................•............. 2-18
2.3 Using the ADC In 12-8it Mode ........................................................... 2-18
2.3.1 Timing ........................................................................ 2-20
2.3.2 Software Example .............................................................. 2-20
3 The AID Controller Hardware ................................................................. 2-21
3.1 ADC Control Registers ................................................................. 2-21
3.1.1 ACTL Control Register .......................................................... 2-21
3.1.2 AID Data Register ADAT ........................................................ 2-24
3.1.3 Input Register AIN ... c......................................................... 2-25
3.1.4 Input Enable Register AEN ...................................................... 2-26
3.2 Current Source ..........•...........•.•............................................... 2-26
3.2.1 Normal Use of the Current Source ............................................... 2-26
3.2.2 Current Source Used for Level Shifting ........................................... 2-30
3.3 SVcc Terminal .......•........•...........•.................••.•.....•..........•...... 2-31
3.3.1 SVcc Terminal Used as an Output for the ADC Reference Voltage .................... 2-31
3.3.2 SVcc Terminal Used as an Input for the ADC Reference Voltage ..................... 2-32
3.3.3 Connection of Current Consuming Loads to SVcc ..............................•... 2-33
3.4 Interrupt Handling ...•.................................................................. 2-34
3.4.1 Interrupt Flags ................................................................. 2-34
3.4.2 Interrupt Handlers .............................................................. 2-34
3.5 ADC Clock Generation ..................•..................................•........... 2-37
4 ADC Characteristics ......................................................................... 2-37
5 Summary ................................................................................... 2-38
6

References ................................................................................. 2-38

Appendix A

Definhlons Used WIth the Application Examples .................................... 2-39

Architecture and Function of the MSP430 14-B1t ADC

2-5

Figures

List of Figures
Hardware of the 14-Bit ADC .•......•.•...........••.....•........................•...•.•....... 2-10
2 Possible Connections to the Analog-ta-Dlgital Converter .............................•............. 2-11
3 Sources of the Conversion Result ...•..........•....•.............................•............. 2-12
4 ADC Spikes Due to Violated Timing Restrictions ••....•........................•....•............. 2-14
5 Simplified Input Circuitry for Signal Sampling ................ , ...................•.••.. ; ..•....... 2-14
6 Relative Measurements With the MSP430C32x ................................................... 2-15
7 Absolute Measurements USing External Reference Voltage ......•....•.........•..................• 2-16
8 Complete 14-Blt ADC Range .............................•.......................•............. 2-16
9 Timing for the 14-blt Analog-to-Digital Conversion ....••....•...................................... 2-17
10 The Four 12-Blt ADC Ranges A to D .....••..•.•...•...•••.......•............•................ 2-18
11 Single 12-Bit ADC Range ....•.....•........•.................•................••.•.•......... 2-19
12 Timing for the 12-Bit AID Conversion •...................................•......•.•.•...•....... 2-20
13 ACTL Control Register ..............................•.......•............•.......•............ 2-21
14 Conversion Start (SOC) ..................................•.....•.•....••.......•.............. 2-21
15 Voltage Reference Bit (VREF) .............•.....••....•.•..................................... 2-22
16 ADC Input Selection Bits .................••...........••..................•.....•............. 2-22
17 Current Source Output Select Bits ........•.....•...•...................•............•......... 2-23
18 Range Select Bits ........•...............................................................•... 2-23
19 Power Down Bit (Pd) ......................................................................... 2-24
20 Clock Frequency Selection Bits ...... : ......................................................... 2-24
21 Bit 15 ..........................•..............•.•.•.............•.••..................••..... 2-24
22 The Data Register ADAT. 12-Blt AID Conversion ................................................. 2-25
23 Data Register ADAT. 14-Bit AID Conversion ..................................................... 2-25
24 Input Register AIN .......................................................•...............•... 2-25
25 Input Enable Register AEN ..................................................................... 2-26
26 The Current Source .......................................................................... 2-27
27 Measurement Circuitry for the Error of the Current Source ..•...................................... 2-28
28 Error of the Current Source at the Umit ......................................................... 2-29
29 Error olthe Current Source at the Umit ......................................................... 2-29
30 Application of the Current Source With the Full ADC Range at Input AO ................••••.•.....•. 2-'30
31 Current Measurement With Level Shifting ......••••........•••.•..............•...••••...••..... 2-'31
32 SVcc Terminal Used as an Output ••••.....•....•.•.......•.....•................•.....•.•...•.. 2-'32
33 SVcc Terminal Used as an Inpullor a Reference Voltage .............•.....•........•........••.•. 2-'33
34 Connection of Current Consuming Loads to SVcc ................................................ 2-'34
35 Error Characteristic Device 1 ................................................................... 2-'37
36 Error Characteristic Device 2 ..•••••.•...••..•.•••......... ; ••..........•..........•....•.••... 2-'37
37 Error Characteristic Device 3 .................................................................. 2-'38
38 Error Characteristic Device 4 .................................................................. 2-'38

2-6

SLAA045

Tables

List of Tables
ADC Input Selection BHs .....................•................................................. 2-22
2 Current Source Output Select Bits ..........•..•....•.....................•...................... 2-23
3 Range Select Bits ........•..................•.......................................•......... 2-23
4 Clock Frequency Selection Bits ........................................................•........ 2-24

Architecture and Function of the MSP430 14-B1t ADC

2-7

SLAA045

Architecture and Function of the MSP430 14-8it ADC
Lutz Bierl
ABSTRACT

This application report describes the architecture and function of the 14-bit
analog-to-digital converter (ADC) of the MSP430 family. The principles of the ADC are
explained and software examples are given. The report also explains the function of all
hardware registers in the ADC. The References section at the end of the report lists,
related application reports in the MSP430 14-bit ADC series.

1 Introduction
The analog-to-digital converter (ADC) of the MSP430 family can work in two
modes: the 12-bit mode or the 14-bit mode. Hardware registers aHow easy
adaptation to different ADC tasks. The foHowing paragraphs describe the modes
and hardware registers.

NOTE: The MSP430 Family Architecture Guide and Module
Ubrary data book[1] is recommended. The hardware-related
information given there is very valuable and complements the
information given in this application report.
NOTE: For related application reports in the MSP430 14-bit ADC
series, see the References section.
Figure 1 shows the block diagram of the MSP430 14-bit ADC.

IntroductIon

D---.--_

AVec
SVccSWllch
~ ACTLI (Vre1)
SVecr-':::::><;----I~ ACTLI2(Pd)
Rex

128

c ~_...;I:;28"--I
128
A~_...;I:::;28"--I

~ND<=~~t+~--~
(AVIS)

ACTl.9. 10(Range)

=:::;::::::f==:t._..J_J-,-I---~J

ACTL11(AU1o)

SAR.13

Figure 1. Hardware of the 14-81t ADC

1.1 Characteristics of the 14-Bit ADC
•
•
•

•
•
•
•
•
•
•
•
•
•
•
•
2-10

Monotonic over the complete ADC range
Eight analog inputs; may be switched individually to digital input mode
Programmable current source on four analog inputs. Independent of the
selected conversion Input: current source output and ADC input pins may be
different
Relative (ratio metric) or absolute measurement possible
Sample and hold function with defined sampling time
End-of-conversion flag usable with interrupt or polling
Last conversion result is stored until start of next conversion
Low power consumption and possibility to power down the peripheral
Interrupt mode without CPU processing possible
Programmable 12-bit or 14-bit resolution
Four programmable ranges (one quarter of SVcc each)
Fast conversion time
Four clock adaptations possible (MCLK, MCLKl2, MCLKl3, MCLKl4)
Intemal and external reference supply possible
Large supply voltage range

SLAA045

ADC Function and Modes

2 ADC Function and Modes
The MSP430 14-bit ADC has two range modes and two measurement modes.
The two range modes are:
• 14-bit mode: The ADC converts the input range from AVss to SVcc. The ADC
automatically searches for one of the four ADC ranges (A, B, C, or D) that is
appropriate for the input voltage to be measured.
• 12-bit mode: The ADC uses only one of the four ranges (A, B, C, or D). The
range is fixed by software. Each range covers a quarter of the voltage at the
SVcc terminal. This conversion mode is used if the voltage range of the input
signal is known.
The two measurement modes are:
• Ratiometric mode: A value is measured as a ratio to other values,
independent of the actual SVcc voltage.
• Absolute mode: A value is measured as an absolute value.
Figure 2 shows different methods to connect analog signals to the MSP430 ADC.
The methods shown are valid for the 12-bit and 14-bit conversion modes:
1. Current supply for resistive sensors
Rsens1 at analog input AO
2. Voltage supply for resistive sensors
Rsens2 at analog input A1
3. Direct connection of input signals
Vin at analog input A2
4. Four-wire circuitry with current supply Rsens3 at output A3 and inputs A4
andA5
5. Reference diode with voltage supply
Dr1 at analog input A6
6. Reference diode with current supply
Dr2 at analog input A7
---'--~~-;SV=

SV= i-------4p--+108

Rv

A3

Rexl

AS 1--1-----.

Vln -'llVIr-.....- - j - - - - - I A 2
A4
Ri
MSP430C32x
"'------1 Ai
AS

R2

A7i--F.r:.

OV

+5V/3V

Figure 2. Possible Connections to the Analog-to-Dlgltal Converter

The calculation formulas for all connection methods shown in Figure 2 are
explained in the application report, Application Basics for the MSP430 14-Bit
ADC (SLAA046). [3J
Architecture and Function of the MSP430 14-Bit ADC

2-11

ADC Function and Modes

2.1

Function of the ADC
See Figures 1, 9, and 12 for this explanation. The full range of the ADC is made
by 4x128 equal resistors connected between the SVcc pin and the AVss (AGND)
pin. Setting the conversion-start (SOC) bit in the ACTL control register activates
the ADC clock for a new conversion to begin.
The normal ADC sequence starts with the definition of the next conversion; this
is done by setting the bits in the ACTL control register with a single instruction.
The power-down (PD) bit is set to zero; the SOC bit is not changed by this
instruction. After a minimum 6-JIS delay to allow the ADC hardware to settle, the
SOC bit may be set. The ADC clock starts after the SOC bit is set, and a new
conversion starts.
• If the 12-bit mode is selected (RNGAUTO - 0) then a 12-bit conversion starts
in a fixed range (A, B, C or D) selected by the bits ACTL.9 to ACTL.1 O.
• If the 14-bit mode is selected (RNGAUTO = 1), a sample is taken from the
selected input Ax that is used only for the range decision. The found range
is fixed afterwards - it delivers the two MSBs olthe result -and the conversion
continues like the 12-bit conversion. This first decision is made by the block
range MUX.
This first step fixes the range and therefore the 2 MSBs. Each range contains a
block of 128 resistors.
To obtain the 12 LSBs, a sample is taken from the selected input Ax and is used
for the conversion. The 12-bit conversion consists of two steps:
• The seven MSBs are found by a successive approximation using the block
resistor decode. The sampled input voltage is compared to the voltages
generated by the fixed 27 (128) equally weighted resistors connected In
series. The resistor whose leg voltages are closest to the sampled input
voltage-which means between the two leg voltages-is connected to the
capacitor array (see Figure 1).
• The five LSBs are found by a successive approximation process using the
block capacitor array. The voltage across the selected resistor (the sampled
voltage lies between the voltages at the two legs of the resistor) is divided into
25 (32) steps and compared to the sampled voltage.
After these three sequences, a 14-bit respective 12-blt result is available in the
register ADAT.
Figure 3 shows where the result bits of an analog-to-digital conversion come
from:
15

13

0

I.BI, CCiftV8f1i1On

'4-Bft Conver8Ion

Figure 3. Sources of the Conversion Result
2-12

SLAA045

ADC Function and Modes

NOTE: The result of the 12-bit conversion does not contain
range information: the result bits 12 and 13 are both zero.lfthese
two bits are necessary for the calculation, they need to be inserted
by software e.g. 2000h for range C.
2.1.1

ADC Timing Restrictions
To getthe full accuracy forthe ADC measurements, some timing restrictions need
to be considered:
• If the ADCLK frequency is chosen too high, an accurate 14- or 12-bit
conversion cannot be assured. This is due to the internal time constants of
the sampling analog input and conversion network. The ADC is still
functional, but the conversion results show a higher noise level (larger
bandwidth of results for the same input signal) with higher conversion
frequencies.
•

•

If the ADCLK frequency is chosen too low, then an accurate 14- or 12-bit
conversion cannot be assured due to charge losses within the capacitor array
of the ADC. This remains true even if the input signal is constant during the
sampling time.
After the ADC module has been activated by resetting the power-down bit,
at least 6 !J.S (power-up time in Figure 9) must elapse before a conversion is
started. This is necessary to allow the internal biases to seUle. This power-up
time is automatically ensured for MCLK frequencies up to 2.5 MHz if the
measurement is started the usual way: by separation of the definition and the
start of the measurement inside of the subroutine:
MOV
CALL

#xxx, &ACTL
#MEASR

Define Me measurement
; Start measurement with SOC-1

; ADC result in ADAT

If higher MCLK frequencies are used, then a delay needs to be inserted between
the definition and the start of the measurement. See the source of the MEASR
subroutine in section 2.2.2. The number n of additional delay cycles (MCLK
cycles) needed is:
n~

(61J.Sx MCLK)-15

•

If the input voltage changes very fast, then the range sample and the
conversion sample may be captured in different ranges. See section 2.2.1 if
this cannot be tolerated. For applications like an electricity meter, this doesn'
matter: the error occurs as often for the increasing voltage as for the
decreasing voltage so the resulting error is zero.

•

After the start of a conversion, no modification of the ACTL register is allowed
until the conversion is complete. Otherwise the ADC result will be invalid.

The previously described timing errors lead to spikes in the ADC characteristic:
the ADC seems to get caught at certain steps of the ADC. This is not an ADC
error; the reasons are violations of the ADC timing restrictions. See Figure 4. The
x-axis shows the range A from step 0 to step 4096, the y-axis shows the ADC error
(steps).
Architecture and Function of the MSP430 14-Bit ADC

2-13

ADC Function and Modes
R••goA

m~

~ ~

·2
·4

i

~

l:!
:;;

·8

~

0

~
l-sar18511

·8

·10
·12
·14

Figure 4. ADC Spikes Due to Violated Timing Restrictions

The ADC always runs at a clock rate set to one twelfth of the selected ADCLK.
The frequency of the ADCLK should be chosen to meet the conversion time
defined in the electrical characteristics (see data sheet). The correct frequency
for the ADCLK can be selected by two bits (ADCLK) in the control register ACTL.
The MCLK clock signal is then divided by a factor of 1,2,3, or 4. See Section 3.5.

2.1.2 Sample and Hold
The sampling of the ADC input takes 12 ADCLK cycles; this means the sampling
gate is open during this time (12 JlS at1 MHz). The sampling time is identical for
the range decision sample and the data conversion sample.
The input circuitry of an ADC input pin, Ax, can be seen simplified as an RC low
pass filter during the sampling period (12/ADCLK): 2 kQ in series with 42 pF. The
42-pF capacitor (the sample-and-hold capacitor) must be charged during the 12
ADCLK cycles to (nearly) the final voltage value to be measured, or to within 2-14
of this value.
RI

Ax

2K

Closed for Is = 121ADCLK

r--'l/I/Ir---<::::>--t-.JV\rv-O------O------t-------*--OV

Figure 5. Simplified Input Circuitry for Signal Sampling

The sample time limits the internal resistance, Ri, of the source to be measured:
(Ri

+2

kQ)

x 42 pF < ~

) 12
l 214 x ADCLK

Solved for Riwith ADCLK '" 1 MHz this results in:
Ri < 27.4 kQ

This means, for the full resolution of the ADC, the internal resistance of the input
signal must be lower than 27.4 k.Q.
If a resolution of n bits is sufficient, then the internal resistance of the ADC input
source can be higher:
2-14

SLAA045

ADC Function and Modes

R· <
I

12
2 kQ
'rn,2,,) x 42 pF x ADCLK -

For example, to get a resolution of 13 bits with ADCLK = 1 MHz, the maximum
Ri of the input signal is:

Ri <

n( )

12
- 2 kQ
I 2 13 x 42 pFx 10 6

= 31.7

kQ - 2 kQ

= 29.7

kQ

To achieve a result with 13 bit-resolution, Ri must be lower than 29.7 kn.

2.1.3 Absolute and Relative Measurements
The 14-bit ADC hardware allows absolute and relative modes of measurement.
2.1.3.1

Relative Measurements

As Figure 6 shows, relative measurements use resistances (sensors) that are
independent of the supply voltage. This is the typical way to use the ADC. The
advantage is independence from the supply voltage; it does not matter if the
battery is new (Vee =3.6 V) or if it has reached the end of life (Vee =2.5 V).
~~----~--;SV~

Rex

Rv

A3

-+108

Rex!
A4
MSP430C32x

t---------;Al

AS

Reena2

OV

Reene3

+6 V/3 V

Figure 6. Relative Measurements With the MSP430C32x
2.1.3.2 Absolute Measurements

As Figure 7 shows, absolute measurements measure voltages and currents. The
reference used for the conversion is the voltage applied to the SVee terminal,
regardless of whether an extemal reference is used or if SVee is connected to
AVee internally. An external reference is necessary if the supply voltage AVee (the
normal reference) cannot be used for reference purposes, for example a battery
supply.

Arohitecture and Function of the MSP430 14-8it ADC

2-15

ADC Function and.Modes
cSO""
RI
,....-JIJVI,--------+----ISVee

Rex!

=

VREF

OV

.sV/3V

Figure 7. Absolute Measurements Using External Reference Voltage

2.2 Using the ADC In 14-Bit Mode
The 14-blt mode is used ifthe range of the input voltage exceeds one ADC range.
The total input signal range Is from analog ground (AVss) to the voltage at SVec
(external reference voltage or AVec).

i

ADCValue
Ovartlow

03~Fh;-------------~~~

O3OOOh

02000h

Range A

01000h
OOOOOh~~-_4-----+------+-----~
Underflow 0
0.26 SVec 0.& aVec
0.75 SVec
aVec

C:J

ADO Input

Voltage

--+

ADO saturation

Figure 8. Complete 14-Bit ADC Range

The dashed boxes at the AVss and SVec voltage levels indicate the saturation
areas of the ADC; the measured results are Oh at AVss and 3FFFh at SVec. The
saturation areas are smaller than 10 ADC steps.
The nominal ADC formula for the 14-bit conversion is:
"N= VAx x2 14 ... VAx = Nx VREF
VREF
214

Where:
= 14-bit result of the ADC conversion
VAx = Input voltage at the selected analog input Ax
VREF- Voltage at pin SVec (external reference or Internal AVec)

N

2-16

SLAA045

M
M

ADC Function and Modes

2.2.1

Timing
The two ADCLK bits (ACTL.13 and ACTL,14) in the ACTL control register are
used to select the ADCLK frequency best suited for the ADC. The MCLK clock
signal can be divided by a factor 1, 2, 3, or 4 to get the best suited ADCLK.
Using the autorange mode (RNGAUTO/ACTL.11 = 1) executes a 14-bit
conversion. The selected analog input signal at input Ax is sampled twice. The
range decision is made after the first sampling of the input signal; the 12-bit
conversion is made after the second sampling. Both samplings are 12 ADCLK
cycles in length. Altogether the 14-bit conversion takes 132 ADCLK cycles. See
Figure 9 for timing details.
121ADCLK

~

r -""He";" - ,

I

ADCLKl12

~

Pd
CONY. START
SAMPLING

--i. I
~

Power-up Time

i
I
I
I

Range Sample

Conversion

I
I
I
I
I

Conversion Sample

--nl-..---I~L-------------I--+I-

END OF CONY. - - - ,.

I
I

f\t'

I
I

I

I

I
I
I
I
I
I
I

II

,~
L _ _ _ _ .J

I

Raeel by Softwara (Nonlnlerrupt Model
or Granting of Interrupt (Inlerrupt_1

I
I
I
I

I

Data valid In ADAT
EOC Flag set
ADCLK DI_ad

Figure 9. Timing for the 14-bit Analog-to-Dlgltal Conversion
The input signal must be valid and steady during this sampling period to obtain
an accurate conversion. It is also recommended that no activity occur during the
conversion at analog inputs that are switched to the digital mode.
If the input voltage to the ADC changes during the measurement, it is possible
for the range decision sample to be taken in a different ADC range than the
conversion sample. The result of these conditions is saturated values:
• Increasing input voltage: nFFFh with range n =0...2
• Decreasing input voltage: nOOOh with range n =1••. 3
The saturated result isthe best possible result under this circumstance: an analog
input that changes from 2FFOh to 3020h during the sampling period delivers the
saturated result 2FFFh and not 2000h.
The following software sequence can be used to check the result of an AID
conversion if the two samples (range and conversion) were taken in different
ranges. If this is the case, the measurement is repeated.
LM MOV
CALL
MOV
AND

#xxx, &ACTL
#MEASR
&ADAT, RS
#OFFFh, RS

Define measurement
Measure ADC input
Copy ADC result
12 LSBs stay
Architecture and Function of the MSP430 14-Bit ADC

2-17

ADC Function and Modes
JZ
CMP
JEQ

Yes,
Bits
Yes,
Both

LM
#OFFFh,R5
LM

ADC value too high (nOOOh)
11 to 0 all IS?
ADC value too low (nFFFh)
samples taken in same range

2.2.2 Software Example
The often-used measurement subroutine MEASR is shown below. It contains all
necessary instructions for a measurement that uses polling for the completion
check. The subroutine assumes a preset ACTL register; all bits except the SOC
bit must be defined before the setting of the SOC bit. The subroutine may be used
for 12-bit and 14-bit conversions. Up to an MCLK frequency of 2.5 MHz no
additional delays are necessary to ensure the power-up time.
ADC measurement subroutine.
Call:
#xxx,&ACTL
MOV

MEASR

MO

2.3

Define ADC measurement.

Pd~O

CALL
BIS

#MEASR
#PD,&ACTL

Measure with ADC
Power down the ADC
ADC result in ADAT

BIC.B

#ADIFG, &IFG2

Clear EOC flag
Insert delays here (Naps)
Start measurement
Conversion completed?
No
Result in ADAT

BIS
#SOC, &ACTL
BIT.B #ADIFG,&IFG2
JZ
MO
RET

Using the ADC in 12·Blt Mode
The following mode is used if the range of the input voltage is known. If, for
example, a temperature sensor is used whose signal range always fits into one
range (for example range B), then the 12-bit mode is the right selection. The
measurement time with MCLK = 1 MHz is only 96 !IS compared with 132 !IS if the
autorange mode is used. Figure 10 shows the four ranges compared to the
voltage at SVcc. The possible ways to connect sensors to the MSP430 are the
same as shown for the 14-bit ADC in Figure 2.
This mode should be used only if the signal range is known and the saved 36
ADCLK cycles are a real advantage.
ADCValue

OFFFh

+----,,.-----,......--,.....---,....,......

OCOOh
0800h
0400h
OOOOOh-f~----~----~~----~------~

Underflow 0

0.25 SVcc

0.5 SVcc

0.75 SVcc

SVcc

Input ---+
Voltage VAx

C::J ADC Saturation «10ADC steps)
Figure 10. The Four 12·8it ADC Ranges A to 0
2-18

SLAA045

ADO Function and Modes

NOTE: The ADC results OOOOh and OFFFh mean underflow and

overflow: the voltage at the measured analog input is below or
above the limits of the programmed range.
All of the formulas given for the 12-bit mode assume a faultless
conversion result N:
O 1.5 MHz

1

ADCLK2

2

MCLKl2

2

ADCLK3

3

MCLK13

MCLK > 3.0 MHz

3

ADCLK4

4

MCLKl4

(MCLK > 4.5 MHz)

EXAMPLE: For MCLK
(1.25 MHz) is set.

= 2.5

MHz, the highest possible ADCLK frequency

MOV #ADCLK2+RNGAUTO+A3+VREF,&ACTL

3.1.1.8 Bit 15
Bit 15 (See Figure 21) should always be set to zero to maintain software
compatibility with future versions of the ADC.

II A+K IPo I -+. ~~ Iau+- +-1 70,+ s+

fREFI soc

1

Figure 21. Bit 15

3.1.2 AID Data ReglsteT ADAT
The ADC data register ADAT contains the result of the last AiD conversion. The
conversion data is valid in the ADAT register at the end of a conversion and stays
valid until another AiD conversion is started with the setting of the SOC bit
(ACTL.O). The read-only structure of the ADAT register does not allow
readlmodifylwrite instructions like ADD or BIC with the ADAT register used as the
destination: only the instructions BIT, TST and CMP may be used this way. With
the ADAT register as a source, all instructions may be used.
Figure 22 shows the result of a 12-bit conversion: the value is always between
OOOh (underflow) and FFFh (overflow), independent of the ADC range used. The
miSSing range information (bits 12 and 13) must be added by the software.
2-24

SLAA045

The AID Controller Hardware
15

"

rO

,0

rO

0

,0

Figure 22. The Data Register ADAT, 12-81t AID Conversion

Figure 23 shows the result of a 14-bit conversion: the value is between OOOOh
{underflow} and 3FFFh {overflow}. Result bits 13 ane 12 indicate the range of the
result:
Range A
o to 0.25 x SVcc
• 00
Range
B
0.25 x SVcc to 0.50 x SVcc
• 01
Range C
0.50 x SVcc to 0.75 x SVcc
• 10
Range 0
0.75 x SVcc to SVcc
• 11
15

:~::I

0

,0

o

13
1

IMSBI

0

I

I I I I I I I I I I

I

LSB IACTL.11=1

,0

Figure 23. Data Register ADAT, 14-8it AID Conversion

To read the result of the last conversion, use a simple MOV instruction:
MOV &ADAT , RS

Copy the ADC result to RS
; A new conversion may begin

3.1.3 Input Register AIN
Input register AIN (see Figure 24) is a read-only word register; however, only the
low byte of the register is implemented. The same access restrictions are valid
as described for the ADAT register. AIN.O to AIN.7 correspond to the input
terminals AO to A7. The high byte of the register is read as OOh. Input register AIN
shows the digital input information at the input terminals that are switched to the
digital mode {AEN.x = 1}. The formula for the bit AIN.x is:
AIN.x = Ax .and. AEN.x

Where:
AIN.x = Bit x of the input register AIN
Ax
= Logic level at the analog input Ax
AEN.x = Bit x of the input enable register AEN

This means, that analog inputs {AEN.x = O} are read as zero.
AIN
0110h L-......I_--L_..J.._....L.._....L.._..I-_.l...........Ii.---L_....L._...I.-_..I-_.l...........I_....J_.....I
rO

Figure 24. Input Register AIN

EXAMPLE: The AS inputterminal is used as a digital input. Test ifthis input is high;
if yes, jump to label A5HI:
Architecture and Function of the MSP430 14-8it ADC

2-25

The AID Controller Hardware
'20h, &AEN

Use pin AS as digital input

BIT

#020h,&AIN

JNZ

ASH!

Pin AS high?
Yes, gete ASH!
No, AS is low

INITAS

BIS

NOTE: Only digital inputs with very low activity or controlled
access (e.g. keyboard scan) should be connected to inputs AD to
A7. Otherwise, this activity Influences the measurement results of
the analog inputs.

3.1.4 Input Enable Register AEN
Input enable register AEN (see Figure 25) is a read/write word. However, only the
low byte of the register is implemented. AEN.D to AEN.7 correspond to input
terminals AD to A7. The high byte of the register is read as OOh. The initial state
of all bits is reset.
AEN
0112h L......J_......L_..J..._.l...._L-.......L_...J.._..L-_L-.......L_...J.._..L...--JI-........L_-I.._....

Figure 25. Input Enable Register AEN
Input enable register bits AEN.x control the function of input pins AO to A7:
AEN.x =0:
Input terminal Ax is used as an analog input. Bit AIN.x is read as
zero.
AEN.x =1:
Digital input. The bit read in the AIN register represents the logical
level at the appropriate Ax terminal.
EXAMPLE: The A5 and A4input t~rminals are used as digital inputs. An
application is given with the AIN terminal example.
BIS

#030h,&AEN

; Pin AS and A4 digital inputs

3.2 Current Source
A stable, programmable current source is available at the four analog inputs AO
to A3. With programming resistor Rex between terminals SVcc and Rex!, it Is
possible to get a defined current, Ics, out of the programmed analog input Ax. Ics
is directly related to the voltage at SVcc. This allows relative measurements to
be made using the current source that are independent from the ADC supply
voltage SVcc. The analog input to be measured and the analog input used for the
current source are independent of each other; this means that the current source
may be programmed to input A3 and the measurement taken from inputs A4 and
A5, as shown in Figure 6 for Rsens3.

3.2.1 Normal Use of the Current Source
Figure 26 shows the normal use of the current source: the generated current Ics
flows through the addressed analog input AO and generates a voltage drop Vin
at the connected sensor Rsens. This voltage drop Vin is multiplexed to the ADC
and measured.
2-26

SLAA045

The AID Controller Hardware

The current Ics defined by the external resistor Rex is:

Ics = 0.25 x Vref
Rex
The input voltage Vin at the selected analog input with the current Ics and a
connected sensor Rsens is:

Vin = Rsens x Ics = Rsens x 0.25· x VREF
Rex

--+

Rsens

Vin
Ics

=

The ADC result N for an input voltage Vin is:

N = 214 x Vin --+ Vin = VREF x N
VREF
214
The above equations lead to the measured sensor resistance Rsens:

Rsens

=

Rex
x Vin
0.25 x VREF

=

Rex
VREF x N = Rex x N x 2-12
0.25 X VREF x 214

The result N of the AID conversion is:

N = 0.25 X VREF x 214 x Rsens = Rsens x 212
Rex
VREF
Rex
Where:
Rex = Resistor between pins SVcc and Rex (defines current Ics)
Rsens= Resistor to be measured (connected between Ax and AGND)
VREF = Voltage at SVcc. External (VREF a 0) or internal (VREF = 1)

[01
[0]

M

AVec C>-_---+
SVccSwttch
~ACTL..'(VREF=')
SVec
~ACTL..'2(Pd=0)
Rex

~C8I

Rex,

O.25xSVec

D~_.....,.....
'28=-_-I

r-::T::',- - - , - ,
lea

'N!-==""""-+

C~_.....,.....
'28=-_-I

VREF

~._.....,.....
'28=-_-I

To
Resistor

_er

A~._......,....:':::28:"---I
BIIa ACTL..x Indicate Stale
For Given Example
I..

"-]I~~~~~~

0---0 t-------;-ToIhoADC
8:'
::

IVI"

ACTL.2,3,4 (0,0.0)
ACTL.5(O)
AGND

Figure 26. The Current Source
Architecture and Function of the MSP430 14-Bit ADC

2-27

The AID Controller Hardware

If the 12-bit conversion is used, the above equations change to:

N=

0.25 x VREF x Rsens - n x 0.25 x
Rex

VREF

VREF

1
x2 4= (Rsens_ n
Rex

)X2 12

This gives, for the unknown resistor Rsens:

Rsens = Rex x

(2~2 + n)

The code sequence for the measurement shown in Figure 26 is:
MOV

#ADCLK1+RNGA+CSAO+AO+VREF,&ACTL

Define ADC

CALL

#MEASR

Measure Rsens at AD

Result in ADAT

When using the current source, it is not possible to use the full range of the ADC:
only the range defined with Load Compliance in the Electrical Description is valid
(0.5 x SVcc, which means only the ranges A and B). Figures 28 and 29 show the
typical error characteristics of the current source at its limit. Figure 28 shows the
error characteristic for Vcc = 4.5 V and a relatively high Rex (1 kG). It shows that
up to a ratio of 0.745 for VAO/SVcc (which means range A, B, and nearly all of
range C) the current source works correctly. Then ~Ics (the difference between
the programmed Ics and the real Ics) increases linearly with
.1 V = Rex
.11

The reason is saturated transistorT1 olthe current source. When T1 is saturated,
only.the external resistor Rex determines the current Ics. Figure 27 shows the
measurement circuitry and an explanation of the error curves. The small dashed
box indicates the area that is magnified in Figures 28 and 29.
~---ISVcc

ILllcsl

i

O.25XVREF/Rex

Rext

Rsen8=lnflnlle

A1

ICB
,..-.!!::=--tAO

L1V/LlI=Rex

Rsens
O•••lnflnlto

MSP43OC32x

0
0

0.25
A

0.5

B

1.0 VAOIAVcc

0.75
C

D

Rangs--'

OV +4.5Y12.5V

Figure 27. Measurement Circuitry for the Error of the Current Source
2-28

SLAA045

The AID Controller Hardware

-

AVec =4.5 11 Rex -1 kO

2.50E-05

85C

2.00E-05

/

1.50E-05
Ales

./

V~~

~

25C
-40C

/ /

1.00E-05

/

./ /. ~

5.00E-05

0.00E+~.74

/
0.741

0.742

0.743

0.744

0.745

/

~

0.746

~

V

/

0.747

0.746

0.749

0.75

RatiO VAO IAVec

Figure 28. Error of the Current Source at the Limit
Figure 29 gives the characteristic at the other extreme: Vee = 2.5 V and
Rex =150 n The slope beyond the operation limit of the current source (here at
VAO/AVcc = 0.7125) is also:
LI V = Rex

Lli

AVec = 2.5 V, Rex=l50 0, T=20-C
2.60E~4

2.00E~4

/

1.50E~

Alc.

/

1.00E~

5.00E-05

O.OOE+OO
0.7

/

V

/

V

/

/

/

0.7025 0.705 0.7076 0.71 0.7125 0.715 0.7175 0.72 0.7225 0.725 0.7275 0.73
Ratio VAo/AVec

Figure 29. Error of the Current Source at the Limit
Architecture and Function of the MSP430 14-Bit ADC

249

The AID Control/er Hardware

The characteristic shown in Figure 29 indicates that the current source works up
to 71% of the applied AVec under worst case conditions; this includes ADC
ranges A, Band 84% of range C. If Rex is chosen as 1 kO and SVec is 4.5 V, then
the current source works up to a ratio of 0.745, which means it covers nearly 98%
of range C.
If the current source is used with an external amplifier (operational amplifier) that
amplifies the output signal coming from the current source, then the full range of
the ADC can be used with a different ADC input. Figure 30 shows such a circuit.
The signal at analog input AO can use the full range of the AID converter; the
signal at A1 is restricted to the working area of Ics that is shown in Figures 28 and
29.
The equations for the circuitry are explained in Application Basics (or the MSP430
14-8ft ADC Application Report (SLAA046).[3]
Rex
Rext

1

SVec
Al
MSP430C32x
AO

let

1

R3

R1

....... .,. 1
...............1

v =R1/(R3I1 R4)

Vm

vp

Raens

.-:

~

R4

AVaa

DVaa

AVec

T

I

OV

+3V(+5V)

Figure 30. Application of the Current Source With the Full ADC Range at Input AO

3.2.2 Current Source Used for Level Shifting
If analog signals that lie partially or totally outside of the ADC range of the
MSP430 (AVss to SVcc), need to be measured then the current source can be
used to shift the signal level into the measurable range.
The current transformer, shown on the left in Figure 31, outputs a secondary
voltage that is proportional to the primary current, lac. The signed output voltage
(symmetrical to the AVss voltage) is shifted into the middle of the ADC range by
a current Ics through the resistor Rsh. This current Ics must be small, due to the
sensitivity of current transformers to de biasing.

2-30

SLAA045

The AID Controller Hardware
To ---4~-~~- To
Charger
Load

SVec

Rex
Rt

Rex!

At
A2

AO
MSP430C32x

AVa

Yo
CUrrent
Rc

lv~ V~l

R2

Shunt

AVu ~----__- -__- - O V

DCM.....remant
VAO=VSh+1c8XRc

AC Measurement
VA2. Vet + lea x Rsh

Figure 31. Current Measurement With Level Shifting

The right side of Figure 31 shows the measurement of a signed dc current. Due
to the two directions of the accumulator current (charge and discharge current)
level shifting is necessary: the charge current generates a positive voltage, Vsh;
the discharge current generates a negative VOltage, Vsh, at the shunt. The
current, Ics, together with resistor Rc, also shifts the voltage drop of the discharge
current into the ADC range.
The advantages of level shifting by the current source are:
• Possibility to measure signals that are outside of the ADC range
• Omission of the saturation area near the AVss voltage
• Possible readjustment of the zero current ADC value during periods with no
current flow

3.3 SVcc Terminal
The SVec terminal is the reference for all ADC measurements. The voltage
applied to this terminal refers to the result value 214 (16,384), regardless of
whether the reference voltage is applied internally or externally (external VREF).
The VREF bit located in the ACTL registers defines whether the internal reference
AVec is used (VREF. 1) or an external voltage is used (VREF = 0).

3.3.1

SVcc Terminal Used as an Output for the ADC Reference Voltage
Typically, the SVec terminal is used to supply the reference and voltage to the
ADC circuitry. It can be activated while measurements are being taken and
deactivated for low power periods. Figure 32 shows an example of this. All of the
sensors connected to the MSP430 are powered by the SVec terminal.
The SVec terminal outputs the AVec voltage if the following conditions are true:
VSVcc = VREF .and. @ Pd .and. VAVcc

Architecture and Function of the MSP430 14-8it ADC

2-31

The AID Control/er Hardware
VR"

- - . -.....-..-1-lSvee

les
A3

Rv

Rex!

A61---+--___
A4

Vln -"<'Vv--e----\------I

--+
Rsens3

R1

R2

Rsens2

Rsens1

~ Vrd
Dr1

OV

+5 V/3 V

Figure 32. SVcc Terminal Used as an Output

The voltage, Vin, at analog input A2 is measured in comparison to the voltage at
SVcc. If the voltage, VREF, at SVcc is known (AVcc is stable and known, ISVcc
is small), then Vin can be measured exactly. Otherwise an external reference
diode (or equivalent) may be connected to a free analog input, and its voltage,
Vrd, is measured. See Figure 32. The formula for Vin is then:

Vin

=

Vrd x Nin x R1 + R2
Nrd
R2

Where:
Vrd = Voltage of the reference diode
[V]
Nin = 14-bit result for Vin
Nrd = 14-bit result for the voltage Vrd of the reference diode

3.3.2 SVcc Terminal Used as an Input for the ADC Reference Voltage
For absolute voltage measurements an external reference voltage, VREF, is
necessary (see Figure 33). The sensor measurements for Rsens1 to Rsens3 are
made the same way as with the internal reference voltage. The only difference
is the VREF bit of the ACTL register: it is set to zero to allow an external reference
voltage to be used. The formula for Vin is:

Vin = VREF x ~ x R1 + R2
214
R2

2-32

SLAA045

The AID Contro/Isr Hardware
Isvcc

Vref

Vaup

SVcc

Rv

--+108

Rex

A3
Rext

Vln

A4

A2
R1

Reane3

A1
AS
R2

Reans2

AD

DV

+5 V13 V

Figure 33. SVcc Terminal Used as an Input for a Reference Voltage
NOTE: If an external voltage reference is used, then it must be
able to deliver not only the current for the external circuitry but also
a maximum current of 80 !iA at 5 V to supply the parts of the ADC
that are connected to SVcc.

The maximum voltage at SVcc when used as an input is the
voltage applied to AVcc.
Measurements with the ADC using external reference voltages down to 1.2 V at
SVcc showed that the ADC does not change its characteristic. However, the
noise of the result doubles when compared to a 5..v supply. This is due to the
voltage-independent noise generated by the ADC.

3.3.3 Connection of Current Consuming Loads to SVcc
If the current drawn by the external ADC circuitry exceeds 8 mA, then an external
switch for the external analog voltage should be considered. A simple PNP
transistor can be used for this purpose as shown in Figure 34. The SVcc terminal
is used as an input pin for the external reference voltage (ADC control bit VREF
= 0). This method allows the full accuracy ofthe ADC also with current consuming
loads. Output TP.O switches the power to the current consuming loads off and on.
The schematic in Figure 34 is simplified for clarity. The connection principle .
shown in Application Basics for the MSP430 14-Bit ADC Application Report
(SLAA046)[3) needs to be applied, especially with the larger currents flowing
here.

Architecture and Function of the MSP430 14-811 ADC

2-33

The AID Controller Hardware
- - -....- - - _ - - -......- _ . - - +5V/3V

Rv
L---~TP.O

~~-------~AO
~------~A1

RaenS2

Rsens1

A2
A3
AVaa

DVaa

----~---~---4_~~-----4--~--OV

Currenl Consuming Analog Parte ~» 8 rnA)

Figure 34. Connection of Current Consumlng.Loads to SVcc
The software for switching the PNP transistor follows. The TP-port handling may
be included in the MEASR subroutine if this is an advantage. The example refers
to the hardware shown in Figure 34. Rsens1 is measured.
BIC.B
BIS.B
MOV
CALL
BIC.B

#TPO,&TPD
; TP.O pin is low if enabled
#TPO,&TPE
; Enable TPO: switch PNP on
#ADCLK+RNGA+CSA2+A2,&ACTL ; ADC: ext. reference
#MEASR
Measure Rsensl at A2
#TPO,&TPE
Switch PNP off: TPO Hi-Z
Result in ADAT

3.4 Interrupt Handling
All of the ADC software examples shown previously use polling techniques to
check for conversion completion. This takes up computing power that can be
used more effectively if interrupt techniques are used.

3.4.1 Interrupt Flags
ADC interrupt flags are not located in the ACTL control register. This allows
advanced interrupt handling. Several interrupt enable flags in a common byte can
be disabled and enabled together with minimal effort, something that is
impossible with flags located in the individual control words. The two flags
controlling the interrupt of the ADC are:
IE2
ADIE

.EQU
. EQU

Olh
04h

ADC interrupt enable bit (IE2.2)

IFG2
ADIFG

. EQU
. EQU

03h
04h

INTERRUPT FLAG REGISTER 2
ADC "EOC" Bit (IFG2.2)

Interrupt Enable Register 2

3.4.2 Interrupt Handlers
The interrupt structure of the ADC allows the conversion time to be used for other
calculations or procesor tasks. Two ADC interrupt handler examples follow:
2-34

SLAA045

The AID Controller Hardware

EXAMPLE: analog input AD (without current source) and A 1 (with the current
source enabled) are measured alternately. The measured 14-bit results are
stored in address MEASD for input AD and MEAS1 for input A 1. The time interval
between the two measurements is defined by the 8-bit timer: each timer interrupt
starts a new conversion for the previously prepared analog input. Other timers
may also be used for the generation of the time interval.
Analog input

Current Source
Result to
Range selection
Reference

AO
OFF
MEASO
AUTO
. SVcc

Al
ON
MEASI
AUTO
SVcc

Initialization part for the ADC:
MOV
#RNGAUTO+CSOFF+AO+VREF,&ACTL
BIS.B #ADIE, &IE2
Enable ADC interrupt
MOV. B #OFFh-3, &AEN
Only AD and Al analog inputs
Initialize other modules
ADC interrupt handler: AD and Al are measured alternately.
The next measurement is prepared but not started.
The interrupt flag ADIFG is reset automatically
ADC INT

ADI

BIT
JNZ
MOV
MOV
RETI
MOV
MOV
RETI

#Al,&ACTL
ADI

Al result in ADAT?
Yes
&ADAT,MEASO
AD value is actual
#RNGAUTO+CSON+Al+VREF,&ACTL
Al next meas.
&ADAT,MEASl
#RNGAUTO+CSOFF+AO+VREF,&ACTL

Al value is actual
AD next meas.

8-bit timer interrupt handler: the ADC conversion is started
for the previously prepared ADC input
T8BINT

BIS

#SOC,&ACTL

; start conversion for the ADC
Execute other timer tasks

RETI
.SECT "INT_VECO"/OFFEAh
. WORD ADC_INT
. SECT "INT_VEC1", OFFFBh
.WORD TBBINT

Interrupt vectors
ADC interrupt vector
a-bit timer interrupt vector

The software for the 12-bit conversion is similar to that for the 14-bit conversion,
the only difference being the replacement of the RNGAUTO bit during the
initialization of the ACTL control register. Instead, the desired range (RNGA,
RNGB, RNGC, or RNGD) is included in the initialization part of each
measurement.
Architecture and Function of the MSP430 14-Bit ADC

2-{35

The AID Controller Hardware

NOTE: An independent timer-like that used in the example
above-is recommended; do not use the ADC interrupt handler
to restart the ADC. If the ADC interrupt handler starts the next
conversion, then any interrupt failure leads to a flip-flop effect; the
missing ADC interrupt does not start a new conversion, and the
ADC activity ceases.
EXAMPLE: for best results the CPU is switched off during the ADC
measurement. The measurement subroutine starts the conversion and switches
off the CPU afterwards. The interrupt routine called by the conversion completion
resets the CPUoff bit (SR.4) of the stored status register SR and allows the CPU
to continue with the measured ADC result. The 12-bit result is moved to R5.
CPUoff

.equ

OlOh

GIE

.equ

008h

SR: CPU off bit
SR: General Intrpt enable

RNGB

.equ

0200h

ACTL: Select Range B

BIC.B

#ADIFG,&IFG2

Reset ADC flag

BIS.B

#ADIE,&IE2

ADC Intrpt Enable

EINT

Enable GIE interrupt

MOV

#RNGB+CSOFF+Al +VREF, &ACTL

CALL

#MEASURE

MOV

&ADAT, R5

; Define ADC

Measure with ADC
Result to R5
Process result in R5

subroutine: CPU is switched off to get minimum noise
MEASURE

BIS

#SOC,&ACTL

BIS

#CPUoff,SR

NOP

; start ADC conversion
Switch CPU off, MCLK active
wait for completion of ADC

RET

Interrupt Handler for the Analog-te-Digital Converter
The CPUoff bit of the saved SR is cleared to allow the
software to continue after the RETI

BIC

#CPUoff,O(SP); Allow SW run (CPUoff - 0)

RETI

Interrupt Vectors

.sect

"INT_VEC1",OFFEAh
; ADC Vector

2-36

SLAA045

ADC Characteristics

3.5 ADC Clock Generation
The frequency of the ADC clock, ADCLK, must be in a certain range as discussed
in section 2.1.1 ADC Timing Restrictions. To allow the adaptation of the ADCLK
to the full range of the MCLK frequency, four possibilities of prescaling are
provided:
•

MCLK

•

MCLKl2

if MCLK < 1.5 MHz
if MCLK > 1.5 MHz

•

MCLKl3

if MCLK > 3.0 MHz

This allows an MCLKlADCLK combination to be selected for nearly all
applications that fits the calculation needs, while providing the necessary ND
conversion speed.

4 ADC Characteristics
The next four figures show typical measured ADC characteristics: the absolute
error (ADC steps) is dependent on the input value (ADC steps from 5 to 16380).
Error characteristics like these are used with Additive Improvement of the
MSP43D 14-Blt ADC Characteristic (SlAA047)[4], Linear Improvement of the
MSP43D 14-Bit ADC Characteristic (SLAA048)[5], and Nonlinear Improvement
of the MSP43D 14-Bit ADC Characteristic (SlAA050)[6] to illustrate the
improvements possible by methods using different hardware and software.

ADCSteps

Figure 35. Error Characteristic Device 1

~ a ~1
.~ ~

8-1
~

~~

~'1"""""1

--~

____________________________________________~__-J
ADCStaps

Figure 36. Error Characteristic Device 2
Architecture and Function of the MSP430 14-Bit ADC

2-37

Summary

i]:~~
ADCSteps

Figure 37. Error Characteristic Device 3

~

g

~

ADCSleps

Figure 38. Error Characteristic Device 4

5 Summary
This application report complements Application Basics for the MSP430 14-Bit
ADC (SLAAD46)[3] that contains applications of the 14-bit ADC. Additive
Improvement of the MSP430 14-Bit ADC Characteristic (SLAA047)[4] explains
different methods to minimize the ADC error, and the limitations of the ADC.
All five of the application reports in the MSP430 14-bit ADC series include system
applications (hardware and proven software) using all parts and modes of the
ADC.

6 References
1. MSP430 Family Architecture Guide and Module Library, 1996, Literature
#SLAUE1DB
2. Data Sheet, MSP430x32x Mixed Signal Microcontroller, 1998, Literature
#SLAS164
3. Application Basics for the MSP430 14-Bit ADC application report, 1999,
Literature #SLAA046
4. Additive Improvement of the MSP430 14-Bit ADC Characteristic application
report, 1999, Literature #SLAA047
5. Linear Improvement of the MSP430 14-Bit ADC Characteristic application
report, 1999, Literature #SLAAD48
6. Nonlinear Improvement of the MSP430 14-Bit ADC Characteristic
Application Report, 1999, Literature #SLAA05D
7. MSP430 Metering Application Report, ·1998, Literature #SLAAE1 DC
2-38

SLAA045

Definitions Used With the Application Examples

Appendix A

Definitions Used With the Application Examples

; HARDWARE DEFINITIONS
AIN

.egu

OllOh

Input register (for digital inputs)

AEN

.equ

Oll2h

0: analog input

1: digital input

AeTL

.equ

01l4h

ADC control register: control bits

SOC

.equ

Olh

Conversion start

VREF

.equ

02h

0: ext. reference

AO

.equ

OOh

Input AO

1: SVcc on

Al

.equ

04h

Input Al

A2

.equ

OBh

Input A2

A3

.equ

Oeh

Input A3

A4

.equ

10h

Input A4

AS

,equ

l4h

Input AS

eSAO

.equ

OOh

Current Source to AO

eSA1

.equ

40h

Current Source to Al

eSA2

.equ

BOh

Current Source to A2

eSA3

.equ

OeOh

Current Source to A3

eSOFF

.equ

100h

Current Source off

CSON

.equ

OOOh

Current Source on

RNGA

.equ

OOOh

Range select A (0

RNGB

.equ

200h

Range select

RNGC

.equ

400h

Range select C (0.5 ... 0.7SxSVcc)

RNGD

.equ

600h

Range select 0 (0.75 .. SVcc)

RNGAUTO

.equ

800h

1: range selected automatically

PO

.equ

1000h

1 : ADC powered down

ADCLKl

.equ

OOOOh

ADCLK

ADCLK2

.equ

2000h

ADCLK

MCLK/2

ADCLK3

.equ

4000h

ADCLK

MCLK/3

ADCLK4

.equ

6000h

ADCLK - MCLK/4

ADAT

.egu

Ollah

ADe data register (12 or 14-bits)

IFG2

.equ

03h

Interrupt flag register 2

ADIFG

.equ

04h

ADC "EOC" bit (IFG2.2)

IE2

.equ

01h

Interrupt enable register

ADIE

.equ

04h

ADC interrupt enable bit (IE2.2)

TPD

.egu

04Eh

TP-port: address data register

TPE,

.equ

04Fh

TP-port: address of enable register

TPO

.equ

1

Bit address ,of TP.O

TPl

.equ

...

0.2SXSVcc)

B (0.25 .. 0.SOxSVcc)

= MCLK

Bit address of TP.l
Architecture and Function of the MSP430 14-Bit ADC

2-39

2-40

SLAA045

Application Basics for the MSP430
14-Bit ADC
Lutz Bieri

~TEXAS

INSTRUMENTS
2-41

IMPORTANT NOTICE
Texas Instruments and its subsidiaries (TI) reserve the rightto make changes to their products or to discontinue
any product or service without notice, and advise customers to obtain the latest version of relevant information
to verify, before placing orders, that information being relied on is current and complete. All products are sold
subject to the terms and conditions of sale supplied at the time of order acknowledgement, including those
pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semiconductor products to the specifications applicable at the time of sale in
accordance with Tl's standard warranty. Testing and other quality control techniques are utilized to the extent
TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily
performed, except those mandated by government requirements. .
CERTAIN APpLICATIONS USING SEMICONDUCTOR PRODUCTS MAY INVOLVE POTENTIAL RISKS OF
DEATH, PERSONAL INJURY, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE (,'CRITICAL
APPLICATIONS"). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, AUTHORIZED, OR
WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT DEVICES OR SYSTEMS OR OTHER
CRITICAL APPLICATIONS. INCLUSION OFTI PRODUCTS IN SUCH APPLICATIONS IS UNDERSTOOD TO
BE FULLY AT THE CUSTOMER'S RISK.
In order to minimize risks associated with the customer's applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assistance or customer product design. TI does not warrant or represent
that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other
intellectual property right of TI covering or relating to any combination, machine, or process in which such
semiconductor products or services might be or are used. Tl's publication of information regarding any third
party's products or services does not constitute Tl's approval, warranty or endorsement thereof.

Copyright © 2000, Texas Instruments Incorporated

Contents
1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 2-45
2 Applications..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 2·46
2.1 Connection of Analog Signals and Sensors ............................................... 2-46
2.1.1 Current Supply for Sensors ...................................................... 2-46
2.1.2 Voltage Supply for Sensors ...................................................... 2-48
2.1.3 Four-Wire Sensors Circuit ....................................................... 2-49
2.1.4 Connection of Bridge Assemblies .........................•...................... 2-50
2.1.5 Reference Measurements ................................•...................... 2-52
2.2 14-Bit Analog-to-Digital Conversion With Signed Signals .................................... 2-54
2.2.1 Virtual Ground IC ....................................•......................... 2-54
2.2.2 Split Power Supply ...•.•....................................................... 2-55
2.2.3 Use of the Current Source ..............................•....................... 2-56
2.2.4 Resistor Divider ..................................................••............ 2-59
2.3 12-Blt Analog-to-Digital Conversion With Signed Signals .................••................. 2-60
2.3.1 Virtual Ground Circuitry .........•............................•.................. 2-60
2.3.2 Use of the Current Source ............•......................................... 2-62
2.3.3 Resistor Divider .................. : ............................................. 2-62
2.4 Reference Resistor Method ............................................................. 2-63
2.4.1 Reference Resistor Method Without Amplification .................................. 2-63
2.4.2 Reference Resistor Method With Amplification •..............•.•.••................ 2-65

3 Hum and Noise Considerations .............................................................. 2-67
3.1
3.2
3.3

Connection of Long Sensor Lines ........................................................ 2-67
Grounding ..........................................•................................. 2-68
Routing ............................................................................... 2-69

4 Enhancement of the Resolution . ............................................................. 2·70
4.1 16-Blt Mode With the Current Source .•.............•.......................••....•....... 2-70
4.2 Enhanced Resolution Without Current Source .....................•....................... 2-72
4.3 Calculated Resolution of the 16-Blt Mode ................................................. 2-75
4.3.1 16-Bit Mode With the Current Source ............................................. 2-75
4.3.2 16-Bit Mode Without the Current Source .......................................... 2-75
5 Hints and Recommendations ................................................................ 2·76
5.1 Replacement oflhe First Measurement ................................................... 2-76
5.2 Grounding and Routing ................................................................. 2-76
5.3 Supply Voltage and Current ............................•................................ 2-76
5.3.1 Influence oflhe Supply Voltage .................................................. 2-76
5.3.2 Battery Driven Systems .......................................•................. 2-77
5.3.3 Mains Driven Systems .......••...•............•.....•.......................... 2-78
5.3.4 Current Consumption ........................................................... 2-78
5.4 Use of the Floating Point Package ...........................•.....•..................... 2-78
6 Addltlonallnformation ...................................................•.................. 2.79
7

References ................................................................................. 2.79

Appendix A

Definitions Used With the Application Examples .................................... 2-81

Application Basics for the MSP430 14-Bit ADC

2-43

- Figures

List of Figures
MSP430 14-Bit ADC Hardware •........•.•........•.••..•..•..•......•........•....... , ....•... 2-45
2 Possible Connections to the ADC ............................................................... 2-46
3 Current Supply for the Sensor Rx ............................................................... 2-47
4 Voltage Supply for the Sensor Ax ................................................................ 2-48
5 Four-Wire Circuit With Current Supply ........................................................... 2-49
6 Connection of Bridge Assemblies ............................................................... 2-60
7 Connecting Reference Elements ................................................................ 2-63
8 Virtual Ground IC for Signed Voltage Measurement ................................................ 2-64
9 SPill Power Supply for Signed Voltage Measurement .............................................. 2-66
10 Current Source Used for Level Shifting ......................................................... 2-67
11 Signed Signals Shifted With the Current Source .................................................. 2-67
12 Signed Current Measurement With Level Shifting (Current Source) .....................••.......... 2-68
13 Resistor Divider for High Input Voltages ......................................................... 2-69
14 Virtual Ground Circuitry for Level Shifting ....................................................... 2-61
15 Current Source Used for Level Shifting ......................................................... 2-62
16 Referencing With Precision Resistors - No Amplification .......................................... 2-64
17 Referencing with Precision Resistors - With Amplification ......................................... 2-66
18 Sensor Connection via Long Cables With Voltage Supply ......................................... 2-67
19 Analog-to-Digital Converter Grounding .......................................................... 2-68
20 Routing That is Sensitive to External EMI ....................................................... 2-69
21 Routing for Minimum EMI Sensitivity ........................................................... 2-69
22 Dividing of an ADC-Step Into Four Steps ........................................................ 2-70
23 Hardware for a 16-Bit ADC ..................................................................... 2-71
24 ADC-Resolution Expanded to 15 Bits ........................................................... 2-72
25 ADC-Resolution Expanded to 16 Bits ........................................................... 2-73
26 Influence of the Supply Voltage ................................................................ 2-77

List of Tables
Resistor Ratios ....••.....•....•.................•..••..................••.................... 2-61
2 Measurement Results of the 16-Bit Method ..................................... ; ................. 2-70
3 Calculation Results for Different 16-Bit Corrections ................................................ 2-75

2-44

SLAA046

Application Basics for the MSP430 14-Bit ADC
Lutz BierI
ABSTRACT

This application report gives a detailed overview of several applications for the 14-bit
analog-ta-digltal converter (ADC) of the MSP430 family. Proven software examples and
basic circuitry are shown and explained. The 12-bit mode is also considered, when
possible. The References section at the end of the report lists related application reports
in the MSP430 14-bit ADC series.

1 Introduction
The application report Architecture and Function of the MSP430 1408it ADC[1J
explained the architecture and function of the MSP430 14-bit analog-to-digital
converter (ADC). The hardware (registers, current source, used reference,
interrupt handling, clock generation) was explained in detail and typical ADC
characteristics were shown.
Figure 1 shows the block diagram of the MSP430 14-bit ADC.
AVcoC>-......- -...
SVccSwltch

~ACTL.l(Vref)

Offset

SV"'r-<::::::>r---I~ ACTL12(Pd)

Rs,
128
128
128
128

~NO<=~~~~--~~

(AVas)

ACTL9. 10(Range)
ACTL "(Auto)

-:;:::jt::=::j~_l...,

,-,-1---+--'

MI~~~~~~ l~AC~T~L.O:'~::)~:=:t~~~~~~~~~~~~~
~

8:1

""
A4

0---0

AS
AS
A7

Input
MUX

input

ACTL2A (Ax)
ACTL5 (None)

SAR.13

SAR.O

16-8" Memory Ollla Bus, MOB

Figure 1. MSP430 14-Bit ADC Hardware
2-45

Applications

2 Applications
This application report shows several methods for connecting resistive sensors,
bridge assemblies, and analog signals to the ADC. Solutions are given for the
12-blt and 14-bit conversions, with and without using the integrated current
source. The equations shown result In voltages and resistances. To calculate the
sensor values (pressure, current, temperature, light intensity a.s.o) normally with
non"linear equations, refer to the following sections of Chapter 5:
• Table Processing (Section 5.2)
• Temperature Calculations for Sensors (Section 5.5.6)
- Table Processing for Sensor Calculations
- Algorithms for Sensor Calculations
- Coefficient Calculations for the Equations
• The Floating Point Package (Section 5.6)

2.1

Connection of Analog Signals and Sensors
Figure 2 shows possible methods for connecting analog signals to the ADC. The
methods shown are valid for the 12-bit and 14-bit conversion modes:
1. Current supply for resistive sensors
Rsens1 at analog input AO
2.. Voltage supply for resistive sensors
Rsens2 at analog input A1
3. Direct connection of input signals
Vin at analog input A7
4. Four-wire circuitry with current supply
Rsens3 at output A3 and inputs
A4andA5
5. Reference diode with voltage supply
Dr1 at analog input A6
6. Reference diode with current supply
Dr2 at analog input A2
The resistance of the wiring, Rwire, in the following equations may be neglected
. if it is low compared to the sensor resistance.
SVec

Rv

Rex

A3

Relit

~n ~~~--~---~A7
R1

AS

t-----..--+ Ics

RVd

1---+--'"

A4

MSP430C32x

.------IA1

88n83

A5
A2t---r~

M

OV

5V/3V

Figure 2. Possible Connections to the ADC

2.1.1 .Current Supply for Sensors
The ADC formula for the resistor Rx in figure 3 (Rsens1 in Figure 2) which is fed
from the current source is (14-bit conversion):
2-46

SLAA046

Applications

N

=

N=

VAO X 214
VREF

=

les

X

(Rx+ 2 X Rwire) X 214
VREF

0.25 X VREFx (Rx + 2
Rex
Vre'

X

Rwire)
X

214 = Rx

+2 X
Rex

.
RWlre x 212

This leads to:
Rx = Rex x

2~2 - 2 x Rwire

For the 12-bit conversion the formula is:
N

= VAO -

nxVREF
0.25 x VREFx 214 = (RX + 2 x Rwire _ n) x 212
Rex

This leads to:
Rx = Rex x

Where:

(2~2 + n)

N

Rx
Rex
Rwire
VREF

VAO

n
Ics

- 2 x Rwire

ADC conversion result for resistor Rx
Sensor resistance
[n]
Current source resistance (defines Ics)
[n]
Wiring resistance (one direction only)
[n]
Voltage at terminal SVcc (internal or external reference) [V]
Voltage at the analog input AO
M
Range number (0,1,2,3 for ranges A,S,C,D)
Current generated by the current source
[A]
SVcc

VREF

Rex
Rex!
Rwlre

Rx

Rwlre

+- res

AD

MSP430

VAO~

OV

SV

Figure 3. Current Supply for the Sensor Rx

Application Basics for the MSP430 14-Bit ADC

2-47

Applications

If the resistance of the wires may be neglected (Rx » Rwire) then the above
formulas simplify to (14-bit conversion):
.

N = Rx
Rex

X

212

Rx= Rex x

2~2

For the 12-bit conversion the formulas become:

(.1:L

Rx = Rex x 212 + n)

N = ( Rx - n) x 212
Rex

2.1.2 Voltage Supply for Sensors
The ADC formula for the resistor Rx in figure 4 (Rsens2 in Figure 2) which is
connected to Vref through the series resistor Rv is (14-bit conversion):

N

=

VAl X
-VREF

214

=

Rx + 2 x Rwire. x 214 -+ Rx = Rv x __
N_ - 2 x Rwire
Rv+ Rx+ 2 x RWlre
214 - N

For the 12-bit conversion the formula is:

N= (

VAl _
VREF

n x 0.25) x 214 = (

Rx + 2 x Rwire. - n x 0.25) x 214
Rv + Rx + 2 x RWlre

Thjs leads to:

Rx = Rv x _-:::.,.;1_ _ _ - 2 x Rwire
214
1
N+nx2'2 Where:

Rv

Resistance of the series resistor
Voltage at the analog input A1

VAl

[a]

----........

VIIIIF

M

sVcc

Rv

Rwlre
Rx

OV

5V

Figure 4. Voltage Supply for the Sensor Rx
Ifthe resistance ofthe wires can be neglected (Rx» Rwire), the above formulas
simplify for the 14-bit conversion to:

N=~ X214
Rv+ Rx
2--48

SLAA046

-+

Rx= Rvx __
N214 - N

Applications

For the 12-bit conversion the formula becomes:
N

= (~
- n x 0.25)
Rv+ Rx

x 214 -. Rx = Rv x

1
214
_ 1
N+nx2'2

2.1.3 Four-Wire Sensors Circuit
Four-wire circuits eliminate errors due to the voltage drop caused by the
connection lines (Rwire) to the sensor. Instead of two lines, four are used-two
for the measurement current, and two for the sensor voltages. The two sensor
lines do not carry current; the current at the analog inputs is in the nanoamp
range, so no voltage drop falsifies the measured values. The four-wire circuit is
used with a heat volume counter shown in the Section 4.5, Heat Volume Counter..
Figure 5 shows the four-wire circuit with its current supply.
VAEF

I

RWire

SVcc

Rex

Rex!

.-.JCB

A2
A1

----.

<~~

VA'

T

1=0
1=0

MSP430

----.
Rwlre

R2~

1
AO

VAO

AVaa

1

DVaa

T
OV

DVcc

I

5V

Figure 5. Four·Wlre Circuit With Current Supply

The difference ~N of the two measurement results for the analog inputs A1 and
AOis:
LI N = (VAl - VAn)

X

14 =
3v REF

LIN = 0.25 x VREF x Rx
Rex

X

los x ((Rx + Rwire + R2) - (Rwire + R2)) x ,~14

vREF

214 =
VREF

Rx
Rex

X 212

This gives for Rx:
Rx = Rex x LIN
212

Where:

aN

Difference of the two ADC results (here NA1 - NAO)

As the two final equations for ~N and Rx show, the influence of the Rwire
resistances disappears completely.
Application Basics for the MSP430 14-Bit ADe

2-49

Applications

NOTE:
The two formulas above are valid for 14-bit and 12-bit conversions. If
the 12-bit ADC results are measured in different ADC ranges, then the
12-bit results need a correction (the missing two MSBs-13th and 14th
bits-of the ADC results must be added): .
Range A: 0 Range B: 1000h Range C: 2000h Range D: not possible
Resistor R2 is necessary, because the ADC cannot measure down to AVss (0 V)
due to saturation effects. R2 may be quite small; it is only necessary to get above
the saturation voltage-'-rlormally less than 30 ADC steps.
The software to measure t.N is shown next. The hardware of Figure 5 is used:
Measure upper leg of Rx at input Al and store ADC value.

The Current Source is connected to A2
MOV
CALL
MOV

#RNGAUTO+CSA2+Al+VREF,&ACTL
#MEASR
&ADAT,R5

Define ADC

Upper leg voltage of Rx (Al)
Store Al value in RS

Measure lower leg of Rx at input AO. Current Src to A2
MOV
CALL

#RNGAUTO+CSA2+AO+VREF,&ACTL
#MEASR

; Define ADC
; Lower leg voltage of Rx (AO)

The difference delta N of the 2 measurements is proportional
to the value Rx: Rx - Rext x del taN x 2A-12
.
SUB

; R5 contains delta N
; Calculat~ Rx

&ADAT,R5

2.1.4 Connection of Bridge AssemblIes
Bridge assembly sensors are best known for pressure measurement. The
voltage difference (Vp - Vm) between the two bridge legs changes with the
pressure to be measured. For clarity, the temperature measurement circuitry that
is normally necessary is not included.
·VAIF - - _ - -.......

OV

3V(5V)

Figure 6. Connection of Bridge Assemblies
On the left side of Figure 6, a bridge assembly creates a voltage difference large
enough to be measured by the ADC with appropriate resolution. The
measurement result is the difference of the two ADC results measured at the A1
and A2 analog inputs.
.
2-50

SLAA046

Applications

AN

=

Where:

VA2 - VA1
VREF
I1N
VAx
11 V
I1Rb
Rb

X 214 __

AV = AN

X

VREF

X 2- 14

=

VREF'X LlRb
Rb

Difference of the two ADC results (here NA2-NA1)
Voltage at the ADC input Ax measured to AVss
M
Difference of the two bridge leg voltages (here VA2-VA1)
[V]
Change of a single bridge resistance due to measured value
[OJ
Nominal value of a single bridge resistor
[OJ

With the above equations, the interesting bridge output value I1RblRb becomes:
ARb = AN x 2- 14
Rb

If the difference of the two measurements is too small to be used, an operational
amplifier may be used as shown on the right of Figure 6. Here the possibility to
measure the reference voltage (one of the two bridge legs) is shown too: analog
input A4 measures the reference that can be used for a better result together with
the input A3.
The voltage difference A V between the analog inputs A3 and A4 is:
A V = VA3 - VM = (v x (Vp - Vm)

AV = R1 x (Vp - Vm) = R1 x

R2

R2

+ Vp) - Vp

VREF «Rb
2xRb

= v x (Vp - Vm)

+ ARb) - (Rb - ARb)) = R1 x VREF x ARb
R2

Rb

The same voltage difference 11 V described with the ADC equation is:
AV

=

VA3 - VA4 =

(~:: - ~~:)

x VREF

= (NA3 -

NM)

X

~~~F

Combining the two equations above delivers the interesting two equations:
AN= vxARbx214=R1 xL1Rbx214
Rb
R2
Rb

For the bridge output value ARbIRb, the following equation is used: the value
I1Rb/Rb is necessary for the final calculation ofthe measured item, e.g., pressure
p = f(I1Rb/Rb):
ARb = ~ = R2 x NA3 - NM
Rb
vx 214
R1
214

Where:

AN
AV

v
Vp
Vm

Difference of the two ADC results (here NA3-NA4)
Voltage difference of analog inputs A3 And A4
(VA3-VA4)
Amplification of the operational amplifier: v=R1/R2
Voltage of the bridge leg connected to the
noninverting input
Voltage of the bridge leg connected to the
inverting Input

M
[V]

M

Application Basics for the MSP430 14-Bit ADC

2-51

Applications

If the reference input (analog input A4 in Figure 6) is not implemented, then the
difference of two measurements at the amplifier output (analog input A3 in
Figure 6) is used. The voltage difference t. V between two measurements is:
.<1Rb1 -.<1RbO
.<1V= VA31 - VA30 = (v+ 0.5) x Vrefx
Rb
The same voltage difference t. V described with the ADC equation is:
.<1 V

=

VA31- VA30

= (NA31
214

- NA30)
214

X

VREF

= (NA31

- NA3o)

X

VREF
214

The two equations above deliver the equation for t.N, e.g., the ADC value
representing the difference of two weights:
.<1N

= NA31

- NA30

= (v + 0.5)

x .<1Rb1 R/ROO x 214

= (~ + 0.5)

x (LJRb1 ;b.<1RbO) x 214

And for the difference of the two bridge output values that represent for example
a weight difference. The value t.RblRb is used for the final calculation of the
measured item, e.g., the weight G =f(t.RblRb):
.<1Rb _ .<1Rb1 - .<1 ROO _
NA31-NA30
Rb Rb
-(v+0.5)x2 14

Where:

t.N
NASO

NASt
t.V
VASO

VASt
v
t.RbO
t.Rb1
t.Rb
Rb

NA31 - NA30

(~ + 0.5)

x 214

Difference of the two ADC results (here NA31-NA30)
ADC result of the 1st measurement, e.g., the zero point
of the bridge
ADC result of the 2nd measurement, e.g., a weight
measurement
Volta.ge difference of two analog measurements
(VA31-VA30)
[V]
Voltage at the analog input A3, e.g., for the zero point
of bridge
[V]
Voltage at the analog input A3, e.g., a weight
measurement
M
Amplification of the operational amplifier: v=R1/R2
Resistor deviation (RbO-Rb) of the 1st measurement [n)
Resistor deviation (Rb1-Rb) of the 2nd measurement [n)
Resistor difference (Rb1-RbO)
Nominal value of a single bridge resistance
[n)

2.1.5 Reference Measurements
The simplest way to get a reference voltage Is to use the supply voltage of the
MSP430. If this is not possible, and a stable reference voltage is needed, e.g. for
voltage measurements, then a reference diode can be used. Figure 7 shows two
ways to connect a reference diode to the MSP430:
• The reference diode Dr1 is fed via the series resistor Rvd
• The reference diode Dr2 Is fed by the current source of the MSP430
2-52

SLAA046

ApplicatIons

vsvcc

~'---_--ISVcc

Rvd

MSP430C32x

Rex!

Vln

-'Vvv-.....- - + - - - - - - - f A 2
R1

......- - - - - I A 1

R2

OV

5V/3V

Figure 7. Connecting Reference Elements
If the external voltage Vin shown in Figure 7 is to be measured, then the following
equations may be used. For reference purposes the voltage VDr is used, not the
unknown supply voltage Vsvcc:

Vin = R1 + R2 x Nin x Vsvcc
R2
214

The unknown voltage Vsvcc is fixed by the measurement of the reference voltage
VDr:
VOr

= 214
NOr

X

Vsvcc- Vsvcc

= 214
NOr

X

Va

r

This leads to:
Vin = R1

Where:

+ R2

R2

x Nin x VOr

Vin
Vsvcc
VOr
Nin
NOR
R1, R2

NOr

Input voltage to be measured
M
Supply voltage at terminal SVcc
[V]
Voltage of the reference diode Dr
[V]
ADC measurement resuH for the input voltage Vin
ADC measurement result for the reference voltage VOr
Voltage divider for input voltage Vin
[0]

If the supply voltage Vsvcc is overlaid by hum (mains driven supply), then the
referencing method shown above gives much better results if the reference diode
Dr is measured twice-once before the input voltage Vin (NorO), and once
afterwards (NOrl). The two ADC results, Noro and NOrl, are used as follows:
Vin = R1

+ R2 x

R2

2 x Nin

NolO

+ NDr1

x VOr

The calculation above uses the mean value of the measured values ofthe voltage
Vsvcc (linear correction).
Application Basics for the MSP430 14-Bit ADC

2-53

Applications

2.2 14-Bit Analog-Io-Digital Conversion With Signed Signals
The MSP43D ADC measures unsigned signals from Vref, the voltage applied to
the terminal SVcc (internal or external), to AVss. If signed measurements are
necessary then a virtual zero point has to be provided. Signals above this zero
pOint are treated as positive signals; signals below it are treated as negative ones.
Four possibilities for a virtual zero point are shown in this chapter:
• Virtual ground IC:
The zero point is provided by a speciallC
• Split power supply: The zero point is provided by two power supplies
The zero point is provided by the current source and
• Current source:
a drop resistor
•

Resistor divider:

The zero point is provided by a resistor divider

The signal source is connected to the virtual zero point with its reference potential
(first two solutions) or to the AVss potential (last two solutions).

2.2.1

Virtual Ground Ie
With the phase splitter TLE2426, a common zero pOint is provided which lies
exactly in the middle of the voltage between the Vref and the AVss potential. The
reference voltage Vref may be internal (AVcc) or external. All signed input
voltages are connected to this virtual ground with their reference potential. The
virtual ground voltage (at analog input AD in Figure 8) is measured after regular
time intervals, and the measured ADC value is stored and subtracted from the
measured analog input signal V1 (here at input A 1). This results in a signed, offset
corrected ADC value for the signal at the analog input A 1. The virtual ground
method is used with some electronic electriCity meters shown in Section 4.1,
Electricity Meters.
VREF

,----------:5:-:V-;-!SVCC

r------IA1
V1

~
2.5V AO

MSP430

NOTE: TheV1 ,angeis-l.5V to 1.5 V for V,ef= 3.0 V

OV

5V

Figure 8. Virtual Ground Ie for Signed Voltage Measurement
The formula for the difference of the ADC results aN is:

LlN = (NA1 _ NAO) = V1

2-54

SLAA046

+ Vvg x 214 _ Vvg x 214 = ~ x 214
VREF
VREF
VREF

Applications

This leads to the formula for V1:
V1

= VREF

Where:

x .!iN
214

V1

aN
VREF

Vvg

Voltage to be measured
Difference of the two ADC results (here NA1 - NAO)
Voltage at the SVcc terminal measured against AVss
terminal
Voltage at the AO terminal (0.5 x Vref)

M
[V]

[V)

EXAMPLE: The virtual ground voltage at AO is measured and stored in location
VIRTGR (register or RAM). The value of VIRTGR is subtracted from the ADC
value measured at input A1; this gives the signed, offset corrected value for the
input signal at the A1 input. The measurement subroutine MEASR shown in
Section 4.1 is used.
VIRTGR . EQU

R6

; Virtual Ground ADC value

Measure virtual ground voltage at input AO and store value
for reference. MCLK = 3MHz: divide MCLK by 2
MOV
CALL
MOV

#ADCLK2+RNGAUTO+CSOFF+AO+VREF,&ACTL
#MEASR
Measure AO (virtual ground)
&ADAT,VIRTGR i Store result: 14-bit value

Measure analog input signal VI (0 ... 03FFFh) and compute
a signed, offset corrected value for VI (OEOOOh ... 01FFFh)
MOV
CALL
MOV
SUB

#ADCLK2+RNGAUTO+CSOFF+Al+VREF,&ACTL
#MEASR
Measure Al (input voltage VI)
&ADAT, RS
Read ADC value for VI
VIRTGR,RS
RS contains signed delta N
VI = Vref x del taN x 2~-14

2.2.2 Spilt Power Supply
With two power supplies, for example with 2.5 V and -2.5 V. a potential in the
middle of the MSP430 ADC range can be created. Figure 9 shows this
arrangement. All Signed input voltages are connected to this voltage with their
reference potential (0 V). The mid range voltage (at analog input AO) is measured
after regular time intervals and the measured ADC value is stored and subtracted
from the measured signal (here at analog input A1). This gives a signed, offset
corrected result for the analog input A1. The split power supply method is used
with some of the electronic electricity meters shown in Section 4.1, Electricity
Meters.

Application Basics for the MSP430 14-Bit ADC

2-65

Applications
2.5 V

~'1

SVCC
Al

V~
AO

OV

MSP430

O.SXVAEt
-2.5 V

-2.5 V

2.5V

Figure 9. Split Power Supply for Signed Voltage Measurement

The formula for the difference of the ADC results aN is:
LlN

= (NA1

=

_ NAO)

V1 + (0.5 x VR£F) x
VR£F

214 _

(0.5 x VR£F) x

214

= 2'L

VR£F

X 214

VR£F

This leads to the formula for V1 :
V1 = VR£F x LlN
214

Where:

V1

aN
VR£F

Input voltage to be measured
Difference of the two ADC results (here NA1-NAO)
Voltage between the SVcc and the AVss terminals

[V]

[V]

The same software example can be used as shown before with the virtual ground
IC.

2.2.3 Use of the Current Source
With the current source method shown in Figure 10, a voltage that is partially or
completely below the AVss potential can be shifted into the middle of the used
ADC range of the MSP430. This is accomplished by a drop resistor Rh whose
voltage drop shifts the input voltage accordingly. This method is especially useful
if differential measurements are necessary, because the ADC value of the
signal's midpoint (zero point) is not available as easily as with the two methods
shown previously. If absolute measurements are necessary, then a calibration or
a measurement with a known input voltage equal to the zero point is needed.

2-56

SLAA046

Applications

VAEF - - -.....---ISVcc
Rex
Rex!
Rh
,---'vVlr---jA1

MSP430

-1.25 V lo1.25V@5V VI

-_>-----_-1 AVss

NOTE: The V1 range is -0.75 V... +O.75 V lor Vrel

=3 V

OV

5V/3V

Figure 10. Current Source Used for Level Shifting
The example of Figure 11 shows an input signal V1 ranging from -1.25 V to
1.25 V. To shift the signal's zero voltage (0 V) to the midpoint voltage Vzv of the
usable ADC range (this range is approximately 0.5 x Vref, so Vzv is 0.25 x Vref)
a current Ics is used. The necessary current Ics to shift the input signal is:

Ics = Vzv -> Rh = Vzv =
Rh
Ics

Vzv

0.25 x VREF

Rex
V1

t

ADC Value

VREF

03FFFh

0.75 x VREF

03000h

0.5 x VREF

02000h

0.25 x VREF

01000h

+-...L--C.-+--+---+--,-O;;:------

o

OOOOOh

+------"""'---------.......;;:===

Signal Zero Voltage

-.

Time

Figure 11. Signed Signals Shifted With the Current Source
Therefore the necessary shift resistor Rh is (Rh includes the internal resistance
of the voltage source V1):

Rh = Vzv x Rex
0.25 x VREF
with Vzv chosen to:

Vzv

= 0.25

X

VREF -> Rh

= Rex

Application Basics for the MSP430 14-Bit ADC

2-67

Applications

Where:

Vzv
VREF
Rex
Rh

Voltage of the signal midpoint (signal zero voltage)
Voltage at the SVcc terminal (external or AVcc)
Resistor between SVcc and Rext terminal (defines Ics)
Shift resistor

[V]

[V]
[0]
[a]

The voltage VAl at the analog input A1 is:
VAl

=

V1 + Rh x les

=
.

V1

+ Rh x 0.25 x VREF
Rex

The offset part (Rh x les) of the last equation is typically measured during a time
when V1 is known to be zero. This offset is stored in the RAM and subtracted from
any measured value for V1. This leads to signed, offset corrected values for V1.
The unknown voltage V1 is:
V1

VA' _ Rh x 0.25 x VREF
Rex

=

With Rh=Rex:

V1 = VREF x

=

VREF x

(2~4 -

(J:L _Rh Rex
x 0.25)
214

0.25 )

Figure 12 gives two practical examples for dc and ac measurements using the
current source. Both applications measure signed voltages that are partially (the
negative parts) out of the ADC range of the MSP430.
AVecJ2
AVecJ4
AVss

To Charger

1

f\

Q

Q

\)

~

or

I
18e+~11

Rsh

~

+le8

Rid

lve.

_ - - _ - roLoad

SVcc

v~l

Rex
+ 10$

R1

Rext

VOli.

A1
Cunent
AD

A2

MSP430032x

L - - _ _ e - - - - - I AVa.
OV

AC Measurement

lVAO

Re
VShl

Ie.
R2

Shunt

AV.. I-----~--__e-_o OV

DC Measurement

Figure 12. Signed Current Measurement With Level Shifting (Current Source)

AC Measurement: A current transformer CT is shown. Its output voltage is
shifted into the ADC range by the current Ics of the current source and the resistor
Rsh. The tolerable range for Ics is:
leSmin

-<

les

-<

Idcmax

Icsmin is defined by the ADC specification, and Idcmax is given by the current
transformer specification. Current transformers normally are sensitive to dc bias
currents. Rcu is the resistance of the transformer's secondary winding (normally
Rid» Rcu).
VA2 = Vet
2-68

SLAA046

+ (Rsh + Reu) x Ics

Applications

This leads to:
Viet =

v:A2 -

RSh

fCS = \.IiREF

X

X

(N
214

-

0.25 x (Rsh
Rex + ReU))

DC Measurement: The charge and discharge currents of an accumulator cause
a voltage drop at the shunt resistor. This signed voltage drop Vsh is shifted into
the ADC range by the resistor Rc (normally Rshunt« Rc).
VAO = Vsh + Re x fcs
This leads to:
Vsh

=

VAO - Re x fes

=

VREF x

(K _0.25Rexx Re)
214

2.2.4 Resistor Divider
If the input voltages are high - which means normally higher than 10 x VREF then, as shown in Figure 13, a simple resistor divider may be used for the level
shift into the ADC range.
V1

VA1

VREF

SVcc

R1

Rh

IV11»
VREF

OV

SVor3V

Figure 13. Resistor Divider for High Input Voltages
For input voltages V1 that are much higher than VREF, the following equation is
valid (Rh » R2):
VAl

=

R111R2
R2
V1 x R1 IIR2 + Rh + VREF x R1 + R2

This leads to:

V1 = VREF

X (

~~~

-

R1

NAI

= '214

X

VREF

~ R2) x ( 1 + R1~k)

To get the full accuracy of the ADC, the condition R1" R2 < 27 kQ must be
fulfilled.

Application Basics for the MSP430 14-Bit ADC

2--59

App/icBlions

For high input voltages V1 the resistors R1 and R2 are normally equaHt is not
possible or necessary to correct the small error of the input slgnal-so the
equation simplifies to:
VAl = V1

x R1 + ~ x Rh + 0.5 x VREF= ~:~x VREF

This leads to'.

V1 = VREF

X (

NAl
2 14 - 0' 5)' x (1

+ 2 xR1Rh)

The de offset part (0.5 x VRIEF) of the last equation is typically measured during
a time when V1 is known to be zero. This measured offset is stored in the RAM
and subtracted from any measured value for V1. This leads to signed, offset
corrected values for V1.
For input voltages that have no dc-part (e.g., sinusoidal signals), the zero point
can be calculated by an integration of the input signal. After a muHiple m of the
signal period, the 'integrated sum of ADC resuHs equals m times the value of the
zero point.

2.3 12-81t Analog-ta-Dlgital Conversion With Signed Signals
The asymmetrical arrangement of the four ADC ranges reduces the number of
solutions that are possible with the 12-bit conversion:
• Normal phase splitter circuits are not able to shift the virtual ground into the
middle of range A, B C or 0 as it is necessary here. See Table 2 column Vvg
for the center values of the four ADC ranges.
• The split power supply method would need two voltages to get the zero point
into the center of the used range: e.g., 0.625 V and 4.375 V for range A if a
5-V supply Is used.
NOTE: The formulas given in this section are valid only if both
measurements for differences (~N) are measured in the same
ADC range. Ifthey are measured in different ADC ranges, then the
12--bit results need a correction (the missing two MSBs of the
ADC result must be added). The correction numbers are:
Range A: 0
Range B: 1000h
Range C: 2000h
Range 0: 3000h

2.3.1

Virtual Ground CIrcuitry
The phase splitter TLE2426 delivers only one half of the input voHage at its output
terminal; it cannot be used here. With a simple op amp as shown in Figure 14,
the necessary output voltages for the four ADC ranges can be obtained:
R .. R1 + R2. See Table 1 for the relative resistor values.

2-60

SLAA048

Applications

Table 1. Resistor Ratios
ADCRange

VoltageVVG

R2

R1

A

0.125 x VREF

0.125xR

0.875 x R

B

0.375 x VREF

0.375 x R

0.625 x R

C

0.625 x VREF

0.625 x R

0.375 x R

D

0.875 x VREF

0.875 x R

0.125 x R

Resistors R1 and R2 can have relatively high resistances. Only the offset current
of the op amp limits these resistor values.
VRIF

.....-------....:..:::=---------1svcc
Rl

. - - - - - - - - - - - 1 AI
-O.6VIoO.6V@5V ~ VI

VI

_--0.......~~~------~-~AO
R2

MSP430

OV
NOTE: The range for V1 is -0.37 V to 0.37 V if VREF is 3 V
OV

5V/3V

Figure 14. Virtual Ground Circuitry for Level Shifting
The formula for the difference of the ADC results AN measured at the analog
inputs A1 and AO is:
-dN

=

(NA1 - NAO)

=

V1 + Vvg
VREF

X

214 _ Vvg
VREF

X

214

=~

X

VREF

214

This leads to the formula for V1:
V1 = VREF x -dN
214
Where:V1
Voltage to be measured inside of one ADC range
IV]
AN
Difference of two ADC results (here NA1-NAO)
VREF Voltage at the SVcc terminal measured against AVss terminal IV]
Vvg Voltage at the AO Input (center of the used ADC range)
M
EXAMPLE: The center voltage of the C range (at analog input AO) is measured
and stored in location VIRTGR (register or RAM). The value of VIRTGR is
subtracted from the ADC value measured at analog input A1; this gives the
signed, offset corrected value for the input signal at the A1 input. The
measurement subroutine MEASR of section 4.1 is used.
Measure center voltage of range C at analog input AD and
store value for reference. MCLK MOV
CALL

3.3MHz: divide MCLK by 3

#ADCLK3+RNGC+CSOFF+AO+VREF,&ACTL
#MEASR
Measure AO (center voltage)

Application Basics for the MSP430 14-8it ADC

2-61

Applications

Store result: 12-bit value

MOV &ADAT , VIRTGR

Measure analog input signal VI (0 ., .OFFFh) and compute
a signed, offset corrected value for V1 (OFBOOh ... 07FFh)
MOV

#ADCLK3+RNGC+CSOFF+A1+VREF,&ACTL

CALL

#MEASR

Measure Al (input voltage VI)

MOV
SUB

&ADAT,RS
VIRTGR,R5

Read ADC value for V1
R5 contains signed delta N
V1 ~ Vref x del taN x 2'-14

2.3.2 Use of the Current Source
For signed signals it is necessary to shift the input signal V1 to the center of the
ranges A or B. See Figure 15.
V,

VA'

VA'

2000h~

VREF ----<11>----1 SVcc

RangeB

Rex

1000h

Range:

Rext

Rh
r---'\/Vv----l A 1
MSP430

-1.6 V 100.6 V@5V
AVss

NOTE: The range for VI is -{l.3? V to 0.3? V if VREF is 3 V

OV

5Vor3V

Figure 15. Current Source Used for .Level Shifting

To get into the center of range n the necessary shift resistor Rh is:
Rh = 0.25 x VREF x 2n + 1 x
Rex
_ Rh = (n + 0.5) x Rex
2
0.25 x VREF
The unknown voltage V1 measured to its zero point in the center of range n is:
V1 = VAx- Rh x Ics

With the above equation for Rh this leads to:
V1 =0.25 x VREF x

.(.l:L + n - Bl1..)
Rex
212

2.3.3 Resistor Divider
The same circuitry is used as shown for the 14-bit conversion. See Figure 13.
With the 12-bit conversion, it only makes sense to use the A range. This means
for resistors R1 and R2, if R = R1 + R2:
R1 = 0.875 x Rand R2 = 0.125 x R.
2--62

SLAA046

Applications

For input voltages V1 that are much higher than VREF, the following equation is
valid (Rh » R2):
VA1 =

V1 x

R111R2
R111R2 + Rh

+ VREF x

R2
R1

+

R2 =

NAl

214

x VREF

With the above values for R1 and R2 this leads to:
V1 = VREF x 0.125 x

(~~;

- 1) x (1

+ 0.125

x

~~875 x R)

To get the full accuracy of the ADC, the condition R111R2 <27 1<0 must be fulfilled.
This means R < 247 1<0.

2.4

Reference Resistor Method
A system that uses sensors normally needs to be calibrated, due to the tolerances
of the sensors themselves and of the ADC. A way to omit this costly calibration
procedure is the use of reference resistors. Two methods can be used, depending
on the type of sensor:
1. Platinum sensors (e.g., PT500, PT100): These are sensors with a precisely
known temperature/resistance characteristic. Two precision resistors are
used with the sensor resistances of the temperatures at the two limits of the
temperature range.
2. Other sensors: Nearly all other sensors have insufficiently tight tolerances.
This makes it necessary to group sensors with similar characteristics, and to
select the two reference resistors according to the sensor resistances at the
upper and the lower measurement range limits of these groups.
If the two reference resistors have-within the needed accuracy-the values of
the sensors at the measurement range limits (or at other well-defined points) then
all tolerances are eliminated during the calculation. Therefore, no calibration is
necessary.
NOTE: For voltage measurements, the reference method

described above can be used with two reference voltages instead
of two resistors. In this case, substitute voltages for the
resistances used with the next equations.

2.4.1 Reference Resistor Method Without Amplification
This method can be used for the input range given by the current source-the A
and B ranges and part of range C. For details, see Architecture and Function of
the MSP430 14-Bit ADq1)

Application Basics for the MSP430 14-Bil ADC

2-63

Applications

The nominal formulas given in the previous section need to be modified if the
tolerances of the ADC, the current source, the extemal components, and the
sensor are considered. The ADC value Nx for a given resistor Rx is now:
Nx = Rx X 212 x Slope
Rex

+ Offset

The slope and the offset are used for the correction of the measured result Nx.
For the calculation of the slope and offset measurements with different resistors,
Rx are necessary. With the hardware shown in figure 16 this calibration process
can be omitted.

R.~[
~

svec

los

Rext
AO
Al

MSP430

A2
Rre!1

Rx

..-:

~

Rret2
AVss
DVss
T

OV

DVec

I

3V/5V

Figure 16. Referencing With Precision Resistors - No Amplification

With two known resistors Rref1 and Rref2 as shown in Figure 16, it is not
necessary to know the slope and the offset to measure the value of the unknown
resistor Rx exactly. Measurements are made for Rx, Rref1, and Rref2. The ADC
results for these three measurements are:
Nx= Rx
Rex

Nref2 = Rref2
Rex

X 212

x 212

The result of the solved equations shown above leads to:
Nx- Nref2
Rx = N f2
fe - Nref1 x (Rref2-Rref1)

Where:

+ Rref2

ADC conversion result for sensor Rx
ADC conversion result for reference resistor Rref1
ADC conversion result for reference resistor Rref2
Resistance of Rref1 (equals Rxmin)
[01
Resistance of Rref2 (equals Rxmax)
[01
As shown, only known or measurable values are needed for the computation of
Rx from Nx. Slope and offset influences of the ADCdisappear completely:
• The offset disappears due to the two subtractions, one in the numerator and
one in the denominator of the fraction above.

2-64

SLAA046

Nx
Nref1
Nref2
Rref1
Rref2

App//cstions

•

The slope disappears due to the division

EXAMPLE: The values of these two reference resistors are chosen here for a
PT1000 temperature sensor:
Rref1: 1000 0: The value of Rxmin. The resistance of a PT1 000 sensor at
O·C (Tmin)
Rref2: 13800: The value of Rxmax. The resistance of a PT1 000 sensor at
100·C (Tmax)

2.4.2 Reference Resistor Method With Amplification
If amplification is necessary to get a better resolution, then the solution shown
below may be used. The full AOC range (0 to 3FFFh) can be used at analog input
A1 despite the use of the current source at analog input AO. As with the section
above, the offset and slope disappear; this is also true for the voltage drop at the
outputs TP.x due to ROSon. The TP port of the measured resistor is switched to
AVss potential; the other ones are set to Hi-Z.
The only error source of this arrangement is the difference of the. internal
resistances of the TP outputs (aROSon). To minimize the influence of different
internal resistances ROSon, only sensors with a minimum resistance should be
used, e.g., PT1000 not PT100.
For the full 14-bit resolution at the analog input Ai the following design equations
are valid (Rref2 > Rref1). They simplify this way if Rex is chosen to:

Rex

= Rref2
2

This results in a maximum voltage of VREF/2-the safe maximum output voltage
the current source can deliver-at the analog input AO for the maximum resistor
value Rref2.
Vm =

Rref1
x VREF
Rref1 + Rref2

v=

VREF
=~
VREF-2 x Vm
R211R3

The calculated amplification vof the op amp needs to be reduced by 10 to 15%
to be sure that VA1 does not saturate under worst case conditions.

Application Basics for the MSP430 14-Bit ADC

2-65

Applications
VRSF

R2

R1
V=R1/(R2I1R3)

--:~

R3
Rref1

1.....
I...... ./

Vm

Rx

Rex

1

l

SVec

Rext
MSP43OC32x
A1

+-

Rref2

AO

les
TP.O
TP.1
TP.2
AVss
OV

DVss

DVcc

OV

5V/3V

I

Figure 17. Referencing With PreCision Resistors - With Amplification
As Figure 17 shows, with two known resistors Rref1 and Rref2 it is possible to get
the values of unknown resistors exactly. The result of the solved equations gives:
Rx = LJNx --: LJNref2 x (Rref2 - Rref1)
LJ Nref2 - LJ Nref1

Where:

t:.Nx
t:.Nref1
t:.Nref2
Vm

+ Rref2

Difference of the two ADC results for Rx
(NA1-NAO)
Difference of the two ADC results for Rref1
(NA1-NAO)
Difference of the two ADC results for Rref2
(NA1-NAO)
Voltage generated by the resistor divider R2 and R3

The differences named above are the differences between the ADC conversion
results measured at the analog inputs A1 and AO for each resistor:
t:.N = NAt - NAO.

2-66

SLAA046

Hum and Noisa Considerations

3 Hum and Noise Considerations
3.1

Connection of Long Sensor Lines
If the distance from the MSP430 to the sensor is long (>30 cm) then it is
recommended to use a shielded cable between the microcomputer and the
sensor. This avoids spikes at the ADC input that cause measurement errors, and
also gives protection to the ADC input. Figure 18 shows this schematic on the left
side. In the same way, four-wire circuitry may be connected to the MSP430.
If a shielded cable cannot be used, the circuitry shown on the right side of Figure
18 should be used; the AVss line in parallel to the signal line gives a relatively
good screening. Twisting the two lines increases the protection.
To protect the measurement against spikes, hum, and other unwanted noise see
Section 5.3, Signal Averaging and Noise Cancellation. This section shows
additional possibilities for the minimization of these influences by software.
SVcc
,- _ _ _ _ _ ,

I

RSEN.
I
I
IL. _ _ _ _ _ .J

SVec

Rv

Long cable

Shield

Rv
Rp

Rp
At

Shield

Long cable

A2
RSENS

MSP43032X

c

C
AVss
DVss

OV

I

No Shield, Twisted Pair

AVss
DVcc

I5V

Figure 18. Sensor Connection via Long Cables With Voltage Supply

With the circuitry of figure 18, the minimum time tdelay between the switch-on of
the voltage SVcc and the actual measurement-to get the full 14-bit
accuracy-is:
tdelsy> In214

x rmax

= 9.704

x rmax = 10 x rmax

The value of 'tmax is:

rmsx = (Rp + RsensmaxllRv) x C
If the current source is used, then:

Rv = 00:

'rmax = (Rp + Rsensmax) x C

Application Basics for the MSP430 14-Bil ADC

2~7

Hum and Noise Considerations

3.2

Grounding
Correct grounding is very important for ADCs with high resolution. There are
some basic rules that need to be observed 1• See Figure 19 also.
1. Use a separate analog and digital ground plane wherever possible: thin
traces from the battery to terminals DVss and AVss'should be avoided.
2. The AVss terminal should serve as a star pOint for all analog ground
connections e.g. sensors, analog input signals. The DVss terminal should
serve as a star point for all digital ground connections e.g. switches, keys,
power transistors, output lines, digital input signals.
3. The battery and storage capacitor Cb should be connected close together
(the capacitor Cb is needed for batteries with a relatively high internal
resistance). From this capacitor two different paths go to the analog and the
digital supply terminals. Two small capaCitors are connected across the
digital (Cd) and the analog (Ca) supply terminals. See Figure 19.
4. .Rules 1 to 3 above are also true for the Vcc paths (DVee and AVec).
5. The AVss and DVss terminals must be connected together externally; they
are not connected internally. The same is true for the AVcc and DVcc
terminals. These connections should be made with the configuration shown
in Figure 19.
6. The coil L should be used in very difficult cases.
7. The connections ofthe capacitor Cb are the star point ofthe complete system.
This is due to the low impedance of this capacitor.
.
4>--~>-----ISVec

Rv
Rex!

......- - - - I A 1
RseNS2

RSSNSI

MSP430C32x

AO

AVes

AVec

DVes

DVec

To Other DlgllBl Parts
To Other Analog Parts

Figure 19. Analog-to-Digltal Converter Grounding
If a metalized case is used around the printed circuit board containing the
MSP430 then it is very important to connect the metallization to the ground
potential (0 V) of the board. Otherwise the behavior is worse than without the
metalization.
1 These grounding rules were developed by E. Haselofl 01 TID.

2-68

SLAA046

Hum and Noise Considerations

3.3

Routing
Correct routing for a PC board is very important for minimum noise. Figure 20
shows a simplified routing that is not optimal; the gray areas receive EMI from
external sources. For a minimum influence coming from external sources these
areas must be as small as possible.

r----------------,

I
I

Figure 20. Routing That Is Sensitive to External EMI
Figure 21 shows an optimized routing; the areas that may fetch noise have a
minimum size.

..------------- -------,I
Rv

SVec

I
I
I
I
I
I
I

I1.. _ _ _ _ _ _

Figure 21. Routing for Minimum EMI Sensitivity
Application Basics for the MSP430 14-Bit ADC

2-69

Enhancement of the Resolution

4 Enhancement of the Resolution
Many applications need a higher resolution than the 14-bit ADC can provide. For
these applications the following hints may be helpful.
NOTE: These enhancements make it necessary to pay attention
to the rules given in Chapter 3. Without observing these rules
strictly, no enhancement will be seen.
4.1

16-Bit Mode With the Current Source
With the use oftwo additional output terminals (I/O-ports or TP-outputs) the 14-bit
ADC may be expanded to a resolution of nearly 16 bits. The principle is simple:
the resistor Rex of the current source is modified by paralleling two additional
resistors (see Figure 23). These resistors have values that represent one half and
one quarter of a single ADC-step. Due to the fact that these fractions of a step
are accurate only at one point of the ADC-range, this enhancement gives only
better resolution, not better accuracy. To get the 16-bit result, four measurements
are necessary: one for every combination of the two additional resistors. If the
results of these four measurements are added, a 16-bit result is reached. See
Figure 22.

i

ADCValue

XX:x::j

XXXX-l

~

~

OOOOOh -4------+--+--+--+--o
VO
Vl
V2
V3

ADe Input Voltage

----.

Figure 22. Dividing of an ADC·Step Into Four Steps
Table 2 shows the different results of these four measurements for the four
possible input voltages vo toV3 inside of one ADC-step; the table refers to the
hardware shown in Figure 23.
Table 2. Measurement Results of the 16-81t Method
INPUT
VOLTAGE

MEASUREMENT 1
TP.l: HI-Z
TP.O: HI·Z

MEASUREMENT 2
TP.l: HI·Z
TP.O: HI OUT

XXXX
XXXX
XXXX
XXXX

XXXX
XXXX
XXXX
XXXX+l

VO
Vl
V2
V3

2-70

SLAA046

MEASUREMENT 3
TP.l: HIOUT
TP.O: HI·Z
XXXX
XXXX
XXXX+l
XXXX+l

MEASUREMENT 4
TP.l: HI OUT
TP.O: HI OUT
XXXX
XXXX+l
XXXX+l
XXXX+l

MEAN VALUE
(BINARY)
XXXX.OO
xxxx.Ol
XXXX.l0
XXXX.ll

Enhancement of the Resolution

r------ITP.O
...----iTP.1
Simplified Circuity of a TP-oulpul

SVec

Vee

TP.x

o

o

Rn

R16

R15

MSP430C32x

L----.....- -...
SVcc8wJt.ch
~ACTL1(Vref)
SV.. .-<::::::>..----l~

ACTLI2(Pd)
128

128

C
ACTL.6.7
ACTL,8
(CSo1I)

128

B

128
A

~ND~~t±i=~--~=

ACTt.9. to(Range)

(AVss)

-~~J[::::~_-1~, ~-;~__+-~

ACTL.11(Auto)

AIM!~~~~~~ 0"'0 l~ACT~LO:(S:OO:)~:::EEEEE~~EEEE~~~~~~-;:C
8"

~:

Input

~

Input

AS
A7

MUX

ACTL2.4 (Ax)
ACTl.5 (None)

1M" Memory Data Bus, MOB

Figure 1. The Hardware of the 14-81t Analog-to-Digital Converter
The methods for the improvement of the ADC described in the next sections are:
• Correction with the mean value of the full ADC range
• Correction with the mean values of the four ranges
• Correction with the centers of the four ranges
• Correction with multiple sections
Linear, quadratic, and cubic corrections are explained in Linear Improvement of
the MSP430 14-Bit ADC Characteristic(3) and nonlinear improvements are
discussed in the Nonlinear Improvement of the MSP430 14-Bit ADC
Characteristic(4).

2-88

SLAA047

The External Cal/bration Hardware for the ADC

2 The External Calibration Hardware for the ADC
All of the methods of improvement discussed in this report need to know the
actual errors of the ADC at different points of the four ADC ranges. See Figure
7 for an example of a noncorrected ADC characteristic.

2.1

Measurement Methods for the ADC Reference samples
The characterization of the ADC for this report is made with three different
methods:
.
• External digital-to-analog converter (DAC): an accurate DAC-controlled by
the measured MSP430-produces precise analog output voltages that are
measured with the 14-bit ADC. The difference of the two numbers is the
absolute error of the ADC.
• External discrete, precise voltages: the MSP430 controls its input voltage via
an external analog multiplexer. If only a few accurate input voltages are
needed, then this method is best.
• External precision resistors: the MSP430 controls which resistor is
measured. For systems that measure the resistance of sensors, this method
is best.
Several other methods exist to measure the errors of different reference points
for improvement of the ADC characteristic including:
• Measurement of a single ADC sample: fastest way, but not recommended
due to statistical reasons.
• Multiple measurements of the same point and calculation of the mean value:
e.g. 16 measurements.
• Multiple measurements of the errors around a given point and calculation of
the mean value: e.g. 16 measurements ±8 (or ±32) around the center point
of interest.
• External 16-bit DAC: measurement of all possible four pOints (xxx.OO, xxx.01 ,
xxx. 10, xxx.l1 for the 14-bit value xxx) and summing them up. This gives an
additional 2 bits of resolution.
• Sophisticated statistical methods.
• Measurement of 12 samples for the same ADC point and rejection of the two
extreme values. The remaining 10 samples are averaged.
These error measurement methods may be used for all of the given improvement
methods in this report. However, they are not discussed with the description of
the improvement methods. See also Section 5.3, Signal Averaging and Noise
Cancellation.
This application report only uses simple measurement methods.

2.2 External Dlgltal-to-Analog Converter
The external hardware connected to the MSP430-PC board (see Figure 3) is
used to obtain the necessary information about the characteristic of the ADC. Its
main part is a precise 14- or 16-bit digital-ta-analog converter (DAC). Figure 2
shows the calibration process:
Additive Improvement of the MSP430 14-8it ADC Characteristic

2-89

The Extemal CalibratIon Hardware for the ADC

Figure 2. Flowchart 1: Calibration With an External Dlgltal-ta-Analog Converter

The measurement sequence for an ADC point is as follows (see also Figure 2):
• The MSP430 outputs via its select lines (parallel DAC) or via an output line
(serial DAC) a 14- or 16-bit number. This number programs the DAC. The
LCD is not damaged, due to the short duration of the signals (microseconds).
• The extemal DAC converts the digital number into a precise output voltage
that corresponds to the input number.
• The MSP430 measures the output voltage of the DAC and compares the
result with the number that was the output. The difference (measured ADC
value - output DAC value) is the absolute error of the ADC at that given point.
• The measured errors are used for the calculation of the correction values.
These are stored in the RAM or in an EEPROM and are used forthe correction
of the ADC characteristic. The format and the number of the stored correction
values depend on the correction method used: 1 to 64 bytes for the examples
given here.

2-90

SLAA047

The External Callbretion Hardware for the ADC

r- ------

, Ir-------------- ---,
I
External Dlgltal.to-Analog Hardware

MSP430 PC Baard

I
I
I

3"'561.8
Ox

--~
t

Ax
SVec

I

I

I

I

i

Port

T

CIN,TPO.5

TXD
RCV

I

-+-

*

To System

I

call~lon~
Connector

-- --

I
!

~

+15 V

DG

I--

OV

Vaa

'=V

-15 V

Vdd
Date
CS

tMlt
DAC

OV

LDAC
VOUT
V..,.

! !

AVss

MSP430C32x

I

I I

020

EEPROMr

I
I
I

I I

;-

019

I

I
I
I

i

I I

V..,-

T
OV

:'--------------OV

----'

To Host Computer

!

~

Figure 3. External, Serially Controlled DAC for ADC Measurement

The loop from Port to CIN that is closed by the external hardware indicates to the
MSP430 during the initialization that the measurement of the ADC characteristic
is active. Like the other DAC control lines, these two liDs may be used for other
system tasks when not in calibration mode.
It is also possible to use a parallel DAC for the calibration of the MSP430 ADC.
The time needed for the measurement of the ADC characteristic is shorter than
with a serial DAC, but the number of connections between the MSP430 board and
the calibration unit are much higher than for a serially controlled DAC. Figure 4
shows this arrangement.

Additive Improvement of the MSP430 t4-Bit ADC Characteristic

2-91

The External Calibration Hardware for the ADC

3'-4561.8
_ _ !kWh!

I

I
I
I
I

--, r - - - - - - - -..,
External Digital-to-AnalOg Hardware

MSP430 PC Board

------

r

-

t

003... 018

I I
I I

020
Ax

EEPROMr..-

I

I

I

NCS
DO
Yout

I

I
I

I

I

l J oIv

J

MSP430C32x

To·svim

callimrtlon
Connector

TXD

I

+15

r-:-- OV

DAC
AD7848

Yref+
Yref-

VO

I~

-15V

I
I

IL _ _ _ _ _ _ OV
_
_.J
To Host Computer

I
-1

RCV

I~
OV

NLDAC

AVo
CIN,TPO.5

I
IL _ _

I

SVcc

Port

I

DBO...16

I

OUI

II
I

Vdd

118/1

I
I
VI

Figure 4. External, Parallel Controlled DAC for ADC Measurement

2.3 External Discrete, Precise Voltages
If only a few points of the ADC characteristic need to be known, then only a few
discrete input voHages are necessary for the calibration process. These few
points can be generated with a precise, external reference voltage or the supply
voltage of the MSP430 and a resistor divider providing some defined output
voltages. Figure 5 shows both possibilities.

, r----------------,
I
I I

MSP430 PC Board

r

External Dlgltal·Io-Analog Hardware

-

---------

Abaolute Reference

3'iS61.B
_ _I

o.

kWh 1

003. ..018
SVec
Ax

I

EEPROMr..-

Ox
AVss

MSP430C32x
TXD
RCV

t

r-

I
I
I
I
I
I

I
I
I
I
I
I
I

I
II
I

I

Rei. Reference

T
Vee

I I

I
I
4
I
!
calliirauon I
Connector I
I
I
I
_ _ _ _ _ _ _ _ _ ..J!
!

1A

1B

2A

2B

3A

--

MUX
TPC4018

4A

XC

SLAA047

3B
4B

Vo

------

.-:: =-Vref

~---------------To Host Computer

Figure 5. External, Precise Voltages for Calibration
2-92

I
I
I
I
I
I
I
I

Q...

I

I
I
I
I
I
I
I
_.J

The External Calibration Hardware for the ADC

2.4 External Discrete Precision Resistors
If the task for the MSP430 ADC is to precisely measure resistance-for example
resistive sensors or platinum-and not external voltages, then this method
should be considered. The external hardware is a multiplexer that connects
precision resistors to one of the analog inputs of the MSP430. For external
resistors with low resistance it may be necessary to use reed relays for this task
due to the Roson reSistance of the multiplexer paths. Figure 6 shows this solution
for two external reference resistors: the current source outputs the current Ics at
the analog input Ax, the voltage drop at the selected external reference resistor
is measured with the same analog input. The number of the external precision
resistors may be adapted to the application needs.
This calibration method includes all onboard error sources such as Rext and the
ADC characteristic.
M5P430 pc Board

External Relerance Resistors

,------------------------,
3~S61.B

I

--~

r-----------------,

501 - 521 1-____---'

I
5Vee
I
I
Calibration
~ les
M5P43OC32x
Connector
I
Rext
I
Referance I
Releranee2
lea
I
AX~----------+~_4~~+__+--_.----------~
Rex

AV_~------------~~_+--+_--------~--------_+~
DVce~------------~~-+--+_----~~~------_,

To Host

L~~~.:.

TXD

DVss ~------2------~~-+-'

__~~~C_~V...._..._......._~o_~xl_-_-_=_"i_~_-_-_-_-_t_:::t-_-_ItJ

4-+-----~~--~--~~~ov

~----------------Figure 6. External Precision Resistors for Calibration

2.5 Storage of the Correction Data
The correction coefficients as calculated by the MSP430 or a host computer are
stored in the RAM or in an external EEPROM:
•

The RAM may be used if a battery is permanently connected to the MSP430
system.

s

An EEPROM is necessary if the supply voltage of the MSP430 system can
be interrupted e.g. due to the mains supply or a switch.
Additive Improvement of the MSP430 11U3it ADC Characteristic

2413

Different Improvement Methods

The format of the used £-bit coefficients is given in Nonlinear Improvement ofthe
MSP430 14-Bit ADC Characteristic, SLAA050 [4J. If the accuracy that can be
reached with these 8-bit numbers is insufficient, then 16-bit numbers-with
doubled RAM space and calculation time-may be used. Also the MSP430
floating point package can be a solution in this case.

3

Different Improvement Methods
To allow a comparison between the different improvement methods, the mean
value, the range, the standard deviation, and the variance of the corrected ADC
characteristic are given. The nearer these values are to zero, the better the
performance of the used improvement method.
The mathematical equations for the used statistical methods follow. They are
applied to every fourth value of the 16383 corrected samples.
The mean value x is calculated by summing all of the errors (ei) of all corrected
samples Ni and dividing this sum by the number of samples k. The mean value
xis:
i=k

X=

I

ei
i=1
-k-

The range R is the difference between the largest error emax and the smallest
error em in (e.g. the most negative error value). The range R is defined as:
R = emax - emin
The standard deviation S is defined as:
i=k

I
.8=

i= 1

ei2 _

(f:i)2
i=~

k_ 1

=

j

Vx k

~1

The formula for the variance V is:
i=k

I

;=1

(f~i)2

e;2 - _'_=_~-

V = -----:-k---

i=k

Iei L

;=k

X'x Ie;

1=1

;=1

k

Where:
k
= Number of included ADC errors ei
ei
= ADC error at ADC step i, ranging from e1 to ek
= Index for ADC errors

2~4

[Steps]

SLAA047

I·

Different Improvement Methods

NOTE: Each measured ADC value needs to be corrected

individually to get a correct result. If differences are measured
(AN) then both values have to be corrected and then the
subtraction executed. A correction of the difference AN alone
leads to false results.
It is importantto note the different scaling that is used for the y-axis
of the graphs with the corrected ADC characteristic. They differ
significantly, dependent on the amount of improvement.
The correction coefficients for all improvement methods are
calculated in such a way that allows addition forthe final correction
of the measured ADC result. This saves execution time and
program space.
All of the calculations used for the correction are made with a floating point
package (like the MSP430 .FPP4 software). If-as is necessary in real-time
systems-an integer package is used, then small rounding errors will occur. In
Nonlinear Improvementofthe MSP430 14-Bit ADC Characteristic[4] the software
routines and their influence on the accuracy of the final result are explained.
The improvement methods and their results for this report are demonstrated with
the characteristic of device 1 due to its worst characteristic compared to the other
three devices shown in Architecture and Function ofthe MSP430 14-Bit ADC[1].
The ADC samples used for the following improvement methods and calculations
were measured the following way:
• Twelve samples with the same ADC input voltage-generated by a 16-bit
DAC-were measured and stored.
• The maximum and the minimum value of these twelve samples were rejected
(rejection of extremes).
• Out of the remaining ten samples the mean value was calculated and used
afterwards.
The improvement methods are always shown for the full ADC range (ranges A,
B, C, and D). If the current source is active, then only ranges A, B, and part of C
can be used: the same improvement methods with the same formulas are valid
but with less needed RAM or EEPROM space for the correction coefficients. Due
to the importance of the current source for several applications, the statistical
results are also shown for ranges A and B only.
The 14-bit oriented correction software is also usable if the 12-bit ADC mode is
used: only the correction coefficients of the applied ADC range are used in this
case.
The orientation of this application report to the ADC ranges (single or multiple
corrections per range) is applicable, due to the visibly different slopes of the four
ranges inside of an ADC characteristic. See the noncorrected ADC
characteristics of device 1 (Figure 7) and devices 2 to 4 in [1] for examples.

3.1

The ADC Characteristic of Device 1 Without Correction
The noncorrected ADC characteristic of device 1 is shown in Figure 7. Its.
statistical values are given in the table below Figure 7.
Additive Improvement of the MSP430 14-8it ADC Characteristic

2--S5

Different Improvement Methods

The circle in Figure 7 indicates the irregularity located in range B. This irregularity
is the reason why more sophisticated methods sometimes have worse results
than simpler ones.
Device 1 Uncorrected

4
2

0
-2

I
I

8C

-4
-6
-6

-10
-12
-14
-16
ADC Steps [0 to 18383]

Figure 7_ The Noncorrected Characteristic of Device 1

The statistical results of the original ADC characteristic of device 1 are:
Full range
Ranges A and B only
Mean Value:
~.95 Steps
-10.51 Steps
Range:
17.00 Steps
10.80 Steps
Standard Deviation:
4.74 Steps
2_61 Steps
22_51 Steps
Variance:
6.80 Steps

3.2 Correction Methods Using Addition Only
These four methods are the fastest because they omit the multiplication. The main
disadvantages are the gaps between the ADC ranges e.g. from ADC step 4095 to 4096,
and the amount of RAM used, but these methods not only show speed advantages but
also the best results. The four methods explained below are best for real-time
applications, where the 50 to 100 cycles that are necessary for a correction that uses
multiplication cannot be spent: they are the fastest way possible for correction.

3.2.1

Correction With the Mean Value of the Full ADC Range
The ADC is measured at k equally spaced pOints. The errors of these k
measurements are calculated and the mean value of these errors is stored and
used for the correction of the ADC. The correction formula for each ADC sample
Ni to get the corrected value Nicorr is:

2-96

SLAA047

Different Improvement Methods

i=k

I-e;

·
1=1
.N/carr
= N'/ + -k-

Where:
Nicorr =Corrected ADC sample
Ni
= Measured ADC sample (noncorrected)
k
= Number of included ADC errors ei
ei
= ADC error i, ranging from e1 to ek

[Steps}
[Steps]
[Steps]

The principle is shown in Figure 8, the full ADC range is corrected with its mean
value. As with all future principle figures in this report, the black straight line
indicates the correction value, the scribbled black line indicates the noncorrected
ADC characteristic, and the white line shows the corrected ADC characteristic.
The small circles indicate the measured ADC points (the 128 circles of Figure 8
are not shown).
Devlca1

...

I
i
8

-1

<

ADCSteps

Figure 8. Principle of the Error Correction by the Mean Value of the Full Range
For k = 128-which means 128 samples over the complete ADC range-the
statistical results are:
Full range
Ranges A and B only
Mean Value:
-0.44 Steps
0.15 Steps
Range:
17.10 Steps
10.80 Steps
Standard Deviation:
4.74 Steps
2.61 Steps
Variance:
22.51 Steps
6.80 Steps
Figure 9 shows the result in a graph. The corrected characteristic is displayed for
the full range and for the ranges A and B only:

Additive Improvement of the MSP430 14-8it ADC Characteristic

2-97

Different Improvement Methods
Device 1 Corrected with the Mean Value of the ueed Range
(Full Range and A and B only)

10

8
6
";j'

I

4

2

~

0

8C

-2

w

-4

-8

-8
-10
ADC Steps [0 to 16383]

Figure 9. Error Correction With the Mean Value of the Used Range
Advantages:

Only one addition is necessary
.
Very fast due to no missing multiplication or shifts
No gaps; the monotonicity of the ADC characteristic remains
Only one byte of RAM is needed for the correction coefficient
Disadvantages: Range, standard deviation and variance are not improved
Many calibration measurements are necessary
NOTE: Within the software examples, the format of the integer number
is noted at the right margin. The meaning of the different notations is:
0.7 Zero integer bits, 7 fraction bits. Unsigned number
±4.3 Four integer bits, 3 fraction bits. Signed number
8.0
Eight integer bits, no fraction bits. Unsigned integer number
±7.0 Seven integer bits, no fraction bits. Signed integer number
The software part after each ADC measurement is as follows:
Correction with the mean value of the full range. 7 cycles
MOV.B

TAB,R5

Correction for full range

±7.0

SXT

R5

Sign extend byte· to word

±15.0

ADD

&ADAT,R5

Corrected ADC value in RS

14.0

Proceed with corrected ADC value
The RAM byte TAB contains the correction for the full range:
the negated mean value
.bss

2-98

SLAA047

TAB,l

Signed a-bit number

±7.0

Different Improvement Methods

EXAMPLE: The ADC is measured at nine points (rather than 128 to keep the
example under control) and the calculated mean value is used for the correction
of the full ADC range. The measured (k+ 1) errors (for device 1) are shown below.
The numbers used for the correction are slightly shaded.
50

2048

4096

I=k

L - ei

Correction:

~ = 6

.

k

+ 8 + 13 + 13 + 10 + 5~~ + 3
9

Corrected ADC sample: Nicorr =Ni + 6.5
Format: ±7.0
±6.1

+ 65
9·

= 58 =

Valid for the Full ADC range
7
0

I0' ai

6.5/20 =6.5 = 07h

I

6.5/2- 1 =13 =ODh

'01

0
0 i 0 '

1

7

i

1 I

1f1j1
0

616 '6'1'1.6;"

3.2.2 Correction With the Mean Values of the Four Ranges
The ADC is measured at (4xk) equally spaced points. The mean value of the k
errors per range is calculated and used individually for the correction of the four
ranges A to D. The correction formula for each one of the four ranges is:
;=k

L-

ei
/11.
;=1
·
N
. lcorr =
I + --kThe principle is shown in Figure 10, each range is corrected with its mean value
(the eight used samples are drawn only in the range A):
DevIce 1 Corrected with the center. 01 the lour rang..

10

I
!
~

5

o
oS

-10
-15
ADCStepa

Figure 10. Principle of the Error Correction WIth the Mean Values of the Four Ranges
For k - 8 (8 samples per range) the statistical results are:
Full range
Ranges A and B only
Mean Value:
~.31 Steps
0.15 Steps
Range:
13.5 Steps
9.80 Steps
Standard Deviation:
2.49 Steps
2.10 Steps
Variance:
6.20 Steps
4.41 Steps
Figure 11 shows the graph for k =8 (eight samples per range, 32 samples over
the full ADC range):
Additive Improvement of the MSP430 1+Bit ADC Characteristic

2419

Different Improvement Methods
Davlce 1 Corrected with the Mean value. of IheFour Ranges

ADC Slaps [0 to 16383]

Figure 11. Error Correction With the Mean Values ~f the Four Ranges
Only one addition is necessary for the correction
Fast due to no multiplication
Only four bytes are needed for the storage of the correction
values
Disadvantages: Range, standard deviation and variance are only slightly
improved
Monotonicity is not preserved: gaps appear at the range
borders.

Advantages:

The software part after each ADC measurement is as follows:
Correction with the mean values of the four ranges. 16 cycles
The four signed correction values are located in four RAM
bytes starting at label TAB
MOV

&ADAT,RS

ADC result Ni to R5 (D ... 3FFFh)

MOV

R5,R6

Copy result for correction

SWPB

R6

Range bits of result to low byte

RRA.B

R6

Calc. byte address for corr.

5.0

RRA.B

R6

Shift two range bits to LSBs

4.0

RRA.B

R6

RRA.B

R6

Range bits now 0 to 3

2.0

MOV.B

TAB(R6) ,R6

Correction fram table TAB

SXT

R6

Signed byte to signed word

t7.0
t15.0

ADD

R6,R5

Corrected result Nicorr in R5

14.0

Proceed with corrected Nicor"r

14.0

The

fo~r

14.0

3.0

signed correction values are located in four RAM bytes

starting at label TAB.
.bss

2-100

SLAA047

TAB,4

Signed a-bit numbers

t7.0

Different Improvement Methods

EXAMPLE: Range A of the ADC is measured at four points and the mean value
is used for the correction of this ADC range. The corrections for the other three
ranges (B, C and D) are calculated the same way. The measured errors for range
A are shown below (for device 1):
ADC Step

Error [Stapsl

1024

2048

\IC;;:~t;rl i;iRli1a~iJJ!j~;

i=k

I - ei

~ = 6

Correction: .

k

+ 8 +412 + 13

= 39 =

4

+ 975
.

Corrected ADC sample: Nioorr = Ni + 9.75
Format: ±7.0

9.75/20", 10 =OAh

= 19.5", 14h

±6.1

9.75/2-1

±5.2

9.75/2-2 = 39 = 27h

Valid for range A
7

0

'0,6'0'6'1'0'1'6,..
7

,0

0

'0'

0 '

1 i

6 '

1 '

0;6 I

7

'0'0'1'6 0'1;1'1'
1

3.2.3 Correction With the Center Points of the Four Ranges
The ADC is measured at the four center points of the ranges A, B, C and 0: the
ADC steps 2048, 6144, 10240 and 14336. The four errors (ee) at these four
center pOints are calculated and stored. To each measured ADC sample Ni the
negated error eo of the pertaining range is added. The correction formula for each
one of the four ranges is:

.Moorr = Ni + ee
Where:
ec = Negated error at the center of the actual ADC range

[Steps]

The principle is shown in Figure 12, the four AID ranges are corrected individually
with the errors of their center points:
DevIce 1

ADCS1aps

Figure 12. Principle of the Error Correction With the Centers of the Four Ranges

Additive Improvement of the MSP430 14-8it ADC Characteristic

2-101

Different Improvement Methods

The statistical results of this simple kind of correction are:
Full range

Ranges A and B only

Mean Value:

0.20 Steps

0.29 Steps

Range:

13.5 Steps

9.80 Steps

Standard. Deviation:

2.56 Steps

2.27 Steps

Variance:

6.53 Steps

5.15 Steps

Figure 13 shows the resulting graph:
Device 1

8
6
4

iS

2

!Il.

g

0

w
()

~

·2
-4
·6
·8
ADC Step. [0 to 16383)

Figure 13. Correction With the Cen~ers of the Four Ranges
Advantages:

Only one addition is necessary for the correction
Fast due to no multiplication
Only four bytes are needed .for the storage of the correction
values

Disadvantages: The range, standard deviation and variance are only slightly
improved
Monotonicity is not preserved: gaps appear at the range
borders.
The software part after each ADC measurement is the same one as shown for
the correction with the mean values of the four ranges.
EXAMPLE: The center point of range C (10240 steps) of the ADC is measured
and the result is used for the correction of this ADC range. The other three ranges
are treated the same way. The measured errors of the centers of the four ADC
ranges are shown below (for device 1):

2-102

ADC Step

2048

6144

Error [Steps]

-6

-13

SLAA047

10240

14336

0

Different Improvement Methods

Correction: ec =

- (-5) =

5
Valid for range C

Corrected ADC sample: Nioo" .. Ni + 5
Format: ±7.0

I

5120 =5 =05h

7
0

I6

0
i

D f

0

i

6 '

1 '

6 ' ,,.

3.2.4 Correction With Multiple Sections
The ADC is measured at (p+ 1) equally spaced points of the full range of the ADC.
This leads to p sections. The resulting errors (ek) are used to calculate the mean
value for each section and the result (ekm) is stored. To each ADC sample Ni the
appropriate negated error (ekm) is added. This method can be enhanced up to
the measurement of all ADC pOints. The correction formula is:
Nicorr

Where:
ekm
k

p
ek
ek+1

= Ni + ekm

ekm

= _ ek + ~ + ek

= Mean value of the ADC errors at the borders of ADC section ek [Steps}

=Index for ADC sections (length 214/p), ranging from 0 to p
=Number of sections (1:S p < 214)

= ADC error at the ADC step Ni .. k x 214/p
ADC error at the ADC step Ni = (k +1) x 214/p

=

[Steps]
[Steps]

The principle is shown in Figure 14. The full ADC range is divided into eight
sections {p =8}. The nine measured ADC samples are indicated with circles.
Dev!ce1

I
ADCSleP8

Figure 14. Principle of the Additive Correction With Multiple Sections (8 sections)

For p =8 {section length is 2048 steps} the statistical results are:
Full range
Ranges A and B only
Mean Value:
-0.14 Steps
0.22 Steps
Range:
8.40 Steps
6.30 Steps
Standard Deviation:
1.47 Steps
1.37 Steps
Variance:
2.16 Steps
1.89 Steps
Figure 15 shows the resutting graph for an additive correction with 8 sections
(p .. 8) over the full ADC range:
Additive Improvement of the MSP430 14-Bit ADC Characteristic

2-103

·Different Improvement Methods
Device 1 Corrected with Eight Sections over \he Full ADC Range

5~----------------------------~-----------------------,

ADC Steps [0 to 163831

Figure 15. Additive Correction With 8 Sections Over the Full ADC Range

For p =16 (section length is 1024 steps) the statistical results are:
Full range
Ranges A and 8 only
Mean Value:
-0.29 Steps
0.05 Steps
Range:
6.40 Steps
4.85 Steps
Standard Deviation:
1.04 Steps
1.01 Steps
Variance:
1.08 Steps
1.02 Steps
Figure 16 shows the resulting graph for an additive correction with 16 sections
(p =16) over the full ADC range:
Device 1 Corrected with Sixteen Section. Over the Full ADC Range

3

2

'[

I.

0

~

·1

8

·2

w

0(

·3
·4
-6

ADC Stepe [0 to 183831

Figure 16. Additive Correction With 16 Sections Over the Full ADC Range

2-104

SLAA047

Different Improvement Methods

For p ~ 32 (section length is 512 steps) the statistical results are:
Full range
Ranges A and 8 only
Mean Value:
-0.14 Steps
-0.05 Steps
Range:
5.20 Steps
3.65 Steps
Standard Deviation:
0.77 Steps
0.65 Steps
Variance:
0.59 Steps
0.42 Steps
Figure 17 shows the resulting graph for an additive correction with 32 sections
(p ~ 32) over the full ADC range:
Device 1 Corrected with 32 Sections Over the ·Full ADC Range

3r-----------------------------------------------------~

·4~

____________________________________________________

~

ADC Sleps [0 10 18383]

Figure 17. Additive Correction With 32 Sections Over the Full ADC Range
For p ~ 64 (section length is 256 steps) the statistical
-0.08 Steps
Mean Value:
Range:
4.60 Steps
Standard Deviation:
0.64 Steps
Variance:
0.41 Steps

results are:
0.02 Steps
3.10 Steps
0.53 Steps
0.28 Steps

Figure 18 shows the resulting graph for an additive correction with 64 sections
(p ~ 64) over the full ADC range. Note the scaling of Figure 18: only ±3 steps I

Additive Improvement of the MSP430 14-8it ADC Characteristic

2-105

Different Improvement Methods
Device 1 Corrected with 64 SectIons Over ths ADC Range

2.5
2
1.6
1

I
~
~

0.5
0
-0.5
-1
-1.6

-2
-2.5

-3
ADC Slaps [0 to 18383)

Figure 18_ Additive Correction With 64 Sections Over the Full ADC Range
Advantages:

Very good improvement with large section counts p
Fast due to no multiplication
The section count p Is adaptable to specific applications.
Disadvantages: Relative large RAM storage is needed for a large section count p
Gaps appear at the section borders: they get smaller with
increasing p
The results for the additive correction with multiple sections are summarized
below for section counts p ranging from 8 to 64. For comparison purposes, the
results for p =4 ( the center of ranges method is used) are given as well.
Mean Value:
Range:
Standard Deviation:
Variance:

p =4
+0.2
13.5
2.56
6.53

P =8
-0.14
8.40
1.47
2.16

P = 16
-0.29
6.40
1.04
1.08

P =32
-0.14
5.20
0.77
0.59

P =64
-0.08 Steps
4.60 Steps
0.64 Steps
0.41 Steps

The improvement of the statistical results with increasing section count p can be
clearly seen. Figure 19 illustrates this.
.

2-106

SLAA047

/,.

.

.-'';'''':';

Different Improvement Methods

p=8

p=16

p=32

Section Counl

p=64

Mean

Value xl 0

Figure 19. Improvement of the ADC Results With IncreaSing Section Count p

The software part after each ADC measurement follows. The addressing of the
correction byte can be adapted easily also to 4, 8, 16, and 32 sections.
Additive correction for 64 sections over the full ADC range.
The 64 signed correction values are located in the RAM
bytes starting at label TAB. 11 cycles
MOV

&ADAT,R5

MOV

R5,R6

Copy Ni for correction

SWPB

R6

MSBs of result to low byte

6.0

MOV.B

R6,R6

OOh ... 3Fh to R6 (0 .. 63)

6.0

MOV.B TAB(R6),R6

Corr. eim from table TAB

±4.0

SXT
ADD

Extend sign of correction

±4.0

Nlcorr = Ni + eim

14.0

R6
R6,R5

ADC result Ni to R5 (0 ... 3FFFh)
14 .0

Proceed with corrected Nicorr
The 64 RAM bytes starting at label TAB contain the corrections
eim for the 64 sections: each one for 256 ADC pOints.
The bytes are loaded during initialization Signed 8-bit numbers
.bss

TAB,64

; 0 .. 255 .. 511 .... 16127 .. 16383 ±4. 0

EXAMPLE: The ADC is measured at nine points (8 sections) like shown in
Figure 14. The measured errors for device 1 are shown below. The correction
coefficient ekm of the 2nd section (2048 to 4095 ADC steps, upper half of range
A) is calculated.
ADCStap

6144

8192

10240

12288

14338

18330

Error [Staps]

-13

-10

-5

0

o

-3

Additive Improvement of the MSP430 14-8it ADC Characteristic

2-107

Different Improvement Me/hods

.
Correction:

=-

ekm

ek+12+ ek

= _ - 1~ -

8

= + 1.0.5

Corrected ADC sample: Nico" =Ni + 10.5

Valid for the 2nd section

Format: ±7.0

10.5/20 = 10.5 .. OBh

I

10.5/2-1", 21", 15h

'0,6'6' "0"'6",

7
0

I0i 0 ' 0

0
i

1

i

0

i

1 '

7

±6.1

1111
0

3.2.5 Summary of the Additive Corrections
Figure 20 gives an overview of all of the described additive correction methods.
The results are given for different section counts p:
• N.C.: the noncorrected device 1
• P =1: correction with the mean value of the full ADC range
• p =2: correction with the mean values of ranges AlB and C/D
• P =4: correction with the center values of the four Ranges
• p =8...64: correction with 8 to 64 (multiple) sections over the full ADC range
As can be seen, the improvement increases significantly from the noncorrected
device 1 to the additive correction with 64 sections.
-

25
20

16
10
5

-5

·10
N.C.

p=1

p=2

p=4
p=8
Section Count

p=16

p=32

p=84

Mean
Value

Figure 20. Overview of the Additive Correction Methods

3.3 Additional Information
The Linear Improvement of the MSP430 14-8it ADC Characteristk;f,3] shows
linear methods for the correction of the 14-bit analog-to-digital converter of the
MSP430. Different correction methods are explained: some with guaranteed
monotonicity and some using linear regression. The methods discussed differ in
RAM and ROM allocation, calculation speed, reachable Improvement, and
complexity.
2-108

SLAA047

References

4 References
1. Architecture and Function of the MSP430 14-Bit ADC Application Report,
1999, Literature #SLAA045

2. Application Basics for the MSP430 14-Bit ADC Application Report, 1999,
Literature #SLAA046

3. Linear Improvement of the MSP430 14-Bit ADC Characteristic Application
Report, 1999, Literature #SLAA048
4. Nonlinear Improvement of the MSP430 14-Bit ADC Characteristic
Application Report, 1999, Literature #SLAA050
5. MSP430 Application Report, 1998, Literature #SLAAE1 OC
6. Data Sheet MSP430C325, MSP430P323, 1997, Literature #SLASE06
7. MSP430 Family Architecture Guide and Module Library, 1996, Literature
#SLAUE10B

Additive Improvement of the MSP430 14-8;t ADC Characteristic

2-109

2-110

SLAA047

Definitions Used Wtlh the Application Examples

Appendix A

Definitions Used With the Application Examples

; HARDWARE DEFINITIONS
ADAT
ACTL

.equ
.equ

011ah
0114h

ADC data register (12 or 14-bits)
ADC control register: control bits

Addillvelmprovement of the MSP430 14-8it ADC Characteristic

2-111

2-112

SLAA047

Linear Improvement of the MSP430
14-8it ADC Characteristic

~1ExAs

INSTRUMENTS
2-113

IMPORTANT NOTICE
Texas Instruments and its subsidiaries (TI) reserve the rightto make changes to their products orlo discontinue
any product or service without notice, and advise customers to obtain the latest version of relevant information
to verify, before placing orders, that information being relied on is current and complete. All products are sold
subject to the terms and conditions of sale supplied at the time of orde.r acknowledgement, including those
pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semiconductor products to the specifications applicable at the time of sale in
accordance with Tl's standard warranty. Testing and other quality control techniques are utilized to the extent
TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily
performed, except those mandated by government requirements.
CERTAIN APPLICATIONS USING SEMICONDUCTOR PRODUCTS MAY INVOLVE POTENTIAL RISKS OF
DEATH, PERSONAL INJURY, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE ("CRITICAL
APPLICATIONS"). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, AUTHORIZED, OR
WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT DEVICES OR SYSTEMS OR OTHER
CRITICAL APPLICATIONS. INCLUSION OFTI PRODUCTS IN SUCH APPLICATIONS IS UNDERSTOOD TO
BE FULLY AT THE CUSTOMER'S RISK.
In order to minimize risks associated wHh the customer's applications, adequate deSign and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assislance or customer product design. TI does not warrant or represent
that any license, either express or implied, is granted under any patent right. copyright. mask work right. or other
intellectual property right of TI covering or relating to any combination, machine, or process in which such
semiconductor products or services might be or are used. Tl's publication of information regarding any third
party's products or services does not constitute Tl's approval, warranty or endorsement thereof.

Copyright © 2000, Texas Instruments Incorporated

Contents
Introduction ............................................................................... 2-117
1.1
1.2

Correction With Linear Equations ; ...................................................... 2-118
Coefficients Estimation ................................................................ 2-120
1.2.1 Linear Equations With Border Fit ................................................ 2-120
1.2.2 Linear Equations With Linear Regression ........................................ 2-130

2 Addltlonallnformatlon ..................................................................... 2-138
3

References . ............................................................................... 2-139

Appendix A

Definitions Used With the Application Examples ................................... 2-141

List of Figures
The Hardware of the 14-Bit Analog-ta-Digital Converter ........................................... 2-118
2 Principle of the Correction With Border Fit (single linear equation per range) ......................... 2-121
3 Error Correction With Border Fit (single linear equation) ........................................... 2-122
4 Principle of the Correction With Border Fit (two linear equations per range) .......................... 2-125
5 Error Correction With Border Fit (two linear equations per range) ................................... 2-126
6 Principle of the Correction With Border Fit (four linear equations per range) .......................... 2-127
7 Error Correction With Border Fit (four linear equations per range) .................................. 2-128
8 Principle of the Linear Regression Method (single linear equation per range) ........................ 2-131
9 Error Correction With linear Regression (single linear equation per range) .......................... 2-132
10 Device 2 Showing the Typical Gaps at the Range Borders ........................................ 2-132
11 Principle of the Linear RegreSSion Method (two linear equations per range) ......................... 2-136
12 Error Correction With Linear RegreSSion (two linear equations per range) .......................... 2-136

List of Tables
Worst Case Coefficients With 8-Bit Arithmetic .................................................... 2-120

Linear Improvement of the MSP430 14-Bit ADC Characteristic

2-115

2-116

SLAA048

Linear Improvement of the MSP430 14-Bit ADC Characteristic
Lutz BierI
ABSTRACT
This application report shows different linear methods to improve the accuracy of the
14-bit analog-to-dlgital converter (ADe) of the MSP430 family. Different correction
methods are explained: some with monotonicity and some using linear regression. The
methods used differ in RAM and ROM allocation, calculation speed, reachable
improvement, and complexity. For all correction methods, proven, optimized, software
examples are given with 8-bit and 16-bit arithmetic. The References section at the end
of the report lists related application reports in the MSP430 14-bit ADC series.

1 Introduction
The application report Architecture and Function of the MSP430 14-8it ADC(1)
gives a detailed overview to the architecture and function of the 14-bit
analog-to-digital converter (ADC) of the MSP430 family. The principle ofthe ADC
is explained and software examples are given. Also included are the explanation
of the function of all hardware registers contained in the ADC.
The application report Application Basics for the MSP430 14-8it ADC(2) shows
several applications of the 14-bit ADC of the MSP430 family. Proven software
examples and basic circuitry are shown and explained.
The application report Additive Improvement of the MSP430 14-8it ADC
Characteristic[3) explains the external hardware that is needed for the
measurement of the characteristic of the MSP430's analog-to-digital converter.
This report also demonstrates correction methods that use only addition. This
allows the application of these methods in real time systems, were execution time
can be critical.
Figure 1 shows the block diagram of the 14-bit analog-to-digital converter of the
MSP430 family.

2-117

Introduction
AY..

I : > -.....- - .
SVccSwlch

~ ____ ~ ACTL1 (Vref)

SYCC,..O..----I~ ACTt..12(Pd)

RextL-<:;;L=:;;-:::1H.

128

c ~_...;1;;28"---I
128

A~_-,1:;28"---I
AGNO

<=..q::j::+=+:+---:::;:

ACTt..9.10(~.'

JAY..,

ACTL.11(Auto)

=:;::::j==:1_..JLur-f---l-J

~:A5'~~ ~~
I ACTACTLLO(SC::C'~_~~~
Input
A6
A7

YUX

ACTL2A (Ax)
ACTL5 (None)

A 7 - - - - AD

SAR.1S

SAR.O

1&.a11 Memory Olla B.... MOB

Figure 1. The Hardware of the 14-81t Analog·to-Dlgltal Converter

The methods for the improvement of the ADC described in the next sections are:
• Linear equations with border fit: single linear equation per range
• Linear equations with border fit: multiple linear equations per range
• Linear equations with linear regression: single linear equation per range
• Linear equations with linear regression: multiple linear equations per range
Quadratic and cubic corrections are explained in the application report Nonlinear
Improvement of the MSP430 14-8it ADC Characteristic[4j.

1.1

Correction With Linear Equations
A good error correction with low RAM requirements is possible if not only the
offset error-like with the additive methods-but also the slope error of the ADC
characteristic can be corrected. However, this requires the use of a multiplication.
The multiplication subroutine used here is is optimized for real time
environments: it terminates immediately after the unsigned operand-the ADC
result-becomes zero due to the right shift during the multiplication. The
subroutine is appended to the first software example (see section 1.2.1.1). The
full code with explanations and timing is contained in Nonlinear Improvement of
the MSP430 14-8it ADC Characteristic, SLAA050[4j.
The generic correction formula for linear correction, which is valid for floating
point or 16-bit integer arithmetic, is:

2-118

SLAA048

Introduction

Nicorr = Ni + (Ni x a1 + aO)
The optimized 16-bit multiplication subroutine for the above formula-including
the calculation software-is included in section 1.2.2.1, Linear Regression:
Single Linear Equation per Range. The full code is described in Section 5.1,
Integer Calculation Subroutines.
The floating point example given for the cubic correction-see Nonlinear
Improvement of the MSP430 14-Bit ADC Characteristic[4]-may be adapted
easily to the calculation of linear equations: the unused terms-the quadratic and
cubic terms-are simply left out.
The formulas to calculate the correction coefficients a1 (slope) and aO (offset) out
of the two known errors e2 and e1 of the ADC steps N2 and N1 are:
a1=_82-81

/II2-M

The advantages of the negated correction coefficients a1 and aO are:
• Shorter and faster software: the INV (invert) and INC (increment) instructions
for th3 negation of the corrections are not necessary
• The ADAT register (ADC result register) is a read-only register and can be
used for additions directly. If the correction needs to be subtracted from the
ADAT register, then an intermediate step is necessary.
All principle figures of this report-as in Additive Improvement of the MSP430
14-Bit ADC Characteristic[3)-have the same structure:
• The black straight line indicates the negated correction value (thiS is to show
the precision of the correction).
• The scribbled black line indicates the noncorrected ADC characteristic.
• The white line shows the corrected ADC characteristic.
• The small circles indicate the measured ADC points (not all measured
samples are shown).
An example using the 16-bit arithmetic is given in section 1.2.2.1, Linear
Regression: Single Equation per Range.
All other given equations in the following sectionS assume the use of the 8-bit
arithmetic as described in Nonlinear Improvement of the MSP430 14-Bit ADC
Characterisitc,SLAA050[4]. Therefore the correction formulas are adapted to the
limited, but fast 8-bit arithmetic. This reduced arithmetic makes relative
addresses for the ADC steps necessary: the full ADC range is divided into
sections and the ADC value is adapted to 128 subdivisions for the full section. The
equations for the 8-bit arithmetic are given and explained with each method.

Unear Improvement of the MSP430 14-811 ADC Cherecleristic

2-119

Introduction

1.2 Coefficients Estimation
With the maximum possible ADC error (±10 steps contained in a band of ±20
steps) the maximum values for the coefficients a1 and aD are:
Table 1. Worst Case Coefficients With 8-Bit Arithmetic

The above maximum coefficients occur for a single equation per range when the
ADC error changes 20 steps within an ADC range (4096 steps) e.g. from +10 to
-10 steps or vice versa. For two and four equations per range, the maximum
change is appropriately smaller (±10 resp. ±5 steps). This leads to smaller
coefficients a1.
.
• The 8-bit arithmetic operates with signed 8-bit coefficients and an ADC result
that is adapted to a value ranging from 0 to 127.
• The 16-bit arithmetic uses the full ADC result (0 to 16383) and signed 16-bit
numbers for the calculations.
• The floating point calculation also uses the full ADC result (0 to 16383) and
a 32-bit number format for the calculations.
NOTE: Within the software examples, at the right margin olthe source
code the format of the numbers is noted. The meaning of the different
notations is:
0.7
No integer bits, 7 fraction bits. Unsigned number
±4.3 Four integer bits, 3 fraction bits. Signed number
8.0
Eight integer bits, no fraction bits. Unsigned integer number
±7.0 Seven integer bits maximum, no fraction bits. Signed integer
number

The statistical results are given separately for the full ADC range (ranges A to D)
and for the ranges A and B only. The reason for the second case is the internal
current source that is used by many applications: with its use the ADC ranges are
restricted to the ranges A, B, and the lower part of range C.

1.2.1

1.2.1.1

Linear Equations With Border Fit
If monotonicity of the corrected ADC characteristic is a requirement, then the
correction methods using the border fit are the right choice. They guarantee, that
the four ranges continue smoothly at its borders. This feature is important if the
differences of two ADC results are used for calculations.
Single Linear Equation per Range

The ADC is measured at the five borders of the four ADC ranges (Ni = 50, 4096,
8192, 12288, 16330). These five results are used for the calculation of the offsets
and the slopes of all four ADC ranges.
2-120

SLAA048

Introduction

NOTE: The ADC points 0 and 16383 (3FFFh) including small
bands cannot be measured. This is the reason for the use of steps
50 and 16330 in the above explanation.
The formula for the offset aO and the slope a1 for each one of the four ranges is:
Nicorr = Ni +
81=

[(4~6 -n) x

eu-el
-128

128 x

ao =

81

+

ao]

- el

Where:
Nicorr = Corrected ADC sample
Ni
=Measured ADC sample (noncorrected)
n
=Range number (0 ...3 for ranges A... D)
al
=Slope of the correction
ao
=Offset of the correction
eu
=Error of the ADC at the upper border of the range
el
= Error of the ADC at the lower border of the range
The term(46::6 -

n) x 128 of the equation

[Steps}
[Steps)
[Steps]
[Steps]
[Steps]

above is the adaptation of a

complete section-here a full range-to 128 subdivisions. The calculation of the
term is made by simple shifts and logical AND instructions and not a division and
a multiplication. See the initialization part of the software example.
The principle of the correction with a linear equation for each range (border fit)
is shown in Figure 2. Border fit means, that the borders of the four ranges A to
D fit together without gaps from one range to the other one: the border value is
used for both ranges.
The improvement methods and their results for this report are demonstrated with
the characteristic of device 1 and device 2 due to their worst characteristic
compared to the other three devices shown in Architecture and Function of the
MSP430 14-Bit ADC.
Device 1

'iii'
a.

5

Ii

·5

~
oli
0
Q
cC

0

·10

·15
ADCSteps

Figure 2. Principle of the Correction With Border Fit (single linear equation per range)

Linear Improvement of the MSP430 14·8it ADC Characteristic

2-121

Introduction

The statistical results for this simple correction method are:
Full range
Ranges A and 8 only
Mean Value:
-0.32 Steps
-0.33 Steps
Range:
5.6 Steps
5.1 Steps
Standard Deviation:
0.94 Steps
0.99 Steps
Variance:
0.88 Steps
0.98 Steps
Figure 3 shows the results of this method in a graph.
Device 1 Corrected With a Single Linear Equation per Range (Border FII)

i

II!.

g

w

g

·1

c(

·4L-----________________________

~

__________________________

ADC Steps [0 10 18383]

Figure 3. Error Correction With Border Fit (single linear equation)
Advantages:
Only five measurements are necessary
No gaps; the monotonicity of the·ADC characteristic remains
Low memory needs: 8 bytes only (four slopes and four offsets)
Good improvement of the ADC characteristic despite low
expense
Disadvantages: Multiplication is necessary
The software part after each ADC measurement is as follows. For lower accuracy
needs the algorithm may be simplified by the use of less accurate slopes and
offsets (fewer fraction bits).
A more detailed description for the 8-bit multiplication is given in Nonlinear
Improvement of the MSP430 14-8it ADC Characteristic.[4] The numbers at the
right margin indicate the used number format (integer.fraction)
Error correction with a Single equation per range

a-bit arithmetic. Cycles needed:
Subdivision - 0:

51 cycles

Subdivision > 3Fh: 100 cycles

int. frct

2-122

MOV

&ADAT, Rs

ADC result Ni to Rs

14.0

MOV

Rs,R6

Address info for correction

14.0

SLAA048

~

Introduction
AND

#OFFFh,RS

Delete range bits

RLA

RS

Calculate Bubdivision

13.0

RLA
RLA

RS

Prepare (Ni/4096-n)x128

14.0

R5

7 bit ADC info to high byte

15.0

SWPB

R5

ADC info to low byte 0 ... 7Fh

7.0

MOV.B R5,IROP1

To MPY operand register

SWPB

R6

MSBs to low byte 0 ... 3Fh

7.0
6.0

RRA.B R6

Calculate coeff. address

12.0

RRA.B R6

5.0
4.0

RRA.B R6
#l,R6
BIC
MOV.B TAB1(R6),IROP2L
CALL
#MPYS8

0 ... 06h: address of slope al
Slope a1

3.0

(Ni/4096-n)x 128 x a1

±5.9

Slope part to aD format

2n (Range) in R6

0 ... 07h

3.0
0.9

RLA

lRACL

SWPB

lRACL

SXT

lRACL

To 16-bit format

±5.2

MOV.B TABO(R6),RS
SXT
R5

Offset aD
To 16-bit format

±S.2

±5.10
±5.2

Ni + correction

ADD

R5,IRACL

RRA

lRACL

RRA

IRACL

Carry is used for rounding

±5.0

ADDC

&ADAT, lRACL

Corrected result Nicorr

14 .0

±S.2
±5.1

Use Nicorr in lRACL

The 8 RAM bytes starting at label TAB1 contain the correction
info a1 and aD. The bytes are loaded during the calibration
.has

TABl,l

Range A a1: lin. coefficient

.bas

TABO,1

aO: constant coefficient

.bss

TABx,6

±0.9

±5.2
Ranges B, C, 0: aI, aD. (like above)

Run time optimized a-bit Multiplication Subroutines

IROP1

. EQO

R14

Onsigned ADC result (7Fh max.)

IROP2L . EQO

R13

Signed factor (80h ... 7Fh)

lRACL

R12

Signed result word

. EQO

Signed multiply subroutine: IROPl x IROP2L -> lRACL
MPYS8 CLRlRACL
TST.B IROP2L
JGE
MAC08

o

-> 16 bit RESULT

Sign of factor (slope al)
Positive sign: proceed

SWPB

IROPI

Negative

SOB

IROP1,IRACL

Correct result

SWPB

IROPI

Unear Improvement of the MSP430 14-Bit ADC Characteristic

2-123

Introduction

MACUS BIT.B #1, IROP1
JZ
L$01
IROP2L,IRACL
ADD
L$Ol

RLA
RRC.B

Test actual bit (LSB)
If 0: do nothing
If 1: add multiplier to result
Double multiplier IROP2
Next bit of IROP1 to LSB
If IROP1 - 0: finished

IROP2L
IROPI
MACU8

JNZ

RET

EXAMPLE: The ADC is measured at the five borders of the ADC ranges. The
measured errors-device 1 is used-are shown below. The correction
coefficients for the range C are calculated. The correction coefficients for the
other three ranges may be calculated the same way, using the appropriate border
errors.
50

ADCStep
Error [Steps]

4096
-13

8192

12288

16330
-3

Error coefficients for the range C:

81 = _eu- el = _ 0 -

(- 10)
128

ao = -91 = - (-10) =

+ 10

128

Correction:

= _.1Q.. =
128

_ 0078125

.

Ni - n) x 128 x a1 + aD = (Ni
( 4096
4096 - 2 ) x 128 x (- 0.078125) + 10.0

The correction for the ADC step 11 OOO-Iocated in range C-is calculated:
(

~~9~ -

2) x 128 x (- 0.078125)

Corrected ADC sample:
Format: a1: ±0.9
aD: ±5.2

Nicorr

+ 10.0

=

= Ni + 3.1

-0.078125/2-41 = -40 = D8h
+10.012-2

+ 3.1

=+40 =28h

Valid for the ADC step 11000
7

C!]"'T" \\ '
t'

0

6 '

1 '

1 ' 6 ' 6' 0•

1 '

0 '

1 ,

0."'

7

10 \ 0 '

The number of fractional bits for a1 is derived from the following consideration:
a1 is maximally to.15625 (see Table 1). This value must be possible with the
largest number that can be expressed with a signed 8-bit number (7Fh):

7Fh x 2- 9 > 0.15625 =
0.24805 > 0.15625 =

1~~ > 7Fh X
122~

2- 10

>. 0.124025

This leads to a valency of 2-4l for the LSB of the 8-bit number. The detailed
explanation for the calculation of the correction coefficients is given in Nonlinear

Improvement of the MSP430 14-Bit ADC Characteristic,[4] Calculation of the
B-Bit Numbers.
2-124

SLAA048

I

04 0 '

0

t'

."

Introduction

1.2.1.2 Multiple Linear Equations per Range
The ADC is measured at (p+ 1) equally distributed points over the full ADC range
(p =2 m ~ 8). These (p+ 1) results are used for the calculation of the offset and the
slope of p linear equations valid for the p sections. The formula for the offset aD
and the slope a1 for each of the p linear equations is (8-bit arithmetic):

N~~4 P - m) x 128 x 81 + ao ]

Nico" = Ni + [(
81

(eu-e~

=-128

Where:
Nicorr
Ni
n1
P
a1
ao
eu
el

80= -el

= Corrected ADC sample
[Steps}
= Measured ADC sample (noncorrected)
[Steps]
= Value of the MSBs of Ni (0 to p-1)
= Number of sections over the full ADC range (8 for Figure 4)
= Slope of the correction
= Offset of the correction
[Steps]
= Error of the ADC at the upper border of the section [Steps]
= Error of the ADC at the lower border of the section [Steps]

n 1 ranges from 0 to (p-1) and has a length of IOr12 P bits. This means for n1 :
• Two linear equations per range (Figure 4): value is 0... 7, length is IOr12 8 = 3
bits;
• Four linear equations per range (Figure 6): value is 0... 15, length is
IOr12 16 = 4 bits;
The term (

N~ ~ P -

m)

x 128 in the equation above is the adaptation of a

complete section-here a half range-to 128 subdivisions. The calculation is
made by simple shifts and logical AND instructions

1.2.1.3 Two Linear Equations per Range
The principle for two linear equations per range (p=B) is shown in Figure 4.
Device 1 Corrected With Eight Linear Equations (Border Fit)

"iii"

5

~
w

oS

i

(.)

c

0

·10

C

·15
ADCSteps

Figure 4. Principle of the Correction With Border Fit (two linear equations per range)

Unear Improvement of the MSP430 14-8it ADC Characteristic

2-125

Introduction

The statistical results for two linear equations per range are:
Full range
Ranges A and B only
-0.02 Steps
Mean Value:
-0.29 Steps
Range:
6.49 Steps
5.3 Steps
Standard Deviation:
0.97 Steps
1.06 Steps
0.94 Steps
1.12 Steps
Variance:
Figure 5 shows the result in a graph.
Device 1 Corrected With Eight Un..r Equattons (Border FH)

ADC Steps [0 to 16383]

Figure 5. Error Correction With Border Fit (two linear ,quatlons per range)
Advantages:

Only few measurements are necessary (p+ 1). Nine for the
example above
No gaps; the monotonicity of the ADC characteristic is
preserved
Belter correction than with a single linear equation per range
Low memory needs: 2 x p bytes (16 for the example)
Disadvantages: Multiplication is necessary
The software is the same as shown in section 1.2.2.2, Multiple Linear Equations

. per Range.
EXAMPLE: The ADC is corrected with eight sections, each one with a length of
2048 steps (p =8). The measured errors-(device 1 of Architecture and Function
of the MSP430 14-BitADC, SLAA045 is used)-are shown below. The correction
coefficients for the lower section of range C-ADC steps 8192 to 10240 (n1 =
4)-are calculated. The correction coeffiCients for the other seven sections are
calculated the same way.
ADCStep

50

nl

o
-a

Error [Steps]

2-126

SLAA048

2048

4096

6144

123

-a

-13

-13

8192

10240

12288

14338

16330

677

o

0

-3

Introduction

Error coefficients for the lower section of range C:
a1 = -

8

- 81

128 = -

= - (-

aD = - 81

Correction:

(N~~/ -n1) x

-

10)

5 - (- 10)
128

=

-

5
128 = - 0.0390625

= + 10

128 x 81

+ aD

= (

N~~4 8 -

4) x 128 x (- 0.03906)

+ 10.0

Lower section of range C
The correction forthe ADC step 9000-located in the lower section of range C-is
calculated (p = 8, n1 = 4):
(

90~~4x

8 _ 4) x 128 x (- 0.0390625) + 10.0 = 50.5 x (- 0.0390625) + 10.0 = + 8.027

Corrected ADC sample:
Format: a1: ±0.10

Nicorr = Ni + 8.03

-0.039625/2-10 = -40 = D8h

Valid for the ADC step 9000 (range C)

[17"

1

I

7
1

0

I1

'

0i

1 '

1 '

0 '

0 I 0

20

ao: ±5.2

+10.0/2-2 = 40 = 28h

'01

I

2-10

7

0
0

'1'6'1'°4°'6,
..

2-2

1.2.1.4 Four Linear Equations per Range

The principle for four linear equations per range (p=16) is shown in Figure 6.
Device 1

'i'
a.

I.
~
8c

4
2
0
·2
·4
·6
-8
·10
·12
·14
·16
ADCStepa

Figure 6. Principle of the Correction With Border Fit (four linear equations per range)

The statistical results for four linear equations per range are:
Full range
Ranges A and B only
Mean Value:
-0.22 Steps
0.07 Steps
Range:
5.36 Steps
4.07 Steps
Standard Deviation:
0.83 Steps
0.65 Steps
Variance:
0.69 Steps
0.42 Steps
Unear Improvement of the MSP430 14-Bit ADC Characteristic

2-127

Introduction

Figure 7 shows the result In a graph.
Device 1 Corrected WIth SlX1een Equations (Border Fit)

3~----------------------------------------------------~

·4L-----------------------------------------------------~
ADC S1eps [0 to 18383)

Figure 7. Error CorrectIon WIth Border FIt (four linear equations per range)
Only a few measurements are necessary (p+ 1). Seventeen for
the example above
No gaps; the monotonicity of the ADC characteristic is
preserved
Better correction than with one or two linear equations per
range
Low memory requirements if p is small: 2 x p bytes (32 for above
example)
Disadvantages: Multiplication is necessary

Advantages:

For 16 linear equations for the full ADC range, the software for each ADC
measurement is as follows:
Error correction with four linear equations per range
(16 for the full ADC range) a-bit arithmetic. Cycles needed:
Subdivision - 0:
49 cycles
Subdivision> 3Fh: 101 cycles
MOV
MOV
AND
RLA
RLA
RLA

&ADAT,RS
R5,R6
#03FFh,R5
RS
RS
R5
RLA
R5
RLA
R5
SWPB R5
MOV.B R5,IROPl

2-128

SLAA048

ADC result Ni to R5
Address info for correction
Delete 4 MSBs (nl bits)
Calculate subdivrsion
Prepare
«Ni x p/2 A 14)-n1)x 128
7 bit ADC info to high byte
ADC info to low byte 0 ... 7Fh
To MPY operand register

4.0
10.0
11.0
12.0
13.0
14.0
15.0
7.0
7.0

Introduction
SWPB

R6

RRA.B R6

Calculate coeff. address

6.0

2 x n1 in R6

5.0

O... 01Fh

BIC

#l,R6

0 ... 01Eh: address of slope al

5.0

MOV.S

TAS1(R6),IROP2L

Slope a1

±0.11
±3.11

CALL

#MPYS8

«Ni x p/2A14)-n1)x 128 x a1

RRA

lRACL

MPY result to aO format

SWPS

lRACL

±3.10
±3.2

ADD.S TABO(R6),IRACL

±5.2

Offset aO

±5.2

SXT

IRACL

RRA

lRACL

RRA

lRACL

Carry is used for rounding

±5.0

ADDC

&ADAT,IRACL

Corrected result Nicorr

14.0

±5.1

Proceed with Nicorr in lRACL
The 32 RAM bytes starting at label TAS1 contain the corr.
coefficients a1 and aO. The bytes are loaded during the

initialization. 8-bit, signed numbers
.bss

TAB1,l

.bss

TABO,l

.bss

TABx, 30

Range A lowest quarter:

a1 ±0.11
aO ±5. 2

Ranges A (3), B, C, D: ai, aO.

EXAMPLE: The ADC is corrected with sixteen sections, each one with a length
of 1024 steps (p =16). The measured errors (device 1 of Architeture and Function
of the MSP430 14-Bit ADC, SLAA045 is used.) are shown below. The correction
coefficients for the lowest section of range C-ADC steps 8192 to 9216 (n1 =
8)-are calculated. The correction coefficients for the other seven sections are
calculated the same way.
ADCSIep
n1

8192

9216

10240
10

Error [Steps]

-5

Error coefficients for the lower section of range C:
a1

eu - el

= -128 = -

- 7 - (- 10)

128

=-

3
128

=-

0.0234375

ao = - el= - (- 10) = + 10
Correction: (

N~~/ _ n1) x

128 x ao + a1 = (

Nl2~416 -

8) x 128 x (- 0.0234375)

+ 10.0

Lower section of range C

Linear Improvement of the MSP430 14-8it ADC Characteristic

2-129

Introductfon

The correction for the ADC step 9000-located in the lower section of range C-is
calculated (p = 16. n1 = 8):
(

900~1~

16 - 8) x 128 x (- 0.0234375)

Nicorr = Ni + 7.63

Corrected ADC sample:
Format: a1: ±0.11

+ 10.0

-0.0234375/2-11

+ 10.0

=-48 -

['I'I!::::! I '

0

I 1 tot ,

~
7

I 0 lot

i

0

tot

1 i

6

iii

6,

0 i 0

I

24

With linear regression the linear equations that best fit the measured ADC
characteristic are used. This leads to good results within the ranges but may
produce gaps at the borders.
The linear regression formulas (Least Squares Method) for the correction
coefficients a1 (slope) and aO (offset) are given below. To simplify the real time
calculations, the negative values of the coefficients are used. The reasons for this
are the same ones as described in section 1.1.

1-1

I=k

a1

k,-1

/=k

"N xel.

-L...

= _ _____...:./=_1~_ _
( 'I,kN)

2

aO=-(i§-a1x1V)

;=k

~-LN2
;=1

The mean values of Nand e are defined as:
;=k

Lei

i§= 1=1

k
Where:
N
ei
a1
ao =
k

Measured ADC sample (noncorrected)
Error of the ADC sample i
Slope of the correction (negated)
Offset of the correction (negated)
Number of the measured samples
Sample index running from 1 to k

[Steps]
[Steps]
[Steps]

The value N represents different values depending on the calculation method:
• B-bit arithmetic: the subdivision of Ni within the appropriate section. The
range for N is 0... 127. See the explanation given in section 1.2.1.1
• Floating Point and 16-bit arithmetic: N equals the full 14-bit ADC value Ni
The examples used are simplified due to the amount of data involved.
2-130

SLAA048

0 i

0
~

0

1.2.2 Linear Equations With Linear Regression

L Nx L ei

+ 7.63

7

DOh

~

i=k

=

Valid for the ADC step 9000 (range C)

+10.0/2-2 =40 '" 28h

ao: ±5.2

= 101.0 x (- 0.0234375)

I

Introduction

1.2.2.1

Single Linear Equation per Range
The ADC is measured at k points inside each ofthe four ranges. Out ofthese (4xk)
results, four linear equations are calculated using the Least Squares Method(see
above formulas). The four slopes and offsets are stored in the RAM or in
EEPROM. The formula for the corrected value Nicorr is:

Nicorr = Ni +
Where:
n
al
ao
k

=
=
=
=

[(4~6 -

n) x 128 x

81

+

ao]

Range number (0 ...3) for ADC ranges A .•. D)
Slope calculated by the host or MSP430
Offset calculated by the host or MSP430
Number of samples for each linear equation (range)

The term (4~6 -

[Steps]

n) x 128 of the above equation is the adaptation

of a

complete section-here a full range-to 128 subdivisions. The calculation is
made by simple shifts and logical AND instructions. See the initialization part of
the example below.
The principle of this method Is shown in Figure 8, the eight measured samples
are drawn only in range A (k = 8):
DevIce 1

ADCSteps

Figure 8. Principle of the Linear Regression Method (single linear equation per range)
Mean Value:
Range:
Standard Deviation:
Variance:

Full range
0.03 Steps
5.09 Steps
0.94 Steps
0.88 Steps

Ranges A and B only
0.12 Steps
4.85 Steps
1.00 Steps
1.00 Steps

The statistical results for 8 and 16 measurements per range are shown below:
as it can be seen, 16 samples per range improve the final result only marginally.
8 Samples per range 16 Samples per Range
Mean Value:
0.03 Steps
0.07 Steps
Range:
5.09 Steps
5.04 Steps
Standard Deviation: . 0.94 Steps
0.92 Steps
Variance:
0.88 Steps
0.85 Steps

Linear Improvement of the MSP430 14-81/ ADC Characteristic

2-131

Introduction

Figure 9 shows the resuH of this method: eight samples per range are measured
(k=8). Note the small range of only ±3 steps.
Devlce 1. Corrected Wllh Four Linear Equations (Unaar Ragraaalon, EIght Samples par Range)

3

2

I

1

0

0

13

oC

·1
·2
·3
ADC S1apa [0 10 16383]

Figure 9. Error Correction With Linear Regression (single linear equation per range)
Advantages:
Good adaptation to the ADC characteristic
Disadvantages: One multiplication IS necessary
Small gaps at the borders of the four ranges
Calculation of the linear regression is necessary during the
calibration
Device 1 does not show gaps at the borders of the four ranges-which is purely
random-therefore another device that shows this disadvantage of the method
more clearly is included in Figure 10. Note the gaps between the ranges A and
B and the ranges Band C.
Davlce2

15

10

i!!l.
~

g

5

0

oC

-6

·10
ADC S1apa [0 10 16383]

Figure 10. Device 21 Showing the Typical Gaps at the Range Borders
1 This Is device 2 from Arohecture end Function of the MSP430 14-B1t ADC Appfication Report #SLAA045.

2-132

SLAA048

Introduction

The correction software for the 8-bit arithmetic is identical to the one shown in
section Single Linear Equation per Range (Border Fit), section 1.2.1.1.
Here an additional solution with 16-bit integer arithmetic is given.
Error correction with a single equation per range

16-bit arithmetic. Cycles needed:
AOAT value - OOOOh: 47 cycles
ADAT value

3FFFh: 178 cycles

MOV

&ADAT, IROP1

ADC result Ni to MPY reg.

14 .0

MOV

IROPl,R6

Calculation of coeff. address

14 .0

SWPB
R6
RRA.B R6

MSBs to low byte 0 .. . 3Fh

6.0

RRA.B R6

4n (Range) in R6

BIC

0 .. . 0Ch: address of slope a1

MOV

'3,R6
TABl(R6),IROP2L

CALL

#MPYS

Ni x al

RRA

IRACM
lRACM

Only HI result is used
To format 4.3 of offset aO

RRA
RRA

5.0
0 .. . 0Fh

Slope al

IRACM

4.0
4.0
0.22

±4.22

±4.5
±4.4
±4.3

ADD

TABO(R6),IRACM

Add Offset aO

±S.3

RRA

lRACM

Nicorr = Ni x a1 + aO

±S.2

RRA
RRA

lRACM
lRACM

Carry is used for rounding

±S.O

ADOC

&ADAT, lRACM

Nicorr in lRACM

14 .0

...

±S.1

Proceed with corr . result Nicorr

The 16 RAM bytes starting at label TAB1 contain the
correction info a1 and aO for all four ranges. The bytes
are loaded during the calibration

.bss

TAB1,2

Range A a1: lin. coefficient

±0.22

.bss

TABO, 2

aO: constant coefficient

±S.3

.bss

TABx, 12

Ranges B, C, D: al, aO.

Run time optimized 16-bit Multiplication Subroutines

. EQU

Rll

Unsigned ADC result (0 .. . 3FFFh)

IROP2L . EQU

IROP1

R12

Signed factor (8000h ... 7FFFh)

IROP2M . EQU

R13

IRACL
IRACM

R14
R1S

High word of signed factor (0)
Result word low
Result word high

. EQU
. EQU

Signed multiply subroutine: IROP1 x IROP2L -> lRACMIIRACL

Unear Improvement of the MSP430 14-81t ADC Characteristic

2-133

Introduction
MPYS

CLR

lRACL

CLR

lRACM

o ->
o ->

TST

IROP2L

Sign of factor al

result word low

result word high

JGE

MACU

Positive sign: proceed

SUB

IROP1,IRACM

correct result

MACU

CLR

IROP2M

Clear MSBs multiplier

L$002

BIT

#1, IROPI

Test actual bit (LSB)

JZ

L$Ol

I f 0: do nothing

ADD

IROP2L,IRACL

I f 1 : add multiplier to result

ADDC

IROP2M,IRACM

L$Ol

RLA

IROP2L

RLC

IROP2M

Double multiplier IROP2

RRC

IROPl

Next bit of IROPl to LSB

JNZ

L$002

If IROPl - 0: finished

RET

EXAMPLE: (8-bit arithmetic). The ADC is measured at five points of the ADC
range A (n ... 0). The measured errors-device 1 is used-are shown below. The
correction coefficients for the range A are calculated with the linear regression
method. The correction coefficients for the other three ranges may be calculated
the same way. The used numbers are shaded.
ADCStep

60

1024

2048

3072

4096

Subdivision

Error [Steps]

The correction coefficients for the range A (n=O), are calculated with the formulas
shown in section 1.2.2.

= + 0.06326
ao = + 4.9312

a1

Correction:

Negated result of linear coefficient
Negated result of constant coefficient

[(4~6-0)x128Xa1+ao] =(~x

0.06326+4.9312)

The correction for the ADC step 2000-Iocated in range A-is calculated:

~ x 0.06326 + 4.93 = 2~~0 x 0.06326 + 4.93 = + 8.88
Corrected ADC sample:
Format:

Nicorr = Ni + 8.9

Valid for the ADC step 2000
7

a1: ±D.9

+0.06326/2-& = +32.4 '" 20h

[!fa

aD: ±5.2

+4.93/2-2 = +19.7" 14h

I 6 I6 '

t'
7

2-134

SLAA048

'0 16

i 1

o
'6'6'6'6'6,
2"

Introduction

EXAMPLE: (16-bit arithmetic). The ADC is measured at five points of the ADC
range C. The measured errors-device 1 is used-are shown in the table below.
The correction coefficients for the range C are calculated with the linear
regression method. The correction coefficients for the other three ranges may be
calculated the same way. The used numbers are shaded.
ADC Step
Error [Steps]

8192

9216

10240

11254

12288

;wit~~;~;~ti~0~~m;0~,

+0.1

The correction coefficients forthe range C are calculated with the formulas shown
in section 1.2.2. The full 14-bit ADC result is used for the calculations due to the
available 16 bits of resolution.
a1 = -0.0026381701
ao = + 31.8695
Correction:

Ni x a1

Negated result of linear coefficient
Negated result of constant coefficient

+ ao = Ni x (-0.00263817) + 31.8695

The correction for the ADC step 12000-located in range C-'-is calculated:
Nix (-0.00263817)

+ 31.8695= 12000 x (-0.00263817) + 31.8695 = + 0.204

Corrected ADC sample: Nicorr = Ni + 0.2
Format:

Valid for the ADC step 12000

-0.0026381701/2-22 =-11065.3 '" D4C7h
15
8 7
I 1 I 1 I 6 ' 1 i 6 i 1 I 6j 6I 1 ,

a1: ±D.22

C~::!:::~::!:!:=1
~

1 ,

6' 6' 6' , ;

0
1 i

~

ao: ±5.3

1I
~

+31.86958564/2-3 = +254.96 '" OOFFh

15

8

10,6' 0 ' 0 '

0

,6'

0'

7

0 '1' l' 1

0

I

1

i

14' • l' 1 I

1.2.2.2 Multiple Linear Equations per Range

The ADC is measured at (p x k) points over the four ranges (p = 2m~ 8). Out of
these (p x k) results p linear equations are calculated using the Least Squares
Method. The calculated slopes and offsets are stored in the RAM or in EEPROM.
The formula for the correction is:

Nicorr = Ni + [(

N~~P - n1) x 128 x a1 + ao]

Where:
Nicorr =Corrected ADC sample
[Steps)
Ni
=Measured ADC sample (noncorrected)
[Steps)
p
=Number of sections for the full ADC range. p is a power of 2.
n1
= Value of the MSBS of Ni. n1 ranges from 0 to (p-1)
a1
=Slope of the correction
ao
= Offset of the correction
k
= Number of samples for each linear equation (section)
The value n1 is explained in section Multiple Linear Equations (Border Fit),
section 1.2.1.2.
Unear Improvement of the MSP430 14-8it ADC Characteristic

2-135

Introduction

The term (

N~ ~4 P - n1) x

128 in the above equation is the adaptation of a

complete section-here a half range-to 128 subdivisions. The calculation is'
made by simple shifts and logical AND instructions.
The principle of this method-with four samples within each one of the eight
sections (k .. 4, P =8)-is shown in Figure 11, the ADC samples are shown only
in range A:
Device 1

Ig
III

g

<

ADCSI8ps

Figure 11. Principle of the Linear Regression Method (two linear equations per range)
The statistical results for 16 points per range-eight samples for each one of the
eight linear equations (k = 8, P = 8)-are:
Full range
Ranges A and B only

Mean Value:
Range:
Standard Deviation:
Variance:

-0.03 Steps
4.84 Steps
0.78 Steps
0.61 Steps

+0.09 Steps
4.80 Steps
0.79 Steps
0.63 Steps

The result is shown in Figure 12. Note the error range of this figure: only ±3 ADC
steps.
Device 1 Corrected With Eight LInear Equations (L1neer Regression Ueed)

2.5
2
1.5

i
~

~
0

Q

<

0.5
0

-0.5
-1
-1.5
-2
-2.5

-3
ADC Steps [0 to 16383]

Figura 12. Error Correction With Linear Regression (two linear equations per range)
2-136

SLAA048

Introduotion

Advantages:

Very good adaptation to the ADC characteristic
Method can be adapted to specific needs with more equations
per range
Disadvantages: Multiplication is necessary
Small gaps at the borders of the four ranges
Calculation of linear regresSion is necessary during calibration
Many measurements are necessary during calibration (64 with
the above example)
The correction software for the a-bit arithmetic:
Error correction with two linear equations per range
(8 for the full ADC range) 8-bit arithmetic. Cycles needed:

subdivision

0:

Subdivision> 3Fh:

48 cycles
97 cycles

MOV

&ADAT, RS

ADC result Ni to R5

MOV

RS,R6

Address info for correction

14 .0

AND

#07FFh,R5

Delete 3 MSBs (nl bits)

11.0

RLA

R5

Calculate subdivision

RLA

R5

Prepare

13.0

RLA

R5

((Ni x p/2 AI4)-nl)x 128

14 .0

RLA

R5

7 bit ADC info to high byte

15.0

SWPB

R5

ADC info to low byte 0 ... 7Fh

7.0

MOV. B

RS,IROPl

To MPY operand register

7.0

SWPB

R6

Calculate coeff. address

6.0

RRA.B

R6

o... 3Fh

5.0

14 .0

to O ... IFh

RRA.B

R6

2 x nl in R6

BIC

#l,R6

0., .OEh: address of slope al

MOV.B

TABl(R6),IROP2L

Slope a1

0 ... 0Fh

4.0
4.0

±0.10

CALL

#MPYS8

((Ni x p/2A14)-n1)x 128 x a1

SWPB

IRACL

MPY result to aD format

ADD.B

TABO(R6),IRACL

(nnn)x 128 x al + aO

SXT

IRACL

RRA

IRACL

To integer format

±5.1

RRA

IRACL

Carry is used for rounding

±5.0

ADDC

&ADAT, lRACL

Corrected result Nicorr

14 .0

±

±4.10
4.2
±5.2
±5.2

Proceed with Nicerr in IRACL
The 16 RAM bytes starting at label TAB contain the correction
coefficients al and aO. The bytes are loaded during the
initialization. 8-bit , signed numbers
.bss

TABl/l

i

Range A: al

±0.9

Linear Improvement of the MSP430 14-8it ADC Characteristio

2-137

Aclditlonallnformatlon.
.bas

TABO, 1

aO

• bea

TABx, 14

Range·S, C, 0: al, aO .

±5.2

EXAMPLE: The ADC ranges are split into two sections each. The measured
errors of five pOints located in the upper section of range ~evice 1 is
used-are shown below (k = 4, P =8). The correction coefficients for this section
are calculated with the linear regression method. The correction coefficients for
the other seven sections may be calculated the same way.
ADC Step

6144

6656

7168

7680

8192

SUbdivision

Error [Steps)

The correction coefficients a1 and ao for the upper section of range B (n1 =3) are
calculated with the formulas shown in section 1.2.2. The subdivision of the ADC
step (0 to 127) is used (8-bit arithmetic).
a1 = + 0.03719
ao = + 14.32

Negated value
Negated value

Correction:
[(

N~~/ _ m) x 128 x ao + 81 ]

= [(

N~~4 8 ,- 3) x 128 x (- 0.03719) + 14.32]

The correction for the ADC step 7000-located in the upper section of range
B-is calculated:
(

70~~4x 8 -

3) x 128 x (- 0.03719) + 14.32 = + 12.33

Corrected ADC sample: NiCO" = Ni + 12.3
Valid for ADC step 7000 range B
Format:
C1:l:1'"1 I 1 I 1 ' 6, , 1 i 1 ' 6 i
al: ±D.l0
-0.03719/2-10 .. -38 = DAh
2'

ao: ±5.2

+14.3212-2 =57.3 '" 39h

2 Additionallnformation
The application report Nonlinear Improvement of the MSP430 14-Bit ADC
Characteristiq4] shows nonlinear methods such as quadratic and cubic
corrections for t!le improvement of the 14-bit analog-to-digital converter of the
MSP430. Also included are the integer multiplication subroutines for the fast
correction software and considerations to the obtainable accuracy with the 8-bit
software. Finally all explained correction methods presented are compared by
ROM and RAM needs, accuracy improvement, and required CPU cycles.

2-138

SLAA048

References

3 References
1. Architecture and Function of the MSP430 14-8it ADC Application Report,
1999, Literature #SLAA045
2. Application Basics for the MSP430 14-8it ADC Application Report, 1999,
Literature #SLAA046
3. Additive Improvement of the MSP430 14-8it ADC Characteristic Application
Report, 1999, Literature #SLAA047
4. Nonlinear Improvement of the MSP430 14-8it ADC Characteristic
Application Report, 1999, Literature #SLAA050
5. MSP430 Application Report, 1998, Literature #SLAAE1 OC
6. Data Sheet MSP430C325, MSP430P323, 1997, Literature #SLASE06B
7. MSP430 Family Architecture Guide and Module Library, 1996, Literature
#SLAUE10B

Unear Improvement of the MSP430 14-8it ADC Cheracterlstic

2-139

2-140

SLAA048

Definitions Used With the Application Examples

Appendix A

Definitions Used With the Application Examples

; HARDWARE DEFINITIONS
ACTL
ADAT

.equ
.equ

0114h
ADC control register: control bits
Ollah; ADC data register (12 or 14-bits)

Unear Improvement of the MSP430 14-81t ADC Characteristic

2-141

2-142

SLAA048

Nonlinear Improvement of the MSP430
14-Bit ADC Characteristic

·~ThxAs
-INSTRUMENTS
2-143

,IMPORTANT NOTICE
Texas Instruments and Its subsidiaries (TI) reserve the right to make changes to their products orto discontinue
any product or service without notice, and advise customers to obtain the latest version of relevant information
to verify, before placing orders, that information being relied on is current and complete. All products are sold
subject to the terms and conditions of sale supplied at the time of order acknowledgement, including those
pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semiconductor productS to the specifications applicable at the time of sale in
accordance with Tl's standard warranty. Testing and other quality control techniques are utilized to the extent
TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily
performed, except those mandated by govemment requitements.
CERTAIN APPLICATIONS USING SEMICONDUCTOR PRODUCTS MAY INVOLVE POTENTIAL RISKS OF
DEATH, PERSONAL INJURY, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE ("CRITICAL
APPLICATIONS"). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, AUTHORIZED, OR
WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT DEVICES OR SYSTEMS OR OTHER
CRITICAL APPLICATIONS. INCLUSION OF TI PRODUCTS IN SUCH APPLICATIONS IS UNDERSTOOD TO
BE FULLY AT THE CUSTOMER'S RISK.
In order to minimize risks associated w~h the customer's applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assistance or customer product design ..TI does not warrant or represent
that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other
intellectual property right of TI covering or relating to any combination, machine, 'or process in which such
semiconductor products or services might be or are used. Tl's publication of information regarding any third
party's products or services does not constitute Tl's approval, warranty or endorsement thereof.

Copyright © 2000, Texas Instruments Incorporated

Contents
Introduction ............................................................................... 2-147
1.1 Correction With Quadratic Equations .................................................... 2-148
1.2 Coefficients Estimation ................................................................ 2-151
1.3 Correction With Cubic Equations ....................................................... 2-154
1.4 Coefficients Estimation ................................................................ 2-156
2 Considerations to the Integer Calculations ................................................... 2-181
2.1 Multiplication Subroutines .............................................................. 2-161
2.2 Maximum Magnitude of the 8-Bit Coefficients ............................................. 2-162
2.3 Number Formats olthe 8-Bit Coefficients ................................................ 2-163
2.4 Calculation olthe 8-Bit Coefficients ..................................................... 2-164
2.5 Accuracy With the 8-Bit Integer Routines ................................................ 2-166
2.5.1 Accuracy for the Linear Correction .............................................. 2-166
2.5.2 Accuracy for the Cubic Correction ............................................... 2-168
3 Comparison ofthe Used Improvement Methods ...• ; ......................................... 2-189
3.1 Comparison Tables ................................................................... 2-169
3.2 Comparison Graph ................................................................... 2-170
4 Selection Guide ............................................................................ 2-172
5 Summary .................................................................................. 2-172
8 References ................................................................................ 2-173

List of Figures
The Hardware of the 14-Bit Analog-to-Digital Converter .....•..................•....... : ....•....• 2-148
2 Principle of the Error Correction With Four Quadratic Equations ........................... '........• 2-150
3 Error Correction Wrth Four Quadratic Equations ..........................................••...... 2-151
4 Principle of the Error Correction With Four Cubic Equations ...........••.................. '.' •....• 2-155
5 Error Correction With Four Cubic Equations ..................................................... 2-156
6 Worst Case ADC Error With Different Improvement Methods .................•..................•• 2-163
7 Number Format With Integers for 8-Bit Calculations .............................................. 2-164
8 Number Format With Fraction Part Only for 8-Bit Calculations ........•...............•..........•. 2-164
9 Comparison of Corrected ADC Characteristics. 8-Bit Results After Rounding ....•..•..•............. 2-167
10 Comparison of Corrected ADC Characteristics. 8-Bit Results Before Rounding ..•........•.......... 2-167
11 Comparison of Corrected ADC Characteristics. 8-Bit Results Before Rounding .•..........•......... 2-168
12 Comparison olthe Non-Corrected ADC Characteristic and the Best Improvement •................•. 2-171

Nonlinear Improvement of the MSP430 14-8it ADC Characteristic

2-145

Tables

List of Tables
2
3
4
5
6
7
.8

Worst Case Coefficients for Quadratic Equations (8-Bit) ...•......•...............•.•.............. 2-151
8-Bit Coefficients for the Four Quadratic Equations of Device 1 .................................... 2-152
Worst Case Cl!bic Coefficients (8-Bit Arithmetic) ................................................. 2-156
Correction Coefficients for the Cubic Equations of Device 1 ........................................ 2-157
Worst Case Correction Coefficients (8-Bit ArithmetiC) ................ : ............................ 2-163
Comparison Table for the Different Improvement Methods ......................................... 2-169
Comparison Table for the Different Improvement Methods ............................... ; ......... 2-170
Selection for the Improvement Methods ......................................................... 2-172

2-146

SLAA050

Nonlinear Improvement of the MSP430 14-8it ADC Characteristic
Lutz Bieri
ABSTRACT
This application report shows nonlinear methods-with quadratic and cubic equations
-to improve the accuracy of the 14-bit analog-t.---I~ ACTt.12(Pd)

-

128
128
C

128
128

A

AGND
(AVa,

c=:.d±±:±::::;---=

ACTL9, 10(Range)

ACTL 11(Autol

AO~

AI

A2

AI!
A4

AS
AS
A7

8:1

.,..-0

''''
MUX

ACTLO(SOC)
Input

ACTL2.4(Ax)
ACTL5 (None)

SAR.13

SAR.D

16-811 Memory Oala. Bus, MOB

Figure 1. The Hardware of the 14-Blt Analog-to-Digital Converter
The methods for the improvement of the ADC discussed in this report are:
• Correction with nonlinear equations
• Correction with one quadratic equation per range
• Correction with one cubic equation per range

1.1

2-148

Correction With Quadratic Equations
The ADC is measured atthree points within all four ranges. These points are used
for a quadratic correction (one correction for each range). It is recommended to
use more than one measurement for each one of these three important pOints.
Additive Improvement ofthe MSP430 14-Bit ADC Characteristic[3] section 2.1 for
details. Normally these three points are the two borders and the center of the
actual range. This has two advantages:
• The ranges continue' smoothly at the common borders.
• Only nine pOints of the ADC characteristic need to be measured for the full
ADC range during the calibration. This is due to the common range border
points.
But other arrangements are possible.
The improvement methods and their results for this report are demonstrated with
the characteristic of device 1 due to its worst characteristic compared to the other
three devices shown in Architecture and Function of the MSP430 14-Bit ADC.
Application Report.[1]
SLAA050

Introduction

The formula used for each range with separate factors ax for 8-bit integer
calculations is:

Nicorr = Ni + ((
Where: Nicorr
Ni
N
n
a2
a1
aO

The term N =

(4~6 -

n) x 256

f

x a2 +

(4~6 -

n) x 256 x 81

+ aD)

Corrected ADC sample
[Steps]
Measured ADC sample (non-corrected)
[Steps]
Subdivision representing the ADC sample (0 ...255)
Range number (0 ...3 for ranges A. .. D)
Quadratic Coefficient of the correction
[Steps-1]
Linear coefficient of the correction
Offset of the correction
[Steps]
Nominal ADC step of the ADC input (DAC output) [Steps]

(4~6 -

n) x 256 of the equation above is the adaptation of a

complete section-here a full range-to 256 subdivisions. The calculation of the
term is made by simple shifts rather than division and a multiplication. Rounding
is used to achieve better accuracy. See the initialization part of the software
example.
The formula above uses the subdivisions (0 to 255) inside of an ADC range (0
to 4095 steps) instead of the full 14-bit position (0 to 16383 steps) of an ADC point.
This is to maintain the accuracy of the calculation with limited coefficient length
(here for 8-bit coefficients). The above formula is used with the 8-bit calculation.
If floating pOint calculation or 16-bit arithmetic is used, the higher resolution
makes the range correction unnecessary: the full 14-bit result may be used for
the calculations.

Nicorr = Ni + (Ni2 x a2 + Ni x 81 +

aD)

The software example given for the cubic correction in section 1.3-which is
written in floating point notation-may be adapted easily to quadratic correction:
the unused cubic part is simply left out and the address calculation for the
coefficients is modified to three coefficients (a2 ..aO) instead of the four (a3 •. aO).
To save multiplications, the so-called Homer scheme is used. This scheme is
applicable for all given examples. The formula using the 8-bit arithmetic now
becomes:

Nicorr = Ni + ((

(4~6 -

n) x 256 x a2 + 81) x

(4~6 -

n) x 256 x

aD)

The 16-bit formula and the FPP formula now require only two multiplications
instead of three.
Nonlinear Improvement of the MSP430 14-8it ADC Characteristic

2-149

Introduction

Nico" = Ni + ((Ni x tt2.

+ a1)Ni + ao)

Figure 2 shows the principle of the correction with four quadratic equations: the
used correction parabolas are. drawn together with the non-corrected ADC
characteristic. As with all principle figures in this report, the black straight line
indicates the correction value, the scribbled black line indicates the
non-corrected ADC characteristic and the white line shows the corrected ADC
characteristic. The small circles indioate the measured ADC points.
Device 1
5

~

-10

-15
ADCSteps

Figure 2. Principle of the Error Correction With Four Quadratic Equations
The statistical results for the quadratic correction are (single measurement for
each one of the nine ADC steps used for the calculation of the correction
coeffiCients):
Mean Value:
Range:
Standard Deviation:
Variance:

Full range
-0.08 Steps
6.78 Steps
1.05 Steps
1.11 Steps

Ranges A and B only
0.24 Steps
5.86 Steps
1.10 Steps
1.21 Steps

If each of the nine ADC steps used for the calculation of the correction coefficients
is measured in a slightly modified way, then the statistical results change also.
Now the mean value of seven measured ADC steps is taken for the calculation.
The seven ADC steps are:

Nn-12, Nn-8, Nn-4, Nn, Nn+4, Nn+8 and Nn+12, where Nn is the ADC step used
in the calculation formula. Now the statistical results are:
Mean Value:
Range:
Standard Deviation:
Variance:

Full range
-0.07 Steps
6.47 Steps
1.00 Steps
1.00 Steps

Ranges A and B only
0.11 Steps
6.02 Steps
1.12 Steps
1.24 Steps

Figure 3 shows the resulting errors of both methods in a graph (differences
cannot be seen):
2-150

SLAA050

Introduction

Device 1 wl1h quadratic Correction
4

3

Ii!.

2

l!

ali

g
C

0
-1

-2
-3
ADC Steps [0 to 16383)

Figure 3. Error Correction With Four Quadratic Equations
Advantages:

Only nine ADC measurements are necessary
No gaps at the range borders: perfect continuation
The MSP430 can calculate the correction coefficients
a2to aO

Disadvantages:

Two multiplications are necessary (with Horner
scheme)

1.2 Coefficients Estimation
With the maximum possible ADC error (±10 steps contained in a band of ±20
steps like shown in Figure 6) the maximum values for the coefficients a2 to aO are
shown in Table 1. Also given are the valences of the MSBs and the LSBs and the
possible coefficient range. In Figure 6, the range C shows the worst case for a
quadratic error curve. This curve is the basis for Table 1.
Table 1. Worst case Coefficients for Quadratic Equations (8-Blt)
MAXIMUM
COEFFICIENT

VALENCE OF MSB
(BIT&)

VALENCE OF LSB
(BIT 0)

±6.103515E-4
±1.171875E-1

Z-11

2-17

±9.7E-4

Unear coefficient a1

2-4

2-10

±1.25E-1

Constant coefficient ao

±2.00000E+1

2+4

Z-2

COEFFICIENT
Quadratic coafficient a2

COEFFICIENT
RANGE

±3.2000E+1

The integer calculation operates with signed 8-bit coefficients and ax ADC result
rounded to 8 bits. The floating point calculation uses the full ADC result (0 to
16383) and a 32-bit format for the calculations.

Nonlinear Improvement of the MSP430 14-Bit ADC Characteristic

2-151

Introduction

To give an idea concerning the actual magnitudes, the twelve calculated
correction coefficients ax for device 1 are:

Table 2. 8-Bit Coefficients for the Four Quadratic Equations of Device 1
COEFFICIENT

RANGE A

RANGE B

RANGEC

RANGED

a2
a1
aO

9.155273E-5

-1.831055E-4

-2.746582E-5

4.687500E-J
6.000000E+O

3.281250E-2
1.320000E+ 1

-3.0859375E-2
9.600000E+O

1.517946E-4
-2.0992208E-2
-1.000000E-1

The three equations to calculate the correction coefficients a2, a1 and aO out of
the three known errors e3, e2 and e1 at the ADC steps N3, N2 and N1 are:

(e 2 - e1) x (N;

- N~) - (a e x (N~ - N~)
(N2 - N x (N; - N~) - (N3 - N x (N~ - N~)

81

2)

3 -

1)

a2=

(e2 - a1)

2)

-

N~

81 X

-

(N2 - N1 )

N~

ao

= - (e1 -

a2 x

N~

- 81 x N1 )

NOTE:
N3, N2, and N1 can be expressed in ADC steps (0 ... 16383), range steps
(0 .. .4095) or subdivisions of the range (0 ...255) for 8-bit calculations.
In the following, N represents subdivisions.
As shown with the linear improvements, using more than one quadratic parabola
per ADC range is also possible. It is only necessary to adapt the 256 subdivisions
to the sections of the ranges, to calculate the new coefficients a2 to aO, and to
modify the addressing of the coefficients.
The software part after each ADC measurement is as follows. The numbers at
the right border-below inUret-indicate the maximum integer bits and the actual
number of fraction bits forthe result (integer. fraction). The Horner scheme is used
for the calculation.
Quadratic error correction with a single equation per range.
S-bit arithmetic. Cycles needed:
Subdivision N =
0: 85 cycles
Subdivision N > 7Fh: 206 cycles
int.frct

MOV
&ADAT,RS
MOV
R5,R6
RRA
R5
RRA
RS
RRA
RS
RRA
RS
ADC.B RS
JNC
L$l
DEC.B R5
L$l SWPB·

RRA.B
RRA.B
RRA.B
BIC

2-152

SLAA050

R6
R6
R6
R6
#1h, R6

ADC result Ni to RS
Address info for correction
Calculate subdivision 0 ... FFh
Prepare N = (Ni/4096-n)x2S6
8 bit ADC info to low byte
Round subdivision 0 ... FFh
If result overflows to IOOh:
Limit subdivision to FFh

Calculate coefficient address
0 ... 1Fh
0 ... 0Fh
O... 07h
O •.• 06h

14 .0
14.0
13.0
12.0
11.0
10.0
8.0

B.O
6.0
S.O
4.0
3.0
3.0

Introduction
Save 0 ... 6h
0 ... 03h
0 ... 9h (3n) pointer to

PUSH
RRA.B
ADD

R6
R6
@SP+ ,.R6

MOV.B

RS,IROPI

3.0
2.0
4.0

a~

; ADC info to MPY register

B.O

MOV.B TAB2(R6),IROP2L
Quadr. slope a2
CALL
RLA
ADD
SWPB

MOV.B

#MPYSB
IRACL

N x a2
To al format

#80h,IRACL
IRACL
IRACL,IROP2L

To MPY register

Round result

MOV.B R5,IROPl
ADD.B
CALL

0.17
+-0.17
+-0.18
+-0.18
+-0.10
+-0.10

; Subdivision to MPY register

8.0

TABl(R6), IROP2L

Linear slope al added
((N x a2) + al) x N

#MPYSB

+-0.10
+-S.10

ADD
#80h,IRACL
Round result
SWPB
lRACL
; To aO format
ADD. B TABO (R6) , lRACL
Add aO
SXT
lRACL
Correction to 16 bit
lRACL
RRA
(((N x a2) + al) x N) + aO
RRA
lRACL
Carry is used for rounding
ADDC
&ADAT,IRACL
Corrected result Nicorr
Use Nicorr in lRACL

+-S .10
+-S.2
+-S.2
+-S.2
+-S.l
+-S.O
14 .0

The 12 RAM bytes starting at label TAB2 contain the

correction coefficients a2, al and aD for the four ranges.
The bytes are loaded during the initialization
. bss

TAB2,1

.bss
. bss
. bss

TABI,l
TABO,l
TABx,9

Range A a2: quadr. coeff .
a1: lin. coefficient

aD: constant coett .
Ranges B, C, D: a2 ... aO .

+-0.17
+-0.10
+-S.2

EXAMPLE: The ADC is measured at the two borders and the middle of ADC
range B (n = 1). The measured errors-device 1 is used-are shown below. The
three correction coefficients a2, a1, and aO for the range B are calculated with the
formulas given before. The correction coefficients for the other three ranges may
be calculated the same way; only the appertaining border'and center errors need
to be used. Twelve measurements were made for each ADC step, and the two
extremes were discarded: this leads to one decimal fraction digit.
ADC Step
Subdivision N
Error e [Steps]

4096
0
-13.2

6144
128
-13.4

8192
256
-9:6

Error coefficients for the range B:

it2

= -{).000183106

81 =

+ 0.0328125

80 =

+ 13.2

For better legibility N = (4:6 Correction:
((N x a2 + 81) x N

+ 80)

n) x 256 is used in the following.

= ((N x (- 0.000183106)

+ 0.0328125)

x N

+ 13.2)

Nonlinear Improvement of the MSP430 14-8« ADC Characteristic

2-153

Introduction

The correction for the ADC step 7000-located in range B-is calculated:

((( ~gg~ - 1) x 256 x (- 0.000183106) + 0.0328125) x ( ~gg~ - 1) x 256 + 13.2) = + 13.3
Corrected ADC sample: Nico" = Ni + 13.3. Valid for ADC step 7000
Format: a2: ±0.17

-0.000183106/2-17 =-24 =E8h
7

Q~1~~~i~~~1:~ 11111

0

i 1 i 0 11 10 i 0 i 0

20

I

~17

+0.0328125/2-10 = +33.6 .. 22h

a1: ±0.10

~~o::r: 0

7

0

I 0 I0 i 1 i 0 i 0 i 0 i 1 i 0 I

aU

2""10

7

aO: ±5.2

+ 13.2/2-2 '" +52.8 .. 35h

0

I0 I0 i 1 i 1 i 0 i 1 ! 0 i 1 I
iJ

2-2

1.3 Correction With Cubic Equations
The ADC is measured at the two borders of each range (common to two ranges)
and at one third and two thirds of each range, which results In 13 measurements:
20, 1366, 2731, and 4096 for range A. The errors of these 13
e.g., N
measurements are used for the calculation of four cubic equations, one for each
ADC range. It is recommended to use more than one measurement for each of
these thirteen points. The resulting correction coefficients a3, a2, a1, and aO for
each ADC range are stored in the RAM or EEPROM.

=

The above method has two advantages:
• The ranges continue smoothly at the common borders.
• Only thirteen points of the ADC characteristic need to be measured for the full
ADC range during the calibration. This is due to the common range border
points.
The used formula for each range with separate factors ax for an 8-bit integer
calculation is:

Nico" = Ni +
Where: N

(foil x

= (4~6 -n)

a3 + /IP x tt2 + N x a1 + ao)

x 256, the ADC result of a range adapted to the

subdivisions 0...255.
Where: Nicorr
Ni
N
n
a3

a2
a1
aO

2-154

SLM050

Corrected ADC sample
.[Steps]
Measured ADC sample (non-corrected)
[Steps]
Subdivision representing the ADC sample (0 ..•255)
Range number (0.•.3 for railges A... D)
Cubic coefficient of the correction
[Stepr2j
Quadratic coefficient of the correction
[Stepr1]
Linear coefficient of the correction
Offset of the correction
[Steps]
Nominal ADC step of the ADC input (DAC output) [Steps]

Introduction

The integer formula above uses the subdivision (0 ..255) inside of an ADC range
(0 to 4095) instead of the full 14-bit position (0 to 16383) of an ADC point. This
is to increase the accuracy of the calculation also with limited coefficient length,
e.g., for 8-bit coefficients.
If floating point calculation is used, the high resolution of the 24-bit mantissa
makes the range correction unnecessary. The equation simplifies to:

Nicorr = Ni + (Nf3 x a3

+ Nfl x

82

+ Ni x

a1

+ ao)

To save multiplications the Horner scheme is used again. This reduces the
number of multiplications from six to only three. The formula using the 8-bit
arithmetic now becomes (N represents the actual subdivision 0 ...255. See
above):

Nicorr = Ni

+ (((N x

a3)

+ a2) x

N

+ a1) x

N

+ aO

The formula for 16-bit and floating point calculations now becomes:

Nico" = Ni

+ (((Ni x

a3)

+ 82) x

Ni + a1) x Ni + aO

Figure 4 shows the principle of the correction with four cubic equations: the
correction parabolas actually used are printed together with the corrected and
non-corrected ADC characteristic. The circles indicate the measured ADC
points.
Device 1
4
2

I

l

0

-2
-4

~

~

w

~

()

-10
-12
-14
-16

~

ADCSteps

Figure 4. Principle of the Error Correction With Fpur Cubic Equations
The statistical results for the cubic correction method are:
Mean Value:
Range:
Standard Deviation:
Variance:

Full range
-0.10 Steps
5.47 Steps
0.93 Steps
0.87 Steps

Ranges A and B only
-0.28 Steps
4.97 Steps
0.97 Steps
0.94 Steps

Figure 5 shows the resulting error correction in a graph:
Nonlinear Improvement of the MSP430 14-8it ADC Characteristic

2-155

Introduction
Device 1 ~ with four CubIc EquaUona

a~

__________________________________

~

____________- ,

2

'!

I

l
~

1

0~~4A~-+~~~~~~~
-1

~~----------------------------------------------------~
ADC Steps [0 to 16383)

Figure 5. Error Correction With Four Cubic Equations
Advantages:
Good adaptation to worst case ADC characteristics
Low storage needs: 16 bytes RAM or EEPROM
(integer calculation)
Monotonicity is ensured due to common samples at the
range borders
Only thirteen ADC measurements are necessary for the
calibration
Three multiplications are necessary (with HORNER
scheme)
Host is necessary for the calculation of the correction
coefficients ax

Disadvantages:

1.4 Coefficients Estimation
With the maximum possible ADC error (±10 steps contained in a band of ±20
steps like shown in Figure 6) the maximum values for the coefficients a3 to aD are
shown in Table 3 (8-bit arithmetic). Also given are the valences of the MSB and
the LSB and the possible coefficient range. In Figure 6, the range D shows the
worst case of a cubic error curve. This curve is the basis for Table 3.
Table 3. Worst Case Cubic Coefficients (8-8It Arithmetic)
COEFFICIENT

MAXIMUM
COEFFICIENT

Cubic coefficient a3

±6.357828H

Quadratic coefficient a2
Linear coefficient B1

±2.441406E-3
±2A73956E-1

VALENCE OF MSB
(Brr8)
2""18

VALENCE OF LSB
(BIT 0)

COEFFICIENT
RANOE

244

±7.57H

z-9

2""15

±3.88E-3

~

z-9
±2A8E-1
2+4
Constant coefficient sO
±2.00000E+1
z-2
±3.2OOE+1
The integer calculation operates with signed 8-bit coefficients and an ADC result
rounded to 8 bits (256 subdivisions).

2-156

SLAA050

Introduction

The floating point calculation uses the full ADC result (0 to 16383) and a 32-bit
format forthe calculations. To give an example, for device 1 the calculated sixteen
correction factors a3 to aO are (12-bit ADC info is used):
Table 4. Correction Coefficients for the Cubic Equations of Device 1
COEFFICIENT

a3
a2
a1

RANGE A
-1.18&-10
1.02E-{)6

RANGEB

RANGEC

RANGED

-6.483598E-10
3.943417E-{)6

3.288326E-11
-3.497543E-07

5.17398E-10
-2.655711 E-Q6

-4.37&-04

-6.153471E-03

-1.486924E-03

3.83333E-03

6.00E+OO

1.320000E+01

9.600000E+00

-1.000000E-01

aO

The algorithm to calculate the four correction coefficients a3 to aO out of the four
measured errors e4, e3, e2 and e1 at the ADC steps N4, N3, N2 and N1 is very
complex. It is recommended to use a mathematical support software running on
a host computer for this task. A simple calculation software routine is available
from Texas Instruments on request.
For the cubic correction an example using the MSP430 Floating Point Package
FPP4 is given below. This software example can be adapted easily to linear and
quadratic correction:
• The parts not used are deleted (e.g., the parts handling the coefficients a3 and
a2 if a linear correction is needed)
• The calculation of the start address of the correction coefficients (address of
a3 in the example) out of the ADC result is modified slightly.
; Cubic error correction with a single equation per range.
; Floating point arithmetic. Cycles needed: 800 to 2400

o

Use .FLOAT format (32 bit)

MOV
CALL
CALL
SUB
MOV
CALL
SUB

#xxx,&ACTL
#MEASR
#FLT_SAV
U,SP
#ADAT,RPARG
#CNV_BINl6U

Define ADC measurement
Measure. Result Ni to ADAT
Save registers R5 to R12
Allocate stack for FP result
Load address of ADC buffer
convert ADC result Ni to FP

#4,SP

New working space for calc.

MOV
SWPB
AND
ADD
MOV
CALL
ADD
MOV
CALL
ADD
CALL
ADD
MOV
CALL
ADD
CALL
ADD
MOV
CALL
ADD
CALL

&A,DAT,R1S
R1S
#0030h,R1S
#a3,R1S
R1S, RPARG
#FLT_MUL
#a2-a3,R1S
R1S,RPARG
#FLT_ADD
U, RPARG
#FLT_MUL
#a2-a3,R1S
RlS,RPARG
#FLT_ADD
U,RPARG
#FLT_MUL
#a2-a3,R1S
R1S,RPARG
tFLTJ.DD
#4,RPARG
#FLTJ.DD

Calc. address of coetf. a3

DOUBLE .EQU

Range x 16: reI. address a3
start address of coeff. block
Points to actual a3
a3 x Ni
Address of a2
Points to actual a2
a3 x Ni + a2
To Ni
(a3 x Ni+a2)Ni
Address of al
Points to actual al
«a3 x Ni)+a2)Ni + a1
To Ni
«(a3 x Ni) + a2)Ni + al)Ni
To actual aO

«(a3 x Ni)+a2)N1+al)Ni+aO
To Ni
Nicorr - Ni + correction

NonUnear Improvement of the MSP430 14-8i/ ADC Characteristic

2-157

Introduction

POP
POP

2 (SP)
2(SP)

Result to top of stack
POPfi correct the stack
Continue calc. with Nicorr
Restore registers R12 to RS
Normal program continues

correction coefficients are loaded from EEPROM during init .
. bss

a3,4

.bas

a2,4

.bss
.bss

al,.4
aO,4

.. bss

ax,48

Range A: Cubic coefficient a3
Quadratic coefficient a2
Linear coefficient al

Constant coefficient aO

Ranges B, C and 0: a3 ... aO

The assembler software part after each ADC measurement is as follows. The
numbers at the right border-below intfrct-indicate the maximum integer bits
and the maximum number of fraction bits (integer.fraction). The Horner scheme
is used for the calculation.
Cubic error correction with a single equation per range.
S-bit arithmetic. Cycles needed:
Subdivision N = 0: lOS cycles; subdivision N > 7Fh: 2S3 cycles

int.frct

L$l

2-158

&ADAT,RS

MOV
MOV
RRA
RRA
RRA
RRA
ADC.B
JNC
DEC.B

RS
R5
R5
RS
RS
L$l
RS

Calculate subdivision 0 .. . FFh
Prepare N == (Ni/4096-n)x256
8 bit ADC info to low byte
Round subdivision 0 .. . FFh
If result overflows to 100h:
Limit sUbdivision to FFh

S.O

SWPB
BIC.B
RRA.B
RRA.B

R6
#OFh,R6
R6
R6

Calculate coeff. address a3
O... 30h
0 .. . 1Sh
0 ... OCh: address of slope a3

6.0
6.0
5.0
4.0

MOV.B
MOV.B
CALL
SIIPB
RRA.B
ADC.B
MOV.B

R5, IROP1
TAB3(R6),IROP2L
#MPYSS
lRACL
lRACL
lRACL
lRACL,IROP2L

Subdivision to MPY register
Cubic slope a3

MOV.B
ADD.B
CALL
RLA
RLA
ADD
SWPB
MOV.B

R5, IROP1
TAB2(R6),IROP2L
#MPYSB
lRACL
lRACL
#OSOh, lRACL
lRACL
lRACL, IROP2L

RS,R6

ADC result Ni to R5
Address info for correction

14.0
14.0
13.0

12.0
11.0
10.0

S.O

S.O

N x a3

0.24
+-0.24

To a2 format
Round result
To MPY register

+-0.15
+-0.15
+-0.15

+-0.16

Subdivision to MPY register
Quadr. slope a2 added
((N x a3 + a2) x N
To a1 format
Round result
To MPY register

8.0

+-0.15
+-0.15
+-0.16

+-0.17
+-0.17
+-0.9
+-0.9

MOV.B R5,IROP1
ADD.B TAB1(R6),IROP2L
CALL
#MPYSS

Subdivision to MPY register
B.O
Linear slope a1 added
0.9
«N x a3 + a2) x N + a1) x N +-S.9

RLA
lRACL
ADD
#80h,IRACL
SIIPB
lRACL
ADD.B TABO(R6),IRACL

To aO format
Round result
To aO format
Add aO

SLAA050

+-S.10
+-S.lO
+-S.2
+-5.2

Introduction
SXT
RRA
RRA
ADDC

lRACL
lRACL
lRACL
&ADAT,IRACL

+-5.2
+-5.1
+-5.0
14.0

Correction to 16 bit
Carry is used for rounding
Corrected result Nicorr
Use Nicorr in IRACL

The 16 RAM bytes starting at label TAB3 contain the

correction coefficients a3, a2, al and aO. The bytes are
loaded during the initialization
. bss
.bss
.bss
.bss

TAB3,1
TAB2,1
TAB1,1
TABO,l

. bss

TABx,12

Range A a3: cubic coeff .
a2: quadr. coeff.
al: lin. coefficient
aO: constant coeff.
Ranges B, C, 0: a3 ... aO

+-0.24
+-0.15
+-0.9
+-5.2

As shown with the linear improvements, it is also possible to use more than one
cubic parabola per ADC range. It is only necessary to adapt the 256 subdivisions
to the sections of the ranges, to calculate the new coefficients, and to modify the
addressing of the coefficients.
EXAMPLE: The ADC is measured at the borders and at one third and two thirds
of ADC range D (n = 3). The measured errors--device 1 is usecl-are shown
below. The four cubic correction coefficients a3 to aO for the range Dare
calculated with a math package running on a pc. The correction coefficients for
the other three ranges maybe calculated the same way using the appertaining
errors of each range. Twelve measurements were made for each ADC step, the
two extremes were discarded: this leads to one decimal fraction digit.
ADCStep
Subdivision N
Error e [Steps]

1228

o

0.1

13653
85.33
-1.5

15019
170.67
-1.1

16350
253.9
-4.0

Error coefficients for the range D:
a3 = + 0.00000146501
a2 = -0.000512371
a1 = + 0.0518045
aO = -0.10
For better legibility N =

(4~6 -n)

x 256 is used in the following.

Correction: «(N x a3) + 82) x N + a1) x N + aD
= «(N x 0.00000146501) - 0.000512371) x N

+ 0.0518045) x

N - 0.10

The correction for the ADC step 1500o-Iocated in range D-is calculated:
N= (

~0~0~

- 3) x 256 = 169.5"" 170

«(170 x 0.00000146501)-0.000512371) x 170 + 0.0518045) x 170-0.10 = + 1.1
Corrected ADC sample: Nicerr = Ni + 1.1. Valid for ADC step15000
Nonlinear Improvement of the MSP430 14-8it ADC Characteristic

2-159

Introduction

Format:

a3: ±0.24

+0.00014650112-24 .. +24.58 = 19h
7

0

~i.O~o~~~~~~~o~~~~~~~o~~ 0 I 0 I 0 i 0 i 1 i 1 i 0 i 0 i,l
I!!J

.-24

a2: ±0.15

-0.00051237112-15 =-16.79 .. EFh

[!~1~~~1~~~1=~>

7

0

1111 i 1 i 0 i 1 i 1 i 1 111

20

a1: ±0.9

2-15

+0.0518045/2-9 =+26.52 .. 1Bh

7

0

[!:i 0 I 0 I 0 i 0 i 1 i 1 i 0 i 1 i,l
..-e

20
7

aO: ±5.2

0

-0.1/2-2 =-0.4 .. OOh I 0 I " i 0 i 0 i 0 i o! 0 i 0 I
I!!J

2-160

SLAA050

....

Considerations to the Integer Calculations

2

Considerations to the Integer Calculations
The calculations for this application report were made with a floating point
package. If the 14-bit ADC is used within a real time system the floating point
calculation time is normally too long. Therefore the necessary loss of accuracy
needs to be known if integer calculations with their restricted bit length are used.
The most time consuming parts are the multiplication subroutines, so they are
shown first.

2.1

Multiplication Subroutines
To reduce the multiplication time as much as possible, two multiplication
subroutines, which terminate immediately after the operand IROP1 becomes
zero are shown; this means that the operand with leading zeroes should be in the
register IROP1-here the subdivision representing the ADC result. 1

2.1.1

8-Bit Multiplication Subroutine

If the operands of the multiplication subroutine are normally shorter than 8 bits,
then the multiplication subroutine below saves time due to its run time
optimization: the multiplication terminates immediately after IROP1 gets zero due
to the right shifts during the processing.
; Run time optimized 8-bit Multiplication subroutines
; Definitions
IROP1
IROP2L
lRACL

.EQU
.EQU
.EQU

R14
R13
R12

Unsigned subdivision (DOh ... FFh)
Signed coefficient
(80h ... 7Fh)
Result word

; Cycles for specific registers contents without CALL:

; TASK

MACU8 MACS8 MPYS8

IROP1

9
34

OOOh x OOOh = OOOOh
OOFh x OOFh = OOElh
OFFh x OFFh - FFOlh

IROP2 Result (MPYS8)

;------------------------------------------------------------MINIMUM
MEDIUM
MAXIMUM

66

12
37
70

13
38

71

Used registers IROP1, IROP2L, IRACL
Signed multiply subroutine: IROPI x IROP2L -> IRACL
MPYS8 CLR

lRACL

; 0 -> 16 bit RESULT

; Signed multiply-and-accumulate subroutine:
; (IROPI x IROP2L) + lRACL -> lRACL
MACS8

TST.B
JGE
SWPB
SUB
SWPB

IROP2B
MACU8
IROPl
IROPl,IRACL
IROP1

Sign of factor
Positive sign: proceed
Negative sign: correction nec.
Correct result word

Unsigned multiply-and-accumulate subroutine (MAC):
(IROPI x IROP2L) + lRACL -> lRACL
MACU8 BIT.B n,IROPl
JZ
L$01
IROP2L,IRACL
ADD
IROP2L
L$Ol
RLA
RRC.B IROP1
JNZ
MACU8
RET

Test actual bit (LSB)
If 0: do nothing
If 1: add multiplier to resultL$01
Double multiplier IROP2
Next bit of IROP1 to LSB
If IROPl = 0: finished

1The idea for these subroutines innially came from leslie Meble 01 TIL.

NonHnear Improvement of the MSP430 14-81t ADC Characteristic

2-161

Considerations to the Integer Calculations

2.1.1.1

16-Bit Multiplication Subroutine
This multiplication subroutine is used if the 8-blt version is not accurate enough.
Like the 8-bit version, the multiplication terminates immediately after IROP1
becomes zero due to the right shifts during the processing. All of the shown ADC
improvement methods may be adapted to the 16-bit multiplication subroutine.
; Run time optimized 16-bit Multiplication Subroutines
IROPl
IROP2L
IROP2M
IRACL
IRACM

. EQU
. EQU
. EQU
. EQU
.EQU

R11
R12
Rl3
R14
R1S

Unsigned ADC result (OOOOh ... 3FFFh)·
Signed coefficient (8000h ... 7FFFh)
High word of signed factor (0)
Result word low
Result word high

; Cycles for specific register contents without CALL:
; TASK
MACU
MACS
MPYS
IROP1 I ROP2 Result (MPYS)

i------------------------------------------------------------MINIMUM
11
14
16
OOOOh x OOOOh = OOOOOOOOh
MEDIUM
MAXIMUM

83

86

88

143

147

149

OOFFh x OOFFh
3FFFh x FFFFh

~

=

0000FE01h
FFFFC001h

Used registers: all of the above ones
Signed multiply subroutine: IROP1 x IROP2L -> IRACMllRACL
MPYS
MACS
MACU
L$002

L$Ol

CLR
CLR
TST
JGE
SUB
CLR
BIT
JZ
ADD
ADDC
RLA
RLC

IRACL
IRACM
IROP2L
MACU
IROPI, IRACM
I ROP2M
H,IROP1
L$Ol
IROP2L,IRACL
IROP2M, IRACM
IROP2L
IROP2M

o -> result word low
o -> result word high
Sign of factor a1
Positive sign: proceed
; Correct result
Clear MSBs of multiplier
Test actual bit (LSB)
If 0: do nothing
; If 1: add multiplier to result

RRC
JNZ
RET

IROPl
L$002

Next bit of IROPl to LSB
If IROPl = 0: finished

Double multiplier IROP2

2.2 Maximum Magnitude of the 8-Blt Coefficients
To get the maximum accuracy with the limited 8-bit format used for the correction
coefficients, it is necessary to calculate the worst case magnitude for each one
of these coefficients. The basis for this calculation is the maximum error of the
14-bit ADC:
± 10 steps within a band of ±20 steps
Figure 6 shows examples for the worst case errors of the 14-bit ADC:
• Range A shows the maximum error band of the ADC: ±20 steps; within this
error band all errors of different devices are contained. The four dark boxes
indicate four possible error ranges of ± 10 steps: they are examples for Single
devices, within such an error band the errors of a single device are contained.
• Range B gives an example for the maximum linear error: within one range
(4096 steps) the error changes by 20 steps.
• Range C is an example for a maximum quadratic error.
• Range D is an example for a maximum cubic error. This means within an ADC
range the ADC characteristic moves from an error of +10 steps at the lower
2-162

SLAA050

Considerations to the IntBgBr Calculations

range border to +2.5 then back to +7.5 and back to 0 steps at the upper range

~~

.

Examples for Worst case ADC Errors

25
20
15

I
~

!
0

Q

c(

10

5
0
-6
-10
-15

-20
Additive, Unsar,Quadratlc and Cubic Worst case CharaClerlatlc8

Figure 6. Worst Case ADC Error With Different Improvement Methods
Table 5 shows the worst case values-the largest possible values-for the 8-bit
correction coefficients that were calculated with the following assumptions:
• The ADC characteristic uses the full error band of ± 10 steps.
• The ADC characteristic changes its direction as often as the order of the
correction formula, e.g., twice for a quadratic correction.
• The correction is made for each range Individually; this means the ADC result
bits 13 and 12-the bits defining the ADC range-are cleared.
• The relative ADC result within each range (12 bits) is rounded to eight bits (0
to FFh) for the calculations (8-blt arithmetic).
• The linear coefficient a1 of each method must allow a ±10 step correction.
• The constant coefficient aO of each method must allow a ±20 step correction.
The maximum correction coefficients calculated with the above assumptions are
listed in Table 5. (NA means not applicable):
Table 5. Worst Case Correction Coefficients (8-Bit Arithmetic)
CUBIC
CORRECTION

QUADDRATIC
CORRECTION

LINEAR
CORRECTION

ADDmVE
CORRECTION

a3

±6.357828E-6

NA

NA

NA

a2

±2.441406E-3

±6.103515E-4

NA

NA

a1

±2.473958E-1

±1.171875E-1

± 1.562500E-1

NA

aO

±2.000000E+1

±2.000000E+1

±2.000000E+1

±2.000000E+ 1

2.3 Number Formats of the 8-Bit Coefficients
The format chosen for the correction data is byte format due to its low storage
needs and the speed advantages for multiplications. Figure 7 shows a signed
8-bit number with three fractional bits (±4.3). The range of this number format is
-16.00 to +15.875.
Nonlinear Improvement of the MSP430 14-8it ADC Characteristic

2-163

'~I(,.•

Considerations to the Integer Calculations

o

!

Integer Bits

Format

Frectlon Bits

7
4.375

0

0

I

0

0

~

0

i

0

•

1

7
-4.375

I I
1

I

a-3

20

0
1

i

.0

zO

23

0

•

1

I

2-3

Figure 7. Number Format With Integers for 8-Blt Calculations
For the coefficients a3 and a2 no integer parts exist, due to the small values of
the resulting numbers. This makes a different format necessary, but the
philosophy is the same, to pack very small numbers with many leading zeros or
ones into a single byte. Figure 8 shows the number format of the quadratic
coefficient a2 used in a cubic correction. All bits of the extended sign have the
same value as the sign bit (bit 7).

IntegerBI!
Format

r-------------------L
__... ______~~~~~ _______

0
.l.I_Sl_g_n..lI_ _ _ _ _ _
Frac_tl_On_B_Its
_ _ _ _ _---'

2-15

20
7

4x2-15 r-o-r_;-i~;'-;T-o-r_;-i-;-ro
L __ _____________ _
~

o

I

0

0

o

o

o

0

zO

l__ ~_

L~_~~ __ ~ __ ~ __

1

7

1

0

,.-"-T--r--.. . . .-..,--,...--,.---.,---.
-I1_l
.....I'--l_____________ I
0

z-e
Figure 8. Number Format With Fraction Part Only for 8-Bit Calculations

2.4 Calculation of the 8-Bit Coefficients
To get the subdivision N out of the ADC value-ranging from 0 to 3FFFh-a short
calculation is necessary:

N=
2-164

I

2-15

'--r-...r-,--T--r---,--'
-4><2""15

0

(4~6 - n)

SLM050

x 128 ranging from 0 to 128 for linear correction

0 .J

2-15

Conslderatkms to the Integer Calculations

n) x 256

N = (4:6 -

ranging from 0 to 256 for quadratic and cubic

correction
With two, three, or four subdivisions N-dependent on the used correction
method-the coefficients ax are calculated. See the appropriate sections.
1. To start, it is necessary to find the minimum valence-a power of 2-of bit 6
(MSB) of the 8-bit number that is sufficient for the worst case value of the
coefficient ax. The formula for this calculation is:
VMSB ~

log2laxl-1

Where:

VMSB
VLSB
ax

Valence for the MSB (bit 6) of the 8-bit number
Valence for the LSB (bit 0) of the 8-bit number
Decimal correction coefficient (a3 to aO)

The above formula ensures that the worst case value of the coefficient ax fits into
an 8-bit twos complement number.
2. The valence VLSB of the LSB is for 8-bit arithmetic
VLSB

=

VMSB -

6

With this valence VLSB the 8-bit coefficient ax8bit is calculated:
ax8bit =

2

ax
Vi

LSB

3. The result ax8bit-which is also named ax in the following equations-is
converted into a signed hexadecimal number using the twos complement
format:
• A positive coefficient is simply converted.
• A negative coefficient is converted and negated afterwards (complemented
and incremented).
EXAMPLE: The worst case value for the cubic correction coefficient a3 is
±6.357828E-6 (see Table 5). To find the minimum valence of the MSB of the
number format the equation above is used:
VMSB ~

log2laxl - 1 = log2 6.357828E - 6 - 1 = - 17.263 - 1 = - 18.263

VMSB ~ -

18.263 ....

VMSB

= - 18

This result means that bit 6-the MSB-of the 8-bit coefficient a3 must have a
minimum valence of 2-18. For the LSB the valence VLSB becomes:
VLSB

= VMSB -

6

=-

18-6 = - 24

This means, a3 can cover the number range from -128 x 2"-24 to +127 x 2-24
(-7.57E-6 to +7.63E-6) In steps of 2-24 (5.96E-8).
Calculation:

a3: ±0.24 +6.357828E-6/2-24 = +106.67 .. 6Bh

This means the worst case of the a3 value results in 107 steps out of 127 steps:
good resolution and enough reserve are given. The number format-shown for
the negative worst case value of a3 (-107 =95h)-is:
NonHnaar Improvement of the MSP430 14-Bit ADC Characteristic

2-165

Considerations to the IntsgerCslculatlons
7

[2~~1~~~~~~~1~~~~~~~1~~ 111

0

I0 i 0 i 1 i 0 i 1 i 0 i 1 I

20

044

The bits 20 to 2-17 for the above example always have the same value: they
contain the extended sign: the same value as the sign bit in bit 7 ofthe 8-bit value
(2s complement arithmetic):
• Zero for a positive coefficient
• One for a negative coefficient
Information iscontained only in the bits 7 to 0 (2-18 to 2-24 forthe above example).
This is possible due to the known maximum value of these coefficients.

2.5 Accuracy With the 8-Bit Integer Routines
To show the loss of accuracy when moving from floating point to integer
calculations with 8-bit coefficients, the results Qf the linear and the cubic
correction are given.

2.5.1 Accuracy for the Linear Correction
The linear correction-which is not sensitive to coefficient truncation due to the
simple algorithm-is shown with both calculation methods. The correction
coefficients a1 and aO ofthe linear equation shown in section 1.2.1.1, single linear
equation per range (with border fit) of Linear Improvement of the MSP430 14-Bit
ADC Characteristic, SLAA048, [4], were recalculated to fit into signed 8-bit
constants with their restricted resolution. With these 8-bit coefficients the
calculations were repeated. The statistictical results in comparison to the floating
paint results are (full range, 8-bit results after rounding):

MaanValue:
Range:
Standard Deviation:
Variance:

32·81t
Floating Point

8-81t Integer
Calculations

-0.32 Steps
5.6 Steps
0.94 Steps
0.88 Steps

-0.32 Steps
6.0 Steps
0.98 Steps
0.96 Steps

Figure 9 compares the corrected ADC characteristics by floating point calculation
vs .8-bit arithmetic (integer result). The difference of the corrected characteristics
(FPP result-8-bit result) is displayed also:

2-166

•

The white, scribbled line indicates the result of the correction using floating
point calculations

•

The black, scribbled line indicates the result of the correction with 8-bit
arithmetic

•

The black line below the above two lines indicates the difference between the
two corrections using the floating point and the 8·bit arithmetic. The offset is
chosen as -4 steps, which means -4 steps represent the zero line of the
difference

SLAA050

Considerations to the Integer Calculations
Device 1 : Comparison between FloaUng Point and II-Blt Arlthmattc
Single Unear Equation par Range (Border Fit)

4

3
2

W

£~

0

Iii

-1

8----l

CIN,CMPI

em
V••

- -....- - - -.....- - - OV

Figure 2. Minimum Sensor Circuit

The voltage at the capacitor em during the measurement is shown in Figure 3.
The equation that describes the discharge curve for the sensor (Rsens) is:
tsens

Vth

Veexe

em x Rsens _>

Rsens = _

tsens
Cmxln Vth

.

The equation for the reference resistor (Rref) is:
2-180

Vee

The Universal Timer/Port Module

VeeXe

Vth

tref
CmxRref

tref

Rref

CmX In Vth
Vee

Vcc

-+-~~....t--------~_...!--

~h~----4-----~~--~----+-~------~

o 4-----~-----4---+----+_--------+_-------

Figure 3. Timing for the Universal Timer/Port Module ADC
Where:
Vth
Vcc
tref
tsens
tc

Threshold voltage of the comparator
Supply voltage of the MSP430
Discharge time with the reference resistor Rref
Discharge time with the sensor Rsens
Charge time for the capacitor

'M
M
[s]
[s]

[s]

The solving of the exponential equation leads to the simple equation in the
following:

Rsens
Rref

-tsens
Vth
CmxlnVee

Cmxln Vth
Vee
x -tref

Rsens

Rref x tsens
tref

With two known reference resistors (Rref1 and Rref2) it is possible to compute
the slope and offset and get the exact values of the unknown resistors. The result
of the solved equations gives:

Using the MSP430 Universallimer/Port Module as an Analog-to·Digital Converter

2-181

The Universal TlmerlPort Module

Rsens =

tsens - trej2
trej2 - tref!

X

(ftrej2 - Rrefl)+ Rrej2

Where:
tsens
tref1
tref2
Rref1
Rref2

[s]

Discharge time.for sensor Rsens
Discharge time for Rref1
Discharge time for Rref2
Resistance of reference resistor Rref1
Resistance of reference resistor Rref2

[s]
[s]
[0]
[0]

As shown only known or measurable values are needed for the computation of
Rsens from tsens. The slope and offset of the measurement disappear
completely.
To get a resolution of n bits, the capacitor Cm must have a minimum capacity:

_2n
em >

Vth.....
RXmJ. x f x In-Vee

The approximate conversion time tconv is:
2n
teonv '" -

f

The complete conversion time tcompl is (reference and sensor measurement):
teompi = 2 x (feonv

+ 5 x em x Rsens )

Where:
f
Measurement frequency (ACLK or MCLK)
RXrnin Lowest resistance of sensor or reference resistor
VthrnaxMaximum value for threshold voltage Vth
tconv Conversion time for an analog-to-digital conversion

[Hz]
[0]

M
[s]

Table 1 gives an overview of different resolutions, capacitors, and conversion
times. The sensor resistance is 1 kn, f = 1.048 MHz:

Table 1. ADC Conversion With the Timer/Port Module

2-182

Resolution Bits

Capacitor
Cm

Conversion TIme
tconv

Complete Conversion Time tcompl

8

232nF

256j.1S

2.8rns

10

1jIF

1 rns

12.0rns

12

3.7 jIF

4.1 rns

45.2 rns

14

15 J1F

16.4 rns

182.8rns

16

60 jIF

65rns

730rns

The Universal TImer/Port Module

EXAMPLE: Use of the Universal Timer Port as an ADC without an interrupt. The
measured time values of the two sensors (Rsens1 and Rsens2) and the
reference resistors (Rref1 and Rref2) are stored in RAM starting at label MSTACK
(Rref1 location). If an error occurs, OFFFFh is written to the RAM location.

MSP430
Enable Control

TPtN.5

TPO.S

TPE.5 TPD.4

TPE.4 TPO.S

TPE.S TPO.2

TPE.2 TPD.l

TPE.1

TPD.O

ll'E.O

cmT

ov

Figure 4. Schematic of Example
DEFINITION PART FOR THE UT/PM ADC
TPCTL

.EOU

04Bh

TPSSELO

.EOU

040h

TPSSEL.O

ENB

.EOU

020h

CONTROLS ElN1 OF TPCNT1

ElNA

.EOO

010h

AS ENB

ElN1

.EOU

OOBh

ENABLE INPUT FOR TPCNT1

TIMER PORT CONTROL REGISTER

RC2FG

.EOO

004h

RIPPLE CARRY TPCNT2

EN1FG

.EOO

00lh

EN1 FLAG BIT

TPCNT1

.EOU

04Ch

LO B-BIT COUNTER/TIMER

TPCNT2

.EOU

04Dh

HI B-BIT COUNTER/TIMER
DATA REGISTER

TPD

.EOU

04Eh

B16

.EOU

OBOh

0: SEPARATE TIMERS

CPON

.EOU

040h

0: COMP OFF

'IlPDMAX

.EOO

OOBh

BIT POSITION OUTPUT TPD.MAX

TPE

.EOU

04Fh

DATA ENABLE REGISTER

MSTACK

.EOU

0240h

Result stack 1st word

NN

.EOU

011h

TPCNT2 VALUE FOR CHARGING OF C

1: 16-BIT TIMER

1: COMP ON

MEASUREMENT SUBROUTINE WITHOUT INTERRUPT. TPD.4 ·AND TPD.5

Using the MSP430 Universal Timer/Port Module as an Analog-te-Digital Converter

2-183

The Universal Tim6llPort Module
ARE NOT USED AND THEREFORE OVERWRITTEN
INIT·IALIZATION: STACK INDEX <- 0, START WITH TPD.3
16-BIT TIMER, MCLK, CIN ENABLES COUNTING
Call:

CALL

#MEASURE
Results for TP.3 to TP.O in MSTACK to MSTACK+6

Return:

Result OFFFFh if error
MEASURE
MEASLOP

PUSH.B

#TPDMAX

START WITH SENSOR AT TPD.MAX

CLR

R5

INDEX FOR RESULT STACK

MOV. B

#(TPSSELO*3)+ENA,&TPCTL

; Reset flags

CAPACITOR C IS CHARGED UP FOR> 5 TAU. N-1 OUTPUTS ARE USED

MLPO

MOV.B

#B16+TPDMAX-1,&TPD

MOV.B

#TPDMAX-1,&TPE

ENABLE CHARGE OUTPUTS

; SELECT CHARGE OUTPUTS

MOV.B

#NN,&TPCNT2

LOAD NEG. CHARGE TIME

BIT.B

#RC2FG,&TPCTL

CHARGE TIME ELAPSED?

JZ

MLPO

NO CONTINUE WAITING

MOV.B

@SP,&TPE

ENABLE ONLY ACTUAL SENSOR

CLR.B

&TPCNT2

CLEAR HI BYTE TIMER

SWITCH ALL INTERRUPTS OFF, TO ALLOW NON-INTERRUPTED START
OF TIMER AND CAPACITY DISCHARGE
DINT
CLR.B

ALLOW NEXT 2 INSTRUCTIONS
&TPCNTl

CLEAR· LO BYTE TIMER

BIC.B

@SP,&TPD

SWITCH ACTUAL SENSOR TO.LO

MOV.B

#(TPSSELO*3)+ENA+ENB,&TPCTL

EINT
Wait until EOC (ENl
MLPl

2-184

; Reset flags

; COMMON START TOOK PLACE
1) or overflow error (RC2FG

1)

BIT.B

#RC2FG,&TPCTL

JNZ

MERR

Yes, go to error handling

BIT.B

#EN1,&TPCTL

CIN < Ucomp?

JNZ

MLPl

NO, WAIT

OVerflow (broken sensor)?

The Universal Timer/Pori Module

ENl

=

0: End of Conversion: Store 2 x 8 bit result on MSTACK

Address next sensor, if no one addressed: End reached

L$301

MOV.B

&TPCNT1,MSTACK(R5)

MOV.B

&TPCNT2,MSTACK+l(R5)

STORE RESULT ON STACK

INCD

R5

ADDRESS NEXT WORD
NEXT OUTPUT TPD.x

HI BYTE

RRA.B

@SP

JNC

MEASLOP

IF C-l: FINISHED

INCD

SP

HOUSEKEEPING: TPDMAX

RET

ERROR HANDLING: ONLY OVERFLOW POSSIBLE (BROKEN SENSOR 7)
OFFFFh IS WRITTEN FOR RESULT AND SUBROUTINE CONTINUED

MERR

1.1

MOV

#OFFFFh,MSTACK(RS)

JMP

L$301

Overflow

Interrupt Handling
If the Universal Timer/Port Module is used as an ADC for applications that need
an accuracy greater than 10 bits, the digital noise generated by the running CPU
has a strong influence on the result. If the flag (EN1) in the hardware register
TPCTL is polled by software for the signal of a completed conversion then the
results are normally different. They show a wide distribution that reflects the
length of the polling loop (Le. the results are concentrated on evenly spaced
numbers with nothing in between). To avoid this effect the CPU is switched off
during the conversion and woken-up at the completion of the conversion by the
ADC interrupt. With this method and adequate hardware, results with much better
accuracy are possible.
The influence of the digital noise is shown in Figure 5. The exponential discharge
curve is relatively flat near the comparator threshold Vth. Therefore noise coming
from the CPU (or other sources of non-wanted noise) can be under the threshold
voltage and terminate the conversion. The result is a timer value tdcw that is too
low. The correct value would be tdcc. The resulting error Ecnv is:
Eenv = tdew - ((lee xl 00
tdee

Where:
tdew
tdcc

Resulting measurement time caused by CPU noise
Correct measurement time

[s1
[s1

Using the MSP430 Universal Timer/Port Module as an Analog-to-Digital Converter

2-185

The Universal Timer/Port Module

Vcm

Vlh

1

--

--1--~-------=::!I'III.J.o=-----

ol-~----~~~~~~
-

Time

Idcc

Figure 5. Noise Influence During Measurement
EXAMPLE: The hardware schematic is shown in Figure 6. Two resistive
temperature sensors are used (RmeasO and Rmeas1) two reference resistors
(RrefO and Rref1) that have the resistance ofthe sensors atthe lower (or upper)
end of the measurement range ar'ld a resistor (Rcharge) that is used only for the
charge-up of the capaCitor (em). This charge resistor is only necessary if the
sensors have low resistance (approximately 100 n.). Otherwise, the reference
resistors can be used for charging.
RrelO

TP.O
TP.1
TP.2

MSP43OX3xx
TP.3
TP.4
CIN.CMPI
Cm

+3V
AGND

Figure 6. Hardware Schematic for Interrupt Example
The example software works with a status byte (MEASSTAT) that defines the
current operation. Normally, this byte is zero, which indicates no activity or after
a complete measurement sequence conversions made. The two reference
resistors and two temperature sensors are measured one after the other; RrefO
first, then RmeasO, then Rmeas1 and finally Rref1.
2-186

The Universal Timer/Port Module

The measured discharge times (a direct measure for the relative resistance) are
placed in successive RAM words starting at label ADCRESULT.
First these RAM words are set to zero (a value impossible as a measurement
result). If an error occurs, the zero value indicates an erroneous result.
The Basic Timer is programmed to 0.5 s interrupt timing. The measurement
sequence is shown in Figure 7. This sequence can be shortened to one reference
resistor and one sensor as well as enlarged up to four sensors and two reference
resistors. It is only necessary to add or delete charging and measurement states
and the accompanying software parts.
The modulation mode of the FLL is switched off during the measurement to have
the exactly same MCLK during all four measurements. Status 9 switches on the
modulation mode again.
The software shown can be used for the MSP430C31 x and MSP430C32x. The
different interrupt enable bits and the different addresses of the interrupt vectors
are used correctly by the definition of the software switch Type. If this switch is
defined as 310, the MSP430C31 x is used; otherwise, the MSP430C32x is used .
.... 0.58 .....
CPUOff_1

(

Measure

NoacUYiIy

e_em

RnoIO

Charge Om

........
Rm....

MOD-'
Measure
Charge Om

Charge Om

R......'

Measure
R",,,

Conver&ions made

I
2

Status 0

3

4

5

7

6

8

9/0

Figure 7. Measurement Sequence
Definitions of the MSP430 hardware
Type

.equ

310

310: MSP43C31x

BTCTL

.equ

040h

Basic Timer: Control Reg.

0: others

BTCNT1

.equ

046h

Counter

BTCNT2

.equ

047h

Counter

BTIE

.equ

OBOh

DIV

.equ

020h

BTCTL: xCLK/256

IP2

.equ

004h

BTCTL: Clock Divider2

IPO

.equ

OOlh

Clock DividerO

SCFQCTL

. egu

052h

FLL Control Register .

MOD

,equ

OaOh

Modulation Bit: 1

CPuoff

.equ

010h

SR: CPU off bit

GIE:

.equ

OOBh

SR: General Intrpt enable

Intrpt Enable

~

off

Using the MSP430 Universal Timer/Port Module as an Analog-to-Digilal Converter

2-187

The UnlvetSBI Timer/Port Module

TPCTL

.equ

04Bh

TPCNTl

.equ

04Ch

TPCNT2

.equ

04Dh

Counter Reg.Hi

TPD

.equ

04Eh

Data Reg.

TPE

.equ

04Fh

Enable Reg.

.if

Type=310

MSP430C3lx?

.equ

004h

ADC: Intrpt Enable Bit

OOSh

MSP430C32x configuration

TPIE

Timer Port: Control Reg.
Counter Reg.Lo

.else
TPIE

.equ
.endi.f

IE2

.equ

OOlh

TPSSEL1

.equ

OSOh

TPSSELO

.equ

040h

ENB

.equ

020h

ENA

.equ

OlOh

Intrpt Enable Byte
Selects clock input (TPCTL)
Selects clock gate (TPCTL)

ENl

.equ

OOSh

Gate for TPCNTx

RC2FG

.equ

004h

Carry of HI counter (TPCTL)

(TPCTL)

RC1FG

.equ

002h

Carry of LO counter (TPCTL)

EN1FG

.equ

OOlh

End of Conversion Flag

B16

.equ

OSOh

Use 16-bit counter (TPD)

RrefO

.equ

OOlh

TP.O: Reference Resistor

RmeasO

.equ

002h

TP.l: SensorO
TP.2: Sensorl

~

Rmeasl

.equ

004h

Rrefl

.equ

OOSh

TP.3: Reference 'Resistor

Rcharge

.equ

OlOh

TP.4: Charge Resistor

RAM Definitions
ADCRESULT

.equ

0200h

MEASSTAT .equ

ADCRESULT+S

; Measurement Status Byte

i

ADC results (4 words)

;-=----======-===---=-==-=======--=--==--======--==----=-=

INIT

2-188

. sect

\\INITIJ',OFOOOh

MOV

#0300h,SP

MOV.B

#DIV+IP2+IPO,&BTCTL

Initialization Section

; Initialize Stack Pointer
i

Basic Timer: 2Hz

The Universal TImer/Port Module
BIS.B

iBTIE, &IE2

Basic Timer Intrpt Enable

CLR.B

&BTCNTI

Clear Basic Timer Regs.

CLR.B

&BTCNT2

CALL

iCLRRAM

Clear RAM

Initialize other Modules

MAINLOOP

Main loop of program

It's time to measure the sensors

MOV.B

#1,MEASSTAT

Activate Measurement

JMP

MEASURE

Go to Measurement Part

Measurement Part: The CPU is switched off to avoid noise
that would falsify the measurements. Interrupt is used

to indicate the. end of conversion (and wake-up the CPU).
The program remains on the NOP until MSTAT9 clears the

CPUoff-bit of the stored SR on
MEASURE

the

stack.

CLR

ADCRESULT

Clear result buffers

CLR

ADCRESULT+2

o

CLR

ADCRESULT+4

CLR

ADCRESULT+6

MOV

#CPUoff+GIE,SR

NOP

indicates error

CPU off, but MCLK on
Wait for end of measurement
Process measured data

Interrupt Handler for the Basic Timer Interrupt: 2Hz

TABLE

PUSH

R5

CALL

#I NCRWTCH

Incr. Watch

MOV.B

MEASSTAT,R5

Calculate Handler

MOV.B

TABLE(R5),R5

Offset for PC

ADD

R5,PC

Add Offset to PC

.BYTE

MSTATO-TABLE

0: No activity

. BYTE

MSTATl-TABLE

1: Charge for RrefO

2 : Measure RrefO

Save Help Register

.BYTE

MSTAT:6-TABLE

. BYTE

MSTATl-TABLE

3 : Charge for RmeasO

. BYTE

MSTAT4-TABLE

4 : Measure RrneasO

. BYTE

MSTATl-TABLE

5 : Charge for Rmeasl

Using the MSP430 Universal TImer/Port Module as an Analog-la-Digital Converter

2-189

The UnlvetBa! TImer/Port Module

MSTATl

MSTAT2

MSTAT4

MSTAT6

MSTAT8

.BYTE

MSTAT6-TABLE

. BYTE

MSTATI-TABLE

7: Charge for Rrefl

. BYTE

MSTAT8-TABLE

8: Measure Rrefl

. BYTE

MSTAT9-TABLE

9: Finished, go on

6: Measure Rmeasl

MOV.B

#B16+Rcharge,&TPD

Charge Cm for 0.5s

MOV.B

tRcharge,&TPE

Use Rcharge

JMP

BT~ET

MOV

tRrefO,R5

Measure RrefO

JMP

MEASCOM

To conunon Part

MOV

#RmeasO,RS

Measure RmeasO

JMP

MEASCOM

To common Part

MOV

#Rmeasl,R5

Measure Rmeasl

JMP

MEASCOM

To common Part

MOV

#Rrefl,R5

Measure Rrefl

MEASCOM BIS.B

#MOD,&SCFQCTL

Switch off FLL Modulation

tSCGO,SR

Loop control of.f

CLR.B

&TPE

TP.x to

MOV.B

tB16,&TPD

TP.x

BIS

LO

HI-Z
(disabled I )

No MCLK for ADC, Clear Flags RC2FG, RCIFG, ENIFG
MOV.B

#TPSSEL1+ENB+ENA,&TPCTL

CLR.B

&TPCNTl

Reset Counter LO

CLR.B

&TPCNT2

Reset Counter HI

BIS.B

R5,&TPE

Enable selected TP.x

MCLK on,

Co~parator

on: Intrpt for Uem < Vth

MOV.B

#TPSSEL1+TPSSELO+ENB+ENA+EN1,&TPCTL

BIS.B

#TPIE,&IE2

BT_RET

INC.B

MEASSTAT

To next sta,tus

MSTATO

POP

R5

If no activity necessary

; Enable ADC Intrpt

RETI

2-190

.-

'.~.

The Universal Timer/Port Module
MSTAT9: Measurements

a~e

completed, CPU is switched on,

MSTAT is set to zero: no activity. FLL loop control on

MSTAT9

BIC

#CPUoff+SCGO, 2 (SP)

; Stored SR on stack

CLR.B

MEASSTAT

No activity

BIC.B

#MOD,&SCFQCTL

Switch on FLL Modulation

JMP

MSTATO

Return

End of Basic Timer Handler

i---------------------------------------------------------Interrupt Handler for the Analog-to-Digital Converter
The results in TPCNTI and TPCNT2 are stored starting at

label ADCRESULT (result for RrefO)
ADC_INT

Check

PUSH

RS

Save Help Register

MOV.B

MEASSTAT,RS

Build offset for results

SUB

#3,RS

Status for RrefO

IN

ADC_F

MEASSTAT < 3: error

for correct result:

If RC2FG

- 1: Overflow of the counter (Rx too high)

If ENl

= 1: False interrupt, conversion not finished

ADC...RET
ADC_F

BIT.B

#RC2FG+ENl,&TPCTL

Error?

JNZ

ADe_RET

Yes, let Oh for error

MOV.B

&TPCNTl,ADCRESULT(RS)

MOV.B

&TPCNT2,ADCRESULT+l (RS)

BIC.B

#TPIE,&IE2

BIC.B

#RC2FG+RCIFG+ENIFG,&TPCTL

POP

R5

; Store result

; Disable ADC Intrpt
; Flags - 0

; Restore RS

RETI
End of Universal Timer/Port Module Handler

;---------------------------------------------------------Interrupt vectors

. sect

'INT_VECTR,OFFE2h

• WORD

BT_INT

.if

Type=310

Basic Timer Vector

Using the MSP430 Universal Timer/Port Module as an Analog-to-DigHal Converter

The UnlvetsSJ Tlmer/Port Module

.sect

'INT_VEC1' ,OF);'EAh ; MSP430C31x

.else

. sect
.end1f
. WORD
.sect
. WORD

'INT_VECl n ,OFFE8h ; Others
ADC_INT
'INT_VEC2H,OFFFEh
INIT

Timer Port Vector (31x)
Reset Vector

1.2 Connection of Long Sensor Lines
If it is a long distance from the MSP430C31x to the sensor (>3Ocm), a shielded
lead between the microcomputer and the sensor is recommended. This gives
protection to the ADC input. Figure 8 shows the schematic. The protection
resistors (Rv/2) need to be included in the calculation and are connected in series
with the sensor.
To protect the measurement against spikes, hum, and other unwanted noise (see
Section 5.3, Signal Averaging. Here are some possibilities for the minimization
of these influences.
Depending on the actual application, the omission of the two resistors (Rv/2) can
give the best results. The relatively low internal resistance of the TP.2 output and
the capacitor alone may get this.
If a .shielded cable is not possible, a twisted cable or a three-core cable should
be used. The unused wire is connected to Vss as shown in Figure 8 with Rsens2.
OV

0-111-.----1

~~QlIIIIII..==~R~V~~~~:~~ TP.O

.\

Shield

MSP430C31x

rJ

No shield, twISted wires
OV

"'V

Figure 8. Connection of Long Sensor Lines

1.3 Grounding
The correct grounding is very important if ADCs with high resolution ari! used.
There are some basic rules that need to be observed.
With the MSP430C31x and the MSP430C33x only the Vss p[n exists as a
common reference point.
1. Use of separate analog and digital ground planes wherever possible. No thin
connections from the battery to VSS pin.
2-192

The Universal TlmflflPort Module

2. The Vss pin is a star point for all O-V connections
3. Battery and capacitor are connected together at this star point. See Figure 9.
4. No common path for analog and digital signals
Rrel

.---r-,.-/ TP.O

_ry Replacement

...

-I---~-"''''''
5V::

J"'"'7""l_-'

TP.1
MS_0C31x
TP.2

__----lOIN

Om

Vss

To other parts

+-----..../1
Tometallization . -_ _ _-.J

Figure 9. Grounding for the Universal Timer/Port ADC

Figure 9 also shows the use of an ac driven power supply. Its Vcc and Vss
terminals are connected where the battery is normally connected. The capacitor
across the MSP430 pins can be smaller when a power supply is used.
If a metallized case is used around the printed-circuit board containing the
MSP430, then it is very important to connect the metallization to the ground
potential (OV) of the board. Otherwise, the performance is worse than without the
metallization.

1.4 Voltage Measurement With the Universal Timer Port/Module
The measurement of a restricted voltage range is also possible with the Universal
Timer/Port Module. Normally a second circuit is used for this purpose.
This solution needs the least hardware effort. This measurement method delivers
a very precise result, if a twa-point calibration-with two voltages at the limits of
the input voltage range-is used. A realized application delivers the following
results:
• Accuracy for an input voltage between +8 V and +16 V better than ±10-3
(±O.1 %). A two-point calibration was used.
• Temperature deviation between -20°C and +30·C better than 45 ppm/·C
(worst case)

1.4.1 Measurement Principle
The Universal TImer/Port Module of the MSP430 family allows the measurement
of a restricted voltage range. Normally a second circuit (analog-ta-digital
converter) is necessary for this task. The measurement principle is explained with
the Circuitry shown in Figure 10.
Using the MSP430 Universal TImerlPort Module as an Analog-to-DIg~a1 Converter

2-193

The Universal Timer/Port Module

For the voltage measurement with the MSP430x3xx family, the comparator input
CMPI-with its well defined threshold voltage 0.25 x Vcc-is used and not the
analog input CIN with its Schmitt-Trigger characteristic. The comparator input
CMPI has different names with the different MSP430 family members. This is due
to the fact that it normally uses the same pin as the highest numbered LCD select
line.
The LCD pin is switched from the select function to the comparator function by
a control bit located in the Universal Timer/Port Module (CPON, TPD.6, address
04Eh).
Figure 10 shows a voltage measurement circuit with two different input stages for
the input voltage Vmeas:
• Input voltages with a relatively low impedance are connected directly to the
input VmeasO. The input impedance of the circuitry is approximately 106 Ohm
(see example Figure 12).
• Input voltages with a very high impedance are connected to the non-inverting
input of the operational amplifier (Vmeas1) with its input impedance of
approximately 109 Ohm.
Only one of the two input stages described in Figure 10 can be used. If more than
one input voltage. is to be measured, than one of the circuits shown later is to be
used.
32kHz

o
Vmeaso

Vee

+5V

TP.3
R1

Vmeas1 :. -

R1.~~.,
V
c

~ ~

•

MSP430

+-.:::.:---......-1 CMPI

R2

v..

--+-----~--~--------~

Figure 10. Voltage Measurement With the Universal Timer/Port Module
The voltage range for the Input voltage Vin (seen at the input CMPI), can be
measured with the circuitry shown previously is restricted to
Vrif(com)1II4X

< Yin ::;; Vee

(1)

This means for a supply voltage, Vee - +5V, voltages between 0,26 x 5 V = 1.3
V and +5 V can be measured.
With the resistor divider consisting of the two resistors R1 and R2, a nominal input
voltage range for VmeasO results in
2-194

The Universal Timer/Port Module

RI + R2
VrefX--- < VmeasO
R2

.,
RI + R2
.ccx--R2

:5;

(2)

The sequence for the measurement of the voltage Vmeas is given in the
following. The numbers used for the sequence correspond to the numbers of the
Conversion States shown in Figure 11. The software is contained in this chapter.
VCm

1I

I

5

3

I

4

I

v""

I

1

Conversion Slates
HighVmeas

Vin
Medium Vrneas
LowVmeas

v,.,

Vin • Vmeas x R21(Rl +R2)

Figure 11. Voltage Measurement
1. The output TP.3 is switched to Hi-Z. The measurement capacitor Cm charges
to the divided input voltage Vmeas during the time tchv between two voltage
measurements.
2. The voltage measurement starts: TP.3 is switched to 0 V and discharges Cm.
At the same time, the measurement of the time tmeas starts with the 16-bit
counter ofthe Universal Timer/Port Module. When the threshold voltage Vref
is reached, the time measurement is stopped automatically.
3. The measured time tmeas is stored.
4. TP.3 is switched to Vee and charges the capacitor Cm to the supply voltage
Vcc. The needed time tchvcc ranges from 5t to 7t dependent on the desired
aeeuracy.
(t ~ R4 x Cm)
5. The reference measurement starts: TP.3 is switched to 0 V and discharges
Cm. At the same time, the measurement of the time !vee starts with the 16-bit
counter. When the threshold voltage Vref is reached, the time measurement
is stopped automatically.
6. The measured time tvee is stored.

NOTE: All formulas only show measured time intervals. The
conversion of these time intervals tx into the measured counts nx
can be made with the formula:

nx

tx = - -

/MCLK

Where fMCLK represents the CPU frequency MCLK of the MSP430.
The voltage Vmeas can be calculated with the two measured time intervals tmeas
and !vee using the following formula:
Using the MSP430 Universal Timer/Port Module as an Analog-ta-Digital Converter

2-195

The Universal Tlmer/Port Module

tmeas- wee

Rl+R2
VeeX---xe
R2

Vmeas

't

Where:
Vmeas Input voltage to be measured
Vcc Supply voltage of the MSP430 (used for reference)
R1,R2 Input resistor divider at input CMPI
tmeas Discharge time of the divided Vmeas until Vref is reached
tvee Discharge time from Vee to Vref
't
Time constant of the discharge circuit ('t .. R4 x Cm)
Vref Threshold voltage of the comparator input CMPI
tconv Time between two complete voltage measurements

(3)

[V]

M
[0]
[s]
[s1
[s]

M
[s1

To get a constant value for the value 't, an expensive, highly stable capacitor Cm
is necessary. To avoid this capacitor, the value 't of the equation (3) is substituted.
From the equation (4) for the discharge of the capacitor Cm
tvee

Vref = Vee
't

X

e

(4)

't

is calculated:
t

= .

tvee

Vee

InVrej

where

Vee =4
Vref

(5)

Inserted into equation (3) this leads to:

Rl + R2
tmeas-'-tvee X In Vee
Vmeas = Veex---xe tvee
Vret
R2

(6)

With equation 6, Vmeas is calculated. Equation 6 is also used with the software
example shown in Section 1.4.4.1.
For the capacitor Cm used for the voltage measurement, it is only important, that
it owns a constant or a very high isolation resistance. The isolation resistor of the
capacitor Cm is connected in parallel with the resistor R2 and changes the
resistor ratio (e.g. due to temperature).
Equation 6 shows the dependence of the voltage measurement to the supply
voltage Vcc (which is the reference), the threshold voltage Vref, the accuracy of
the resistors R1 and R2 and the temperature drift of these values. To get a
measurement aeeuracy of ±1 % for Vmeas without calibration, the following
basics are necessary:
• Stable supply voltage Vee: Vee needs to be within ±25 rriv for the defined
temperature range. The actual value of Vee does not matter, if a two-point
calibration is used.
2-196

The Universel Timer/Port Module

•

•
•

Input CMPI is used for the comparator input: the relatively good defined
threshold voltage Vref (0.25 x Vcc) allows better results than the normal
Schmitt-Trigger input CIN with its large tolerances for the threshold voltages.
Temperature drift of the resistor divider maximum ±SO ppm/oC
Sufficient charge-up times for the measurement capacitor Cm:
- For an accuracy of one per cent approximately 5't are necessary (e5 =
148,41)
- For an accuracy of 0.1 % approximately 7T. are necessary (e 7 = 1096.63)

If a two-point calibration is used, the calculated values for slope and offset are
stored in an external EEPROM, or if the battery is connected continuously to the
MSP430 system, they are stored in the RAM.

1.4.2 Resolution of the Measurement
The resolution for one counter step nmeas of the voltage measurement is:

dVmeas
--=
dnmeaa

Vmeas

Vmeas
R4 x Cmx jMCLK

't X jMCLK

(7)

This means for the circuit shown in Figure 12 (worst case) (Vmeas = Vmeasmax):
dVmeas
dTlnU!aa

18

3

---:;-----;:--------6 = 2.7 x 1047 X 103 x47x10-9 x 3xlO

The resolution is for the worst case 2.7 mV for Vaccu = 18 V, Cm = 47 nF, R4 =
47 kO, fMCLK = 3 MHz. This equals an analog-to-digital converter with a bit length
a of:

18V
a = l d - - = 12,703

(8)

2,7mV

(Id =1092) The previous result means, the resolution ofthis circuit ranges between
a 12-bit and a 13-bit analog-to-digital converter.
For the interesting voltage range at the input CMPI (Vref to Vee) the non-iinear
characteristic of the exponential function can be substituted by a hyperbola. This
method has the advantage of no time-consuming exponential function, only one
division:
Vmeas

A

------+C
(tmeas- tvcc) + B

(9)

The values for A, B, and C can be determined by the solution of three equations
or with a PC-software program like MATHCAD.
For the calculation of all of the previous formulas, the MSP430 floating point
package FPP4 is ideally suited. The package contains all necessary functions
like the exponential and the logarithm function. An example of its use is given in
Section 2.2.4.4.1.
Using the MSP430 Universal Timer/Port Module as an Analog-to-Digital Converter

2-197

The Universal Timer/Port Module

1.4.3 Measurement Timing
With the formulas shown previously, the worst case time interval tconv for a
complete voltage measurement can be calculated.
This is the time interval that determines the highest repetition rate for a complete
voltage measurement. The time interval tconv is the sum of all time intervals that
are shown in Figure 11.
(10)

tconv = tchv + tmeas + tchvcc + tvcc

With the values that determine the time intervals of equation 10, the worst case
value for the complete measurement time tconv can be calculated. The accuracy
is assumed to be 1%. If the accuracy needs to be higher, then the In100 in
equation 11 must be replaced by the .logarithm of the desired accuracy (e.g. by
In 1000 for 0.1 %). The time tmeas is assumed to be the maximum one, this means
forVin = Vcc

tconv = IniOO x Cmx RilIR2 +t

X

Vcc
Vcc
In-if+t x IniOO +t x In" if
Vre
.re

(11 )

With the components of Figure 12 (right circuit), the time interval tconv between
two complete voltage measurements is:

tconv = Cmx(lniOOxRiIIR2+2xR4xln4+lnlOOxR4)

(12)

tconv = O,155s
If an accuracy of 0.1 % is used (10-3), the time interval tconv gets 233 ms. With
a modification of the values for R1, R2, R4, and em, the time interval between
two complete measurements can be greatly changed. The component
calculation of Figure 12 was made for a high-precision voltage measurement.
The values of the components can be changed if the accuracy needs are less
important.

1.4.4 Applications
This section shows how to connect different voltage sources to the Universal
Timer/Port Module. Dependent on the structure of the external voltage source
different hardware configurations are necessary.
2-198

The Universal nmer/Port Module

1.4.4.1

Voltage Measurement

Figure 12 shows two circuits for the voltage measurement of a 12-V voHage
source. The voHage reference is-like with all other circuits too-the supply
vOltage Vcc. The supply voltage can be between +3 V and +5 V. If the supply
voltage is changed from +5V, only resistor Rl needs to be modified.
Two different circuits are shown. The input voltage Vmeas has different influence
during the conversion.
• For the right hand circuit in Figure 12, the input voltage Vmeas also shows
during the reference measurement with Vee a small influence (approximately
R4/Rl here)
• Forthe left hand circuit, the output TP.2 isolates the aeeumulatorvoltage from
the reference measurement. TP.2 is always switched the same way, similar
to TP.3 (0 V, +5 V, Hi-Z). After the charge of Cm the input voHage does not
have an influence on the conversion.
Vmeas (7 -18V)

Vmeas (7 -18y)

Vee 1='----\--;
TP.2 ........- -......
TP.3
MSP430

Ves

Vee

1-'-"''----\--4

TP.3
MSP430

Vss

--~--~~-~--~-w
Voltage Measurement without influence by Vmaas

Vollag.M.....roment

Figure 12. Voltage Measurement of a Voltage Source

Software Example: the voltage calculation is mad~ for the right-hand circuit
shown in Figure 12. The measurements for tmeas and tvee are made as
described previously. Equation 6 is implemented in software.
For the calculations the MSP430 floating point package FPP4 is used (32-bit
format). All subroutine calls call FPP4 functions.
RAM word ADCref contains the 16-bit resuH of the Vee measurement tvee
RAM word ADCbatt contains the 16-bit result of the Vmeas measurement tmeas
Both time intervals are measured with MCLK Cycles.
Voltage measurement of Vmeas:
Vrneas
Where
Input:

= factor * exp«(trneas/tvcc) -1)* In(Vcc/Vref))
factor

= Vce

ADCref:

x (R1+R2)/R2

Measured reference value Vee: tvcc
Using the MSP430 Universallimer/Port Module as an Analog-to-Dlgltal Converter

2-199

The Unlv8f8a1 TImer/Port Module
, ADCbatt:
output:

Measured voltage value: tmeas

Act. Stack

Calc_VoltSUB
MOV

Calculated voltage vmeas:

@SP

U,SP

Reserve stack

#ADCbatt, RPARG

ADC value of-voltage tmeas

CALL

#CNVJjINl6U

Convert to unsigned number

MOV

@RPRES+,x

Store result to x. MSBs

MOV

@RPRES+,x+2

LSBs

MOV

#ADCref,RPARG

ADC value of vcc tvcc

CALL

#CNV_BINl6U

Convert to unsigned number

MOV

#x,RPRES

Address trneas

CALL

#FLTJ)IV

trneas/tvcc

IN

CalC_Error

Error

RPARG

MOV

#FL~r1,

CALL

#FLT_SUB

(trneas/tvcc) - 1.0

MOV

#FLTLN4,RPARG

Address Ln(Vcc/Vref)

CALL

#FLT_MUL

[(troeas/tvcc)-l] * In(Vcc/Vref)

CALL

#FLTJlXP

exp[(troeas/tvcc) - l)*ln4]

Address 1.0

IN

Calc_Error

MOV

#factor, RPARG

Address vcc x (Rl+R2)/R2

CALL

#FLTjlUL

Vrneas

factor' exp[ ... ]

~

Correction of Vmeas with calculated slope and offset

vmeas'

= fadtor*exp[(troeas/tvcc)-1)*ln4]*slope + offset
MOV

#Slope, RPARG

CALL

#FLT_MUL

vroeas- .. slope

MOV

#Offset, RPARG

Address offset

CALL

#FLT_ADD

Vmeas'

MOV

@RPRES+,6(SP)

Corrected vrneas on Stack

MOV

@RPRES+,8(SP)

LSBs

ADD

#4,SP

VIneas

Return

Calculation error (N -

2-,200

=

Release stack

RET

CalC_Error MOV

Address slope

1

after return): FFFF,FFFF result

#OFFFFh,6(SP)

MOV

#OFFFFh,8(SP)

ADD

#4,SP

Correct stack

• slope + offset

The Universal Tlmer/Port Module
SETN

set N-bit for error indication

RET

Return with N - 1

factor describes supply voltage and resistor·divider
factor
,FLTLN4
FLTl

SV. (3,OM+820k)/820k

.float 23.292683
.float 1.38629436

1n Vcc/Vref.

. float 1.0

Constant 1. 0

(nom. In 4.0)

1.4.4.2 Current Measurement
Current that nows through a shunt resistor can also be measured with the
Universal Timer/Port Module. The generated voltages are small, due to the
normally low resistance of the shunt (this is because of the generated power 12
x Rshunt). The voltage across the shunt is not divided by a resistor divider to have
the full resolution.
Figure 13 shows the circuit for the current measurement. The voltage across the
shunt resistor ranges from -0.3 V to Vref (Vref is 0,25 x Vee for the MSP430). The
value -0.3 V is the most negative voltage that is allowed for an MSP430 input.
To be able to also measure currents or voltages around the zero point (0 V), an
inversion of the measurement method shown previously is necessary: The
capacitor Cm is discharged to the voltage to be measured respective to the
potential 0 V. Afterwards Cm is charged. During the charge-up, the time interval
is measured until the comparator threshold Vref. is again reached. This
measurement method shows a smaller resolution than the method shown
previously-due to the smaller available voltage range for the charge-up-but is
able to also measure voltages around the zero point.

o

32kHz

Rl

~

Imeas

TP.O
MSP430
CMPI

Rl »R2

1 - - - - -..
Cm

Rshunt

Vss

---.-------------~--------~-OV

Figure 13. Circuit for the Current Measurement
Figure 14 shows the voltage at the capaCitor Cm during the measurement of two
currents: VinO is a positive one, Vin1 is a negative current. As described before,
the measured time interval tvcc is used for reference purposes. The supply
voltage Vee is measured. In the previous circuitry, the voltage curve show the
influence of the state of TP.O (Vss, Vcc, Hi-Z). The equation for the calculation of
the current Imeas is:
Using the MSP430 Universal TImer/Port Module as an Analog-to-DigHaI Converter

2-201

The Universal Timer/Port Module
tmeas

Imeas

1
--xln
---x(Vcc+(Vref-Vcc)xe /Vee
Rshunt

Vrq
(1--»
Vee

(13)

Equation 13 looks complicated but it can be substituted by the form
tmeas x 0,2876821

lmeas = a+bxe

/Vee

where a and b are constants, given by the values of the supply voltage and the
shunt resistor.

""

van t

I

t

f:

~.v !.v

V ref

VinO -P---f-

o ;---~----+---~~----~----~--ff-------r---~
Vin1 -/----+------i----+.----t-----...300-r

Vin .. Imeas x Rshunt

tchvx .. tchargex

tmx .. tmeasx

Figure 14. Current Measurement
The circuit shown in Figure 13 owns the advantage that the measurement value
that represents the voltage 0 V (Vss) is known exactly. It is the value tvcc. This
means no additional measurements are necessary to know the zero point (Imeas
.. 0) of the circuit.
The resolution of the current measurement can be calculated with equation 14.
For the current Imeas, the difference for the counter steps Anin results in:

llnin =

't X

/MeLK x (In (1 _ Vref - Imeasx Rshunt )_ In (1 _ Vref»
Vcc- Imeasx Rshunt
Vee

(14)

The first logarithm function shows the counter steps for the current Imeas, the
second one shows the counter steps for a zero current.
2-202

The Un/versal Timer/Port Module

With R2 = 47 \<.Q, Cm = 33 nF ('1: - 1.55 ms) and fMCLK = 3.3 MHz, equation 14
results in 1036 counter steps per volt. This means, if 1A flows through a shunt
having a resistance of 0.1 n, then the resolution is approximately 10 mA.

1.5 Temperature Calculation Example
The temperature of an NTC sensor is calculated out of two time measurements:
• The time for the sensor Rsens-in parallel with the reference resistor Rref for
linearization-to reach the lower threshold voltage VT- of the input CIN
• The time for the reference resistor alone to reach VT- of the input CIN
The measurement software is contained in Section 2.2.1.
The reference resistor Rsens is used three ways:
• As a reference for the measurement
• For the charge-up of the capacitor Cm before the measurement (eventually
in parallel with the sensor for fastening)
• For the linearization of the sensor Rsens (this function defines the resistor
Rre!)

o

32kHz

....-----1 TP.O
TP.1

Vee

+5V

Are!
10k

MSP430
L--4___--I CIN

Cm
Vss

---~----~----w

Figure 15. Temperature Measurement
EXAMPLE: the calculation of the sensor temperature for the hardware shown in
Figure 15 is given in the following. The Floating Point Package is used for the
calculations. The sensor characteristic is described in table NTC TAB. For
sensors with another characteristics only the sensor resistances at thenecessary
temperatures need to be changed.
Temperature Calculation SW for Timer/Port ADC

Input: ADCref
ADCsens
Output:

contains tref (MCLK cycles for Rref alone)
contains tsens (MCLK cycles for Rsensl IRref)
Temperature on TOS (C)

CALC_TEMP SUB

#FPL,SP

Free work space

MOV

#ADCsens, RPARG

tsens

CALL

#CNV_BIN16U

Convert tsens to FP (NTC)

(RrefIIRsens)

Using the MSP430 Universal TImer/Port Module as an Analog-to-DigRaI Converter

2-203

The Universal Timer/Port Module

CTLOOP

MOV

@RPARG+,FPL+2(SP)

MOV

@RPARG+,FPL+4(SP)

To result area

MOV

tADCref,RPARG

tref

CALL

#CNV~IN16U

Convert tref to FP

(Rref)

ADD

#FPL+2, RPARG

Point to tsens

CALL

#FLTJlIV

tref/tsens (Rref/RrefIIRsens)

MOV

@RPARG+,FPL+2(SP)

Store to result area

MOV

@RPARG+,FPL+4(SP)

MOV

tNTC_TAB,R15

store pointer to NTC_TAB

MOV

R15,RPARG

Find lower margin

CALL

#FLT_CMP

tref/tsens - tab-value

JHS

CTCALC

Ratio> tab-value

ADD

#FPL,Rl5

To next ratio in table

CMF

#NTCTEND,Rl5

End of table reaohed?

JLO

CTLOOP

No. If yes use last values

Linear approximation is used between the two temperatures

CTCALC

2-204

PUSH

R15

Save pOinter to lower ratio

MOV

@SP,4(SP)

New work area below pointer

MOV

R15,RPARG

MOV

SP,RPRES

ADD

#FPL+4,RPRES

CALL

tFLT_SUB

tref/tsens - (lower ratio)

MOV

#FLT5, RpARG

To 5.0

CALL

#FLT....MUL

5. 0* (tref/tsens-lower ratio)

SUB

#FPL,SP

MOV

2*FPL(SP),RPRES

MOV

RPRES, RPARG

Point to tref/tsens

Address lower ratio

SUB

tFPL,RPRES

Address upper ratio

CALL

'FLT_SUB

Delta ratio

ADD

#FPL,RPRES

to 5 x ...

CALL

#FLTJlIV

5xO/delta ratio

MOV

@RPARG+,FPL(SP)

MOV

@RPARG+,FPL+2(SP)

MOV

2*FPL(SP),RPARG

Pointer to lower ratio

SUB

#NTC_TAB,RPARG

Delta start of table +90C

RRA

RPARG

Divide by 4: .FLOAT length

RRA

RPARG

PUSH

RPARG

The Universal Timer/Port Module
MOV

SP,RPARG

CALL

#CNV_BIN16U

MOV

#FLT5,RPARG

CALL

#FLT_MlIL

x SC

MOV

#FLT90,RPRES

To +90C

Calculate offset (C)

CALL

#FLT_SUB

90C - lower temperature

ADD

#FPL+2,RPARG

To delta within 5C ratios
minus offset - - 25 deg

CALL

#FLT....ADD

MOV

#FLT25,RPARG

CALL

#FLT_SUB

MOV

@SP+,2*FPL+4(SP)

MOV

@SP+,2*FPL+4(SP)

ADD

#2*FPL,SP

RET

Sensor temperature to TOS

Free stack
Result on TOS

FLT5

· float

5.0

Delta T for table NTC_TAB

FLT90

· float

90.0

T.emp. at table start NTC_TAB

FLT25

. float

25.0

offset -25 deg

The NTC table contains the ratios for the temperature range
-40C to +90C. Table values are for the ratio:
Rref/(RrefIIRsens) - 1.0 + Rref/Rsens.

Rref - 10kOhm

The sensor resistance Rsens is shown after the temperature
Temp
NTC_TAB

Rsens

· float

1.0+1.OE4/0.9B12E3

+95C: 0.9B120

. float

1.0+l.0E4/0.1l2BE4

+90C: 1.12BkO

. float

1.0+1.OE4/0.l301E4

+B5C: 1. 30lkO

· float

1.0+l.0E4/0.1507E4

+BOC: 1.s07k0

· float

1.O+1.0E4/0.1751E4

+75C: 1.75lkO
+70C: 2.043kO

· float

1.0+1.OE4/0.2043E4

· float

1.O+1.OE4/0.2393E4

+65C: 2.393kO

· float

1.O+1.OE4/0.28l6E4

+60C: 2.8l6kO
+55C: 3.327kO

· float

1.O+1.0E4/0.3327E4

.·float

1.O+1.0E4/0.3949E4

+50C: 3.949kO

· float

1.0+1.0E4/0.470BE4

+45C: 4.70BkO

· float

1.0+1.0E4/0.564lE4

+40C: 5.641kO

· float

1.O+1.OE4/0.6792E4

+35C: 6.792kO

· float

1.O+1.OE4/0.B2l9E4

+30C: B.219kO

· float

1.O+1.OE4/l.0000E4

+25C: 10.OOkO

· float

1.O+1.OE4/1.223E4

+20C: l2.23kO

Using the MSP430 Universal T1merlPort Module as an Analog-to-DigHal Converter

2-205

The Universal Timer/Pon Module

NTCTEND

. float
. float
. float
. float
. float
. float
. float
. float
. float
. float
. float
. float
. float
. float

+15C:
+10C:
+ 5C:
OC:
- 5C:
-10C:
-15C:
-20C:
-25C:
-30C:
-35C:
-40C:
-45C:
-SOC:

1. O+LPE4/1. 505E4
1.0+1.0E4/1.S62E4
1.0+1.0E4/2.319E4
1.0+l.OE4/2.905E4
1.0+1.0E4/3.663E4
1.0+l.0E4/4.650E4
1.0+1.0E4/5.945E4
1.0+1.0E4/7.654E4
1.0+1.0E4/9.930E4
1.0+l.0E4/12.9SE4
1.0+1.0E4/17.11E4
1.0+l.0E4/22.73E4
1.0+1.0E4/30.47E4
1.0+1.0E4/41.21E4

15.05kO
lS.62kO
23.19kCl
29.05kO
36.63kO
46.50kO
59.45kO
76.54kO
99.30kO
129. SkO
171.1kO
227.3kCl
304.7kO
412.1kO

1.6 Measurement of the Position of a Potentiometer
The relative position of a potentiometer can be measured with the hardware
shown in Figure 16. Independent of the accuracy of the potentiometer itself and
the resistor Rv the relative position can be found with three measurements. The
measurement of the two maximum positions allows a secure decision if these
positions are reached or not. The measurements are:
1. Measurement of (Rpoti + Rv) with TP.3
2. Measurement of (Prel x Rpoti + Rv) with TP.4
3. Measurement of (Rv)with TP.5. Rv is necessary because a zero resistance
cannot be measured with the Universal TImer/Port Module.

0
+5V

32kHz

Vee

TP.O
TP.1
TP.2
TP.3
TP.4
ROm

RUn

Rnto

Rref

TP.5
MSP430

CIN
Vss

--~~--------~------------w

Figure 16. Measurement of a Potentiometer's Position
The formula to get the relative position Prel'out of the three measurements is:

Prel =
2-206

t4-tS
t3-tS

The Universal Timer/Port Module

Where:
Prel
t3
t4
t5

Relative position of the moving arm (0 to 1)
Result of the time measurement with TP.3 (Rpoti + Rv)
[sl
Result of the time measurement with TPA (Prel x Rpoti + Rv) [sl
Result of the time measurement with TP.5 (Rv)
[sl

1.7 Measurement of Sensors With Low Resistance
Figure 17 shows a hardware solution for low-resistive sensors « 1 1<0). With
these sensors, the ROSon of the TP-ports (166 0 to 333 0) plays a big role. To
minimize this influence, NPN-transistors or FETs with Iowan-state resistance can
be used for the switching of the sensors and reference resistors: The software
is the same one as shown in Ihe example in Section 1, only the switching of the
TP-ports TP.O to TP.3 needs to be changed:
• Sensor or reference resistor off: TP.x is switched to Vss
• Sensor or reference resistor on: TP.x is switched to Vcc

Om

Figure 17. Hardware Schematic for Low-Resistive Sensors
Another way to eliminate the influence of the ROSon of the TP-ports is the use
of a multiplexer with very Iowan-state resistance. The multiplexer shown in
Figure 18 has a typical on-state resistance of only 5 n This is small compared
to the resistance of nearly all sensors.

Using the MSP430 Universal TImer/Port Module as an Analog-to-Digttal Converter

2-207

The Universal TImer/Pori Module

TP.D...TP.3

MSP430x3xx

1.

t--L_j------t-i

TP.4

+---------1-1

CINlCMPI

em

Vas

Vee

ov

~v

Figure 18. Solution With a Low-R'eslstlve Multiplexer
1.8 Measurement of CapacItance
Figure 19. shows the hardware for the measurement of a capacitor Cx using a
reference capacitor Cref. With the TP.1 output, the capacitor Cref is connected
to Vss during the reference measurement, with TP.2 the unknown capacitor Cx
is switched to Vss during the Cx measurement. The TP-ports are otherwise
switched to Hi-Z.

o
TP.D

32kHz

Vee

+3V/SV

. - - - -.....----1 CIN.CMPI

TP.l
' - - - . . . . . - - - - \ TP.2

Vas
DV

Figure 19. Measurement of a Capacitor Cx
The equation that describes the discharge curve is:
lref

Vth

This leads to:
2-208

=

Vcc'Xe-(cref+C')XR

IX

=

VccXe (Cx+C.)xR

External Ana/og-To-Digital Converlers

ex

=

~x(eref+es)-es
tref

Where:
Vth

Vee
Iref
tx

tc
Cx
Cref
Cs

Threshold voltage of the comparator
Supply voltage of the MSP430
Discharge time with Ihe reference capacitor Cref
Discharge time with the unknown capacitor Cx
Charge time for the capacitors
Capacitor to be measured
Reference capacitor
Circuit capacity (may be omitted)

M
M
[s]
[s]
[s]

[F]
[F]
[F]

The voltage at the capacitors Cx and Cre! during the measurement is shown in
Figure 20.

Vee4-~--~------------~~--

Vth

--I----+-----~I..o-----j'__-+_----..-:::!"""'__

O~----~----~--~----+_--------+_----~--

Figure 20. Timing for the Capacity Measurement

2 External Analog-To-Digital Converters
2.1

External Analog-To-Digital Converter les
The MSP430 can also use external ADCs. Figure 21 illustrates how to connect
three different ADCs to the MSP430. This is especially important for MSP430s
without an internal ADC.
Some low-cost possibilities are shown for the connection of 8-bit ADCs to the
MSP430C31x and MSP430C33x.

Using the MSP430 Universal Timer/Port Module as an Analog-to-DigHal Converter

2-209

External Analog-To-Digital Converters

rlDIf

Z

TP.x,Oyy
TP.5.PO.x
XBUF "kit<
TemperatureClrcult

R~~
Rrel

.4~'n
.~

,TXO

RCV

TP.O
TP.1

Vee
TP.II,O'I'J
TP.x. Oyy

TP.x.Oyy
MSP430

CIN

PO.'
PO.1

...

-

--

liS

Vee

IN.

CIk

IN-

00

[GNO

Tl.COIIalx

Vas PO.S

Vlf-ConverIer~

REF

L~
r--

r-

Vee

J

CHO

CIk-

CHl

00

-

-

,[GNO
01I
TLC0832x

OV
-Yin

OV YO llVI

L~

-

VO

Vee

CHO

Ok

CHl

00

; - - CH2

II

n·

01
CH3 AGND
DGND REF

f-

r--

~

TL.CIIII34x

Figure 21. Analog-to-Dlgital Conversion With External ADCs

At the right-hand side three different 8-bit ADCs are connected to the MSP430.
An 8-channel version TLC0838x with the same kind of control is also available.
Voltages higher than +5 V can be connected to the ADC inputs via resistor
dividers or operational amplifiers.
Due to the interrupt capability of all PortO inputs, voltage/frequency converters
(V/f converters) can also be connected very easily. This is shown at input PO.3.
For the time base one of the MSP430 timers is used.
The chapter "Electricity Meters" contains an application that uses an external .
16-bitADC.

2.2

R12R Analog-To-Digital Converter
Due to its many II0s the MSP430C33x can use the Rl2R method, which allows
strongly monotone and accurate analog-to-digital converters. Figure 22 shows
an 8-bit ADC with four analog inputs. For the conversion, the successive
approximation method is used. This means, that after n approximations-n
equals the number of implemented bits-the conversion is complete.
If only one analog input is needed, the multiplexer can be omitted.
The MSP430C31x family can use the Rl2R method also if enough outputs are
available (e.g. the O-outputs if no LCD is used) (idea from F. KirchmeierITlD).

2-210

External Analog-To-Digital Converters

MSB

LSB
P4.7
P4.n
P4.2
P4.1
P4.0

MSP430C33x

OV
R

PO.7

po.•
Vee

V••

+5V

OV

'2
VlnO _ Vln1 __
Vin2. _
Vin3 __

Figure 22. R/2R Method for Analog-to-Digltal Conversion

Using Ihe MSP430 Universal TImer/Port Module as an Analog-Io-Digital Converter

2-211

External Anatog.;To-Dlgltal Convarters

2-212

Chapter 3

Hardware Applications

3-1

·3.1

110 Port Usage

The each I/O of PortO, Port1, and Port2 has interrupt capability for the leading
edge and trailing edge of an input signal. This has the following advantages:

o
o

3.1.1

More than one interrupt input is available
Eight resp. 24 external events can wake-up from Low Power
Modes 3 or4

o

No glue logic is necessary for most applications: all inputs can be observed without the need of gates connecting them to a Single interrupt
input.

o
o

Wake-up is possible out of any input state (high or low)
Due to the edge-triggered characteristic of the interrupts, no external
switch-off logic is necessary for long-lasting input signals, therefore no
multiple interrupt is possible therefore.

General Usage
Six peripheral registers controiing the activities of the I/O-PortO are shown in
Table~1.

Table 3-1. II00PoriO Registers
Register
Input register

Usage
Signals at 110 terminals

state After Reset
Signals at 110 terminals

Output register

Content of output buffer

Unchanged

Direction register

0: Input 1: Output
0: No Interrupt pending
1: Interrupt pending
0: Low to high causes Interrupt
1: High to low causes Interrupt
0: Disabled
1: Enabled

Interrupt flags
Interrupt edges

Interrupt enable

3-2

Reset to input direction
Set to 0
Unchanged

Set to 0

The interrupt vectors, flags and peripheral addresses of I/O-port 0 are shown
in Table 3-2.

Table 3-2. Ilo-PoriO Hardware Addresses
Name
Input Register
Output Register
Direction Register
Interrupt Flags

Interrupt Edges
Interrupt Enable

Mnemonic
POIN
POOUT

Address
010h

011h

Contents
POIN.7 ... POIN.O
POOUT.7 ... POOUT.O

PODIR

012h

POIFG
IFG1.3
IFG1.2

013h
002h
002h

PODIR.7 ... PODIR.O
POIFG.7 ... POIFG.2

POlES

014h

POIES.7 ... POIES.O

POlE

015h

POIE.7 ... POIE.2

IE1.3

OOOh

IE1.2

OOOh

POIE.1
POIE.O

POIFG.1
POIFG.O

Vector

-

OFFEOh
OFFF8h
OFFFAh

The other I/O-Ports are organized the same way except the following items:

o

Port1 and Port2 contain eight equal II0s, the special hardware for bits 0
and 1 is not implemented. Additionally, the ports have two function select
registers, P1 SEl and P2SEl •

o

Port3 and Port4 do not have interrupt capability and registers P31FG,
P41FG, P31ES, P41ES, P31E and P41E do not exist. Additionally, the ports
have two function select registers P3SEl and P4SEL. These registers determine if the normalllO-Port function is selected (PxSEL.y = 0) or if the
terminal Is used for a second function (PxSEL.y =1) (see Table 3-3).

The MSP430C33x uses the two function select registers P3SEl and P4SEl
for the following purposes:

o
o

P3SEL.y =1: The limer_A I/O functions are selected (see Table 3-3)
P4SEL.y = 1: The USART functions are selected (see the MSP430x33x
Data Sheet, SLAS163)

Hardware Applications

3-3

Table 3-3. TimecA Ilo-Port Selection
P3$EL.y= 1
Compare Mode

P3SEL.y=O

P3SEL.y= 1
Capture Mode

Port 110 P3.0

Port I/O P3.0

Port 110 P3.1

Port I/O P3.1

Port 110 P3.0
Port 110 P3.1

Port 110 P3.2

Timer Clock Input TACLK

Timer Clock Input TACLK

Port 110 P3.3

Output TAO

Capture input CCIOA

Port 110 P3.4

Output TA1

Capture input CCI1A

Port VO P3.5

Output TA2

Capture input CCI2A

Port 110 P3.6

Output TA3

Capture input CCI3A

Port 110 P3.7

Output TM

Capture input CCI4A

Example 3-1. Using TimecA in the MSP430C33x System

An MSP430C33x system uses the limecA. The Capture/Compare
Blocks are used as follows:

a
a
o
o

An external clock frequency is used: input at terminal TACLK (P3.2)
Capture/Compare Block 0: outputs a rectangular Signal at terminal TAO
(P3.3)
Capture/Compare Block 1: outputs a PWM signal at terminal TA 1 (P3A)
CaptureiCompare Block 2: captures the input signal atterminalTA2 (P3.5)
~.

To initialize Port3 for the previous functions the following code line needs to
be inserted into the software (for hardware definitions see Section 6.3, TimeeA):
MOV.B

#TA2+TA1+TAO+TACLK,&P3SEL; Initialize Timer I/Os

Example 3-2. MSP430C33x System uses the USART Hardware for SCI (UART)

A MSP430C33x system uses the USART hardware for SCI (UART). To initialize terminal P4.7 as URXD and terminal P4.6 as UTXD the following code is
. used:
MOV.B

3-4

#URXD+UTXD,&P4SEL

; Initialize SCI l/Os

Example 3-3. The I/O-ports PO.O to PO.3 are used for input only.
The I/O-ports PO.O to PO.3 are used for input only. Terminals PO.4 to PO.7 are
outputs and initially set low. The conditions are:
PO.O

Every change is counted

PO.l

Any high-to-low change is counted

PO.2

Any low-to-high change is counted

PO.3

Every change is counted

RAM definitions
.BSS

PO_OCNT,2

Counter for PO.O

.BSS

PO_1CNT,2

Counter for PO.l

.BSS

PO_2CNT,2

Counter for PO.2

.BSS

PO_3CNT,2

Counter for PO.3

Initialization for PortO
MOV.B

#OOOh,&POOUT

MOV.B

#QFOh,&PODIR

PO.4 to PO.7 outputs

MOV.B

#OOBh,&POIES

PO.O to PO.3 Hi-Lo, PO.2 Lo-Hi

MOV.B

#OOCh,&POIE

PO.2 to PO.3 interrupt enable

BIS.B

#OOCh,&IEl

PO.O to PO.l interrupt enable

output register low

Interrupt handler for PO.O. Every change is counted
PO_OHAN

INC

PO_OCNT

Flag is reset automatically

XOR.B

n,&pOIES

Change edge select

RET!
Interrupt handler for PO.l. Any Hi-Lo change is counted
PO_1HAN

INC

Flag is reset automatically

RETI
Interrupt handler for PO.2 and PO.3
Hardware Applications

3-5

The flags of all read transitions are reset. Transitions
occurring during the interrupt routine cause interrupt after
the RETI
PO_23HAN PUSH
MOV.B
BIC.B
BIT
ADC
BIT

Save RS
Copy interrupt flags
Reset read flags
PO.2 flag to carry

RS,&POFLG
#4,R5
PO_2CNT

Add carry to counter
PO.3 flag to carry

#8,R5

INC

L$304
PO_3CNT

XOR.B

lIB,POIES

POP
RETI

R5

JNC

L$304

R5
&POFLG,RS

PO.3 changed
Change edge select
'Restore RS

. SECT

"INT_VECT",OFFF8h

. WORD
. WORD

PO_1HAN
PO_OHAN

PO.l INTERRUPT VECTOR;
PO.O INTERRUPT VECTOR;

. SECT

"INT_VECT1",OFFEOh
PO_23HAN

PO.2/7 INTERRUPT VECTOR

. WORD

3.1.2 Zero Crossing Detection
With the external components shown in Figure 3-1 it is possible to build a zero
crossing input for the MSP430. The components shown are designed for an
external voltage ac = 230 V. With a circuit capacitance (wiring, diodes) of
C1 =30 pF as shown in Figure 3-1, the following delays occur (all values for
ac =230 V, f =50 Hz, Vee =+5 V, timing is in lIS):

Vee

Vac

Vportx
1 MO
To Portx
--~~--~.---~----~­

Ri

Protection Diodes

Figure 3-1. Msp430 Input for Zero-Crossing

MSP430

Port Input
Voltage

Vac

i

VpOrtx

I
I
I
I
I
O;-~~~--4--r------------------~-r~~----

I

I

I
I

30)J.S~

J4-54)J.S~
j4--

I

i

65)J.S ~

6)J.S~
16JlS

I4-iI

~

I

---+
Time

j4- 30 liS -tt

Figure 3-2. Timing for the Zero Crossing
Delay caused by RC (1 Mel x 30 pF): 30 fJS or 0.54 0 (same value for leading
and trailing edges).
Delay caused by input thresholds:
Leading edge: 24 fJS to 35 fJS. (VT+ =2.3 V to 3.4 V)
Trailing edge: 14 fJS to 24 fJS. (VT_ = 1.4 V to 2.3 V)
The resulting delays are:
Leading edge: 54 fJS to 65 fJS.
Trailing edge: 6 fJS to 16 fJS.
These small deviations do not playa role for 50 Hz or 60 Hz phase control applications with TRIACs. If other input conditions than 230 V and 50 Hz are used
then the resulting delays can be calculated with the following formulas:
to "" SVT;
V
Where:
to
VT
Sv
c.o
U

S - d(U x sinc.ot) "" U x c.o x cosc.ot
V dt

Delay time caused by the input threshold voltage [s]
Input threshold voltage
M
Slope of the input voltage
[VIs]
Angular frequency 2m
[1 Is]
Peak value of the input voltage Uac
M
Hardware Applications

3-7

For t .. 0 (zero crossing time) the previous equation becomes:

to --

VT
U

XCI) X

1

..

VT
U

XCI)

3.1.3 Output BufferIng
The outputs of the MSP430 (PO.x, P1.x, P2.x, P3.x, P4.x, Ox) have nominal
internal resistances depending on the supply voltage, Vee:
Vee = 3 V: Max. 333 a

(IN .. O.4V max. @ 1.2mA)

Vee = 5 V: Max. 266 a

(/lV .. O.4V max. @ 1.5mA)

These internal resistances are non-linear and are valid only for small output
currents (see the previous text). If larger currents are drawn, saturation effects
will limit the output current.
These outputs are intended for driving digital inputs and gates and normally
have too high an Impedance level for other applications, such as the driving
of relays, lines, etc. If output currents greater than the previously mentioned
ones are needed then output buffering is necessary. Figure 3-3 shows some
of the possibilities. The resistors shown in Figure 3-3 for the limitation of the
MSP430 output current are minimum values. The application is designed for
Vee" 5 V. The values shown in brackets are for Vee" 3 V.

3-8

5V

D 32kHz

+--

le=1.5mAx~ (le=1.2mAx~)

+--

Ie = 350 mA

SVec
2.7 kO (1.8 kO)
PO.x, Oy t---'lIV\r---I

MSP430

OV

8.2 kO (3.3 kO)
PO.x, Oy t---"I/V'v---i

ULN2OO1A

PO.x, Oy
ULN2003

+--

Ie

=200 mA

3 kO(2 kO)
PO.x, Oy t---'lIV\r---I

OV

5V

OV

OV

Figure 3-3. Output Buffering
3.1.4 Universal Timer/Port 1I0s
Ifthe Universallimer/Port is not used for analog-to-cligital conversion or is only
partially used for this purpose, then the unused terminals are available as outputs that can be switched to high impedance. The Universallimer/Port can
be used in three different modes (see Figure 3-4):

o Two a-bit timers, two inputs, one I/O, and 5 output terminals
DOne 16-bit timer, two inputs, one I/O, and 5 output terminals
o An analog-to-digital converter with two to six output terminals
Ports TPO.O to TPO.5 are completely independent of the analog-to-digital converter. Any of the ports can be used for the sensors and reference resistors.
After a power-up, the data register is set to zero and all TPO.x ports are
switched to high impedance.
Hardware Applications

3-9

r----~--------------------------------~
I Enable
MPS430
I

li~~-~~£~~~~~~~J
CIN

TPO.S

TPO.4

TPO.3

TPO.2

TPO.1

TPO.O

Figure 3-4. The I/O Section of the Universal Timer/Port Module
3. 1.4. 1 VOs Used with the Analog-fa-Digital Converter

The analog-tCHligital conversion uses terminal CIN and at least two of the
TPO.x terminals (one for the reference and one for the sensor to be measured);
therefore up to 4 outputs are available. Bit instructions BIS.B, BIC.B, and
XOR.B can only be used for the modification of the outputs. This is due to the
location of the control bits in the data register TPD and data enable register
TPE. The programming of the port is the same as described in the following
section.
Note:
For precise ADC results, changes of the TP-ports during the measurement
should be avoided. The board layout and the physical distance of the
switched port determine the influence on the CIN terminal. Spikes coming
from the switching of ports can change the result of a measurement. This is
, especially true if they occur near the crossing of the threshold voltage.
3.1.4.2 VOs Used Without the ADC

This mode allows 5 outputs that can be switched to high impedance (TPO.O
to TPO.4) and one I/O terminal (TPO.5). Additionally, two 8-bit timers or one
16-bit timer are available. If one of the timers is used, only bit instructions
BIT.B, BIS.B, BIC.B, or XOR.B can be used to operate the port. The four timer
control bits are located in the data register TPD and data enable register TPE.
If the MOV.B instruction is used, all the bits are affected.

3-10

Example 3-4. All Six Ports are Used as Outputs
All six ports are used as outputs. The possibilities of the port are shown in the
following:
Definitions for the Counter Port
TPD

.EQU

04Eh

Data Register

TPE

.EQU

04Fh

Data Enable Register. 1:
output enabled

TPO

.EQU

OOlh

TPO.O bit address

TPI

.EQU

002h

TPO.l bit address

TP2

.EQU

004h

TPO.2 bit address

TP3

.EQU

OOSh

TPO.3 bit address

TP4

.EQU

OlOh

TPO.4 bit address

TPS

.EQU

020h

TPO.5 bit address

Reset all ports and switch all to output direction
BIC.B

#TPO+TP1+TP2+TP3+TP4+TPS,&TPD

Data to low

BIS.B

#TPO+TP1+TP2+TP3+TP4+TPS,&TPE

Enable outputs

Toggle TPO.O and TPO.4, set TPO.S and TPO.2 afterwards
XOR.B

#TPO+TP4,&TPD

Toggle TPO.O and TPO.4

BIS.B

#TPS+TP2,&TPD

set TPO.S and TPO.2

Switch TPO.l and TPO.3 to HI-Z state
BIC.B

#TP1+TP3,&TPE

HI-Z state for TPO.l
and TPO.3

3.1.5 110 Used for Fast Serial Transfers
The combination of hardware and software, shown in the following, allows a
fast serial transfer with the MSP430 family. The data line needs to be Px.O. Any
other port can be used for the clock line. Any data length is possible. The LSB
is transferred first. This can be easily changed by using RLC instead of RRC.
Hardware Applications

3-11

POOUT

.EQU

Ollh

PODIR

.EQU

012h

PortO output register
PortO Direction register

POO

.EQU

01h

Bit

POl

.EQU

02h

Bit address of PO.1: Clock

~ddress

of PO.O: Data

MOV

DATA,R5

1st 16bit data to R5

CALL

#SERIAL_FAST_I~IT

1st transfer, initialization

MOV

DATA1,R5

2nd 16bit data to R5

CALL

#SERIAL_FAST

2nd transfer, LSB to MSB
aso.

Initialization of the fast serial transfer: uses SERIAL_FAST too
SERIAL_FAST_INIT

Initialization part

BIC.B

#POO+P01,&POOUT

Reset PO.O and PO.l

BIS.B

#POO+P01,&PODIR

PO.O,and PO.l to output dir.

Part f,or 2nd and all following transfers
SERIAL_FAST

Initialization is made

RRC

R5

LSB to carry

ADDC.B

#P01,&POOUT

Data out, set clock

4 cycles

BIC.B

#POO+POl,&POQUT

Reset data and clock

5 cycles

1 cycle

RRC

R5

LSB+l to carry

ADDC.B

#P01,&POQUT

Data out, set clock

4 cycle

BIC.B

#POO+P01,&POQUT

Reset data and clock

5 cycles

1 cycle

Output all bits the same way
RRC

R5

; MSB to carry

ADDC.B

#P01,&POQUT

; -Data out, set clock

4 cycles

BIC.B

#POO+P01,&POQUT,

; Reset data and clock

5 cycles

RET

3-12

1 cycle

Each bit needs 10 cycles for the transfer, this results in a maximum baud rate for
the transfer:

Baud ratemax =

MCLK
10

This means if MCLK =1.024 MHz then the maximum baud rate is 102.4 kbaud.

o

po.o

o

Data

MSP430

PO.1

Clock

Vss vee
OV

5V

Figure 3-5. Connections for Fast Serial Transfer

Hardware Applications·

3-13

3.2 Storage of Calibration Constants
Metering devices, such as electricity meters, gas meters etc., normally need
to store calibration constants (offsets, slopes, limits, addresses, correction
factors) for use during the measurements. Depending on the voltage supply
(battery or ac), these calibration constants can be stored in the on-chip RAM
or in an external EEPROM. Both methods are explained in the following
sections.

3.2.1

External EPROM for Calibration Constants
The storage of calibration constants, energy values, meter numbers, and device versions in external EEPROMs may be necessary if the metering device
is ac powered. This is because of the possibility of power failures.
The EEPROM is connected to the MSP430 by dedicated inputs and outputs.
Three (or two) control lines are necessary for proper function:

D Data line SDA: an I/O port is needed for this bidirectional line. Data can
be read from and written to the EEPROM on this line.

o

Clock line SCL: any output line is sufficientforthe clock line. This clock line
can be used for other peripheral devices as long as no data is present on
the data line during use.

D Supply line: if the current consumption of the idle EEPROM is too high,
then switching of the EEPROM Vee is needed. Three possible solutions
are shown:

3-14

•

The EEPROM is connected to SVce. This is a very simple way to have
the EEPROM powered off when not in use.

•

The EEPROM is switched on and off by an external PNP transistor
driven by an output port.

•

The EEPROM is connected to 5 V permanently, when its power consumption is not a consideration.

Sto,!ge of Calibration Constants

r--------

5V

I
I
I
I

I 5V
I
I
I
I
VCC

SVCC

t--'VVv---t PO.x,Oy

MSP430

Clock

SCL ....==-+--1 PO.y,Oy

X24LCxx
Ax
SDA ....-=D=atB=-......... Po.x
Vas
Vas

VCC

OV
OV

5V

Figure 3-6. External EPROM Connections
An additional way to connect an EEPROM to the MSP430 is shown in Section
3.4, /2C Bus Connection, describing the 12C Bus.
Note:
The following example does not contain the necessary delay times between
the setting and the resetting of the clock and the data bits. These delay times
can be seen in the specifications of the EEPROM device. With a processor
, frequency 9f 1 MHz, each one of the control instructions needs 5 lIS.

Example 3-5. External EEPROM Connections
The EEPROM, with the dedicated 1/0 lines, is controlled with normal I/O
instructions. The SCl line is driven by 017, the S.DA line is driven by PO.6. The
line is driven high by a resistor and low by the output buffer.
POOUT

.EQU

Ollh

PODIR

.EQU

O12h

Porta Output register
Porta Direction register

SCL

.EQU

OFOh

017 controls SCL, 039h LCD Address

SDA

.EQU

040h

PO.6 CONTROLS SDA

LCDM

.EQU

030h

LCD control byte

,
INITIALIZE I2C BUS PORTS:
INPUT DIRECTION:

BUS LINE GETS HIGH

OUTPUT BUFFER LOW: PREPARATION FOR LOW SIGNALS

Hardware Applications

3-15

Storage of Calibration Constants

BIC.B
BIS.B
BIC.B

#SDA,&PODIR
#SCL,&LCDM+9
#SDA,&POOUT

SDA TO INPUT DIRECTION
SET CLOCK HI
SDA LOW IF OUTPUT

START CONDITION: SCL AND SDA ARE HIGH, SDA IS SET LOW,
AFTERWARDS SCL GOES LO
BIS.B
BIC.B

#SDA,&PODIR
#SCL,&LCDM+9

SET SDA LO (SDA GETS OUTPUT)
SET CLOCK LO

DATA TRANSFER: OUTPUT OF A "1"
BIC.B

#SDA,&PODIR

BIS.B

#SCL,&LCDM+9

SET SDA HI
SET CLOCK HI

BIC.B

#SCL,&LCDM+9

SET CLOCK LO

DATA TRANSFER: OUTPUT OF A "0"
BIS.B
BIS.B

#SDA,&PODIR
#SCL,&LCDM+9

SET SDA LO

BIC.B

#SCL,&LCDM+9

SET CLOCK LO

STOP CONDITION: SDA IS LOW, SCL IS HI,

SET CLOCK HI

SDA IS SET HI

BIC.B

#SDA,&PODIR

SET SDA HI

BIS.B

#SCL,&LCDM-t9

Set SCL HI

The examples, shown in the previous text, for the different conditions can be
implemented into a subroutine, which outputs the contents of a register. This
shortens the necessary ROM code significantly. Instead of line Ox for the Sel
line another 1/0 port PO.x can be used. See SeCtion 3.4, /2C Bus Connection,
for more details of such a subroutine.

3.2.2 Internal RAM for Calibration Constants
The Intemal RAM can be used for storage of the calibration constants, if a permanently connected battery is used for the power supply. The use of low power
mode 3 or 4 is necessary for these kinds of applications and can get battery
life times reaching 8 to 12 years.
3-16

.

M-Bus Connection

3.3 M·Bus Connection
The MSP430 connection to the M-Bus (metering bus) is shown in Figure 3-7.
Three supply modes are possible when used with the TSS721:

o
o
o

Remote supply: The MSP430 is fully powered from the TS8721
Remote supplylbattery support: The MSP430 power is supplied normally
from the TSS721. If this power source fails, a battery is used for backup
power to the MSP430
Battery Supply: The MSP430 is always supplied from a battery.

All these operating modes are described in detail in the TSS721 M-Bus Transceiver Applications Book.

o

32kHz
METERBU8
2150

PO.1 RXD

BUSL1

PO.2TXD

T88721

2150

BUSL.2

Ay/RST/PO.y
M8P430

1000

Ax/PO.x

RXI
AzlRST/PO.z

1200

BUSL1
PF

5MB740CA

TSS721

BUSL.2
1000

1200

Figure 3-7. TSS721 Connections to the MSP430
Two different TSS721 connections are shown in Figure 3-7:

o

If the 8-bit interval timer with its UART is used then the upper connection
is necessary. TXI orTX are connected to RXO (PO.1) and RXI or RX is connected to TXO (PO.2).

o

If a strictly software UART or an individual protocol is used, then any input
and output combination can be used

The second connection uses a proven hardware for environments with strong
EMV conditions. The 40-V suppressor diode gives the best results with this
configuration.
For more details, see Section 3.8, Power Supplies for MSP430 Systems.
Hardware Applications

3-17

.

/2C Bus Connection

3.4 J2C Bus Connection
If more than one device is to be connected to the 12C-Bus, then two I/O ports
are needed for the control of the 12C peripherals. This is needed to switch SDA
and SCL to a high-impedance state.

Figure 3-8 shows the connection of three 12C peripherals to the MSP430:

o
o
o

An EEPROM with 128x8-bit data
An EEPROM with 2048x8-bit data
An 8-bit DAC/ADC

The bus lines are driven high by the Rp resistors (PO.x Is switched to input
direction) and low by the output ports itself (PO.x is switched to output direction).
+5V

RP6

Rp

TPO.xlPO.8

sel

PO.b
MSP430

I
sel SOA
EEPROM

vee

vss

I

I

+5V

OV

128x8
vOO

I

A1
AO

A2

~

....

EEPROM

A1
AO

Vss

2048x8
voo

Vss

I

I

I

~

OV

+5V

sel SOA

SCl SOA
A2

+5V

SOA

I

OV

~

I-

Ax

AINx
AOUT
vss

ADClDAC

~

vOO

I

+5V

-*

~

I

OV

Figure 3-8. /2C Bus Connections
The following software example shows a complete 12C handler. It is designed
for an EEPROM 24C65 with the following values:

o
o
o

MCLK Frequency: 3.8 MHz
Address Length: 13 bits
Device Code: selectable by Code definition

I2C-Handler: Transmission of a-bit data via the I2C-bus
Author: Christian Hernitscheck TID
Definitions for 12C Bus
3-18

12C Bus Connection

SCL

.EOU

040h

PO.6 controls seL line (pull-up)

SDA

.EOU

oaOh

PO.7 controls SDA line (pull-up)

SCLIN

.EOU

OlOh

PO input register PO IN

SDAIN

.EOU

OlOh

PO input register PO IN

SCLDAT

.EOU

Ollh

POOUT register address

SDADAT

.EOU

Ollh

PO output direction register PODIR

SCLEN

.EOU

O12h

PODIR register address

SDAEN

.EOU
.equ

O12h

PO direction register

Code

OAOh

Device Code 10 (24C65)

Address

.EOU

0200h

address pointer for EEPROM

12CData

.EOU

0202h

used for I2C protocol 1

Register definitions
Data

.EOU

Count

.EOU

R6

Mask

.EOU

R7

RS

Initialization in main program
BIC.B

#SCL+SDA,&SDAEN

seL and SDA to input direction

BIC.B

#SCL+SDA,&SDADAT

SCL and SDA output buffer 10
Continue

Subroutines of the I2C-Handler
Write a-bit data  into EEPROM address 
: Call MOV
, Address MOV.B ,I2CData a-bit data CALL U2C_Write Call subroutine EEPROM data address JC Error Acknowledge error IN Error Arbitration error Continue program Hardware Applications 3-19 /2C Bus Connection Read a-bit data from EEPROM address
: MOV
, Address EEPROM data address CALL #I2C_Read Call subroutine JNC Error Acknowledge error IN Error Arbitration error Data in 12CData (byte) Status Bits on return: C: Acknowledge Bit N: 1: Arbitration Error 0: no error Used Registers: RS = Data (pushed onto Stack) R6 = Count (pushed onto Stack) R7 = Mask Used RAM: 12C_Write Address MOV.B 0200h 12CData 0202h 12CData+l 0203h 12CData+2 0204h 12CData+3 020Sh 12CData+4 0206h 12CData,I2CData+3 Data to be written to EEPROM ; CALL #ControlByte MOV.B Address+l,I2CData+l Hi byte of EEPROM address Delete A2, Al and AO bits AND.B II'OlFh,I2CData+l MOV.B Address,I2CData+2 JMP 12C 12C_Read CALL 3-20 (pushed onto Stack) ; Control byte Lo byte of EEPROM address ; To common part #ControlByte 12CData MOV.B Address+l,I2CData+1 Hi byte of EEPROM address AND.B #OIFh,I2CData+l = Control byte ; Delete A2, Al and AO bits 12C Bus Connection MOV.B Address,I2CData+2 Lo byte of EEPROM address MOV.B I2CData,I2CData+4 Control byte 2 BIS.B #01h,I2CData+4 , To common part Common I2C-Handler I2C PUSH Count PUSH Data PUSH Mask CLR Count Save registers BIS.B #SDA,&SDAEN Start Condition: set SDA Lo MOV.B I2CData, Data Send slave address and RW bit CALL #I2C_Send JC I2C_Stop BIT.B #01h,I2CData+4 JC 12C_SubRead Write or Read? Write data (R/W I2C_Data INC R/W bit is 1: read 0) Count CMP #4, Count JEQ I2C_Stop CALL #I2C_Send JNC I2C_Data Stop Condition: I2C_Stop BIS.B #SCL,&SCLEN SCL BIS.B #SDA,&SDAEN SDA - 'L' NOP 'L' Delay 7 cycles NOP NOP NOP NOP NOP NOP BIC.B #SCL,&SCLEN SCL 'H' Hardware Applications 3-21 /2C Bus Connection CALL #NOP9 BIC.B #SDA,&SDAEN Delay 9 cycles CLRN I2C~End POP Mask POP Data POP Count Restore registers RET Carry info valid Read data (R/W I2C_SubRead INC SDA = 'H' Reset error flags 1) Count CMP #3,Count JEQ I2C_SubReadl CALL #I2C_Send JC I2C_Stop JMP I2C_SubRead I2C_SubReadl BIS.B #SCL,&SCLEN 'CALL #NOP9 BIC.B #SCL,&SCLEN SCL='L' SCL='H' NOP NOP NOP NOP NOP SCL='H', SDA='H' => 'L' #SDA,&SDAEN MOV.B I2CData+4,Data CALL U2C_Send Send Control Byte BIS.B #SCL,&SCLEN SCL 'L' BIC.B #SDA,SDAEN SDA Input CLR I2CData MOV #8,Count I2C_Readl BIT.B 3-22 Start condition: BIS.B BIC.B Read 8 bits #SCL,&SCLEN #SDA,&SDAIN SCL = 'H' Read data to carry /2C Bus Connection RLC.B 12CData Store received Bit #SCL,&SCLEN SCL NOP NOP BIS.B 'L' NOP NOP NOP NOP NOP NOP DEC Count CALL U2CJlckn JMP 12C_Stop Test acknowledge bit to C Send byte 12C_Send MOV.B #80h,Mask 12C_Send1 BIT.B Bit mask: MSB first Mask,I2CData(Count) Info bit -> Carry JC 12C_Send2 BIS.B #SCL,&SCLEN Info is 0: SCL BIS.B #SDA,&SDAEN SDA - 'L' CALL #NOP9 BIC.B #SCL,&SCLEN BlS.B #SCL,&SCLEN BIC.B #SDA,&SDAEN SCL 'L' 'H' Info is 1: SCL 'L' SDA - 'H' CALL #NOP9 BIC.B #SCL,&SCLEN SCL - 'H' BIT.B #SDA,SDAlN' Arbitration JNC Error_Arbit RRC.B Mask CLRC Next address bit Hardware Applications 3-23 12C Bus Connection NOP NOP NOP JNC No Carry: continue 12C.-Ackn NOP NOP BIS.B tSCL,&SCLEN SCL - 'L' Acknowledge Bit BIC.B #SDA,&SDAEN SDA CALL iNOP8 = 'H' BIC.B tSCL,&SCLEN SCL - 'H' BIT.B #SDA,&SDAIN Read data to carry (acknowledge bit) RET 12C-Bus Error Error_Arbit ADD #2,SP SETN JMP Remove return address Set arbitration error 12C_End Build control byte ControlByte CLR 12CData MOV.B Address+l,I2CData RRC 12CData RRC 12CData ; Hi byte of EEPROM address ; Shift MSBs to bits 3 .. 1 RRC 12CData RRC 12CData AND.B #OEh,I2CData A2, A1 and AO ADD.B #Code,I2CData Add device code (24C65) RET Delay subroutine. Slows down 12C Bus speed to spec NOP9 NOP 9 cycles delay NOpa RET a 3-24 cycles delay Hardware Optimization 3.5 Hardware Optimization The MSP43D permits the use of unused analog inputs (A7 to AD) and segment lines (S29 to 52) for inputs and outputs, respectively. The following two sections explain in detail how to program and use these inputs and outputs. 3.5.1 Use of Unused Analog Inputs Unused analog-to-digital converter (ADe) inputs can be used as digital inputs or, with some restrictions, as digital outputs. 3;5.1.1 Analog Inputs Used for Dlgltsllnputs Any ADe input A7 to AD can be used as a digital input. It only needs to be programmed (for example, during the initialization) for this function. Three things are important if this feature is used: o Any activity at these digital inputs has to be stopped during ongoing sensitive ADe measurements. This activity will cause noise, which invalidates the ADe results. Activity in this case means: • No change of the AEN register (switching between digital and analog mode) • No input change at the digital ADe inputs (this rarely allows changing signals at these inputs). o All bits that are switched to ADO inputs will read zero when read. Therefore, it is not necessary to clear them with software after reading. o Not all analog inputs are implemented in a given device Example 3-6. AD - A4 are used as ADC Inputs and A5 - A7 as Digital Inputs AIN .EQU OllOh Address DIGITAL INPUT REGISTER AEN .EQU Oll2h Address DIGITAL INPUT ENABLE REG. A7EN .EQU OBOh Bits in Dig. Input Enable Reg.: A6EN .EQU 040h 0: ADC ASEN .EQU 020h 1: Digital Input INITIALIZATION: A7 TO A5 ARE SWITCHED TO DIGITAL INPUTS A4 TO AO ARE USED AS ANALOG INPUTS MOV #A7EN+A6EN+A5EN,&AEN A7 TO A5 DIGITAL MODE Hardware Applications 3-25 H..ardwa!~ Optimization NORMAL PROGRAM EXECUTION: CHECK IF A7 OR AS ARE HIGH. IF YES: JUMP TO LABEL L$100 BIT #A7EN+ASEN,&AIN A7 .OR. AS HI? JNZ L$lOO YES NO, CONTINUE CHECK IF ALL DIG. INPUTS A7 TO AS ARE LOW. IF YES: Go to L$200 TST &AIN A7 TO AS LO? JZ L$200 YES, (ANALOG INPUTS READ ZERO) 3.5.1.2 Analog Inputs Used as DIgItal Outputs If outputs are needed then the unused ADC inputs with the current source connection can be used with the following restrictions: D Only one ADC input can be high at a given time (1 out of n principle) D Only the ADC inputs AO to A3 are usable (only they are connected to the current source) D The outputs can go high only while the ADC is not using the current source. D The output current is directly related to the supply voltage, Vee. D The output voltage is only about 50% of the supply voltage, Vee. Logic levels have to be carefully monitored. A transistor stage might be necessary (if not there already, e.g. for a relay). D The output current is the current of the current source. Again; logic levels have to be carefully monitored. The pull-down resistor has to be big enough to allow the maximum output level. The example in Figure 3-9 shows the ADC using inputs AO and A1 as digital outputs driving two stages; a transistor stage (energy pulse, e.g. with an electriCity meter) and a 3.3-V gate (3.3 V ensures that the input levels are sufficient). 3-26 Hardware Optimization o 32kHz ICs =0.25 x SVCclREXT SVcc ~1C8 Rext 5V lJ Rex Energy Output MSP430 AO _'VVv-.....- - I OV 3.3v JL A1 H . . - - t - - - - i T03VLogic OV OV OV Figure 3-9. Unused ADC Inputs Used as Outputs Example 3-7. Controlling Two Inputs as Outputs To control the two outputs shown in Figure 3-9, the following software program is necessary: ACTL .EQU 0114h VREF .EQU 02h ADC CONTROL REGISTER ACTL 0: Ext. Reference AO .EQU OOOOh AD Al .EQU 0004h CSAO .EQU OOOOh CSAI .EQU 0040h CSOFF .EQU 0100h 1: SVCC ON INPUT SELECT AD Al CURRENT SOURCE TO AO Al CURRENT SOURCE OFF BIT SET AO HI FOR 3ms: SELECT AO FOR CURRENT SOURCE AND INPUT MOV #VREF+AO+CSAO,&ACTL PD = 0, SVCC CALL #WAIT3MS WAIT 3ms BIS #CSOFF,&ACTL CURRENT SOURCE OFF; = on SET Al HI FOR 3ms: SELECT Al FOR CURRENT SOURCE AND INPUT MOV #VREF+AI+CSAI,&ACTL PD - 0, CALL #WAIT3MS WAIT 3ms svtc = on Hardware Applications 3-27 Hardware Op!imizalion BIS 3.5.2 #CSOFF,&ACTL ; CURRENT SOURCE OFF Use of Unused Segment Lines for Digital Outputs The LCD driver of the MSP430 provides additional digital outputs, if the segment lines are not used. Up to 28 digital outputs'are possible by the hardware design, but not ali ofthem will be implemented on a given chip. The addressing scheme for the digital outputs 02 to 029 is as illustrated in Table 3-4. Table 3-4 shows the dependence of the segment/output lines on the 3-bit value LCDP. When LCDP =7, all the lines are switched to LCD Mode (segment lines). Only groups of four segment lines can be switched to. digital output mode. LCDP is set to zero by the PUC (06 to 029 are in use). Note: Table 3-4 shows the digit environment for a 4-MUX LCD display. The outputs 00 and 01 are not available: 80 and 81 are always implemented as LCD , outputs. (digit 1). The digital outputs Ox have to be addressed with all four bits. This means that . Oh and OFh are to be used for the control of one output. Only byte addressing is allowed for the addressing of the LCD controller bytes. Except for SO and S1, the PUC switches the LCD outputs to the digital output mode (LCDP = 0). Table 3-4. LCD and Output Configuration Address 6 5 4 3 2 1 0 DlgltNr. LCDP 029 028 Digil15 6100 03Eh 027 026 Digil14 6100 03Dh 025 024 Digit 13 5100 03Ch 023 022 Digit 12 5toO 03Sh 021 020 Digit 11 4 to 0 S20i821 03Ah 019 018 Digit 10 4toO 039h 017 016 Digit 9 3toO 038h 015 014 Digit 8 3to 0 037h 013 012 Digit 7 2100 036h 011 010 Digit 6 2 to 0 810/811 035h 009 008 Digit 5 1100 034h 007 006 Digit 4 1 toO 033h 005 004 Digit 3 0 032h 003 002 Digit 2 0 Digit 1 80/81 031h . 3-28 7 03Fh h g f e d c b a Hardware Optimization Example 3-8. 80 to 813 Drive a 4-MUX LCD 80 to 813 drive a 4-MUX LCD (7 digits). 014 to 017 are set as digital outputs. LCD Driver definitions: LCDM .EQU 030h ADDRESS LCD CONTROL BYTE LCDMO .EQU 001h 0: LCD off 1: LCD on LCDM1 .EQU 002h 0: high 1: low Impedance MUX .EQU 004h MUX: static, 2MUX, 3MUX, 4NUX Segment/Output Definition LCDM7/6/5 LCDP .EQU 020h 014 .EQU OOFh 014 Control Definition 015 .EQU OFOh 015 016 .EQU OOFh 016 017 .EQU OFOh 017 ; INITIALIZATION: DISPLAY ON: 014 TO 017 ARE OUTPUTS: MOV.B LCDMO = 1 HI IMPEDANCE LCDMI = 0 4MUX: LCDM4/3/2 7 LCDM7/6/5 = 3 #(LCDP*3)+(MUX*7)+LCDMO,&LCDM INIT LCD NORMAL PROGRAM EXECUTION: SOME EXAMPLES HOW TO MODIFY THE DIGITAL OUTPUTS 014 TO 017: BIS.B #014,&LCDM+B BIC.B #015+014,&LCDM+B RESET 014 AND 015 MOV.B #015+014,&LCDM+B SET 014 AND 015 MOV.B #017,&LCDM+9 RESET 016, SET 017 XOR.B #017,&LCDM+9 TOGGLE 017, 016 STAYS UNCHANGED SET 014, 015 UNCHANGED Hardware Applications 3-29 D/gjtal-!?"~na/og Convef!~n: w. 3.6 Dlgltal-to-Analog Converters The MSP430 does not contain a dlgital-ta-analog converter (DAC) on-chip, but it is relatively simple to implement the DAC function. Five different solutions with distinct hardware and software requirements are shown in the following: o o o o o The R12R method The weighted-resistors method Integrated DACs connected to the 12C Bus Pulse width modulation (PWM) with the universal timer/port module Pulse width modulation with limer A 3.6:1 R/2R Method With a CMOS shift register or digital outputs, a DAC can be built for any bit length. The outputs Ox of the shift register switch the 2R-resistors to 0 V or Vee according to the digital input. The voltage at the non-inverting input and also at the output voltage Vout of the operational amplifier is: n Vout =.!.. xVCC 2 Where: k n Vee Value of the digital input word with n bits length Number of 0 outputs, maximum length of input word Supply voltage Signed output is possible by level shifting or by splitting of the power supply (+ Vecl2 and -Vee/2). With split power supplies the voltage althe output ofthe operational amplifier is: Vout= k 2" x Vee - Vee' 2 = Vee (k 2"-'21) Advantages of the R/2R Method o o o o o 3-30 Only two different resistors are necessary (R and 2R) Absolute, monotony over the complete output range Internal impedance independent of the digital value: impedance is always R Expandable to any bit length by the adding of shift registers With only three digital outputs (Ox, TPO.x, Portx) , an inexpensive solution Is possible. Dlgltal-to-Analof! Converters If enough digital outputs are available in an application, then the shift register(s) can be omitted. The outputs QA to QH of Figure 3-10 are substituted by o outputs, ports or TP outputs of the MSP430. LSB Shift Register MSB Ox,PO.a Oy,PO.b MSP430 vo 2R DAC'Output To System 0 To VCC VCC Vas 5V OV Figure 3-10. R12R Method for Digital-to-Analog Conversion 3.6.2 Weighted Resistors Method The simplest digital-to-analog conversion method, only (n+3) resistors and an operational amplifier are required for an n-bit DAC. This method is used when the DAC performance can be low. The example shown in Figure 3-11 delivers 2n+1different output voltage steps. They can be seen as signed.if the voltage Ved2 is seen as a zero point. The output voltage Vout of this DAC is: . Vout = Vnlnv - I In x R = V~e x Where: Vout Vnl nv Vee R a...x (1" + (a x 2 -1 + b x 2 - 2 + c x 2 - 3 . . . + x x 2 - (n + 1»)) Output voltage of the DAC Voltage at the noninverting input of the operational amplifier (Ved2) Supply voltage of the MSP430 and periphery Normalized resistor used with the DAC Multiplication factors for the weighted resistors R to 2n x R: +1 if port is switched to Vss o if port is switched to input direction (high impedanCe) -1 if port is lIwitched to Vee Normally all ot the ports are switched to the same potential (VSS or Vee) or are disabled. This allows signed output voltages referencad to Ved2. Hardware Applications 3-31 Digital-to-Analog Converters o o Advantage of the Weighted Resistor-Method: Simplicity Disadvantage: Monotony not possible due to resistor tolerances Vee Ri PO.a PO.b PO.c R2 Vo R4 DACOulput To System 0 To Vce MSP430 PO.x Vec Vss 5V Rn OV OV Figure 3-11. Weighted Resistors Method for Digital-ta-Analog Conversion 3.6.3 Dlgltal-to-Analog Converters Connected Via the 12C Bus Figure 3-12 shows two different DACs that are connected to the. MSP430 via the 12C Bus: o A single output 8-blt DAC (with additional 4 ADC inputs); one analog output. AOUT. is provided. o An octuple 6-blt DAC; eight analog outputs. DACO to DAC7. are available for the system DigitaJ.to-A~a/og. Converters The generic software program to handle these devices is contained in the Section 3.4, /2C Bus Connection, explaining the 12C-Bus. 5V ,-I'-:.. Rp Rp TPO.xlPO.a SCL PO.b SDA SCL SDA DAC vmax DACx max.DAC Output Voltage Outputs To System Vee Vss 5V OV Figure 3-12. 12C-Bus for Digital-ta-Analog Converter Connection 3.6.4 PWM DAC With the Universal Tlmer/Port Module The two timers contained in the universal timer/port module can be used for one or two independent PWM generators. The ACLK frequency is used for the timing of these PWMs. The basic timer determines the period of the PWM signals.lts interruQt handler sets the programmed outputs and loads the two timer registers TPCNT2 and TPCNT1 with the negated pulse length values (see Table 3-5). The universal timer/port module terminates the pulses. Its interrupt handler resets the outputs when the counters, TPCNTx, overflow from OFFh to DOh. The length of one step is always l/ACLK, which is 30.51758 jJS if a 32.768 kHz crystal is used. Table 3-5 shows the necessary basiC timer frequency, which is dependent on the PWM resolution used. Table 3-5. Resolution of the PWM-DAC Resolution Bits 8 7 6 5 Resolution Steps 256 128 64 32 Beale Timer Frequency 128 256 512 1024 Hardware Applications 3-33 Dlgital-to-;~a/og Converters Table 3-6 shows the values to be written into timer register TPCNT1 or TPCNT2 to get a certain PWM output value (related to Vee); It is the d~slred value subtracled from the resolution value. The PWM switch (a byte In RAM) determines If the output is enabled (1) or disabled (0). Table 3-6. Register Values for the PWM-DAC PWMOutput (Relative to Vee) TPCNTx Value 256Step8 TPCNTx Value 128 Steps 0 0.25 0.50 0.75 1.00 x x eOh 80h 40h OOh EOh eOh AOh 80h TPCNTx Value 64 Steps TPCNTx Value 32 Steps PWM SwItch x x FOh EOh DOh eOh F8h FOh E8h EOh 0 1 1 1 1 i i Note: The interrupt latency time plays an important role for this kind of PWM generation. Real time programming is necessary. Therefore, the first instruction of each interrupt handler must be the EINT instruclion. i Example 3-9. PWM DAC With Timer/Port Module Two PWM outputs with 8-bit resolution are realized. To get the highest speed, TPO.2 and TPO.1 are used as outputs (they have the same bit addresses as the flags RC2FG and RC1 FG). The schematic is shown in Figure 3-13. The output ripple is shown in an exaggerated manner. If the PWM information is needed (as for DMC) then the signal at TPO.x is used directly. r---------PWM~ut vce Vss Buffered DC Output I' ov 5V OV ' - - - - - - - - - PWM output Figure 3-13. PWM for the DAC 3-34 TPO.x PWM output ~DCOutput. OV TPO.2 ....-A.I'VIr--e---1 I4-TUT H_-_n. ~~~ I I I ITUTXfBTxvCC TPO.1 ....-A.I'VIr--e-- DC OUtput MSP430 ~ Digital-to-Analog Converters Figure 3-14 illustrates the counting of the 8-bit counter during the PWM generation. The interrupt handler ofthe basic timer sets the 8-blt counterto a negative number of counts (-01) and sets the output to high; the interrupt handler of the universal timer/port resets the output to zero when it overflows. TPCNTx t if.-- 1/128 Hz ---.I OFFh ~~r---~--~r-------+---~--------~~~--trCNTx .. 32718 Hz 258 Steps RMoIuUon 128 Hz Reps11110n FIala At1 .. n1/ACLK ~put ~______~__~~______~__~________~__~___ I Basic T. RCxFG StarIIPWM I Basic T. RCxFG lei: Intenupt Latency and SW Exacuuon nme Interrupta Generated BasIeT. Figure 3-14. PWM Timing by the Universal Timer/Port Module and Basic Timer MSP430 Software for S bit PWM with Universal/Timer Port Definitions of the MSP430 hardware Type .equ 310 310: MSP43C31x BTCTL . equ 040h Basic Timer: Control Reg . BTCNTl .equ 046h Counter BTCNT2 .equ 047h Counter BTIE .equ OaOh Intrpt Enable SSEL .equ OaOh DlV .equ 020h BTCTL: xCLK/256 IP2 .equ 004h BTCTL: Clock Divider2 IP1 .equ 002h lPO .equ 001h SCFQCTL .equ 052h FLL Control Register MOD .equ OaOh Modulation Bit: 1 CPUoff .equ 010h SR: CPU off bit GlE .equ OOSh SR: General Intrpt enable 0: others Clock DividerO = off Hardware Applications 3-35 DigltaJ..to-Ana~ Con~~rters AU Timer Port: Control Reg. TPCTL .equ 04Bh TPCNTl .equ 04Ch Counter Reg.Lo TPCNT2 .equ 04Dh Counter Reg.Hi TPD .equ 04Eh Data Reg. TPE .equ 04Fh TPl .equ 002h TP2 .equ 004h TP3 .equ OOBh TPO.3 TP4 .equ OlOh TPO.4 TPS .equ 020h TPO.S .if Type-310 MSP430C31x? .equ 004h ADC: Intrpt Enable Bit OOBh MSP4 3 O'C3 2x conf igura tion OOlh Intrpt Enable Byte TPIE Enable Reg. Bit address TPO.l TPO.2 .else TPIE .equ .endif IE2 .equ TPSSEL3 .equ OBOh TPSSEL2 .equ ·040h OBOh TPSSELl .equ Selects clock input (TPCTL) TPSSELO .equ 040h ENB .equ 020h ENA .equ OlOh ENl .equ OOBh Gate for TPCNTx RC2FG .equ 004h Carry of HI counter (TPCTL) RCIFG .equ 002h Carry of LO counter (TPCTL) ENIFG .equ OOlh End of Conversion Flag " B16 .equ OBOh Use l6-bit counter (TPD) Selects clock gate (TPCTL) (TPCTL) RAM Definitions SW_PWM .equ 0200h Enable bits for TPO.2 and TPO.l TIM...,PWMl .equ 0201h Calc. PWM result PWMl TIM_PWM2 .equ 0202h Calc. PWM result PWM2 i-======================================================== 3-36 Oigital-to-Analog Converters INIT .sect "INIT",OFOOOh MOV #0300h,SP Initialize Stack Pointer MOV.B #IP2+IPl+IPO,&BTCTL Basic Timer 12BHz Initialization Section MOV.B #TPSSELO+ENA,&TPCTL ACLK, CLR.B &TPCNTI Clear PWM regs CLR.B &TPCNT2 CLR.B &TPD output Data MOV.B #TPSSEL2+TP2+TPl,&TPE TPCNT2: ACLK TPCNT1 EN1~1, = BIS.B #TPIE+BTIE,&IE2 INTRPTS on CLR.B SW_PWM No PWM output BIC.B #RC2FG+RC1FG,&TPCTL Reset flags Low EINT Continue with SW Start both PWMs: calculation results in R6 and R5 MOV.B R6,TIM....PWM1 MOV.B R5,TIM_PWM2 (256 - result2) BIS.B np2+TP1, SW_PWM Enable PWM2 and PWMI (256 - resultl) Continue Disable PWM2: Output zero BIC.B Disable PWM2 Interrupt Handler for the Basic Timer Interrupt: 128Hz BIC.B #RC2FG+RC1FG,&TPCTL Clear flags MOV.B TIM....PWM2,&TPCNT2 (256 - time2) MOV.B TIM_PWMl,&TPCNTl (256 - timel) BIS.B SW_PWM,&TPD Switch on enabled PWMs RETI Hardware Applications 3-37 Dig/ta/-to-AnaJog Converters ; End of Basic Timer Handler i---------------------------------------------------------Interrupt Handler for the Universal Timer/Port Module For max. speed TPO.2 and TP"Q.I are used (same bit locations as RC2FG and RCIFG). If other locations are used, RLA instructions have to be inserted after the flag clearing UT_HNDL PUSH.B &TPCTL INTRPT from where? AND #RC2FG+RCIFG,O{SP) Isolate flags BIC.B @SP,&TPCTL Clear set flag{s) BIC.B @SP+,&TPD Reset actual I/O{S) RETI End of Universal Timer/Port Module Handler ;---------------------------------------------------------. sect "INT_VECT",OFFE2h . WORD BT_INT .if Type=310 . sect "INT_VECI",OFFEAh MSP430C3lx "INT_VECI",OFFEBh Others . WORD UT_HNDL UTP Vector (3lx) . sect "INT_VEC2",OFFFEh . WORD INIT Basic Timer Vector .else .sect .endif ; Reset Vector Example 3-10. PWM Outputs With 7-Bit Resolution Two PWM outputs with 7-bit resolution are realized. TPO.4 and TPO.3 are used as PWM outputs (this makes shifting necessary). The schematic is shown in Figure 3-15. Due to the inverting filters at the PWM outputs, the outputs of the MSP430 are also Inverted to compensate for this. The output ripple is shown 3-38 Diqital-to-Analog Converters in an exaggerated manner. If the PWM information is needed (as for DMC) then the signal at TPO.x can be used directly. v=--v- -ill /f-TUT TPO.3 t-'\I'V\r-.......-...... DC Output ~1/faT~ I I I TPO.x PWM Output I TUTXfBTXVCC ~DCOUlput MSP430 TPO.4 ...."IN'v--'V'.,!\.,-4H DC Output VCC Vss OV O.5VCC PWMOutput 5V OV Figure 3-15. PWM for DAC Figure 3-16 illustrates the operation of the B-bit counter during the PWM generation. The interrupt handler of the basic timer sets the B-bit counter to the negative number of counts (-n1) and resets the output to low; the interrupt handler of the universal timer/port sets the output to high when it overflows. Hardware Applications 3-39 D/gltal-to-Ana!og Converters TPCNTx ii ~ 11258 Hz ---.t ~h~------~--~~-------4--~~----­ ~1 ~--------~~~~--------~~~~----- trCNTx .. 32788 Hz 11m ~ Resolution 258 Hz RapatItIon Rate Oh~~------~--~~~-----+----~~---- =n1/ACLK Id: Interrupt Latency and .1.11 SW ExecutIOn Time Basic T. RCxFG Basic T. RCxfG Interrupla Figure 3-16. PWM Timing by Universal Timer/Port Module and Basic Timer MSP430 Software for 7 bit PWM with Universal/Timer Port Definitions of the MSP430 hardware like above INIT . sect "INIT",OFOOOh MOV #0300h,SP MOV.B HP2+IP1, &BTCTL Initialization Section ; Initialize SP Basic Timer 256Hz MOV.B #TPSSELO+ENA,&TPCTL ACLK, EN1-1, TPCNT1 CLR.B &TPCNTl Clear PWM regs CLR.B &TPCNT2 BIS.B #TP4+TP3,&TPD output Data - high MOV.B #TPSSEL2+TP2+TP1,&TPE TPCNT2: ACLK BtS.B #TPIE+BTIE,&IE2 INTRPTS on CLR.B SW_PWM No output BIC.B #RC2FG+RC1FG,&TPCTL Clear flags EINT Start both PWMs: Calculation results in R6 and R5 3-40 MOV.B R6,TIM_PWM1 (128 - result) BIS.B #TP3,SW_PWM Enable PWMl MOV.B R5,TIM_PWM2 (128 - result) BIS.B #TP4,SW_PWM Enable PWM2 Digilal-Ia-Analog Converters Disable PWMs: Output is zero No output BIC.B Interrupt Handler for the Basic Timer Interrupt: 256Hz The enabled PWMs are switched on BIC.B #RC2FG+RC1FG,&TPCTL Clear flags MOY.B TIM_PWM2,&TPCNT2 (128 - time2) MOY.B TIM_PWM1,&TPCNTl (128 - timel) BIC.B SW_PWM,&TPD Switch on enabled PWMs RETI End of Basic Timer Handler ;---------------------------------------------------------Interrupt Handler for the UT/PM. The PWM-channel that caused the interrupt is switched off. UT_HNDL PUSH MOY.B R6 Save R6 &TPCTL,R6 INTRPT from where? AND #RC2FG+RC1FG,R6 Isolate flags BIC.B R6,&TPCTL Clear set flag(s) RLA R6 To TPO. 4/TPO. 3 RLA R6 BIS.B R6,&TPD Set actual I/O(s) POP R6 Restore R6 RET I End of Universal Timer/Port Module Handler ;---------------------------------------------------------; Vectors like with the example before Hardware Applications 3-41 Digital-to-;Ana/og Converte'!.." 3.6.5 PWM DAC With the Tlmer_A Timer_A of the MSP430 family is ideally suited for the generation of PWM signals. The output unit of each one of the (up to five) capture/compare registers is able to generate seven different output modes. The PWM generation depends mainly on which mode of the Timer_A was used. o Continuous Mode: the timer register runs continuously upwards and rolls over to zero after the value OFFFFh. The capture/compare register 0 is used like the other capture/compare registers. This mode allows up to five independent timings. The continuous mode is not intended for PWM applications. But, it can be used for relatively slow PWM applications, if other timings are also needed. Interrupt is used for the setting and the resetting of the PWM output. The output unit controls the PWM output and the interrupt handler adds the next time interval to the capture/compare register and modifies the mode of the output unit (set, toggle, or reset). o Up Mode: The timer register counts up to the content of capture/compare register 0 (here the period register) and restarts at zero when it reaches this value The capture/compare register 0 contains the period Information for all other capture/compare registers. o Up-Down Mode: The timer register counts up to the content of capture/ compare register 0 (here the period register) and counts down to zero when it reaches this value. When zero is reached again, the timer register counts up again. capture/compare register 0 contains the period information for all other capture/compare registers. All three modes are explained in detail In the Section 6.3, Timer_A. Software program examples are also given. If dc output is needed, the same output filters can be used as shown in the previous section. The only difference is the possible speed of the Timer~ (input frequency can be up to the MCLK frequency). 3.6.5.1 PWM DAC With T/mer_A Running In Continuous Mode Up to five completely different PWM generations are possible. If the limer Register equals one of the four capture/compare latches (programmed to compare mode), the hardware task programmed to the output unit is performed (set, reset, toggle etc.) and an interrupt is requested. Figure 3-17 illustrates the generation of a PWM Signal with the capture/compare registers O. The interrupt handler is reSpOnsible for the following tasks: o 3-42 The time difference (represented by the clock count nx) to the next interrupt Is added to the used capture/compare register by software: once AtO, onceAt1 , I?,lgital-to-A~B!.o.E qonverlers o The output unit is programmed to the appropriate mode: set TAO if at1 is added, reset TAO if atO is added. o Other tasks if necessary Note: The continuous mode is not the normal mode for PWM generation due to the software overhead that is necessary. It is used for this purpose only if other independent timings are necessary that cannot be realized with the up mode or the up-down mode. O~h ~------------------~~------------------~------- n1 nO Oh~~~~--~~----+-~~~~----+-~--~~--~~~ Interrupt Events: Example EQUO EQUO Interrupte Add to To CCRO Set Output Unit To Reeet Add t1 To CCRO Set Output UnIt To Set Figure 3-17. PWM Generation with Continuous Mode 3.6.5.2 PWM DAC With Tlmer_A Running In Up Mode Up to four different PWM generations with an equal period (repetition rate) are possible. If the timer register equals one of the four capture/compare latches (programmed to compare mode), the hardware task programmed to the output unit is performed (set, reset, toggle etc.) and an interrupt is requested. During the execution of the interrupt handler, the necessary software task is completed. No reloading of the capture/compare register is necessary except if the pulse width changes. If the timer register reaches the programmed value of the capture/compare register 0, then it is reset to zero and restarts there. Figure 3-18 illustrates the generation of two independent PWM signals with the capture/compare registers 1 and 2. Hardware Applications 3-43 OFFFFh CCROr---------~~----------~-------- CCR1 r-----~~--_r----~~--_+------~ CCR2~~----~--_r~~--~--_+~~---­ ~~~----~--~~~---+--~~~----- TA1 Output (CCR1): Output Mode 2: PWM TogglelReset or of---+....I.--+--+-~- Output Mode 3: PWM Set/Reset I-+--..... . . . . .,-.--+---J--..f.,--... . --+--f-,EQU2 EQUO EQU1 EQU2 EQUO EQU1 EQU2 EQUO TA2 Output (CCR2): Output Mode 6: PWM Toggle/Set or Output Mode 7: PWM Re88t1Set Interrupt Generated Figure 3-18. PWM Generation With Up Mode 3.6.5.3 PWAf..DAC With Tlmer_A Running In Up-Down Mode Up to four different PWM generations with an equal period are possible. If the timer register equals one of the four capture/compare latches (programmed . to compare mode), the hardware task programmed to the output unit is performed (set, reset, toggle etc.) and an Interrupt is requested. During the interrupt handler, the necessary software task Is completed. No reloading of the capture/compare register is necessary except If the pulse width changes. The timer register continues to count upward until the value of capture/compare register 0 is reached. Then it counts downward to zero. When it reaches the value of a capture/compare register, the programmed task is made by the output unit and an interrupt is requested again. When zero is reached, the sequence restarts. This way, symmetric PWM generation is possible. The value of the capture/compare register is reached twice for each up-down cycle. Figure 3-19 illustrates the generation of two independent PWM signals with the capture/compare registers 1 and 3. 3-44 Connection of Large Extemal Memories OFFFFh CCRO 1 - - - - - 7 I r - - - - - - - - ; . k - - - - - CCR1 ~-~~~-----~~~---- Oh~~-4-+4-~~-+--+_r+-4-~~~ TAa output (CCRa): I I Output Mode 8: PWM TogglelSet or t-~--r-irt_f-"1""-f_-;--;-t_+_- Output Mode 4: Toggle TA1 Output (CCR1): Output Mode 6: PWM Toggle/Set or I---+-~r,-+-t-_+_-t_-++_......+_- Output Mode 4: PWM Toggle TIMOV eQU3 IEQuol EQUl EQUl EQU3 TIMOV EQoo I Eauol EQU3 EQUl EQUl Interrupt Generated Figure 3-19. PWM Generation with Up-Down Mode 3.7 Connection of Large External Memories For a lot of MSP430 applications, it is necessary to be able to store large amounts of measured data. For this purpose external memories can be used: o o o o Dynamic RAMs like the TMS44460 (1 M x 4 bits) Synchronous Dynamic RAMs like the TMS626402 (2M x 4 bits) Flash memories like the TMS28F512A (512K x 8-bits) EEPROMs DRAM versions with a self-refresh featllre are recommended, otherwise the necessary refresh cycles would waste too much of the processing time. Figure 3-20 shows the simplest way to control external memory. The unused LCD segment lines are used for addressing and control of the external memory. Four bidirectional 110 lines of port 0 (or another available port) are used for the bidirectional exchange of data. The necessary steps to read from or write to the example TMS44460 DRAM memory are: 1) Output row address to address lines A9 to AO 2) Set the RAS control line low 3) Output column address to address lines A9 to AO 4) Set CAS control lines low and reset them back to high 5) If a read is desired, set OE low and W control lines high. Then read data from 004 to 001. 6) If a write is desired, set OE high, set W low, and then write the data to 004 to 001. Hardware Applications 3-45 connectio!' of L,arg~.~xtemal Memories The proposal shown in Figure 3-20 needs approximately 200 MCLK cycles for each block of 4-bit nibbles when the O-output lines are used. Control TPO.x10 TPO.x113 TPO.xte TPO.x113 CA~AS1 RAS x 012~21 PO.z OE VI 10 Address 4 Data A9-A0 DQ4-DQ1 Figure 3-20. External Memory Control With MSP430 Ports Example 3-11. External Memory Connected to the Outputs For the circuit shown in Figure 3-20, the 10 address lines of an external memory are connected to the O-outputs, 012 (LSB) to 021 (MSB). The subroutine 0 _HNDLR is used for the row and column addressing. The driver software and the subroutine call follows: N .EQU 10/2 10 O-outputs are controlled (013 to 04) O_STRT .EQU 037h Control byte for 012 and 013 (1st byte) Start with row addressing MOV #03FFh,R5 CALL #O_HNDLR MOV R9,R5 Column address in R9 CALL #O_HNDLR Output column address output @RAS signal Output @CAS signals Subroutine outputs address info in RS to O-outputs Bit 0 is written to the MSB of the O-outputs. RS is destroyed Execution time: 69 cycles for 8 O-outputs (including CALL) 129 cycles for 16 o-outputs (like above) 3-46 R6 Clear counter RS,R4 Copy actual info Connection of Large Extemal Memories AND #3,R4 Isolate next two address bits MOV.B TAB(R4),0_STRT(R6) Write address bits RRA RS Prepare next two address bits RRA RS INC R6 Increment counter CMP #N,R6 Through? JNZ O_HN No, next two bits RET Table contains bit pattern used for the O-outputs TAB . BYTE O,OFh,OFOh,OFFh . ; Patterns 00, 01, 10, 11 Figure 3-21 gives an example to use when the LCD segment lines are not available. Two 8-bit shift registers are used for addressing and control of the external memory. Four bidirectional VO lines of port 0 (or another available port) are used for the exchange of data. Instead of outputting the address and control signals in parallel, this solution's signals are output in series. The output enable signals G2 and G1 are used to omit bad signals that are due to the shifting ofthe information. The example shown in Figure 3-21 needs approximately 500 cycles for each block of 4-bit nibbles. COM SEL -" -./ ~S6'.B _Em TPO.xlO TPO.xI& TPO.xI(jI TPO.xI& S1 so F Control E G2-G1 D CLK C SR B-A MSP430 X ~ OE W CAS4-CAS1 RAS A9-A8 TMS44460 TPO.xlO PO.1i Serial Date In 4 II QH' S1 SO ~ G2-G1 H-A CLK SR ~ Addrese A7-AO IrDQ~1 Date Figure 3-21. External Memory Control With Shift Registers With nearly the same two hardware solutions, other external memories can be controlled also. Hardware Applications 3-47 c.on~?Ction of L~rge Ext;ms/ Memories o Synchronous Dynamic RAM (TMS626402 2M x 4 bits) with 12 address lines and 6 control lines. Rowand column addressing is used. It also uses 4 data bits. o Flash memory (TMS28F512A 512K x 8-bit) with 16 address lines and 3 control lines. Direct addressing is used. It also uses 8 data bits. Any combination of unused outputs (port, TPO.x, Oy) and·shift registers can be used. If DRAMs without self-refresh are used, the low address bits should be controlled by a complete port (port 1 ,2, 3, or 4) to get minimum overhead for the refresh task. The different versions of the MSP43OC33x allow a much simpler and faster solution because of the five available I/O ports. Figure 3-22 illustrates the connection of an AT29LV01 OA EEPROM (128K x 8 bit) to the MSP430C33x. The example shown in Figure 3-22 needs approximately 30 to 50 MCLK cycles for each byte read or written. The control lines at the MSP430 are II0s with no second function. All the peripheral functions are available and can be used freely. The MSP30C31 x and 32x can address this type of memory by its TPO.x and Ox ports. -" COM SEL -,/ 'iS6 .B'iS61B _am Control P3.o PO P2 Pi OE W P3.1 P4.i P4.0 MSP430C33x CE Ai6 AT29LVOi0A 8 Address 8 , Address 8 Data Ai5-A7 A7-AO U07-1100 Figure 3-22. EEPROM Control With Direct Addressing by 110 Ports Figure 3-23.shows the use of an MSP430C33x for the addressing of an externa11-MB RAM. The actual address of the external memory is stored in I/O Ports PO, P2, and P4. The special architecture of the MSP430 allows this method to be used. This method results in the fastest possible access time. The software used for addressing and reading of the next byte is in the following text (this assumes that the address ports are initialized). 3-48 ') Connection of Large External Memories Cycles L$l INC.B &P20UT Address next Byte 4 JNC L$l No carry to AlS .. AS 2 ADC.B &POOUT Carry to AlS .. AS MOV.B &PlIN, RlS Read data at Portl The reading of a byte needs (4 + 2 + 3) = 9 cycles. An MCLK frequency of 3.8 MHz results in a read time of 2.371JS. This access time can be compared with the internal access time of an 8-bit microcomputer. The initialization of a 64-KB memory block is shown in the following text (memory block 1). Cycles = 00 MOV.B #O,&P20UT A7 •. AD MOV.B #O,&POOUT AlS .. AS MOV.B #CSl+WE,&P40UT Address memory block1 COM SEL ~ 4 --tS6 .B--tS61B Control OE WE Memory 0 64kx8Blt MSP430C33x PO P2 8 Addre. . ,8 Addre.. 8 Pi P4.1 P4.2 P4.3 4 roI _ _ 0 P4.5 P4.4 P4.0 00 = - A15-A8 A7-AO Data I/07-VOO r Decoder r-. R CE CE Memory 1 CEMemory2 ~ CEMemory3 12 CE Memory 4 to 15 Figure 3-23. Addressing of 1-MB RAM With the MSP430C33x Figure 3-24 shows how to address an external 1-MB RAM with an MSP430C31 x. The actual address olthe external memory (stored in the internal RAM) is output with the O-outputs (alternative use of the select lines) and the 6 TP ports. The software for addressing and reading of the next bytes is given in the following text (the address ports are initialized). Hardware Applications 3-49 CO['nection of Large External Memories Cycles INC.B Address next byte JNC No carry to A1S .. AB 2 ADC.B Carry to A1S .. AB 4 4 Address A1S to AB is output to 017 to 010. This part is necessary for only 0.4% of all accesses MOV.B MOV . A1S_B,R14 A1S .. B -> R14 R14,R1S 3 1 AND #3,R15 Next 2 address bits 2 MOV.B TAB(R15),&036h A9 .. B to 011 .. 10 6 RRA R14 Next 2 address bits 1 RRA· R14 1 MOV R14, R15 1 AND #3,R15 Address A7 .. 6 aso. 2 4 x the same A15.;6 36 Address bits A7 to AO output to TP-Port and 027/26 L$l MOV.B A7_0,&TPD A7 .. A2 to TP-Port MOV.B A7_0,R1S A!. .AD generated 3 AND #3,R15 A!. .AO in R1S 2 MOV.B TAB(R15),&LCDx Al .. AO to 027 and 026 6 MOV.B &POIN,R15 Read data at PortO 3 Process data TAB 3-50 .BYTE 0, OFh, OFOh, OFFh For O-outputs 6 Connection of Large External Memories The reading of one byte needs 26 cycles (addresses A15 - AS are unchanged) or 83 cycles when A15 - AS must be changed. An MCLK frequency of 3.8 MHz results in 6.9 J1S or 21.S J1S for one byte, respectively. The decoding of the 64-KB memory blocks is made with a normal4-to-16 line decoder. COM SEL 0 P _156_ .B Control 07 08 Memory 0 64 kx 8 Bit MSP430C31x 017/10 027/26 TPO.IHI PO 8 Addre88 ~ Addre88. 8 09 023 022 018 OE WE - Date TP Decoder A15-A8 A7-A0 1/07-1/00 CE ~. CE Memory 1 R ~ CEMemory2 CE Memory 3 CE Memory 4 to 15 Figure 3-24. Addressing of 1-MB RAM With the MSP430C31x Hardware Applications 3-51 Power Supplies for MSP430 Systems 3.8 Power Supplies for MSP430 Systems There are various ways to generate the supply voltage(s) for the MSP430 systems. Due to the extremely low-power consumption ofthe MSP430 family, this is possible with batteries, accumulators, the M-Bus, fiber-optic lines, and ac. Every method uses completely different hardware and is explained in depth. Wherever possible, the formulas necessary for the hardware design are given too. 3.8.1 Battery-Power Systems Due to the extremely low current consumption of the MSP430 family it is possible to run an MSP430 system with a O.5-Ah battery more than 10 years. This makes possible applications that were impossible before. To reach such extended time spans, it is only necessary to observe some simple rules. The most important one is to always switch off the CPU when its not needed (e.g., after the calculations are completed). This reduces the current consumption from an operational low of 400 !.IA down to 1.6 !.IA. The Figures 3-25 and 3-26 are drawn in a way that makes it easier to see how the battery needs to be connected to get the highest accuracy out of the ADC. Figure 3-25 illustrates the MSP430C32x with its separated digital and analog supply terminals. This provides a separation of the nOise-generating digitai parts and the noise-sensitive analog parts. Figure 3-26 shows how to best separate the two parts for the MSP430 family members with common supply terminals for the analog and digital parts of the chip. If the battery used has a high internal resistance, RI, (like some long-life batteries) then the parallel capacitor Cch muSt have a minimum capacity. The supply current for the measurement part (which cannot be delivered by the battery) is delivered via CCh. The equation includes the small current coming from the battery. lAM 1) echmin ~ t meas x ( IN - if ch I Between two. measurements, the capacitor Cch needs time, tch, to get charged-up to Vee for the next measurement. During this charge-up time, the MSP430 system runs in low-power mode 3 to have the lowest possible power consumption. The charge-up time, tch, to charge Cch to 99% of Vee is: 3-52 Power Supplies for MSP430 Systems Where: lAM t meas tNch RI Medium system current (MSP430 and peripherals) Discharge time of Cch during measurement Tolerable discharge of Cch during time tmeas Internal resistance of the battery Rext AO MSP430C323 PO.x, TPO.y (0) ._0 SEL e-------IAf (V) 2.3.'i. 123'iS61.B COM RV (A) (s) 1+----+ 1108 To Other Digital Parts To Other Analog Parts AGND oV ...---It-.. 3 V Figure 3-25. Battery-Power MSP430C32x System Hardware Applications 3-53 . Power Supplies for MSP430 Systems RREF COM TDP.O RMEAS1 SEL 2.3.t.t. 12:3t.f:S6 __ m TPO.1 MSP430C31x TPO.2 po.x, TPO.y RMEAS2 1108 crN C1 To Other System Pans Vss OV Vee ! To Other system Parts AGND Figure 3-26. Battery-Power MSP430C31x System Note: The way the battery is connected to the MSP430 (shown in Figures 3-25 and 3-26) is not restricted to battery-driven MSP430 systems. The decoupling of the analog and the digital parts is necessary for all methods of supplied power. The following schematics are drawn in a simpler way to give better , readability. 3.8.2 Accumulator-Driven Systems The MSP430 can also be supplied from an accumulator. An advantage of this solution is thatthe MSP430 can also take over the battery management for the accumulator. o Current Measurement: Summing up of the charge and discharge currents. If these currents (measured with Sign) are multiplied with constants that are unique for the accumulator type used (e.g. NiCd,Pb) then it is possible to have a relatively accurate value for the actual charge. The current is measured with a shunt. The measured voltage drop is shifted into the middle of the ADC range by the current Ics (generated by the MSP430's internal current source) that flows through Rc. This method allows signed current measurements. Power Supplies for MSP430 Systems o Temperature Measurement: All of the internal processes of an accumulator (e.g., maximum charge, self discharge) are strongly dependent on the temperature of the pack. Therefore, the temperature of the pack is measured with a sensor and used afterwards with the calculations. When the MSP430's current source is used, the voltage drop of its current Ics across the sensor resistance is measured with the ADC input A2. o Voltage Measurement: The voltage of an accumulator pack is an indication of the states full charge and complete discharge. Therefore, the voltage of the pack is measured with the voltage divider consisting of R1 and R2. o Charge Control: Dependent on the result of the charge calculations, the MSP430 can decide if the charge transistor needs to be switched on or off. This decision can also be made in PWM (Pulse Width Modulation) mode. Figure 3-27 shows three possible charge modes. If replaceable accumulators are used, the charge control is not needed. o Rest Mode Handling: During periods of non-use, the low power mode 3 of the MSP430 allows the control of the rest mode. The rest mode has nearly· no current consumption. In fact, the supply current has the same magnitude as the self-discharge current of the accumulator. All system peripheralsare switched off; the MSP430 wakes-up at regular intervals, which are controlled by its basic timer. It then calculates, every few hours, the amount of self discharge of the accumulator. This calculated value is subtracted from the actual charge level. Figure 3-27 illustrates an MSP430 system driven by an accumulator. The battery management is done by the MSP430 also. The hardware needed is simple. As shown in the figure, just a few resistors and a temperature sensor. The actual charge of the accumulator is indicated in the LCD with a bar graph ranging from Empty to Full. All necessary constants and a security copy ofthe actual charge are contained in an external EEPROM typically with 128 x 8 bits. Hardware Applications 3-55 Power SUPf/f!S for MSP430 Systems Note: The hardware shown In Figure 3-27 can also be used for an intelligent accumulator controller. Only the hardware necessary for this task is shown. The measurement parts for voltage, current, and temperature are exactly the same as shown. COM SEL I'romSyatem ~ PO.x ,----., I Keyboard sVcc ~ PO.y L _ _ _ .J =:> - -------1 .ICS To System +5 V Rext - Rex I Voltage I I Regulator I VCC I RCV PO.l TXD PO.2 CLK EEPROM 0818"' A2 PO.4 AI AO VOltage --: ~ T Accul Currant He ~ A2 MSP430C32X ToCherger ± Temp8l'lJture I a . . R1 PO.3 -~ 123'-1561.8 TPO.O I ..l ShUnt ~ Vss VTPO. Full Charge PWM Charge OV I L-+ Trlckle Mode TIme Figure 3-27. Accumulator-Driven MSP430 System With Battery Management 3.8.3 AC-Drlven Systems The current consumption of microcomputer systems gets more and more important for ac-driven systems. The lower the power consumption of a microcomputer system, the simpler and cheaper the power supply can be 3-56 Power Supplies f~ ,!SP430 Systems 3.8.3.1 Transformer Power Supplies .Transformers have two big advantages: o Complete isolation from ac. This is an important security attribute for most systems. o Very good adaptation to the needed supply voltage. This results in a good power efficiency. Most ac-driven applications are only possible because of the isolation from the ac the transformer provides. Half-Wave Rectification Half-wave rectification uses only one half-wave of the transformer's secondary voltage, VSEC, for the powering of an application. Figure 3-28 illustrates the voltages used with the equations. t ---1- = ~- VCH H:.....,r--~-~-----~......,H--I---+ Vsec x-12 Vchmax Vce i4---.. tcils - - - - - l i t I ~~---- T ----~~ Figure 3-28. Voltages and Timing for the Half-Wave Rectification o Advantages • • o Simplified hardware Rectification with the voltage drop of only one diode Disadvantages • • • Charge capacitor, CCH, must have doubled capacity compared to fullwave rectification Higher ripple on the dc supply voltage DC flows through the transformer's secondary winding Figure 3-29 shows the most simple ac driven power supply. The positive halfwave of the transformer's secondary side charges the load capacitor, CCH •. Hardware ApplicatIons 3-57 Power S!fifl"l!. for.MSP430 ~ystems The capacitor's voltage Is stabilized with a Zener diode having a Zener voltage equal to the necessary supply voltage Vcc of the MSP430. Two conditions must be met before a final calculation is possible: VSECmin x /2 - hVch > Vz and: T VSECmin x /2 - hVch - Vz IAMmax . 2 x Cchmin < Rv < The charge capacitor, CCH, must have a minimum capacity: C . ( >Ix ...L+ chmm-2 RV I) AM V x/2-v SECmln z The peak-to-peak ripple voltage VN(PP), of the supply voltage, VCC, is: V CC II Rz lAM Vnpp .. -.!..!7;v--Rv + -IC_C II Rz AM The final necessary secondary voltage, VSEC, ofthe ac transformer is (aVCH =O.1xVCHmax): 1 VSECmin ~ /2 x Where: lAM T aVch Vee Vz Rz Rv Vsec 3-68 [ 0.45 x T x lAM 1 _ 0.45xT + Vz Cchmln Rv Medium system current (MSP430 and peripherals) Period of the ac frequency Discharge of Cch during time tdis Supply voltage of the MSP430 system Voltage of the Zener diode Differential resistance of the Zener diode Resistancg of the series resistor Secondary (effective) voltage of the transformer (full load conditions) [A] [s] . M M M [AV/aA] [0] M Power Supplies for MSP430 Sy~tems Nonreguleted Voltage To Peripherals RV DZ CCH OV Vss Figure 3-29. Half-Wave Rectification With 1 Voltage and a Zener Diode Figure 3-30 shows a simplified power supply that uses a voltage regulator like the JlA78L05. The charge capacitor, Cch, must have a minimum capacity: Cchmin ~ lAM x tdis IN ch The peak-to-peak ripple VN(PP) on the output voltage Vreg depends on the used voltage regulator. The regulators ripple rejection value can be seen in its specification. The necessary secondary voltage Vsec of the ac transformer under full load conditions is: The discharge time tdis used with the previous equations is: AV ch ) arcos ( 1 _ . VSEC x./2 12n Where: tdis Vd Vr Vreg Discharge time of Cch Voltage drop of one rectifier diode Dropout voltage (voltage difference between output and input) of the voltage regulator for function Nominal output voltage of the voltage regulator Hardware Applications [s] M M M 3-59 For first estimations the value of·tdis is calculated for two different discharge values: o o 10% discharge of Cch during tdis 30% discharge of Cch during tdis tdis = O.93T tdis =O.88T Nonragulated voltage To Perlpherala Figure 3-30. Half-Wave Rectification With One Voltage and a Voitage Regulator Figure 3-31 shows an MSP430 system that uses two supply voltages: +5 V and -5 V. The negative supply voltage is used for analog interfaces. Simple resistor dividers interface the 10-V analog part into the 5 V range of the MSP430. The formulas for the calculation of the charge capacitor, Cch, and the necessary secondary voltage, Vsec, are the. same as shown for the circuitry in Figure 3-30. The same circuitry can be used for a system with +2.5 V and -2.5 V (see Figure 3-37 for more details). 3-60 Power Supplies for MSP430 Systems To Peripherals VREG ~~---+~----------"~Vcc lAM 5V A1 2.5V -7"0<"-'b -- ~----~~~-----.e--4~---- MSP430 OV __--~~~'-;VSS_ _--, OV~ CcH 1-+----+--*----+ -a V To System --~...-- 5V -r--I--'- 0 V --""-- -a V Input Figure 3-31. Half-Wave Rectification With Two Voltages and Two Voltage Regulators Full-Wave Rectification Full-wave rectification uses both half-waves of the secondary voltage, Vsec, for the powering of the application. i~1 ~lH-___I ---f' 1 VCH 1 I I VCC IiII 1 tI 14 Vsec x .J2 =VChrnax I! tdls T I ~I Figure 3-32. Voltages and Timing for Full-Wave Rectification o Advantages • • • o Smaller charge capacitor Cch Lower ripple voltage No dc current through transformer's secondary winding Disadvantages • • Four diodes or a transformer with center tap is necessary Voltage drop of two diodes in series (except with a transformer having a center tap) Hardware Applications 3-61 ~~,,!,:r Supplies for MSP430 Systems Figure 3-33 shows a simple power supply that uses a !1A78L05 voltage regulator. The charge capacitor, Cch, must have a minimum capacity: Cchmin ~ lAM x 'dis AV ch The peak-to-peak ripple, Vnpp, on the voltage, Vcc, depends on the voltage regulator used. The ripple rejection value can be seen in the voltage regulator specification. The necessary secondary voltage, Vsec, of the ac transformer is for the upper rectifier with four diodes (full load conditions): 1 x ( Vreg + Vr + 2 x Vd + 'dis x -C-lAM ) VSECmin ~ r;; ,,2 chmin For the center tap transformer, Vd, in the previous equation is multiplied by one (1 x Vd). The discharge time tdis used with the previous equations is: 'dis = Tx For first estimations the value of tdis is calculated for two different discharge values: . o o 10% discharge of Cch during tdis 30% discharge of Cch during tdis tdis = O.43T tdis =0.38T Nonregulated Voltage To Peripherals Figure 3-33. Full Wave Rectification for one Voitage with a Voitage Regulator Power Supplies for MSP430 Systems Figure 3-34 shows an MSP430 system that uses two supply voltages: +2.5 V and -2.5 V. The formulas for the calculation of the charge capacitor, Cch, and the necessary secondary voltage, Vsec, are the same as given for the circuitry in Figure 3-33. The circuitry of Figure 3-34 can also be used for a system with +5-V and -5-V supply (see Figure 3-31 for more details). Also shown, is how to connect a TRIAC used for ac motor control. The relatively high gate current needed is taken from the non-regulated positive voltage. This reduces the noise within the regulated MSP430 supply. The current flowing through the motor is measured with the ADC for control purposes. The ADC result for DV (measured at AD) is subtracted from the current ADC value and results in a signed, offset-corrected value. If a single supply voltage is used (+5V only), the current source can be used to shift the signed current information into the range of the ADC. See Figure 3-27 for the current measurement circuit. To Perlpher-ra.;;.ls_ _--, 2.SV AC Vcc MSP430 >-....-IA1 HH--4~---I Vss TPO. o OV Current Measurement Figure 3-34. Full-Wave Rectification for Two Voltages With Voltage Regulators 3.8.3.2 Capacitor Power Supplies Applications that do not need isolation from the ac supply or that have a defined connection to the ac supply (like electricity meters) can use capacitor power supplies. The transformer is not needed and only the series capacitor, Cm, must have a high voltage rating due to the voltage spikes possible on ac source. Hardware Applications 3-63 ~owt;r S~pp!/eS for MSP430 S~ems The ac resistance of the series capacitor, em, is used in a voltage divider. This means relatively low power losses. The active power losses are restricted to the protection resistor, Rm, connected in series with em. This protection resIstor is necessary to limit the current spikes due to voltage spikes and high frequency parts overlaid to the ac voltage. The current lac through the circuitry is: lAM ---+ Vac ..-L-c + Rm ICIlx m Where: Vac .fac Cl) em Rm lvcc Vac __ 1_+R2 CIl2xc~ m acvoltage Nominal frequency of the ac Circle frequency of the ac: Cl) =2m Series capacitor Series resistor [V] [Hz] [1/s] [F] [0] The previous formula for lac is valid for all shown capacitor power supplies. The formula assumes low voltages will be generated « 5% of the ac voltage). For a de current, lAM, the necessary ac current lac is: lac ~ lAM x fi = lAM x 2.221 The capacitor, em, is: Cmmin 1 ~ "". ,,- f • x x acmln --;::::.====::===== 2 ( 12)'. - Rmmax Vacmin x ltxl AM 2 This formula for Cm is valid for all shown capacitor supplies. The calculated value for em includes the tolerances for the ac voltage and the ac frequency; the minimum values used for Vac and fac ensure this. The protection resistor, Rm, for a maximum spike current Imax generated by a voltage spike Vspike is: 3-64 Power Supplies for MSP430 Systems The charge capacitor, Cch, must have a minimum capacity: 'AM x T eohmin;:: 2 x tNoh o Advantages • • o No transformer necessary Very simple hardware Disadvantages • No isolation from ac Capacitor Supplies for a Single Voltage Figure 3-35 shows the simplest capacitor power supply. The Zener diode used for limiting the voltage ofthe charge capacitor, Cch, is used for the voltage regulation too. The peak-to-peak ripple voltage, Vnpp, on voltage, Vee, is: Vnpp " 'AM x - T e2 ch x The voltage of the Zener diode, Oz, is: VZ"Vee+Vd Cch is calculated as shown in Section 3.8.3.2, Capacitor Power Supplies. To Peripherals VC 5V --+ lAM AC Vz=5.8V DZ MSP430 CeH Vss QV Figure 3-35. Simple Capacitor Power Supply for a Single Voltage Figure 3-36 shows a hardware proposal for a regulated output voltage, Vee. The voltage, Vz, of the Zener diode, Oz, must be: Vz ;:: Vd + Vreg + Vr + T x 2 x 'AM e . ohmln Hardware Applications 3-65 Power Supplies for MS!,430.Srstems Cch is calculated as shown in Section3.B.3.2, Capacitor Power Supplies. To Peripherals AC ov Figure 3-36. Capacitor Power Supply for a Single Voltage Capacitor Supplies for TWo Voltages Applications that need two voltages (e.g., +2.5 V and -2.5 V) can also use a capacitor supply. Figure 3-37 shows a split power supply with two regulated output voltages. Together, they deliver the supply voltage, Vee. The split power supply allows the measurement of the voltage of the O-V line at AO. This value can be subtracted from all other measured analog inputs. This results in offset corrected, signed values. The voltage, Vz, of each Zener diode, Oz, must be: Vz~Vr+Vreg+Tx2 lAM x e . chmln The two charge capacitors, Cch, must have the values: echmin ~ lAM x T AV ch x 2 To Peripherals CM -l f-"v\I'\r-+~+--+--I RM AC To Peripherals Figure 3-37. Split Capacitor Power Supply for Two Voltages 3-66 Power Supplies for MSP430 Systems Figure 3-38 shows a split power supply for +2.5 V and -2.5 V made in a completely different way. It is capable of delivering relatively large output currents due to the buffer transistors. If the high current capability is not needed, the transistors can be omitted and the loads connected to the outputs of the two operational amplifiers directly. The reference for all voltages is a reference diode, LMx85. The highly stabie 1.25 V output of this diode is multiplied by two (for +2.5V) or multiplied by -3 and added to the reference value, which delivers -2.5 V. The voltage drop of each one of the two diodes, D, is compensated by the series connection of the two Zener diodes, Dz. The required Zener voltage, Vz, of the two diodes Dz is: Where: VeE Vom Basis-Emitter voltage of a transistor Maximum peak output voltage swing of the operational amplifier with VC [V] [V] AC ~CM RM -vc D D DZ To Peripherals CCH ov To Peripherals Figure 3-38. Split Capacitor Power Supply for Two Voltages With Discrete Components Hardware Applications 3-67 :!!wsr Supplies for MSP430 Systems 3.8.4 Supply From Other System DC Voltages Existing dc voltages ofthe controlled system, like +12 V or +24 V, can be used for the supply to the MSP430 system. This is possible due to the low current consumption of the MSP430. So there is nearly no power wasted in the voltage regulator for Vee. If relays and other power consuming peripherals need to be used, the system dc voltage, Vsys, can be used (see Figure 3-40). This solution has two advantages: o o The switching noise is generated outside of the MSP430 supply The power for the switched parts does not increase the power of the MSP430 supply Figure 3-39 and 3-40 show four different possible supplies for an MSP430 system from an existing +12 V (or +24 V) power supply. 3.8.4.1 Zener DIode A simple configuration of a series resistor Rv with a Zener diode Dz delivers an output voltage of +3 V or +5 V. The resistor (Rv) is: Vsysmin - Vz Rvmax > .......-..,....,..Izmin + lAM Where: Vz Iz Vsys Zener voltage of the Zener diode Current through the Zener diode Nominal system voltage M [Al M 3:8.4.2 Zener DIode and OperatIonal Amplifier If larger currents or a higher degree of decoupling Is necessal)', then an operational amplifier can be used additionally. This way the series resistor Rv can have a much higher resistance than without the operational amplifier. The NPN buffer transistor is only necessary if the operational amplifier cannot output the needed system current. The series resistor Rv is calculated with: Rvmax > 3-68 Vsysmin - Vz Izm1n ~-7-'-"'"'--­ Power Supplies f~~ MSP430 Srstems 3.8.4.3 Reference Diode With Operational Amplifier The low voltage of a reference diode (e.g., LMx85) is amplified with an operational amplifier and also buffered. The series resistor, Rv, feeds only the reference diode and has a relatively high resistance. Therefore, it is calculated the same way as shown in Section 3.8.4.2, Zener Diode. The output voltage, Vout, is calculated with: V out = V z x R1 ~2 R2 VSYS (12 V to 24 V) R1 (3xR) 5V 5V 5V DZ VZ=5V DZ ---.--------~~--------~~------------ Zener Diode Supply Zener Diode With Operational Amplifiers Supply ____--------OV Reference Diode With Operational Amplifiers Supply Figure 3-39. Simple Power Supply From Other DC Voltages 3.8.4.4 Integrated Voltage Regulator Figure 3-40 illustrates the use of an integrated voltage regulator. Here a TPS7350 (regulator plus voltage supervisor) is used, so a highly-reliable system initialization is possible. The TPS7350 also allows the use of the RST/NMI terminal of the MSP430 as described in Section 5.7, Battery Check and Power Fail Detection. The RST/NMI terminal is used while running a normal program as an NMI (Non-Maskable Interrupt). This makes possible the saving of important data in an external EEPROM in case of power failure. This is because PG Hardware Applications 3-69 :'?wer Supplies for MSP430 Systems outputs a negative signal starting at Vee =4.75 V, which allows a lot of activities until Veemln of the MSP430 (2.5 V) is reached. VSYS D1 TP73060 +5V IAl!..,.. OUT IN Vcc MSP430 SENSE ResetlNMI TPO.x Vss PG 101J.1' cs [ DZ Vz=VSYS+3V OV Figure 3-40. Power Supply From Other DC Voltages With a Voltage Regulator With two additional components (an RC combination) the MSP430 system can be protected against spikes and bridging of supply voltage dropouts is po&sible. The diode, 01, protects the capacitor, Cb, against discharge during dropouts in voltage Vsys. The series resistor, Rv, is: Rvmax < (VSYSmin - Vd"- Vee - Vr) lAM + lregmax The minimum capacity of Cb is: At x (lAM + Ireg) > ------~--------~~--~------------- Vsysmin - (lAM + lregmax) x Rvmax - Vrmax - Veemln Where: lAM Ireg Vsys Vd Vr Vee At 3-70 System current (medium value MSP430 and peripherals) Supply current of the voltage regulator System voltage (e.g., +12 V) Diode forward voltage ( < 0.7 V) Dropout voltage of the voltage regulator for function Supply voltage of the complete MSP430 system Dropout time of Vsys to be bridged [A) [A) M M M M [s) Power Supplies for MSP430 Systems 3.8.5 Supply From the M Bus If the MSP430 system is connected to the M-Bus, three possibilities exist for the supply of the MSP430: o Battery Supply: The supply of the MSP430 is completely independent of the M-Bus. This method is not shown in Figure 3-41 , because it is the normal way the MSP430 is. powered (see Section 3.S.1, Battery Driven Systems). OM-Bus Supply: The MSP430 system is always supplied by the M-Bus. During off phases of the M-Bus, the MSP430 is not powered. o 3.8.5.1 Mixed Supply: Normally the M-Bus supplies the MSP430 and only during off phases of the M-Bus does the battery of the MSP430 provide power. M-Bus Supply The MSP430 is always powered from the M-Bus. The TSS721 power fail signal, PF, indicates to the MSP430 failure of the bus voltage. This early warning enables the MSP430 to save important data in an external EEPROM. The capacitor, ech, must have a capacity that allows this storage: lAM x Istore C h . > ..,.-!':!!!l..-;-;'=::<"" C min - VOO - VCCmin Where: System current (MSP430 and EEPROM) Processing time to store important data into the EEPROM Voo Supply voltage delivered from the TSS721 VCCmin Minimum supply voltage of the complete MSP430 system lAM tstore Hardware Applications [AI [sl [V] M 3-71 Power ~uf!P"es for MSP430 Sy~t*![!'~_ •• 3.8.5.2 Mixed Supply The MSP430 is powered from the M-Bus while bus voltage is available. During times without bus voltage. the battery powers the MSP430. Therefore. a smaller battery can be used when normal bus power is available. The MOS transistor switches to the battery when there is a dropout of the M-Bus voltage. DetailS are described in the TSS721 M-Bus Transceiver Application Report. Meter Bus CCH ov~~I~~------------~~~ 2150 Vss vee RX TX TXI RXI PO.O PF MSP430 TSS721 2150 M-BUS Supply 1N6263 BSS84 OV~~~~-'----~--------"--, Vss vcc MSP430 TSS721 GND STC sc 2150 RIS RIDD BUSL2 J....JI.Mr__ Mixed Supply oV Figure 3-41. Supply From the M Bus 3-72 2150 BAT VDD VS BUSL1 ~t--'--'-- __--' Power Supplies for MSP430 Systems 3.S.6 Supply Via a Fiber-Optic Cable The MSP430 needs a supply current of only 400llA, if supplied with a voltage of 3 V and operating with an MCLK of 1 MHz. This low power can be transmitted via a glass-fiber (fiber-optic) cable. This allows completely isolated measurement systems, which are not possible with other microcomputers. This transmission mode is an advantage for applications in strong electric or magnetic fields. Because the data transmitted from the host to the MSP430 is also used for the supply ofthe MSP430 system, a certain amount of light is required continuously and is independent of the transmitted data. Possible ways to reach this are: D Use of extended charge periods between host-to-MSP430 data transfers. The MARK level of the RS232 protocol Is used for this purpose. This method is shown in Figure 3-42 with every logical one, stop bit, and MARK level used for the supply. . D Use of a transmission code that always transmits the same number of ones and zeroes, independent ofthe transmitted data. (e.g., the Bi-Phase Code) To achieve a positive current balance, a few conditions must be met: D The complete hardware design uses ultra-low-power devices (operational amplifiers, reference diode, measurement parts etc.). D The MSP430 is in Low Power Mode 3 anytime processing power is not needed. D The measurement unit is switched on only during the actual measurement cycle. D All applicable hints given in Section 4.9, U1tra-Low-Power Design with the MSP430 Family are used. 3.8.6.1 Description of the Hardware The host sends approximately. 15 mW of optical power into the fiber-optic cable. This optical power is made with a laser diode consuming 30 mW of electrical power. At the other end of the fiber-optic cable, the optical power is converted into 6 mW of electrical power with a power-converter diode. The opencircuit voltage of the power converter (approximately 6 V) decreases to 5 V with the load represented by the MSP430. The received electrical energy is used to charge the capacitor, Coh. The charge-up time required is approximately 300 ms for a capacitor with 30 IIF. The uppermost operational amplifier is used for the voltage regulation of the system supply voltage (3 V to 4 V). Hardware Applications 3-73 P~~r.Supp/~ for MS!,430 Systems If Ii stabilized supply voltage is unnecessary, then this operational amplifier can be omitted, as well as the diodes and pull-up resistors althe RST/NMI and PO.1 inputs. The reference for the complete system is an LMx85 reference diode. This reference voltage (1.25 V) is used for several purposes: trigger threshold for the Schmitt-triggers, reference for the calculation of Vee, and reference for the voltage regulator. The operational amplifier in the middle works as a reset controller. The Schmitt-trigger switches the RST/NMI input of the MSP430 to a high level when VC reaches approximately 4 V. The RST/NMI input is set low when VC falls below 2.5 V. The· third operational amplifier decodes the information out of the charge voltage and data of the· power converter output. This decoder also shows a Schmitt-trigger characteristic. The measured data is sent back to the host by an IR LED controlled by an NPN transistor. The data format used here is an inverted RS232 protocol and has no current flow for the MARK information (e.g. stop bits). 3.8.6.2 Working Sequence The normal sequence for a measurement cycle is as follows: 1) The host starts a measurement sequence with the transmission of steady light. This time period is used for the initial charge-up of the ch~rge capacitor, Cch. 2) When this capacitor has enough charge, which means a capacitor voltage (VC) of approximately 4 V is reached, then the reset-Schmitt-trigger switches the RST/NMI input ofthe MSP430 from low to high. The MSP430 program starts with execution 3) The MSP430 program initializes the system and signals its readiness to the host by the transmission of a defined code via the back channel (a second fiber-optic cable). 4) After the receive of the acknOWledge, the· host sends the first control instruction (data) to the MSP430. 5) The MSP430 executes the received.control instruction and sends back the measured result to the host via the back channel. 3-74 Power Supplies for MSP430 Systems 6) Items 4 and 5 are repeated as often as needed by the host. Charge ..... VC From Host ~~~ :;: PPC-SE-sMA CCH r- PowarConverter 2.4xR1 ~l Flbar-Optlc ( )aLight .... ~ ~~ OV av Rl :::: ~ .. .... VC Raaat VREF " IR·LED 1N229-SMA .... I~ T AXV'-- I'r- Vss I~ =:f:'$1078CN SVCC Vec Data RST/NMI AO Analog Data Maaa.Unlt PO.x ~ Contral XBUF 132~ Clock AGND ~ PO.1 (RCV) . ]BSpaca ilia Mark PO.2(TXD} OV Figure 3-42. Supply via Fiber-Optic Cable 3.8.6.3 Conclusion The illustrated concepts for supplying the MSP430 family with power demonstrate the numerous ways this can be done. Due to the extreme low power consumption of the MSP430 family, it is possible to supply them with all known power sources. Even fiber-optic cables can be used. Hardware Applications 3-75 Power Supplies for MSP430 Systems 3-76 Chapter 4 Application Examples Several MSP430 application examples are given in the following sections. Common to nearly all of them is the storage of calibration data, tables, constants, etc. in the external EEPROMs. External EEPROMs are used for safety reasons. If the microcomputer fails completely, it is still relatively easy to read out the accumulated consumption values. This is usually impossible if these values reside in internal EEPROMs. These EEPROMs can also store tables that describe the principal errors of a given measurement principle that is dependent on the input value (current, flow, heat etc.). The MSP430, with its excellent table processing capabilities, can determine the right starting value out of these tables and calculate the linear, quadratic or cubic approximation value. The following figure shows the principal error of a meter. The complete range starting at 1% up to 200% is divided into sub ranges of different length. A stored table would contain the starting point, the different distances and the inherent error at the beginning of each range. With this information, the MSP430 can calculate the error at any pOint of the measurement range. 4-1 4.1 4.1.1 Electricity Meters Overview The MSP430 can be used in two completely different kinds of electronic electricity meters. The difference between the two methods is mainly where the electrical energy W= fUX,Xdt is measured: D The electrical energy is measured in a front-end separated from the MSP430. Several methods exist for doing that: Hall effect sensors, Ferraris wheel pick-ups, analog multipliers, etc. The interface to the MSP430 is normally a train of pulses, where every pulse represents a defined amount of energy (Ws, kWs, Wh). All family members can be used for this purpose. D The electrical energy is calculated by the MSP430 itself, using its 14-bit analog-to-digital converter (ADC) for the measurement of current and voHage. Only the MSP430C32x can be used for this purpose. The two different methods are shown in Figure 4-1 o sv .-------~ COM ee SEL 3t.t5Eil.B _IBI~ MSP430C31x PO.x Frontend Pulses o 32kHz 1--. Perlphsrals 32kHz COM sVcc SEL LCD MSP430C32x Voltage PO.xl--. Peripherals PO.y Current Vss Vee Vss Vee Figure 4-1. Two Measurement Methods for Electronic Electricity Meters The 'second method is mainly used with the electricity meters described in this chapter. The unnecessary front end gives a cost advantage when compared 4-2 to the two-chip solution. An example for the 1st method that uses a front end is shown at the end of this chapter. 4.1.2 The Measurement Principle The principle used (Reduced Scan Principle) measures current and voltage in regular time intervals and multiplies the current and voltage samples. The multiplication results are summed up, with the sum representing the consumed energy (Ws, kWh). While the method normally used measures voltage and current at exactly the same time, the Reduced Scan Principle (a protected TI method) alternately measures voltage and current samples. Every sample is used twice; once it is multiplied with the value measured before and once with the value measured afterwards. To further reduce the required multiplications, these two multiplications are reduced to one by using the sum of the two voltage samples. This measurement principle is shown in Figure 4-3. The following shows the measurement sequence for a single-phase measurement. Current and voltage are measured alternately. The time, (1, represents the angle between related voltage and current samples. ~a-.l Voltage 1/ARR tI+- I I Current VOltage ~ Repetition Time ! --I Current I --+ Time Figure 4-2. Timing for the Reduced Scan Principle (Single Phase) Where: Inherent Phase Shift of the Measurement Method [rad] Repetition Time Length of a complete measurement cycle [s] 1/ARR lime Distance between two ADC Conversions [s1 (1 Note: The Reduced Scan Principle is intellectual property of Texas Instruments. This measurement principle may be used only with the microcomputers pro, duced by Texas Instruments. Application Examples 4-3 o Sampling Point --+ Time Figure 4-3. Reduced Scan Measurement Principle The measured energy W (for a single phase) is: t=QQ W = I in x (u n - 1 + un + 1) x bot 1=0 Where: W in un-1 un+1 .1.t 4-4 Accumulated energy [Ws] Current sample at time tn [A] Voltage sample at time t n-1 [V] Voltage sample at time tn+ 1 [V] Sampling interval between appertaining voltage and current measurements [s] 4.1.2.1 The Inherent Error of the Reduced Scan Principle The Reduced Scan Principle has a small inherent error caused by the phase shift At, once inductive and once capacitive, due to the time interval between voltage and current measurements. Any calculated energy sample shows this error, it is independent of the phase angle q> between voltage and current. The value, e, of this error is: e = (cos (6.1 x f x 2lt).- 1) x 100 where: e At Error Sampling interval between voltage and current measurements AC frequency [%) [s] [Hz] For example, with the values (f = 60 Hz, At =300 ~) the inherent error.is -0.639%. This error can be eliminated during runtime by a multiplication of the accumulated energy with the correction factor c: c = 1 oos(6.t x f x 2:n:) The correction factor, c, is normally included in the calibration constants (slope and offset) and not used explicitly. For a multiple-phase electricity meter, the Reduced Scan Principle is used for all phases one after the other. This is described in the following chapters. Derivation of the Inherent e"or The flawless equation (except the quantization error) for the electric energy W is: t-= W = L in x un x 6.1 tzO The equation used for the Reduced Scan Principle is: t-~ W = L in x (U n _ 1 + Un +1) x 6.t t-O Application Examples 4-5 Where: un = U x sinrot in .;, I x sin(rot+cp) un-l .. U x sin(rot-«) Un+ 1 = U x sin(rot+a.) a. 6t cp Voltage sample at time t Current sample at time t Voltage sample at time t - 6t Voltage sample at time t + 6t Angle in radians between current and voltage samples (a. .. ro6t .. 21tXfxA.t) Time between appertaining current and voltage samples Phase angle in radians between voltage and current The error e of an energy sample due to the Reduced Scan Principle is: e = erroneous - 1 correct 0.5 x I x sln(6lt e = + : Sample frequency: Voltage: Current: 8190 steps (1 FFEh) 49.98% of full ADC range 5s (calibration points are measured this time) 9s 50 Hz 1 (0 0 ) , 2048 Hz (488.3 IJ.S sample distance) 100% Vpp uses 90% of the ADC range 100% Ipp uses 90% of the ADC range Note: The drawings on top of the columns of Table 4-5 indicate the ADC error in dependence ofthe ADC value. Figure 4-5 shows the drawing above the second column in a magnified form. Application Examples 4-13 Table 4--5. Errors With One Current Range and Single Calibration Range Load Current - ~ Pt ~ ~ J?+4 0.1% +0.n71% +7.79% -2.93% +0.45% +0.57% +3.94% 1% -0.0114% +0.83% -0.24% 0% +0.01% +0.38% 2% +0.0620% +0.50% +0.01% +0.01% 0% +0.24% Calibr. P. 5% -0.0001% 0% 0% 0% 0% 0% 10% +0.0005% -0.19% -0.01% 0% 0% -0.09% 25% 0% -0.27% -0.01% % 0% -0.13% 50% -0.0001% -0.31% -0.01% 0% 0% -0.15% 75% +0.0001% -0.17% 0% 0% 0% -0.09% calibr. P. 100% -0.0002% 0% 0% 0% 0% 0% The large errors at 0.1 % of the nominal current resultfrom the relatively far dis-tance from the 5% calibration point and from the missing resolution of the ADC at this small load. The peak-to-peak value of the ADC result is only 14.7 steps. These errors can be reduced drastically by using one of the following methods. 4.1.3.1 Methods to reduce the Error of the Energy Measurement Three relatively simple methods are given to reduce the error of the energy measurement. In any case, the values used for the correction are stored in the EEPROM and are loaded into the RAM during the initialization. Using a Second Hardware Range This method is shown with all hardware examples. An analog switch like the TLC4016 SYfitches a second resistor in parallel to the one used for the low current range. Both ranges uses its own set of calibration constants (slope and offset) that are measured during two Independent calibration runs for every phase. The advantage of this method is the real increase of resolution for the low current range. Using a Second calibration Range This method only uses a second set of calibration constants (slope and offset) without additional hardware for the low current range (e.g., from 0.1 % to 5% of the nominal current). This method needs two calibrations per phase, but uses only three measurements (one measurement is used for both ranges). 4-14 Table 4-6 shows the enhancement of the accuracy when a second calibration run is made for the low current range, 0.1 % to 5% of the nominal value. The calculations are made with the same conditions used with Table 4-5. The enhancement can be seen with a comparison of the two tables. The errors, for the range 5% to 100% of the nominal current, are the same as shown in Table 4-5. Table 4-6. Errors With One Current Range and Two Calibration Ranges Load Current I I I Calibr.P. I ~ Pt hA- ~ ~ 0.1% +0.004% +0.004% +0.002% +0.005% +0.005% +0.003% 0.5% -0.236% -0.002% +0.190% -0.163% -0.041% -0.119% -0.075% -0.251% -0.003% -0.161% 1% -0.040% +0.056% 2% -0.018% +0.262% +0.098% -0.005% -0.012% +0.122% 3% -0.006% +0.062% +0.024% -0.013% -0.012% +0.022% 4% -0.010% -0.035% -0.025% -0.009% -0.007% -0.023% 0.000% 0.000% 0.000% 0.000% 0.000% O.Oqo% Calibr.P. 5% Measurement of the ADCs Characteristic This method uses the actual deviations of the ADC for a rough correction of the measurement results. During a first run, the ADC characteristic is measured and correction constants are calculated for any of 8 to 32 software subranges of the ADC. These correction constants are written into the EEPROM and loaded into the RAM for use. For every subrange, one byte is needed, which allows corrections up to ±127 steps. The correction for the samples needs only seven instructions per 14-bit value. The advantage of this method is the adaptation to the actual deviation of the individual ADC. Figure 4-6 shows the correction with the ADC characteristic using only 8 correction values. The deviations reduce to one quarter of the original ones. If the correction shows a step near the virtual zero point like shown in Figure 4-6, the subranges 81 and CO can be corrected in a way that omits this step. Chapter 2, The Analog-To-Digital Converters gives more information. Application Examples 4-15 i ADC Deviation (Steps) . 20 RangeD ~ Range A SubrangOI Subrango I .Corrected ADC Characterlatlc All A1 o Correction Valuaa For The Subrangaa Agure 4-6. Use of the Actual ADC Characteristic for Corrections (8 Subranges Used) 4.1.3.2 Dependencs on the Voltage and the Phase Angle cp Table 4-7 shows the dependence of the MSP430 using the Reduced Scan Principle on the load current. the ac voltage and the phase angle. cpo between current and voltage. The ADC is assumed to be error-free; the saturation effect at the range limits is included. Single calibration with only one range is used. Nominal voltage is used for the load current dependence and nominal current (100%) is used with the voltage dependence. The calculations are made with the same Conditions used for the calculations in Table 4-5. Table 4-7. Errors in Dependence on Current, Voltage and Phase Angle Angle,!, ACVoitage Load Current 1% 100/0 100% 80% 800/0 1100/0 Ind. -80' +4.119% +0.447% +0.046% +0.048% +0.047% +0.045% +0.010% -60' +0.857% +0.099% +0.010% +0.009% +0.010% -40' +<>.257% +0.003% +0.003% +0.003% +0.004% -20' +0.047% +0'032% +0.009% +0.001% 0.000% +0.001% +0.001% 0.000% 0' -0.011% +0.001% 0.000% +20' +0.043% +0.004% 0.000% +40' +0.248% +0.021% +60' +0.844% Cap. +80' +4.051% 0.000% 0.000% +0.001% +0.001% 0.000% 0.000% +0.004% +0.003% +0.001% +0.075% +0.007% +0.012% +0.009% +0.005% +0.376% +0.037% +0.056% +0.046% +0.031% , 4.1.3,3 Derivation of the Measurement Formulas The electronic meter equivalent of the meter constant of a Ferraris wheel meter (revolutions per kWh) is the meter constant. Cz. that defines (ADC steps)2 per Ws. The corrected equation used for the electric energy W is: 1-~ W = cos(2n 4-16 ~ f x At) x ~ in x (U n _ 1 + un + 1) x At [Ws] With the ADC results ADCi (current sample) ADCu (voltage sample) and ADCOu and ADCOi (zero volt samples) the previous equation gets: I-~ W = cos(2lt ~ f x At) x I ki x (ADCin - ADCOi) x ku x (ADCU n _ 1 + ADcu n + 1 - 2 x ADcou) x At 1-0 Separation into variable and constant values results in: I-~ W = cos(2lt ~ f x At) x At x ki x ku x ~(ADCin - ADCOi) x (ADCu n _1 + ADCu n+ 1 - 2 x ADcou) Where: f At ki ku ADCi n ADCun-1 ADCun+1 ADCOu ADCOi AC frequency [Hz) Sampling interval between appertaining voltage and current samples [s] Current multiplication factor [A/step). See Section 4.1.4.5 for more details Voltage multiplication factor. [V/step] See section 4.1.4.6 for more details ADC value of current sample taken at time tn ADC value of voltage sample taken at time tn-1 (tn - At) ADC value of voltage sample taken at time tn+ 1 (tn + .6t) ADC value of voltage zero point (measured or calculated) ADC value of current zero point (measured or calculated) The first, constant part of the equation is the inverse value of the meter constant ,Cz: Cz = cos(lbt x f x At) At x kl x ku [Steps2/Wsl The values for kl and ku for different interfaces are explained in detail In Section 4.1.4. For a system using a current transformer and a resistor divider for the voltage, the previous equation gets: W __ 1 SVCC x wsec SVCC x (Rm + Rc) x At x x x cos(lbt x f x At) 214 x wprim x Rsec 214 x Rc -=--'--:--..,-,:" t=OD I(ADCi n - ADCOi) x (ADCU n _ 1 + ADCu n + 1 - 2 x ADCOU) I~O Application Examples 4-17 Where: Rsec Load resistor (s.econdary) of the current transformer [0] wsec Secondary windings of the current transformer Wprim Primary windings of the current transformer SVCC Voltage at terminal SVCC (AVCC or external reference voltage) M Rm Voltage divider: resistor between ac connection and analog input [0] Voltage divider: resistor between analog input Rc and zero volts [01 The first, constant part of the equation is the inverse value of the meter constant Cz: cos(2;t x f x At~ x 228 x wprim x Rsec x Rc AI x SVCC 2 x wsec x (Rm [Steps2/Ws] + Re) With the previous value of ez, the equation for the energy W is: t-~ W= I(ADCi n - ADCOi) x (ADCU n ':' 1 + ADCu n + 1 - 2 x ADCOU) ~t-~O ______ ~ ________, ,___________________ [Ws] Cz If the energy W is to be expressed in kWh: t-~ W= I (ADCin - ADCOi) x (ADCu n _ 1 + ADCu n + 1 - 2 x ADCOU) __________________ ~t-~O ~ _________________ [kWh] 3.6 x 109 x Cz The value W needs to be corrected with the slope and offset calculated during the calibration process. 4.1.4 Analog Interfaces to the MSP430 This chapter describes some important topics that can affect the overall accuracy of the electricity meter. 4.1.4.1 Analog and Digital Grounding The following schematics are drawn in a simplified manner to make them easier to understand. In reality, It is necessary to decouple the analog and the digital part as shown in Figure 4-7. This is to avoid digital noise on the analog signals to be measured. 4-18 230 V Reference -41--4~---tSVcc REXT '--1-_"'-,-01..:.11.:.98'-1 A1 MSP430C323 Current AO A5 AVss AVCC DVSS DVCC ToAVCC To Other + ____- J Analog Paris To Other DlgllIl Parts AGND oV .--il--" 5V "--y--J Powar Supply Figure 4-7. MSP430 14-Bit ADC Grounding 4.1.4.2 ADC Input Considerations The ADC accurately operates up to 1.5 MHz. If the processor clock MClK is higher than this frequency, it is recommended that one of the prescaled ADC . clocks (ADCll<) be used. The possible prescaled frequencies for the ADClK are MClK, MClKl2, MClKl3 and MClKl4. The sampling of the ADC to get the range information takes 12 ADClK cycles. This means, the sampling gate is open during this time (12 J1S at ADClK = 1 MHz). The input of an ADC terminal can be seen as an RC low-pass filter, 2 1<0 together with 42 pF. The 42-pF capacitor must be charged during the 12 ADClK cycles to the final value in order to be measured. This means charged within Z-14 of this value. This time limits the internal resistance RI of the source to be measured: (Ri + 2 kQ) x 42 pF < In 2 14 12 x ADCLK Solved for Rio the result is 27.4 k.Q. This means, to get the full 14-bit resolution of the ADC, the internal resistance of the input signal must be lower than 27.4 1<0. The given examples use lower source resistances at the ADC inputs. Application Examples 4-19 4.1.4.3 Offset Treatment If the voltage and current samples contain offsets, the equation for the measured energy W is: t-= W I(~n + Ou) x (in + 0,) x At = t-O ' t_m W = I (un x in + un x OJ + jn x 0u + OJ x Ou) x At 1-0 Where: Ou OJ un Offset of voltage measurement [V] Offset of current measurement [A] Sum of the two voltage samples un-1 'and un+1 M The terms (un x OJ) and (in x Ou) get zero when summed-up over one full period (the jntegral of a sine curve from 0 to 2n is zero) but the term (Oi x Ou) is added erroneously to the sum buffer with each sample result. If one of the two offsets can be made zero then the error term (Oi x Ou) is eliminated: this is the case -for all proposals. Two different ways are used: o Voltage representing OV is measured (see Sections 4.1.4.4.1 and 4.1.4.4.2) , o Summed-up ADC value for a full period is used for this purpose (see Section 4.1.4.4.3). 4.1.4.4 Adaptation to the Range of the Analog-ta-Digital Converter The analog-to-cfigital converter of the MSP430 is able to measure unsigned voltages ranging from AVss up to the reference voltage applied to the input SVcc. If signed measurements, as for electricity meters, are necessary then a virtual zero point must be provided. Voltages above this zero point are treated as positive ones, voltages below it are treated as negative voltages. A few possibilities are shown how to provide this virtual zero point. For more information see Section 3.8, Power Supplies for the MSP430. Split Power Supply To get a common reference voltage in the middle of the ADC's voltage range, two voltage regulators with output voltages of +2.5 V and -2.5 V can be used. In this case, the common zero connection is the reference for all current and voltage measurements. This zero point is connected to one of the analog inputs (AO in Figure 4-8). The measured ADC value of this reference voltage is 4-20 subtracted from every voltage and current sample. This way signed, offset corrected measurement values are generated. The schematic is shown in Figure 4-8. I 2.5 V $ 2.5 V T SVec AVec A1 -4.3V102.3V OV AO MPS43OC32x -4.5 V AVss . DVss I -2.5 V DVec I 2.5 V Figure 4-8. Split Power Supply for Level Shifting Use of a Virtual Ground Ie A virtual ground IC can be used to get a measurement reference in the middle of the ADC range. The TLE2426 is used for this purpose. All current and voltage inputs are referenced to the virtual ground output of this circuit. The main advantage is the ability to measure the ADC value of this reference without the need to switch off the voltage and current inputs. The measured value (at analog input AO), is subtracted from every measured current or voltage sample, which generates Signed, offset corrected results (see Figure 4-9). Typical electrical characteristics of the TLE2426: Supply Current Output Impedance Output Current Capability Power Rating at 25°C Derating Factor above 25°C 170 !lA 0.00750 ±20mA 725mW 5.8mW/oC No load connected For sink and source For the Small Outline Package ApplicatIon Examples 4-21 5V .---------iA1 1-......--~Iio;L;LlAO MPS43OC32x '-------O;;..V"-IAVSS DVss OV DVCC 5V Figure 4-9. Virtual Ground Ie for Level Shifting Resistor Interface (Software Offset) This method uses the fact that the integral of a sine curve is zero, if integrated over the angle 21t. Two counters add up the ADC results separately for each voltage and current signal. These counters contain the two offsets (in ADC steps) after a full period of the ac frequency. These offsets are subtracted from the appertaining ADC samples. The results are signed, offset corrected samples. The current and voltage signals are shifted into the middle of the ADC range by simple voltage dividers or with the help of the internal current source. Without A Current Source The necessary shift of the signed voltage and current signals is made by resistor dividers. The resistor divider of the voltage part is also used for the adaptation of the ac voltage to the ADC range. The current part allows two (or more) current ranges. With the closed range switch, high currents can be measured. With the switchopen, a better resolution for the low currents is possible. No dc flows through the current transformer due to the high input resistance of the ADC inputs. 4-22 230 V --~ 1 ~ AVec SVcc 22kf.l 1.6Mf.l AO ~ H-o~l TLC40161 Range SwItch 5V T A1 MPS43OC32x 22kf.l OV AVSS DVSS I OV DVCC I 5V Figure 4-10. Resistor Interface Without Current Source With A Current Source Four ACe inputs can be used with the internal current source. A current, defined by an external resistor Rex, is switched to the ACe input and the voltage drop at the external circuitry is measured with the ACe. This current is relative to the reference voltage SVcc and delivers constant results also with different values of SVcc. If a second current range is needed, a reed relay is needed to switch the second load resistor of the current transformer. Note: The signal at the current transformer has a negative going part-outside of , the ACe voltage range-therefore a TLC4016 cannot be used). The current Ics flows through the current transformer's secondary windings. This will need to be checked to see if it is usable. Application Examples 4-23 IIOa: 230 V ~ -- 1.6MO 1 ~Rex 5V T AVcc sVcc REXT AO MPS430C32x +-ICS A1 1.25 V 5.61<0 AVSS 108 = SVCC 4xRex OTV DVSS I OV DVCC I 5V Figure 4-11. Resistor Interface With Current Source Note: If the current source is used, only ADC ranges A and B can be used. This is because of the supply voltage the current source needs for operation. The resolution is therefore only one-half of the normal value. The midpoint of the ADC range is then 01 OOOh. 4.1.4.5 Current Measurement The main problem of the current measurement is the large dynamic range of the input values; ranging from 0.1 % up to 1000% of the nominal value. The common methods used to solve this problem are shown in Figure 4-12 and are explained in the following text. If range switches are used, it is recommended that a hysteresis for the range selection criteria be used. Shunt The load current IL flows through a resistor Rshunt (0.3 mO to 3.0 mO) and the voltage drop of this resistor (shunt) is used for the current measurement. Due to the small voltage drop, especially with low currents, it is necessary to amplify this voltage drop with an operational amplifier. This operational amplifier can have only a very small phase shift (0.1 0) to get the needed accuracy. The out4-24 put voltage VOut. which is proportional to the current IL. is measured by the MSP430. The amount of VOut is: ~~ Vout =- Iload x Rshunt x Vout =- R2i I R3 Iload x Rshunt x -R-1- (open switch. low current) (closed switch. high current) The value ki lA/step]. used for the calculation of the meter constant Cz (see Section 4.1.3.3) is: ki SVcc = --X 214 SVcc R1 ---x.".-----:-''-';:v;;--;--;::;.:;214 Rshunt x R2i I R3 ki o (open switch. low current. see Figure 4-12) (closed sw~ch. high current) Advantages • o R1 Rshunt x R2 -.o--""-~ Resistive behavior • Simple • More than one range possible with switches Disadvantages • High losses with high currents • Very low output voltage with small currents (amplifier necessary) • Only usable with single-phase meters Application Examples 4-25 --. lload Live - - - - - - - - - - - . : ; ; . ..... Wprlm Live -Weec Load Load R2 R3 RSHUNT Neutral Neutral ~ VOUT----< Current Transformer -2.5 V R2 Shunt Figure 4-12. Current Measurment Current Transformer ' The secondary current Isee of the current transformer, which is flows through a resistance Rsec (the resulting resistance of the two resistors R2 and R3) and generates a voltage VOUT, which is measured by the MSP430: w prlm Vout = wsee x Iload x Rsee Where: Rsec= R2 Rsec .. R211R3 (switch open, low cU,rrents) (switch closed, high currents) The value ki [A/step], used for the calculation of the meter constant Cz (see Section 4.1.3.3) is: ki o ~26 SVcc wsee =-- x =---'~=<--214 Rsee x wprim (see Figure 4-12) Advantages • Isolation from ac • High accuracy for the magnitude of the current (0.1 % reachable) • o More than one range possible with switched resistors Disadvantages • Sensible to dc current: may lead to saturation • Costly Ferrite Core The load current Iload flows through a ferrite core with a single winding. The ferrite core has a small air gap. The magnetic flux crossing this air gap goes through an air-core coil, which is not loaded. The small output voltage VIc of this coil is amplified, integrated, and measured by the MSP430. The voltage gain of the preamplifier is used for the range switching. The ferrite core behaves as an inductivity L i.e. the output voltage VIc is: VIc dl load = di x L This means, the voltage VIc has a leading phase shift of 90° compared to Iload. This phase shift can be corrected by two methods: 1) Software shift: All current samples are delayed by the time representing 90° of the ac frequency. This is possible with a circulating buffer and a carefully chosen sampling frequency. 2) Analog shift: An integrator combined with a pre-amplifier is used as shown in Figure 4-13. The value ki [Alstep], used for the calculation of the meter constant Cz (see Section 4.1.3.3) is : ki = -SVcc - xex - R1 214 vx L The formula is valid only ifR2 »R1 (normal case). o o Advantages • Isolation from the ac • No saturation possible by dc parts of the load current due to the air gap Disadvantages • Low output voltage due to loose coupling • Output voltage leads 90° compared to load current Application Examples 4-27 • Fast load current changes cause relatively high output voltages (di/dt) • Circular buffering or amplification and integration necessary VOUT ov -2.5 V Compensated Ferrite Core Ferrite Core Figure 4-13. Current Measurment With a Ferrite Core Compensated Ferrite Core The load current !load flows through a closed ferrite core with a primary winding wprim (normally a single winding). The magnetic flux created by the primary winding is sensed by the sensor winding wsense. The voltage of the sense winding is amplified and the output current of the amplifier is sent through the secondary winding wsee in a way that compensates the primary flux to (nearly) zero. This means that the driving of the resistor Rsee is made by the amplifier and not by the ferrite core. The compensated ferrite core shows only negligible errors. It is only necessary to distribute the two windings in a very equable way over the entire core (not as it is shown in Figure 4-13 for simplicity). Additional current ranges are possible with switched resistors in parallel with Rsec. The output voltage Vout is: Vout = II Wprim wsensex Rsec wsec + vXRsense ad x Rsec x ___..L:..::..:.:...----,=_- o The term wsense x Rseclv x Rsense is the remaining error of the compensated ferrite core. 4-28 The value ki [A/step], used for the calculation of the meter constant Cz (see Section 4.1.3.3) is (the error term is not included due to its low value): ki = o 214 Rsec. w prim Advantages o 4.1.4.6 - SVcc - - x -1- xwsec -- • Isolation from ac • Nearly complete compensation of the ferrite core's hysteresis and nonlinearity errors Disadvantages • Amplifier necessary • Difficulties to stabilize feedback loop Voltage Measurement The problem of the current measurement, the large dynamic range, does not exist for the voltage measurement. AC voltage always has a nearly constant value. Two measurement methods are used normally. ILOAD. Live - - - -.....- - - - - , RM RC - --1'-;::;:;:;=:;::::;--, Load Load Ne~ml ----~---~ ADC 1 I--- Live -+----+-..1 Neutml - -.... VSEC +---- VSEC OV ADC ....- - O V Resistor Divider Voltage Transformer Figure 4-14. Voltage Measurement Application Examples 4-29 Resistor Divider The ac voltage Vac is adapted to the range of the ADC by a simple resistor divider. All of the examples given use this method. The amount of Vsec is: Vsec = Rm R~ Rc x Vac The value ku [V/step], used for the calculation of the meter constant Cz (see Section 4.1.3.3) is: SVcc Rm + Rc ku = -x--- 214 Rc [V/step] (see Figure 4-14) Voltage Transfomer A voltage transformer is used if the ac voltage is very high or if galvanic isolation is needed. Protection (PR) at the secondary side is needed, due to the low output impedance of the voltage transformer. The amount of Vsec is: Vsec Wsec = -.x wpnm Vac The value ku [Vlstep], used for the calculation of the meter constant Cz (see Section 4.1.3.3) is: SVcc wprim ku = - - x - 214 wsec [V/step] (see Figure 4-14) 4.1.5 Single-Phase Electricity Meters The next two electronic electricity meter proposals are made for the measurement of European ac. From the utility, one phase and ground are wired into the house. In this way a nominal voltage of 230 V is available. ' The reduced scan principle is applied exactly as described in Section 4.1. To measure the electric energy consumed, a current transformer or a shunt resistor is necessary, both solutions are shown. The voltage of the phase is also measured. With this configuration, the energy consumption of the load can be measured exactly. The measurement sequence for a Single-phase meter is shown in Figure 4-2. The ADC of the MSP430 measures the voltage between the AVss and SVcc connections with a resolution of 14 bits. To shift the signed voltages coming 4-30 from the current transformer and voltage divider into the unsigned range of the ADC, a split power supply with +2.5 V and -2.5 V is used. The common ground of the two power supplies has a voltage of one-half of the voltage SVcc. This voltage is used as a base for the ADC voltages. The MSP430 measures this base voltage at regular intervals and subtracts it from every measured current or voltage sample. In this way, signed measurement is possible. To have a reference for the measurements a reference diode LM385-2.5 is used. The voltage of this diode is measured in regular intervals and the measured value is used as a base for the·SVcc relative ADC measurements. 4.1.5.1 Current Measurement With a Shunt The solution which uses a shunt resistor for the measurement of the load current is shown in Figure 4-15. The load current Iload flows through the shunt, which has a resistance of approximately 1.0 mOo The voltage drop at the shunt is amplified and measured by the MSP430. The output voltage Vout seen at the ADC of the MSP430 is like described in Section 4.1.4.5.1. If needed, additional current ranges can be implemented (three analog switches of the TLC4016 are not used). A backup battery allows the time information (provided by the basic timer) to be kept and is also used during power-down periods. All current-consuming peripherals may be switched off. Therefore; the reference diode, the range switch, and the amplifier are switched off by the SVcc output. The EEPROM is switched off with a TP-output. A prepayment interface is connected to the MSP430. It allows the ac to be switched on after the insertion of a valid prepayment card. Application Examples 4-31 ILOAD. live - ......-----------=;-----, Load FlSHUNT Neutral .....-I------::::-----<'""'vv-~ Vout 4.7MO Flange SwItch 2.5 V SEL .--+--I--+--I SVcc 1.-.--1 TP.O TP.2 .---t--+-~::-::,-IA1 VOltage 82 k1l 123~S6'.B _ _ lkWhl J--===::::;-----------J. TP.11---+i L.....--~-IAO 33 k1l 2.3.'"I. COM AVCC Current oV __.......----+------fA5 PO'0r-;:::::=! PO.2 TXD Fleterance A4 PO.1 ~~L_---I IFlCV LMxB5Urel PO.3 1+---+1 ""'-----1 AVSS -i.5V Key PowerFlelay PO.4 t----(~ 2.5 V TP.3 1--.... Pul8e We '--.-11-i.5V 2.5V -i.6 V Backup Battary Figure 4-15. Single-Phase Electricity Meter With Shunt Resistor 4.1.5.2 Current Measurement With a Current Transformer The solution, which uses a current transformer for the measurement of the load current, is shown in Figure 4-16. The secondary current Isec of the transformer flows through two paralleled resistors and generates a voltage Vsec which is measured by the MSP430. For currents greater than a certain value, the resistor with the lower value is switched on by the analog switch TLC4016. For low currents, this switch is· opened to get a higher voltage and, therefore, a better resolution. The range switch algorithm uses a certain hysteresis to avoid too much switching. 4-32 If needed, additional current ranges can be implemented with the three analog switches of the TLC4016 that are not used. An AC Down signal out of the power supply connected to the interrupt 1/0 terminal PO.6 allows the MSP430 to save important values (Le., energy consumption) in the EEPROM in case of a power-fail. See Section 5.7, Battery Check and Power Fail Detection. The RF-readout module is connected to free outputs; this can be an unused segment line, a TP output, or an 1/0 pin of PortO. The timing for the RF readout is made by the internal Basic limer. It delivers the needed interrupt frequencies. The supply voltage needed for the RF interface is done with a step-up voltage supply. It transforms the available 5 V to 6 V or more. Live - ......--""'--'-U_.A~---~I:-LO-A-D----, 2.5 V I ISEC--+ WSEC vv--." t-...JVR2 T+_-f=r~;:TNeutralRange RF·Antenna -2.5 V Load 1I1IL1'" __-;::==~_Se=I-~u,p-FreqUenCY RF-Inlertace MOD Switch = 4.3MO 2.6 V 2.3.'i. 123"'561.8 _ _ lkWhl AVCC SVec TP.O Voltage 33kr.l 2.5 V 82kr.l Current At AO TP.l OV-4-+--__--+---------; A5 Reference A4 PO.l LMX85U,e' AVSS PO.3 -2.5 V Key AcDown PO.8 PO.4 DVss DVec PO.5 -4.5 V ~2.5V PulseWs 2.6 V Figure 4-16. Single-Phase Electricity Meter With Current Transformer and RF Readout Application Examples 4-33 4.1.5.3 Calculations For four single-phase versions, the typical values are calculated: o Version with minimum current consumption (low CPU and ADC speed) o Compromise between current consumption and resolution (medium CPU speed, medium ADC speed). The basic timer is used for the time base. o Compromise similar to 2, but with the use of the universal timer/port module for the time base. o Version with high resolution due to sampling speed. If necessary, the ADC Clock can be up to 1.5 MHz. Table 4-8. Typical Values for a Single-Phase Meter ITEM MINIMUM CONSUMPTION COMPROMIZE 1 COMPROMIZE 2 HIGH RESOLUTION 50Hz 50 Hz 50Hz 50Hz lime Base for ARR AClKl18 Basic limer 2048 Hz AClKl9 AClKl5 MClK (CPU Clock) 0.754 MHz 0.754 MHz 1.048 MHz 2.195 MHz ADC Clock (ADCLK) 0.754 MHz 0.754 MHz 1.048 MHz 1.097 MHz 23 23 32 67 1620.4 Hz 2048 Hz 3640.9 Hz 6553.6 Hz AC Frequency N (MClKlAClK) ADC Repetition Rate ARR Phase Repetition Rate (ARRl2) . 910.22 Hz 1024 Hz 1620.4 Hz 3276.8 Hz Phase Repetition Time (21ARR) 1098.63118 976.56118 549.32118 305.18118 36.4 41.0 72.8 131.1 9.88" 8.79 0 4.94 0 2.750 -1.5% ~1.2% -0.37% -0.11% ADC Conversion lime te (14 bits) 175.1118 175.1118 125.89118 120.251J.S Interrupt Overhead tl 22 MClKa§ 29.2118 29.21'8 10.5118 10.01lS lime per Measurement tc + tl 204.3118 204.31lS 136.4118 130.3118 lime between interrupts l/ARR Measurements per 360· (50 Hz)t Sample Phase Shift a Inherent Error:!: 549.3118 488.31's 274.71lS 152.6I's ADC loading (tc + til x ARR 37.2% 41.8% 49.7% 85.4% CPU loading by MPysf 19.3% 21.8% 27:.6% 23.8% Approx. Icc (nominel) for MSP430C323 820 IlA 6201lA 10351lA 1872jJ.A t ADC conversions per complete mains period (voltage and current samples) :I: The Inherent Error-a constant value-ls compensated with the calibration values § lime from ADC Interrupt acknowledge until next conversion is started (after 22 MClKs) \I One Signed multiplication per phase repetttion time; 160 cycles for each one 4-34 4.1.6 Dual-Phase Electricity Meters The measurement sequence for a dual-phase electricity meter is shown in Figure 4-17. a---'I I I , I I I I ~ I Vr Vs Ir I I ~1/ARR r I Is Vr I I Va Ir Is Vr • Time Repetition Time ~ Figure 4-17. Timing for the Reduced Scan Principle (Dual-Phase Meter) Where: Repetition Time 1/ARR a Vx Ix 1{Phase Repetition Rate. Length of a Complete Measurement Cycle Repetition Rate of the ADC Inherent Phase Shift of the Measurement Method Voltage sample Phase x Current sample Phase x Two electronic electricity meters are shown, designed for the measurement of US domestic ac. As power connections, two phases and a neutral line are led into the house. This enables the use of two voltages: 120 V and 240 V. To measure the electric energy used, two current transformers are necessary. The voltage of each phase is measured directly. With this configuration, the energy consumption of any load connection can be measured exactly. Loads from any phase to neutral (120 V) are measured as well as loads connected between the two phases (240 V). 4.1.6.1 Current Measurement With Current Transformers and Virtual Ground IC A solution which lJses two current transformers for the measurement of the load currents is shown in Figure 4-18. The secondary current Isec of the transformer flows through two parallel resistors and generates a voltage Vsec, which Is measured by the MSP430. For currents greater than a certain value, the resistor with the lower value is switched on by the analog switch TLC40161. For low currents this switch is opened to get a higher voltage and, therefore, a better resolution. The range switch algorithm used has a certain hysteresis to avoid too much switching. The virtual ground IC delivers a voltage exactly in the middle between SVcc and AVss. All measurements refer to'this potential. The virtual ground voltage Application Examples 4-35 itself is measured with the analog input A5 and the measured value is subtracted from each voltage and current sample. If needed, additional current ranges can be implemented with the two analog switches of the TLC4016 that are not used. A backup battery allows the time information (provided by the basic timer) to be kept during power-down periods. All current-consuming peripherals can be switched off; the reference diode, the range switches, the virtual ground with the SVcc output, and the EEPROM with a TP output. Current Transformer Live - -.....-...,.,..~-----..... - , -- Range Load Switch 120V Load 240 V Neutral-.-~~--+-~~---t Load 120V Live -f....+-+-vvUJ--H---6---1 -- 32kHz U 2x2.2MC TP.O 2.1~. COM TP.1 SEL 5V SVec Curre," VOl I23'iS61.B AVec _ _ !kWh! TP.3 AO A1 A2 e A3 TP.2 2x33kO 82110 PO.2 Virtual Ground Reference A5 PO.1 A4 PO.3 LMx86Uref OV ~2.5V PO.4 AVSS PuIaeWs DVSS DVCC PO.5 IOV BV 4.5V Backup Battery Figure 4-18. Dual-Phase Electricity Meter With Current Transformers and Virtual Ground 4-36 4.1.6.2 Current Measurement With Current Transformers and Software Offset Figure 4-19 shows a two-phase electricity meter that uses voltage dividers to get reference voltages in the middle of the supply voltage for current and voltage inputs. The resistors of this voltage dividers are chosen to be smaller than the maximum source impedance of the ADC (see Section 4.1.4.2, ADC Input Considerations). To getthe ADC value ofthe virtual midpoint ofthe ADC range, the software offset method is used (see Section 4.1.4.4.3, Resister Interface (Software Offset). This value is subtracted from each voltage and current sample to get signed, offset-corrected results. No backup battery is provided. This means, tbat in regular time intervals, the actual amount of the energy consumption needs to be stored in the EEPROM. If the power supply used provides an ac down, this storage is only needed when this signal is activated. An ac down signal from the power supply connected to the interrupt 1/0 terminal PO.6 allows the MSP430 to save important values (Le., energy consumption) in the EEPROM in case of a power failure (see Section 5.7, Battery Check and Power Fail Detection). Application Examples 4-37 2XlSOkn PO.S Key POA --......-----4~------+__IAVSS ACDown DVSS DVCC PO.S OV ~2.5V PulseWs 5V Figure 4-19. Dual-Phase Electricity Meter With Current Transformers and Software Offset 4.1.6.3 Calculations For three dual-phase versions, the typical values are calculated: o o o Version with minimum current consumption Compromise between current consumption and resolution Version with high resolution due to sampling speed. If necessary, the ADC Clock can be set up to 1.5 MHz (see Table 4-10). .. Table 4-9. Typical Values for a Dual-Phase Meter ITEM AC Frequency MINIMUM CONSUMPTION COMPROMISE 60Hz 60 Hz ACLK17 MCLK (CPU Clock) ACLKl9 0.754 MHz 1.048 MHz ADC Clock (ADCLK) 0.754 MHz 1.048 MHz N (MCLKlACLK) 23 3640.9 Hz 32 4681.1 Hz 910.22 Hz 1170.3 Hz 1098.63 !IS 30.34 854.5 !IS Time Base for ARR ADC Repetition Rate ARR Phase Repetition Rate (ARR/4) Phase Repetition Time (4/ARR) Measurements per 360' (60 Hz)t Sample Phase Shift ex 39.0 HIGH RESOLUTION 60 Hz ACLKJ5 2.195 MHz 1.097 MHz 67 6553.6 Hz 1638.4 Hz 610.35 !IS 54.6 11.86' 9.22' 6.59' Inherent Error; -2.10% -129% -0.66% ADC Conversion Time te (14 bits) Interrupt Overhead til 175.1 !IS 29.2 !IS 125.9 !IS 120.3 iJS 21.0 !IS 10.0 !IS Time per Measurement te + ti 204.3 iJS 146.9 !IS 130.3 !IS Time between interrupts l/ARR 274.7 !IS 74.4% 213.6 !IS 152.6 iJS 68.8% 38.6% 35.7% 1035 jJA 85.4% 23.8% ADC Loading (te + ti)xARR CPU Loading by MPyslf Approx. Icc (typical) for MSP430 820jJA 1872 jIA t ADC conversions per complete ac cycle and phase (voltage and current samples) ; The Inherent Error, a constant value, is compensated with the calibration values § Time from ADC interrupt acknowledge until next conversion is started (after 22 MCLKs) If Two Signed mu~iplications per phese repeWion time; 160 cycles for each one 4.1.7 Three-Phase Electricity Meters Two electronic electriCity meters are discussed and designed for the measurement of European domestic ac. As power connections, three phases and a neutral connection are led into the house. This enables the use of two voHages: 230 V (phase to neutral) and 400 V (phase to phase). To measure the electric energy used, three current transformers or ferrite cores are necessary. The voltage of each phase is measured directly. With this configuration, the energy consumption of any load connection can be measured exactly. Loads from any phase to neutral (230 V) are measured as well as loads connected between the phases (400 V). Application Examples 4-39 The measurement sequence is shown in Figure 4-20. i4-- a---.l I Vr I Vs Vt Ir Is It I I I I I I ~ Vs I I I I I ~1/ARR I Vt Vr • Time ~I Repetition Time Figure 4-20. Normal Timing for the Reduced Scan Principle (Three-Phase Meters) Where: Repetition Time 1/ARR a. 1/Phase Repetition Rate. Length of a Complete Measurement Cycle Repetition Rate of the ADC Inherent Phase Shift of the Measurement Method If a more evenly spaced sequence is desired (Le., for better distribution of the multiplications), the following sequence can be used. Current and voltage samples are made alternating. i4-- a---.l I Vr It I I Vs I Ir Is I I I ~1/ARR I~ I Vt Repetition Time Vr It I I I I I Vs • Time ~ Figure 4-21. Evenly Spaced Timing for the Reduced Scan Principle (Three-Phase Meters) 4.1.7.1 Current Measurement With Ferrite Cores and Software Offset Figure 4-22 shows a three-phase electricity meter that uses voltage dividers to get reference voltages in the middle of the supply voltage for each voltage input. The resistors of these voltage dividers are chosen to be smaller than the maximum source impedance of the ADC (see Section 4.1.4.2, ADC Input Considerations). To get the ADC value of the virtual middle of the ADC range, the software offset method is used. This value is subtracted from each voltage and current sample to get signed, offsel-corrected results. The range is selected by different amplifications of the coil preamplifier. 4-40 The reference is provided by the stable +5 V supply. If needed and with more TLC4016 ICs, additional current ranges can be implemented. A backup battery allows the time information (provided by the basic timer) to be kept during power-down periods. All current-consuming peripherals can be switched off; including, the resistor dividers, the range switches, the amplifiers (integrators) by the SVcc output, and the EEPROM with a TP output. Application Examples 4-41 SVec PmueR-------.-HE3..-----------------.---.-., ...J=:;:=~§I~----...J...J"9"~ Phase S - - -..... Range Phase T -,.-+--I-+--1--1E311----H-t+........."'" Loads 230 V Range Switch.. Vo I I I I I II.. _ _ _ _ _ _ _ _ _ .JI Vo .....-'::T~P.0-2~-....., Ferrite Core Interlace A2 CurrenlB A1 AO 2.3.'i. 123'i561.B 3x4.1Ma 5V AVec -.~ SVCC 3x58kn A5 Volta s A4 A3 .3x56kn AVss PulaaWs OV OV 5V Backup Battery Figure 4-22. Three-Phase Electricity Meter With Ferrite Cores and Software Offset 4-42 4.1.7.2 Current Measurement With Current Transformers and Split Power Supplies The six analog inputs of the MSP430C32x only allow the measurement of the three currents and three voltages without external circuitry. If a reference diode is needed (Le., because the power supply cannot be used as a reference) or one of the methods using a ground that needs to be measured is used, then an analog multiplexer, like the TLC4016, is needed (see Figure 4-23). With its three outputs (TP.3 to TP.5) the MSP430 selects the phase to be measured. No backup battery is provided, this means that in regular time intervals, the actual amount of energy consumption needs to be stored in the EEPROM. If the power supply used provides an ac Down, this storage would only necessary when this signal was activated. The same circuitry can be used with a virtual ground IC. Only a few modifications are necessary (see Figure 4-18). An ac down signal from the power supply connected to the interrupt I/O terminal PO.6 allows the MSP430 to save important values (Le., energy consumption) in the EEPROM in case of a power failure (see Section 5. 7, Battery Check and Power Fail Detection). Application Examples 4-43 PhaseR = ~ Range Switch Loads 400 V ~ PhaseS -=== ~ 1 Current· Transformar Phase T = Loads 230 V ~ NeulraI TP.l AI TP.O Currents Xln AO RangeSwHch 3x4.3MO 2.5 V T TP.2 XBUF AVec COM SEL SVCC .... rlA IB ' - 2A 2B t1 '- 3A 3B ~ 1- 4A 4B I- MSP430C32x 82kn Reference PO.7 A4 Voltagas PO.O A3 ~ ~ LM386 PO.2 xC 3 x 3.3 kCI OV ...... n I TLC4018 r-+- PO.I PO.& PO.3 AS 3 TP.3-li 2.1'i. 123~S61B _ _ !kWh! I:==:l I ~ CL"i:EPROM DATA ~ TSS721 MBUS ~ IfI.IF Key DVSS DVCC PO.5 AC Down 1--+ POA ~~2.5V AVSS ~1v % XOUI 1-T32kHz A2 ~ PulseWs 1 1 4.5 V 2.5 V Figure 4-23. Electricity Meter With Current Transformers and Split Power Supply 4.1.7.3 Calculations For four three-phase electricity meters, the typical values are calculated: o o o 4-44 Version with minimum current consumption Compromise between current consumption and resolution Version with high resolution. This version can be used with an MCLK frequency of 3.3 MHz, when a maximum calculation performance is needed. o Table 4-10. Version with the highest resolution due to the maximum sampling speed Typical Values for a Three-Phase Meter ITEM AC Frequency MINIMUM SUPPLY CURRENT COMPROMISE HIGH RESOLUTION 50 Hz 50 Hz 50 Hz 50 Hz HIGHEST RESOLUTION Time Base for ARR Basic Timer 4096 Hz AClKJ6 AClKJ5 Basic Timer 8192 Hz MClK (CPU Clock) 1.048 MHz 2.097 MHz 2.195 MHz 2.949 MHz ADC Clock (ADCll<) N (MClKJAClK) 1.048 MHz 1.048 MHz 32 64 1.097 MHz 67 1.475 MHz 90 ADC Repetition Rate ARR 4096Hz 5461.3 Hz 6553.6 Hz 8192 Hz Phase Repetition Rate (ARR/6) 682.67 Hz 910.22 Hz 1092.3 Hz 1365.33 Hz Phase Repetition Time (61ARR) 1464.81J.S 27.3 13.19· 1098.63 1J.S 36.4 9.88· 915.531J.S 43.7 8.24· 723.41J.S 54.6 6.59· Measurements per 360· (50 Hz)t Sample Phase Shift a -2.6% -1.5% -1.03% -0.66% ADC Conversion Time tc (14 bits) Inherent Error:!: 125.91J.S 125.91J.S 120.31J.S 89.5 lIS Interrupt Overhead ti§ 21.0 IJ.S 10.51J.S 10.0 lIS Time per Measurement tc + ti Time between interrupts 1/ARR 146.9 lIS 244.1 lIS 136.4 lIS 130.3 lIS 152.61J.S ADC loading CPU loading by MPYs~ 60.2% 31.3% Approx. Icc (typical) for MSP430 1035 ItA 183.11J.S 74.5% 7.5J.LS 97.0 lIS 122.1 lIS . 85.4% 73.3% 20.8% 23.8% 20.8% 1800 ItA 1872 ItA 2423 ItA t ADC conversions per complete ac cycle and phase (voltage and current samples) :I: The Inherent Error, a constant value, is compensated with the calibration values § TIme from ADC interrupt acknowledge until next conversion is startlld (after 22 MClKs) 11 Three signed multiplications per phase repetition time; 160 cycles for each one 4.1.7.4 TImIng and Software The timing in Figure 4-24 is shown for the compromise solution in Section 4.1.7.3, Calculations, (see Figure 4-22). The interrupt of the universal timerl port module (UT/PM) reads out the actual ADC result, prepares and starts the next measurement. The ADC interrupt is not used. The instruction timing is shown in CPU cycles (MClK = 2.097 MHz). The ADC timing uses an ADCLK = 1.048 MHz (MCLKl2). Register R5 is used exclusively by the interrupt handler (status word) to reduce the execution time of the interrupt handler. Figure 4-24 shows the timing without latencies due to other interrupts. If these latencies are included, the overall timing can increase by several cycles. This Application Examples 4-45 makes strict real time programming necessary. For example, any interrupt service handler (except the UT/PM handler) must have the instruction EINT (Enable Interrupt) at its beginning. Calculations show that the interrupt latency time does not influence the measurements. The statistical distribution results in an error are nearly zero (see Section 4.1.2.5, Measurement Error in Dependence of the Interrupt Latency Time). UT/PM Interupt UT/PM Interupt Start Conversion 132 ADCLKS (te) c';;;;';'i;co;;;-p;'-'q....---IRETI RaadADC II ~ l.-I 22c "- tl I 3Bc ---..: I = ACLK 32!768 kHz MCLK = 2.0972 kHz ADCLK = 1,.0486 kHz 136.4p.8 - - - - - -... ~ J'II ---G-+ I I i4~--------- 183.1 p.8 - - - - - - - - -..... ACLKl6 ~ ~~--------- 152.6p.8 ---------~~ ACLKl5 Figure 4-24. Timing for the Reduced Scan Principle The interrupt software used is: (Register R5 is reserved for the interrupt handling to get the shortest possible time) Hardware Definitions ADAT .EQU OllBh ADC l4-bit result buffer ACTL .EQU O1l4h ADC control word M2 .EQU 02000h ADC prescaling: ADCLK = MCLK/2 Rauto .EQU OBOOh Automatic range selection CSoff .EQU OlOOh Current Source off A5 .EQU Ol4h Analog input A5: Vt A4 .EQU OlOh Analog input A4: Vs A3 .EQU OOCh Analog input A3: Vr A2 .EQU OOSh Analog input A2: It Al .EQU 004h Analog input AI: Is AD .EQU OOOh Analog input AO: Ir soc .EQU OOlh Conversion Start 4-46 TPCTL .EQU 04Bh UT/PM control word RCIFG .EQU 002h UT/PM interrupt flag TPCNTI .EQU 04Ch UT/PM counter 0,0,0,0,0,0 Ir,Vt,Is,Vr,It,Vs storage; RAM Definitions ADCTAB . WORD MCLK Cycles ; Interrupt Latency UT_HNDLR MOV TAB 6 &ADAT,ADCTAB(RS) Store act. ADC result 6 MOV TAB(RS),PC Go to individual handler 3 . WORD Vt,Is,Vr,It,Vs,Ir Six meas. handlers Individual handler parts for each phase (current and voltage) The next sample is selected and the measurement started. MOV #M2+Rauto+CSoff+AS+CS,&ACTL JMP UT_COM Is MOV #M2+Rauto+CSoff+Al+CS,&ACTL JMP UT_COM Vr MOV #M2+Rauto+CSoff+A3+CS,&ACTL JMP UT_COM It MOV #M2+Rauto+CSoff+A2+CS,&ACTL JMP UT_COM Vs MOV #M2+Rauto+CSoff+A4+CS,&ACTL JMP UT_COM Ir MOV #M2+Rauto+CSoff+AO+CS,&ACTL MOV #-2,RS vt Select vt 6 Select Is 6 Select Vr 6 Select I t 6 Select Vs 6 Select Ir 6 ;2 ;2 ;2 ;2 ;2 ; Restart sequence with Vt 2 Common part: time base is subtracted from UT/P. UT/P Flag is reset. Next measurement is prepared SUB.B *6,&TPCNTI ACLK/6 is time base S BlC.B #RCIFG,&TPCTL Reset UT lNTRPTflag 4 ADD #2, RS To next measurement Application Examples 1 4-47 ; Return from INTRPT RETI 5 Nearly the same interrupt handler can be used with sample timing defined by the basic timer. The differences are: o o No resetting of the interrupt flag is necessary. It resets automatically. No reloading of the timer register is necessary. The timer runs continuously. This shortens the interrupt handler by 12 cycles. ; Interrupt Latency UT_HNDLR MOV ADD TAB &ADAT,ADCTAB(RS) #2,RS Store actual ADC result ; To next measurement MOV TAB-2(R5),PC Go to individual handler . WORD Vt,Is,Vr,It,Vs,Ir Six measurement handlers 6 6 1 Individual handler parts for each phase (current and voltage) The next sample is selected and the measurement started. Vt MOV #M2+Rauto+CSoff+AS+CS,&ACTL ; Select vt Return from INTRPT RETI Is MOV #M2+Rauto+CSoff+Al+CS,&ACTL Select Is RETI Vr MOV MOV #M2+Rauto+CSoff+A3+CS,&ACTL Select Vr MOV #M2+Rauto+CSoff+A2+CS,&ACTL Select It 6 5 #M2+Rauto+CSoff+A4+CS,&ACTL Select Vs RETI Ir 6 5 RETI Vs 6 5 RETI It 6 5 6 5 MOV #M2+Rauto+CSoff+AO+CS,&ACTL ; Select Ir 6 CLR R5 Restart sequence 1 Return from interrupt 5 RETI The previous interrupt handler can also be adapted to the electricity meter shown in Figure 4-23. The input selection with the TP outputs must be in4-48 cluded into the parts serving the three ac voltages. The selected ADCinput is A3 for all voltage measurements. 4.1.8 Measurement of Voltage, Current, Apparent Power, and Reactive Power The reduced scan principle measures only active power. If reactive power or apparent power is to be measured, other methods have to be used. The implemented measurement method also depends on the main application of the electricity meter. A meter for the measurement of reactive power only probably uses a different algorithm than an electricity meter for active power that does the reactive power measurement as a background task only. This section shows simple methods that use as much as possible the voltage and current samples measured for the active power calculation. 4. 1.B. 1 Measurement of Voltage and Current The measurement of voltage and current is possible by summing up the absolute values ofthe ADC results during integer numbers of full periods. The result is an indication of the average value of the voltage Vavrg respective of the current lavrg. If corrected as shown, the current and voltage values can be used for other purposes. The formula for a sinusoidal voltage is shown in the following. The one for the current is equivalent to it. Vavrg x p r;:: 2,2 = 1.11 x Vavrg 4.1.8.2 Measurement of the Apparent Power The apparent power is defined by the formula Papp =U x I. There is no exact definition for the apparent power when harmonics are included. A possible solution is to use the voltage and current samples (see Section 4.1.8.1 , Measurement of Voltage and Current) taken for the active power measurement. These samples are made absolute and summed up for an integer number of ac periods. If these summed-up values, representing the average value, are multiplied and corrected the apparent power is the result. The correction is necessary due to the difference of the average value and the effective value of a sinusoidal current or voltage (see Section 4.1.8.1). The apparent energy Wapp is: Wapp = Vavrg x lavrg x 1.11 2 x t Application Examples 4-49 4.1.8.3 Measurement of the Reactive Power Two simple methods exist for the measurement of the reactive power: o Delay of the voltage (or current) samples for the time representing 90· (1tI2) of the ac frequency. o Calculation of the apparent power and the active power Delay of Samples With a carefully chosen sampling frequency, the angle 90° (1tI2) can be made an integer multiple of the sampling interval. If each voltage sample is delayed with a RAM-based by this integer number and multiplied with the actual current sample, the result is the reactive power. EXAMPLE: ac frequency 50 Hz, 90° are 5 ms, with a sampling frequency of 2000 Hz the necessary FIFO buffer is 5 ms x 2000 Hz = 10 words. For every phase 20 bytes of RAM are needed for the FIFO. Calculation out of the Apparent Power The apparent power is calculated as described in Section 4.1.8.2. The reactive power is calculated with the values of the active power and the apparent power by the form ula: Wreact = jWapp2 - wact 2 Note: All the calculations described previously can be made with the MSP430 floating-pOint package. It is available with two lengths of mantissa; 24 bits and 40 bits (see Section 5.6, The Floating Point Package). 4.1.9 Calculation of the System Current Consumption The base of the following current consumption table is derived from the following data sheet information: 4-50 Table 4-11. Current Consumption of the System Components Device fose lee Vee MSP430C32x (ADC on)t 1000 J,IA 1 MHz N/A TA 5V -40'C 10 85'C 25'C TLC4016 20 J,IA TLE2426 TSS721'1: 170J,IA 18mAmax. N/A 5V 5V N/A 5V 25'C -40'C"lo 85'C EEPROM 24AA01§ 100 J,IA max. N/A 5V 0'Cl070'C OPAMP TLC1 079 40 J,IA N/A 5V 25'C LM385-2.51l LCD 20mmx100mm# Cryslal ll 30 J,IA 26 J,IA N/A N/A 5V 5V 2J,IA 32.768 kHz N/A t The supply current of the MSP430 (excluding the ADC) depends on the MCLK In a linear manner. The supply current oflhe ADC depends mainly on the current flowing through the internal resistor divider and is, therefore, treated as constant. :I: Power for the TSS721 is taken from the M-BUS, so the electricity meter's supply is not used. § Standby current of the Microchip EEPROM. Read and write currents are 1 mA and 3 mAo The EEPROM can be switched off completely during the standby periods. II The reference diode can be switched off when not used for the reference measurements. # A typical current value of 13 nNmm2 Is used. II A typical driver power of 10 IlW Is assumed. With the previous data, the system consumption is calculated under the following conditions: o The compromise solutions shown in Sections 4.1.5, 4.1.6, and 4.1.7 are used for the six hardware proposals o o o Nominal current consumption is assumed for all system components The ac voltage has its nominal value The ac load current is assumed to be zero. This eliminates the influence of different current interfaces. Application Examples 4-51 Table 4-12. System Current Consumption for Six Proposals MSP430C32x 820J,tA Single Phase Current Transf. 820 J,tA 1035 J,tA 1035 J,tA TLC4016 20 J,tA 20 J,tA 20 J,tA 20 J,tA 1800 J,tA 20 J,tA 1800 J,tA 40 J,tA TLE2426 - - 170 J,tA - - - - - EEPROM OPAMPs 100 J,tA 40 J,tA 100 J,tA 100 J,tA 100 J,tA 100 J,tA - - - 100 J,tA 40 J,tA LM385-2.5 30 J,tA 30 J,tA 30 J,tA 30 J,tA 30 J,tA 30 J,tA LCD I Crystal 28 J,tA 28 J,tA 28 J,tA 28 J,tA 28 J,tA 28 J,tA - - - 1038 J,tA 12mW 998 J,tA 12mW 1383 J,tA 134 J,tA 1347 J,tA 134 J,tA 2152 J,tA 1998 J,tA 13mW 15mW 44mW 37mW Device Single Phase Shunt TSS721 Resislor Dividers System Current VoHage Path - Dual Phase Virtual GroundlC Dual Phase Software Offset Three Phase Ferrite Core Three Phase Current Transf. - - - The value given for the voltage path shows the power needed for the voltage dividers adapting the ac voltage to the analog inputs. All phases of a system are included as well as dc and ac energy. 4.1.10 System Components The complete electricity meter system consists of the following parts. The system components not described until now are explained in the following: CJ CJ CJ CJ CJ CJ CJ CJ CJ The microcomputer MSP430C32x with its 14-bit ADC The LCD with up to 10.5 digits (4 MUX) The EEPROM with 128 bytes (256 bytes) The current interface and the current range switches The power supply including the ADe offset generation The M-Bus interface (TSS721) The infrared interface The reference diode (LM385-2.5) Other peripherals The last four components are not necessary in all applications, they can be omitted when not necessary. 4.1.10.1 The Microcomputer MSP430 The MSP430 is described in detail in Chapter 1. 4-52 4.1.10.2 The LCD Any customized LCD can be connected to the MSP430, as long as it meets the electrical specifications (i.e., maximum capacitance per segment and common lines). Every segment ofthe LCD can be controlled independently of the others. This means 256 (or 512) (3 MUX) possible combinations. SL means number of segment lines. The number of digits dependent on the multiplexing scheme: 4MUX 3MUX 2MUX 1 MUX digits = SU2 digits =SU3 digits =SU4 digits =SU8 The unused segments H (decimal points) of the digits can be used for the display of complete words (kWh, Ws, Low Tariff, etc.). This is used within the figures showing the electricity meter proposals. 4.1.10.3 The EEPROM The EEPROM contains data that must not be lost during power down cycles. o o o o o Calibration data (slopes and offsets for every range and phase) Meter number and other device related numbers Summed-up energy (stored in regular intervals (e.g., every 12 hours)) Other data (e.g., statistical data) Error characteristics (current transformer, ADC, etc.). For the summed-up energy, a kind of circular buffer can be used, which avoids the use of the same cells for every update. No painter should be used for this purpose. A simple check for the lowest stored energy value determines the next storage location. This check can be made during the power-up sequence and the result is stored in the RAM for later use. This pointer is updated after each write cycle to the EEPROM. A checksum or an CRC (cyclic redundancy check) can be used for the safety of the stored data. The tables containing the error characteristics of the current transformer and the ADC can be used for correction purposes if needed. Dependent on the amount of data to be stored, an EEPROM with 128 bytes or 256 bytes is required. The EEPROM is driven with a software handler. Clock and data lines are set and reset by software (also see Section 3.2, Storage of Calibration Constants, and Section 3.4, 12C Bus Connections). The EEPROM can be switched off by an output, if it is not in use to save current. Application Examples 4-53 4.1.10.4 The Range Switches The resolution and accuracy of an electricity meter can be increased if more than one current range is used. The analog switch TLC4016 with its four channels is suited very well for this purpose. The MSP430 decides independently, for any phase, which current range is to be used. The ranges should be overlapping and the design should use a SCHMITI-trigger characteristic for the change in ranges. This is done to avoid too many changes. 4.1.10.5 Power Supplies The stability of the power supply used decides if a reference voltage (see Section 4.1.10.8) is necessary or not. If the power supply is stable enough, it can be used as the reference also. This simplifies the system in three ways: o No reference measurements are necessary in regular time intervals (e.g., every second) that makes the omission of one sample necessary. o No correction calculations are needed to correct the summed-up energy values. o No reference diode and additional hardware is necessary. The analog input can be used for other purposes. The stability of the power supply should be better than a factor of 4 of the desired accuracy of the electricity meter. This is due to the quadratic influence of SVcc. See Section 4.1.3.3. More information is given in the Section 3.8, Power supplies for the MSP430.. . 4.1.10.6 The M·Bus Interfsce TSS721 (Option) The M-Bus interface allows the connection of the electricity meter to networks. The M·Bus interface uses the on-chip UART or one input and one output with a software driven protocol. Applications of the M·Bus interface: o o Calibration: connection to the calibration hardware Automatic readout by a host: the actual consumption and other interesting values can be read out with a customer defined protocol. o Tariff switching: the host defines the actual tariff by sending the appropriate information o Test: start of ROM-based testing routines or down-loading and starting of RAM-based test routines Instead of the M-Bus, any other bus can be used with the MSP430. 4.1.10.7 The Infrared Interface The infrared interface allows bidirectional data transfer for calibration, test, and readout. One of the PO-ports can be used with its interrupt capability for bidirectional transfers. 4.1.10.8 The Voltage Reference To have a reference for the measurements, a reference diode LM385-2.5 can be used. The voltage of this diode is measured in regular intervals and the measured value is used as a base for the SVcc relative AOC measurements. To reduce the supply current, the LM385 can be switched on only during the reference measurements.(see Figure 4-15). No reference diode is necessary if a 5-V voltage regulator (or two 2.5-V regulators) is used with the necessary accuracy and long term stability (see Section 4.1.10.5, Power Supplies). The stability of the reference should be better than a factor of 4 as the desired accuracy of the electricity meter. 4.1.10.9 Peripherals Some options show how to interface the MSP430 to other devices. o Pulse Output: this outputchanges Its state when a certain energy amount Is consumed and Is usable during calibration or accuracy checks. Mechanical displays can use this pulse output. o Key Interface: keys can be Interfaced very simply to the inputs of the MSP430. Interrupt is possible with all PortO inputs. o LEOs: currents up to 1.5 mA @ 0.4 V voltage drop can be driven without external buffers.. o Relays: driving is possible with a simple npn transistor and two resistors. The crystal buffer output XBUF provides four different, software selectable frequencies that may be used for the peripherals. These frequencies are: MCLK, ACLK (32.768kHz), ACLKl2 (16.384kHz), ACLKl4 (8.192kHz). 4.1.10.10 Summary As this chapter shows it is possible to build cost-effective, domestiC electricity meters based on the ultra-low-power mixed-Signal RISC-processor MSP430. Application Examples 4-55 The 14-bit ADC and the reduced scan principle eliminate the need for a special front end. All necessary system functions are realized with the on-chip peripherals of the MSP430C32x. With appropriate calibration methods, the deviations of the ADC can nearly be eliminated. This allows electricity meters to be built for classes 2, 1 and 0.5 ranging from Single-phase meters to threephase meters. A customer developed a Single-phase electricity meter with the following properties: o o o o o o o o Class 0.5 meter for the range 0.5 A to 130 A Error within 0.2% from 300 mA to 40 A Use of the full 14-bit ADC range for current and voltage Reduced scan principle is used for the energy calculation (inclusive correction formula) Use of a virtual ground and use of the measurement result for the offset correction Current transformer is used for current measurement (a low cost version is planned with a shunt) Single range only for current measurement (no range switches) Meaningful current measurements down to 25 mA . 4.1.11 Electricity Met~r With an External ADC Modern three-phase electriCity meters of the upper classes must provide an enormous calculation power. Additional to the multiplications cif the current and voltage samples for the active power measurement, it is necessary to calculate additional, very computation intensive values: o o o o Apparent power for all phases Sum of the capacitive reactive power Sum of the inductive reactive power Calculation of the coscp for every phase These calculations need to be done in real time, a microcomputer with high throughput like the MSP430C33x is necessary. With an external ADC three different scan principles can be used: 4-56 o The reduced scan principle that was used with all electricity meters shown in the previous sections. Only one ADC is necessary for current and voltage with this method. o The alternating scan principle-a TID invention-that also needs only a single ADC. Due to pending patent reasons, It cannot be explained further. The hardware is Identical to the hardware for the reduced scan principle. o The typical way with two ADCs: one for the voltage path(s) and one for the current path(s). Figure 4-25 shows a three-phase electricity meter with a 16-bit ADC. This single ADC allows the application of the reduced scan principle and the alternating scan principle. With this hardware in use, class 0.2 is reachable. Mains ~ II 1f.BHADC U OV OV AGND DGND 32kHz Xln Xout Voltage R UR US UT CurrentR IR IS 5V LMx85 BO 4 MHz CLK B1 RD PO.3 Pulse OUtputs B2 CNVST POA AcUva Power R B3 CNfL PO.5 B4 00-015 B5 BUSVnNT B8 CS B7 INPUT SELECT Active Power S Active Power T Ports PO.7 TP.2-TP.4 Apparent Power R Apparent Power S VDD DVDD OV -6V BV Analog cap. Reactive Power Ind. Reactive Power Apparent Power T 5V TP.x MSP430C33x 5V V LEDs 5V 123~2.1~. 123~S6'.B COM SEL TP.y MAINSUF ~ TO The Load PO.1 P4.x CoUpllng-Capa UTXD URXD + 0-- 5V Key(s) Sysl8lll PO.O Vee PO.2 Vss 5V Digital OV Figure 4-25. Electricity Meter With an External 16-Bit ADC Application Examples 4-57 4.1.12 Error Simulation for an MSP430C32x-Based Electricity Meter The simulation methods that lead to the results shown in this chapter are explained in detail. 4.1.12.1 Abstract The way the calculation of the error of a simulated electricity meter built with the MSP430C32x family is shown in detail. A single-phase is simulated; this can be the only phase or one phase of a poly-phase meter. The error simulator (I:S) simulates nearly exact an MSP430C32x working as an electronic electricity meter. All influences due to the MSP430 hardware are taken into account. o o The error due to the characteristic of the ADC The error due to the interrupt latency of the MSP430 interrupt system o The error due to the range transition for samplEls at the boundaries of the four ADC ranges o The error due to the used reduced scan principle for the measurement 4.1.12.2 Common Measurement Conditions The ES asks at the beginning for' the conditions that are used for all measurement pOints (they are written to the listing file): o o Listing path name The characteristic of the ADC; the ADC errors (in steps) at the five range boundaries are defined. See Figure 4-25 for explanation. o The time interval between voltage and current sample pairs (sampling interval) o The nominal ac frequency o The maximum interrupt latency time; the worst-case value for the time interval from an interrupt request to the actual start of the interrupt handler. o o The correct ADC value for the external reference voltage 0 V The measurement time for each measurement 4. 1.12.3 Callbrstlon The next step is the calibration for the simulated system. Two calibrations are necessary for the complete current range (the ranges shown In the following can be changed if needed): 4-58 o One for the current range from 0% to 5% of the maximum current. The calibration points are 0.5% and 5% of the maximum current. o One for the current range from 5% to 111 % of the maximum current. The calibration pOints are 5% and 100% of the maximum current. The calculated energy for the low and the high calibration points are summedup for five seconds each. The conditions are: 0 Voltage = 100% Nominal ac voltage 0 CoS

Oy 5-0-- + Pulse Liters Figure 4-31. Electronic Water Flow Meter Application Examples 4-69 Heat Allocation Counter 4.4 Heat Allocation Counter A heat allocation counter with the possibility of sending out the consumption information via RF frequencies is shown in the following figure. The RAM information is scrambled by the DES standard and sent out using the biphase code with .19.2 kBaud. The software routines used for the scrambling and the transmission are contained in Section 5.5.7. Data Security. The heat consumption is computed from the measured room temperature and the heater temperature. The heat consumption is summed up in the RAM and can be read out by the LCD, the M-BUS connection or the RF interface. The calibration constants and all other important data are contained in the MSP430's RAM. Low-power mode 3 (CPU off, oscillator on) is used normally; the CPU wakes-up at regular intervals (e.g., 3 minutes), measures the heater and the room temperature. and then calculates the actual energy consumption of the radiator. The formulas used take into account the non-linear characteristics given by the thermodynamic theory. This is possible by the use of tables or quadratic or cubic equations. o 32kHz SVDD Rex! ..-:--:-:---1 A1 19.2kBaud P0.4 1 - - - -...... BlphaSil Code A2 MSP430x32x L-_--<_.._--I AGND LCD PO.z PO.y . COM SEL 123liS61.B _ _ IT] Twisted Pair Figure 4-32. Electronic Heat Allocation Meter With MSP430C32x The heat allocation meter can be built-up also with the MSP430C31 x version. Figure 4-33 shows the schematic for this configuration. 4-70 Heat Allocation Counter D 32kHz ov -11---<......--1 CIN TP.O 18.2kBaud PO.41-----t-lRF-Unlt Blphase Code TP.1 TP.2 MSP430x31x --[!] LCD PO.z po.y Twisted Pair COMH SEL 123~S6'.B Figure 4-33. Electronic Heat Allocation Meter With MSP430C31x Application Examples 4-71 Heat Volume Counter . 4.5 Heat Volume Counter The heat volume counter shown in Figure 4-34 was developed for relatively long sensor lines. An LC filter is used to prevent spikes and noise at the analog inputs of the MSP430. The system nonnally runs in low-power mode 3 (CPU off, oscillator on) but any change at one ofthe inputs will wake-up the MSP430. Every platinum sensor from 100 0 to 1500 0 can be used with the MSP430. The current source is able to drive them. Inlat I waterFlow + ,.....J1J(!I.~rnrY'l._--I OU\Iat'-'IIQi,~r'0~""'-I PI100lPlSOO Enable Volu"" !---'V""1_ _ _ _ _ _ _ _ _. . Interface V2 ::....JLJ V1 ~V2 Figure 4-34. Heat Volume Counter MSP430C32x The four-wire circuitry can also be used here. It is possible to use only five analog inputs with the following schematic. The signals at A2 and A5 can share one input and one resistor connected to AVss. 4-72 Heat Volume Counter LCD 123~S6'.B __ m SVCC Rex Inlet Pt100JPt600 MSP430x32x Ran OY AG Ai po.x A2 TXD AGND RCD AS A4 ~ WaterFlow PG.y A3 ModelLCD PO•• 1----(5'---0--+ Outlet Pt100/pt500 Enable Vi V2 OX PO.k PO.I PO.m VCC Battery Pulse Liters Vss 3V11.81lA Figure 4-35. Heat Volume Counter With 4-Wire-Circuitry MSP430C32x Figure 4-36 shows the same heat volume counter as Figure 4-35 but with an enlargement of the ADC resolution to 16 bits. The principle is explained in Chapter 2. Application Examples 4-73 . Heat Volume Counter , o 32kHz ._m lCD TP.O TP.1 sVcc R15 COM SEl MSP43Ox32x Rex! Inlet P11001P1500 OY AO A1 AI PO.x TXD AGND RCD AS A4 AS ~ waterFlow PO.y ModeIlCD OUIIet P1100/PI6OO Volume Inter1ace Enable V1 V2 ::...ns- PO.z OX PO.k PO.I PO.m V1 .JLJV2 123'f561.B Vee Battery >-0-- + Pul_llte,. Vss SV/1.8 ""' Figure 4-36. Heat Volume Counter With 16 Bits Resolution MSP430C32x 4-74 Battery Charge MaJ.?' 4.6 Battery Charge Meter The battery charge meter shown in Figure 4-37 monitors the charge of a battery by means of the measurement of all relevant parameters: o Battery voltage is measured with the voltage divider R1/R2. This voltage is used for the recognition of the end of charge (the battery voltage reduces in a defined manner) and for safety reasons. o Battery current: the voltage across a shunt gives an exact indication of the current flowing. The low shunt voltage is shifted into the AOC range by a resistor R3 using the current source of the MSP430. The battery current is measured signed (positive sign means charge, negative sign means discharge) to give the possibility of treating charge and discharge currents differently. o Battery temperature: the resistance of the temperature sensor is measured with the current of the current source. The battery charge meter shown is not restricted concerning the magnitude of voltage, current, or capacity of the batteries controlled. These depend only on the design of the shunt resistor, the voltage divider, and the calibration constants used. It can be used for cascaded batteries as well as for single ones. This means, it is applicabie from camcorders to forklifts. The reference voltage for the system is delivered by the voltage regulator output. Therefore, the voltage needs to be sufficiently stable. Referencing by a reference diode (LMx85) is also possible. This reference diode can be measured at regular intervals and the result stored. It is not necessary to have the reference always switched on. The charge indication can be given with a numerical LCD or, as shown in the following, with a battery symbol showing 20% steps. Other methods for indication are also possible (e.g. LEOs with different colors that are enabled for a short time by a key stroke). The voltage regulator needs to have a very low supply current, not exceeding some micro amps. This is needed because of the long periods the system can be in rest mode (no load). The charge part shown is not necessary for all applications. It can be omitted if, for example, the available space is not provided. The charge transistor Q1 is switched on by the MSP430 if a certain (low) charge level is reached. The charge current can be fine tuned by PWM. If the charge current is above the maximum current the transistor is switched off due to safety reasons. The host connection (for example via 232 using the MSP430's UART) can be used for the transfer of data; charge, temperature, voltage, current, and other Application Examples 4-75 Battery Charge Meter system related data. In the other direction, the host can transfer Instructions; stop or start of charge, start of data transmission, etc. The EEPROM contains the characteristic of the controlled accumulator (maximum current, nominal capacity, end of charge criteria etc.) The EEPROM also contains the actual capacity (dependent on age and charge cycles) and a safety copy of the actual charge register. For additional hardware proposals see Section 5.7, Battery Check and Power Fail Detection. To Host ~ Load To Charger Current R3 AO J---'I/I,fy-f---l--' R2 Figure 4-37. Battery Charge Meter MSP430C32x 4-76 Shunt Connection of Sensors 4.7 Connection of Sensors The MSP430 family allows the connection of nearly all types of sensors. Some special connections are shown in the following sections. 4.7.1 Sensor Connection and Linearization Figure 4-38 shows the connection of simple resistive sensors to the MSP430C32x. The current source resistor Rex needs to be calculated in a way that allows its use for both sensor circuits (Rsens2 and Rsens3). The different connections, shown in Figure 4-38, are described in detail in Chapter 2, The Analog-to-Digital Converters. Rex SVee RV ICs+ SVee A3 R1 AS A4 VI A1 RSENS4 AO RSENS AS A7 RSE --<_-.. . --.. . RUN R1 -_-IAGND V AGND I--~~-~~ Vee OV 3Vor5V Figure 4-38. Resistive Sensors Connected to MSP430C32x 4.7.1.1 ~oltage Supply The sensor Rsens1, in Figure 4-38, is connected this way. Resistor Rv supplies the sensor and is used for the Linearization also. The optimum value of Rv with dependence of Rsens is: Rv = Rm x (Ru + Roj - 2 x Ru x Ro Ru + Ro - 2 x Rm Where: Ru Ro Rm Sensor resistance at the lower temperature limit Tu Sensor resistance at the upper temperature limit To Sensor resistance at the midpoint temperature (To + Tu)/2 The ACC values measured are independent of the supply voltage Vcc because the measurements are made relative to Vcc. AppUcation Examples 4-77 Connection of Sensors 4.7.1.2 Current Supply Sensor Rsens2, in Figure 4-38, is connected this way. If a linearization of the sensor is desired, the same formula used for the resistor Rv with voltage supply can be used for the resistor Rlin (see Section 4.7.1.1, .Voltage Supply). 4.7.1.3 Use of Reference Resistors Two measurement methods with reference resistors are possible; use of one reference resistor, and, use of two reference resistors: o Measurement with one reference resistor: the reference resistor is chosen so that it equals the sensor resistance at the most important measurement point. Eventually, sensor and reference resistors are selected as pairs. The offset error is completely eliminated. So, only the slope error needs to be corrected. o Measurement with two reference resistors: the two reference resistors represent the sensor resistances at the limits of the measurement range. This method also corrects the influence of the internal resistance (RDSon of the TP outputs). If sensor and reference resistors are paired, no calibration is necessary with this method. . With two reference resistors Rref1 and Rref2 it is possible to compute slope and offset and to get the value of an unknown resistors Rx exactly: Rx = Nx - Nref1 x (Rref2 - Rref1) Nref2 - Nref1 + Rref1 Where: Nx Nref1 Nref2 Rref1 Rref2 ADC conversion result for Rx ADC conversion result for Rref1 ADC conversion result for Rref2 Resistance of Rref1 Resistance of Rref2 [0] [0] As previously shown, only known or measurable values are needed for the calculation of Rx from Nx. Slope and offset of the ADC are corrected automatically. 4-78 Connection of Sensors TP.O TP.l TP.2 .- TP.3 RSENSI .-: '>;.RSENS2~'>;. ). RREF2 elN el ;::f:: AGND Vss vee I I OV 3Vor5V Figure 4-39. Measurement With Reference Resistors 4.7.1.4 Connection of Bridge Assemblies This kind of sensor is best known for pressure measurement: the voltage difference of the bridge legs changes with the pressure to be measured. - - 4 -......,.:.--1 SVec SVee J.._ _ _ _ _ _B_rl_d.:.,geAaHmbly2 ReXI MSP430x32X ....- l - - - - - - I A 2 A3 ......--~Al AO A4 )..!!!!!!!!!!!!!5 Ah). 4-94 Ultra-Law-Power Design With th~."1S':43..0family LCD 123--t561B --~ ov Figure 4-55. Conventional Solution for a Battery-Driven System The MSP430 family allows the realization of the system shown previously as a one-chip solution with all the external components shown being on-chip peripherals. Figure 4-56 shows this advanced MSP430 solution. The cost advantage with fewer external components is obvious. LCD 123--t561B PO.x ---... Port Signals ~ Port --+ Port vss AO A1 A2 --~ Peripherals 8eneors VDD 0.5 Ah BaIIery .Figure 4-56. Solution With MSP430 for a Battery-Driven System The only constantly active components are the 32-kHz,osciliator, the basic timer (which wakes-up the CPU in regular time intervals), the RAM, the LCD driver, and the interrupt circuitry. The CPU, the ADC, and other peripherals are switched-on only when needed. Application Examples 4-95 ~ltra-Low-Pow?r Design ~h the MSP43C! Fa"!~y. The advantages of this concept are: o o o o o Smaller boards due to reduced chip count Lower assembly cost with fewer components Simplicity of design Lower current consumption (smaller power supply or battery needed) Faster development The following examples use the current characteristic shown in Figure 4-57 (these values are only approximated and are not assured). NOMINAL CHARACTERISTICS OF LPM3 AND LPM4, NO PERIPHERAL MODULE ACTIVE 5 4.3 4 ~ I ~ LP~ 3 2 1.44 0.055 -40 o 1.36 0.055 1.35 0.05 o 1.8 -< 3/ 2.8 1.8/ 2.8 / ~PM4 1.1 ~ 20 40 60 85 T - Temperature -"C Figure 4-57. Approximated Characteristics for the Low Power-Supply Currents 4.9.2 Current Consumption and Battery Life To reduce the current consumption of an MSP430 system as far as possible, it is necessary to use low power mode 3 nearly all the time. The basic timer, LCD, and interrupt circuitry are switched on. The CPU is switched off and is active only in programmed time intervals (e.g., every second). The current consumption characteristic of such a system, that is active every second and that measures and calculates only once a minute, looks as seen in Figure 4-58. 4-96 Ultra-Law-Power Design With the MSP430 Family MSP43O-Currenl Consumption i 1 mA IAMAD - lAM - - lADe trim 100 IIA 10ILA ILPM3 - - 111A I j4- 12 ~ I ~~---------11----------·~ n n+1 n+2 n+3 n+60 n+61 ---+ Time s Figure 4-58. Current Consumption Characteristic Where (all times in seconds): t1 Time interval between two measurements (here 60 s) t2 Time interval between two wake-ups (here 1 s) t-nm Processing time after the wake-up. Typically 25 J.I.S to 1 ms. (e.g., incrementing of a second counter, check if t1 elapsed) tADe Processing time with switched-on ADC (100 J.I.S to 150 J.I.S per measurement) tproc Processing time with enabled CPU. Typically 1 ms to 100 ms. (e.g., calculations after measurements) tLPM3 Time, the system runs in low power mode 3 The average current Icc taken out of the battery by the MSP430 is: 'ee = 1 (11 11 x trim - lADe - Iproc) ) IT i2 x Irim x 'AM + Iproc x 'AM + tADe x 'AMAD + ( t1 - i2 x 'LPM3 This can be simplified, if tTlm, tADe and tproc are much shorter than t1 (normal case): 'ee .. ~ x trim x 'AM + il(lproc x 'AM + tADe x 'AMAD) + 'LPM3 EXAMPLE: with TA =20·C, t1 =60 S, t2 =1 s, tTlm =0.5 ms, tADe =0.15 ms and tproc = 10 ms a medium current Icc results: 'ee .. 1~ x 0.5 ms x 0.35 rnA + s6s (10 ms x 0.35 mA + 0.15 ms x 0.8 mAl + 1.6 IIA = 1.83 IIA Application Examples 4-97 Ultra-L?w;Power Design With the MSP430 Family With the previous example, the current consumption increases by 15% when compared to the consumption of low power mode 3 (1.6 J1A). 4.9.3 Minimization of the System Consumption· The overall current consumption of an MSP430 system is composed of three components: o o o The consumption of the MSP430 The self-discharge of the battery The consumption of the other system components The minimization of the current consumption of each o(these three parts is discussed in detail. 4.9.3.1 Consumption of the MSP430 The low power mode 3 needs to be the normal mode. Active mode and active mode with ADC are used only when necessary. The rules for the minimization of the current consumption are: 4-98 o Leaving of the low power mode 3 (wake-up) as rarely as possible, for example only every two seconds. o The program executed after the wake-up should be as short as possible (e.g. incrementing of a counter and test, if other activities are necessary). If this is not the case, immediately return to the low power mode 3. o The time intervals between active periods (calculations) should be as long as possible (e.g., 60 s or longer). o Only the necessary peripherals should be switched-on (e.g., the ADC should be on only during a conversion). After the completion of a conversion, the ADC should be switched-off. This can be supported by the use of the ADC interrupt. The interrupt service routine of the ADC switches off the ADC supply SVcc after the conversion is completed. o Use of the interrupt capability of PortO to react to external changes. The inputs can interrupt using the leading or trailing edge of an input signal. This ensures the detection of any changes at the inputs without currentwasting polling. o Extremely long calculations (Mclaurin-series, Taylor-series) should be avoided. Instead tables should be used. The seven addressing modes, provided by the MSP430, are tailored especially for fast table processing. o Subroutine CALls should be avoided in frequently used software parts due to the overhead time they need. Instead, the code should be rein- Ultra-Low-Power Design With the MSP430 Family serted two or three times (like a MACRO). More ROM space may be needed, but lewer CPU cycles are needed. D Short loops should be avoided due to the overhead needed for the loop control. Instead, the loop should be placed into a linear code sequence. D For longer software parts, the working registers R4 to R15, should be used. This results in shorter execution times and in less needed ROM space. D Immediate stop 01 the calculation il ORe 01 the lactors-and therefore the result too-is zero II the previouly mentioned recommendations are applied, the current consumption 01 the active mode is 01 second order only. The exceptionally high calculation power 01660 million instructions per Ws (MIPS/w) allows it to ignore the influence of a single instruction. Much more important is the current consumption during the low power mode 3. 4.9.3.2 Self Discharge of the BsUery The self discharge element of the current consumption can not be Influenced. The battery manulacturer recommendations should be followed. It is recommended that the battery be placed in a relatively cool location inside of the case. This means do not place the battery next to hot parts (e.g., the radiator to be measured with a heat cost allocator). An estimation value often used for the self discharge of a battery during 10 years, is to calculate only with 70% of the nominal charge. This relates to 3.5% self discharge per year. Expressed by a discharge current this means 2 pA for a 0.5 Ah battery. 4.9.3.3 Current Consumption of Other System Components This current is composed of different parts. The most important ones are discussed. Crystal The desire for good quality and a low frequency (32,768 Hz) results in a need for a driver power ranging from 1 J!W to 10 J!W. With a supply voltage of 3 V, the current consumption ranges from 333 nA to 3.33 pA (with an average of 1 pA). This current is always being consumed, because the 32-kHz oscillator is used for the time base. Liquid Crystal Display The desire lor good quality and a low Irequency (128 Hz) results in a need for current consumption of approx. 13 nNmm2 segment area. For an LCD with 100 mm 2, this means a current near 1 pA (1.3 pA). Application Examples 4-99 Ultra-Low-Power Design With the MS':'430 Fam~y The MSP430 allows the optimization ofthe chosen LCD with external resistors for the threshold generation. External Circuitry Keys and switches connected to inputs that can be closed during long periods (e.g. the contact of a flow meter with no consumption) should have the possibility to be switched-off. This is done to avoid the currentflowing through the internal or external pulldown resistor. Figure 4-59 shows three examples: If a contact is closed longer than a defined time, the external pulldown resistor or the contact is switched off. From then on a regular polling is necessary to monitor contact.lfthe contact opens again, the normal mode is installed again. Internal Pulldown Reelstor OV MSP430 3V From System - --o---(C>---<.....-i--. _...J External Pulldown Resistor OX,PO.y,TP.z 3V 6 No Pulldown Resistor OV Figure 4-59. Connection of Keys to Inputs Inputs of the MSP430 should always have a defined potential, otherwise a current flows inside of the input circuitry. Figure 4-59 shows three possible ways to connect an Input to a defined potential. 4-100 o Input with an internal pulldown resistor: The key'is switched off with an output. This is made by switching the output to Vss (DVss) or to high impedance. o Input with an external pulldown resistor: The resistor itself is switched to the potential given by the switCh. This means that if the switch is open Vss potential, when it is closed Vcc potential. o No pulldown resistor: The switch connects to defined potentials in both positions Ultra-Low-Power Design With the MSP430 Family External circuitry (e.g., sensors) should be turned off if not in use. This can be established by the use of the SVcc terminal. (Figure 4-60, left). If the current is too high for the SVcc terminal (I >1 OmA), then a pnp transistor may be used forthis purpose (Figure 4-60, right). The SVcc terminal is used then as a reference input for the ADC. While a 1-k.Q sensor sinks 3 rnA when always connected to a voltage Vcc = 3V, the same sensor sinks a very low average current if connected only every 60 s during the conversion time of the ADC (135j1S @ ADCLK = 1 MHz): - 675 A I sensor -- 3Vx135us 1 kOx60s - . n The average currentthrough the sensor is now only 6.75 nA if it is consequently switched on only during the conversion time. 32kHz _riDE 3V PO.X,Oy f...- sVec sVcc ~ f"'- [ [<10mA >10mA MSP430X32x External ClrcuHry - 1 A3 AO AVss AVss DVss DVec External Clrculby 1 1 I~ Figure 4-60. Turnoff of External Circuits With the consumption values now known, the lifetime of the battery can be calculated: Where: tBatt Lifetime of the battery in hours Application Examples 4-101 Ult~.-Low-~ow~ Design With the. MSP430 Family Qeat! Icc ISys Usable charge of the battery in Ah (70% of 0,5 Ah for this example) Supply current of the MSP430 in A (1.831JA for this example) Current through the external circuitry (crystal, LCD, peripherals) in A (2.31JA for this example) For a free-air temperature TA =20°C and the consumption values calculated before the lifetime of the battery is: teat! = 0.7 x 0.5 Ah 1.83 IlA + 2.3 IlA = 84745 h This number of hours is equivalent to 9.6 years. For ambienttemperatures deviating from TA =209C the typical values for ILPM3 can be seen in Figure 4-57. The exact values for the self-discharge of a battery can be found in the device specification. 4.9.4 Correct Termination of Unused Terminals (3xx Family) MSP430 terminals not used need to be treated in a defined manner. Table 4-13 defines the correct termination for every terminal not used in a given application. The termination shown assures lowest supply current. 4-102 Unra-Low-Power Design With the MSP430 Family Table 4-13. Termination of Unused Terminals PIN POTENTIAL COMMENT Necessary for EPROM programming also AVec AVss SVec Rex! AO to A7 Xin Xout XBUF OVcc OVss Open Open Open Vcc Open Open CIN TPO.O to TPO.5 PO.Oto PO.7 Vss Open Open Can be used as a digital input TP.5 switched to output direction, others to high impedance Unused ports switched to output direction R03 R13 R23 R33 Vss Vss Vss Display off: LCOMO - 0 SOtoS1 S3to S20 ComOtoCom3 RST/NMI TOO TOI TMS TCK Open Open Open Open OVcc resp. Vcc Same as AVec Can be used as a low impedance output Switched to analog inputs: AEN.x - 0 If no crystal is used If no crystal is used Output disabled Switched to output direction Pull-up resistor 100 kO Refer to the specific device data sheet Refer to the specific device data sheet Refer to the specific device data sheet Refer to the specific device data sheet Application Examples 4-103 Other!"SP430 .Af,?.'~/on~ 4.10 Other MSP430 Applications 4.10.1 Controller for a Heating Installation A very big part of the energy consumed in Europe is used for the heating of rooms. An intelligent controller for heating is a good investment. The controller shown in Figure 4-61 has the following possibilities for the optimum alignment: o Opening and closing of the mixing valve (regulates the mix of hot boiler water with the warm reflux). o o Control of the burner (off/on). Control of the circulation pump (off/on respective of the speed control with a TRIAC). If the outdoor temperature is above a programmable limit (e.g. 20°C) then the circulation pump is off. o Supervision of the boiler temperature: measurement with a temperature sensor. o Supervision of all temperature sensors (feasibility checks) The criteria for all of these decisions comes from the following inputs: . 0 The measured outdoor temperature is the most important value. It is measured with an outdoor temperature sensor. o o 4-104 The system and calibration data stored in an EEPROM: • The individual characteristic of the building stored as the slope and offset for the characteristic of the temperature of the Circulating water to the outside temperature • The dependence of the boiler temperature on the outdoor temperature • The outdoor temperature that stops the activity ofthe circulating pump (above this temperature only the warm water supply stays active) • The minimum switch-on time of the burner (a burner must be on for a minimum time to stay within given environmental limits) • Recording of errors for the field service (maintenance) The mean value of the outdoor temperature for the last 24 hours. This gives a value for the storage of heat in the walls and influences the necessary amount of energy. Other M,SP430 AppHcations o The chosen mode: • Summer Mode: Only the warm water supply is on, the mixing valve is always closed, the circulation pump is always off • Winter Mode: Normal heating is on • Maintenance Mode: For repair and maintenance only • Day Mode: the heating installation runs always independent of the time • Night Mode: the heating installation runs always with the lowered values for the night • Switch-off or temperature lowering during the night (circulating pump on resp. off) The advantages of a microcomputer controlled heating installation are: o Self calibration of the complete system is possible: learning phase and final optimization. o Exact tuning of the optimum mixing temperature due to the involvement of all relevant data o o o Exact knowledge of the timing for the temperature lowering at evening Optimum usage of the heating material with minimum pollution Different concepts are possible for the control of the heating installation Application Examples 4-105 Othe~ MSP430 APP!icatlons MON 23:'15 2lB!~D r----4--''Mr-I TPO.1 MPS43031x .-------+~Nv-lTPO.2 1/0 1/0 1/0 1/0 1/0 Open Mixing Value Close Mixing Value Burner on Circulation Pump on (TRIAC Control) I/O OV 5V Figure 4-61. Intelligent Heating Installation Control With the MSP430 In a very similar manner to the heating installation controller of Figure 4-61, for a house with more than one zone or area, the MSP430 can also be used in a temperature controller for a single-family home. Figure 4-62 illustrates this example. The boiler control is made by a second MSP430 or by the same MSP430 as shwon in the figure (with the 232 driver shown dotted). The room temperature selection-is made with a potentiometer or a small keypad. Both possibilities are shown in Figure 4-62. 4-106 Other MSP430 Applicat;?f1~ TUE 2D.lr-¢-D Room Temperature Sensor .....-"IQ'v-i _"'IA1\r-t 22:--t9 TDX to Boller Controller RCV From Boller Controller TPO.2 oV -jI - - - + - - - i CIN C1 Burner on Pump on 110 Vss VCC OV 5V Figure 4-62. Heating Installation Controller for a Single-Family Home 4.10.2 Pocket Scale Figure 4-63 shows a simple battery-driven scale. The measurement is made with a strain gauge bridge that changes its resistance ratio when loaded with a weight. A tare key allows it to zero the scale in an unloaded state. The measured zero value of the ADC is stored hi the RAM and subtracted from every measurement value. To hold the highly temperature-dependent bridge assembly in the ADC range where the calibration was made, a simple hardware fix is added to the MSP430. The fixing of the bridge output Is made by two TP outputs with the resistor values Rand 3R (see Figure 4-63). The software modifies the output state of these two TP outputs in a way, that for a known state of the bridge (e.g. no load), the amplifier output is within a certain range of the· ADC. Due to the possible TP-port output states Vee, Vss and high impedance, nine different and nearly equally spaced correction currents lcorr are available. The correction is possible for the positive and for the negative direction (signed correction). The correction current Icorr can also be fed into the bridge leg Vm if needed. The calibration data (e.g., slope and offset) is located in the RAM or-if existent-in an external EEPROM. The software normally uses the low power mode 3 (LPM3) whenever possible to reduce the current consumption: Application Examples 4-107 Other MSP430 Applications o After the completion of a measurement and accompanying calculation, the result is moved to the LCD controller and the external components are switched off with SVcc. The CPU is then switched off (with the LCD staying on). o With the On/Off key the scale can be switched off, which means that the LPM3 is used until the On/Off key is pressed once more. It is also possible to use the low power mode 4 (Icc = 0.1 jJA) instead of the LPM3. o I~S6B 32kHz COM SEL --~ RB MSP430C32x A 3 1 - - -.....- C Ranga + --&-C ---o--"""C A4 PO.3 PO.4 3 V/1.6 p.A TP.1 PO.II AOND Vee Vss i RS 3R Tare Key +~ Reference TP.O· On/Off + Bridge AlI88I11bly (Strain Gauge) SVcc Icorr +-+ R t - - i t - -.. 3V Figure 4-63. Simple Battery Driven Scale 4.10.3 Remote Control Applications The MSP430 can also be used for remote control applications like a car lock or a TV remote control. 4-108 o During the inactive time periods LPM3 or LPM4 may be used. This prolongs the life of the battery~ven for relatively small ones-to several years. o The Interrupt capability of all PortO inputs (8) ensures an extremely fast response to a pressed key. Without polling of the keypad, the software is within 8 cycles at the start of the interrupt handler. Other M~P430 Applications Figure 4-64 shows a transmitter for security applications. The storage of the secret code for the execution of the function is shown in three ways (only one is actually in use): o o o Storage in a small EEPROM Storage in a diode matrix. An inserted diode means a 1 otherwise a O. The maximum number of diodes defines the number of possible codes (2n). Rolling Code: The software generates random numbers and stores them in the RAM. These random numbers are synchronized for the transmitter and the receiver. Any activation of the key means a step to the next code. No external hardware is necessary If the current through the infrared diode is less than 20 rnA, then the npn transistor can be replaced by parallel TP ports. This is shown in Figure 4-64. 3V TP.4 TP.3 TP.2 PO.7 MSP430C31x r-"':':';¥--I 02-On Ox ~ PO.y ' _ _ - - - ' PortO VCC TP.1 ........\I\I\,--~ Vss i t--It:-~l-____..J 3 V/1.611A 3V Figure 4-64. Remote Control Transmitter for Security Applications A remote control transmitter for audio or video sets is shown in Figure 4-65. Normally for this purpose, no external memory is necessary just a keypad with a lot of keys. The high currents through the IR diode need another power stage with a very large capacitor in parallel. This is necessary because the battery cannot deliver the high peak currents. Application Examples 4-109 Other MSP~ App/~ations o 32kHz 3V MSP430C31x 2.20 TP.4 q TP.3 Ox TP.2 PortO PO.y ' - - - - - - - ' Vee .,. 3V11.ellAl VSS r i r-:-_____....-1 1 mF 3V Figure 4-65. Remote Control Transmitter for AudioNideo The MSP430 can be used also for the remote control receiver. Only a simple, inexpensive IR receiver without decode logic is necessary for this application. The received instruction can be decoded directly by the MSP430 with its high calculation power. This is possible for all the modulation modes used (amplitude modulation, biphase code, biphase space code). The decoded signal is used immediately (car lock application) or given to a host computer (video set). o 32kHz Pre-Bit IR-Slgnal of Remota Control Tr. \ III I11II l1li IR Info J J ---u--uu-u-u- MSP430C31x PO.l (RXD) 110 I-~n~. To The Controlled System l1li '\ Pre-Bit OV 3V/6V Figure 4-66. Remote Control Receiver With the MSP430 4.10.4 Sub-Controller for a TV Set The following functions of a TV set can be handled by a an MSP430: o 4-110 Receive of the IR remote control signals. Only a simple and inexpensive IR receiver without decode logic is necessary. The received information Is decoded by software and Is sent to the host computer in serial or parallel form. Other MSP430 Applications D Keypad scan D Channel display and control of LEOs. D Protection for children: This is done by programming a key sequence that protects the TV set against unauthorized use. D Security function for the host computer: If the host computer does not respond within a given time interval, the MSP430 resets the host. D Real-Time Clock: The 32-kHz ACLK frequency is used for the clock function of the complete system. This can also be used for turn-off sequences; if for longer than 10 minutes, no sender was active, or no remote control input was received. If an MSP430 is used for the functions described previously, then anything can be switched off except the IR receiver. The power consumption decreases to few milliwatts. All necessary data and instructions use the infobus (watchdog response, keyboard inputs, remote control signals, LED information etc.). 0 32kHz LCDorLEDs SEL Pre-BII J J IR-Slgnal of Remote Control Tr. \ III COM Info MSP430C31x 'lJL.fln...flf" IR Receiver 1055, 6 J18IBII l1lil1li 11191111 " Pre-BII TV Set AC PO.1 (RXD) b::-::-::-.Tubs Heating (PWM) n ......-~1I0 TV-Controller ~----------~----~~I~ Information Bus 1 1 0 " " ' - - - - - - - - - - 1 Out Watchdog In 110 OV Watchdog Out RESET 5V Figure 4-67. MSP430 in a TV Set Application Examples 4-111 Other AfSP430 Applic~!~ons 4.10.5 Sub-Controller of a Personal Computer The MSP430 can handle the energy management and switch off all currently unused peripherals (disk, screen, CPU, etc). When they are needed again, it can switch them on in a defined manner. Within an ac-powered PC, the MSP430 can take over the following functions: o o o o o o Switching off the PC when it is not used for a defined time period. Watchdog function for the host computer Defined switch off for all currently unused peripherals Defined turn on procedure for needed peripherals Keyboard/keypad scan Real time clock: The basic timer with its accurate crystal frequency is used for the time base 32kHz rlDh' PO ox Ringer Frequency PO PO.1 (RCV) elephone Network Interface Oy Control ~ in Keyboard INTERPT To Modem/ FAX·Hardware ,..---., ,I ~ '- _ _ _ ...I Kayboard Or PO Oz Op Om PO Data/lnstructlona Wstchdoa Out RESET Watchdoa In Disk On/Off PC-Interface Screen On/Off CPU On/Off Real-time Clock MSP430C31x P1 VSS VCC I I OV 5V Figure 4-68. MSP430 in an AC-Powered Personal Computer If the personal computer is powered by a battery (i.e., a Laptop computer), an MSP430C32x can take over the complete battery management: 4-112 o Turn on and turn off of the charger as indicated by the charge state of the battery o Calculation of the actual charge state out of weighted charge and discharge currents Other MSP430 Applications D Battery protection against overcharge, overload, and excessive temperatures D Measurement of current, voltage, and temperature of the battery. The onchip 14-bit ADC is used for this purpose. D Transmit of the measured and calculated battery state to the host computer. 32kHx I rlDh' "I Telephone Network Po..1 (RCV) OlakOn/Off Oy Control Keyboard INTERPT Or Po. RESET Watchdog In Po. Interface To Modem/ FAX·Hardware Watchdoo Out Ox Ringer Frequency in DataJlnstructlons Po. PC·lnterface Seresn OnlOff Ox CPU On/Off Op Realtime Clock Om Po. ,.---, I1..Keyboard ~ P1 _ _ _ -' SVCC RaX! ] I Voltege I ToCherger I Regulator I VOO A2 5V ± Temperatura ~ /. A1 AO MSP430C32x Om Vss Vss Voltage T I Akkum. I .-L Currant Shunt ~ o.V VCC I I o.V 5V Figure 4-69. MSP430 in a Battery-Powered Personal Computer With Battery Management Application Examples 4-113 Other MSP430 Applications 4.10.6 Subcontroller of a FAX Device Within a FAX device, the MSP430C31 x can take over the following functions: o o o o o o Switch off of the device if no activity is needed Switch on for a recognized telephone call Keyboard scan and information transmit to the host computer Display control for a 12.5-digit LCD display Real-time clock for the complete system Watchdog function with the on-chip watchdog o Telephone Network 32kHz Ringer Frequency PO.1 (RXD) SEL Interface Control COM 1+-------1~I/O n MSP430C31x FAX·Hardware Figure 4-70. MSP43D-Control/ed FAX Device 4-114 2.3.a.t. 123'iS61.B _"IErrorl Malna Fax Equipment Digital Motor Control 4.11 Digital Motor Control The MSP430 family is shown with digital motor control (DMC) applications. Several hardware proposals are given for pulse width modulation (PWM) and TRIAC-control applications for electric motors. Numerous circuit and pulse diagrams show the application of the MSP430 family for different electric-motor types and control concepts. For each hardware proposal the applicable motor types are named. 4.11.1 Introduction The application of DMC has some advantages compared to conventional concepts for motor control: o o o o o Better energy efficiency Better control of motor behavior (speed, torque, direction of rotation) Easy supervision of important motor conditions (temperature, current, speed) Use of smaller motors due to the better adaptability to the given application Use of motor types not applicable without DMC (brush less dc motors, reluctance motors) If the accuracy of fixed-point calculations is not sufficient then a floating point package (FPP), designed especially for real time applications, is available from TID. This memory and speed optimized FPP can be configured for two different number formats: 32 bits or 48 bits. The high speed results from the RISC-mode it uses (mainly single~cle instructions) and the Involved hardware multiplier (see Section 5.6, The Floating Point Package). Additionally a C Compiler with a very good code efficiency is available. 4.11.1.1 The MSP430 Family The MSP430 family with its 16-bit RISC architecture is capable to realize very advanced control concepts. This is especially true for the MSP430C33x with its hardware multiplier (16 x 16 bits) and its 16-bit limer_A allowing fourindependent PWM-outputs. All MSP430 family members use the same instruction set and the same CPU. This eases the use of existing user software enormously. Operating frequencies up to 3.8 MHz and singl~cle instructions when the register/register addressing mode is used for the source and the destinationthe normal addressing combination for real-time applications-results in calculation speeds formerly only known by DSPs. This high throughput allows calculations and algorithms needing more than 16 times the capability of 8-bit microcomputers. Application Examples 4-115 Digital Motor Control Actually, the MSP430 family consists of three different subfamilies. The hardware peripherals of the different stlbfamilies are listed in Table 4-14. The instruction set is the same for all members of the family. Table 4-14. Peripherals of the MSP430 Sub-Families HARDWARE ITEM MSP430x31x MSP430x32x 21 MSP430x33x Yes Yes Yes No Yes 8 8 0 0 24 16 Yes LCD Segment lines 23 14-BitADC Universal Timer/Port Module No I/Os with Interrupt 1I0s without Interrupt 30 16-Bit Timer_A No No USART (SCI or SPI) No No Yes HW/SWUART Yes Yes No Yes Yes Yes No Yes Yes Yes Watchdog Timer 16 x 16 HW Multiplier Basic Timer Yes Yes Oscillator FLL Yes Yes Yes LPM3 (Sleep Mode) Yes Yes Yes LPM4 (Off Mode) Package Yes Yes Yes 56SS0P 64QFP 100QFP The Low Power Modes The MSP430 family is designed for minimum power consumption. This feature-which allows full CPU activity with only 400-11A current consumption (730 IIA for the MSP430C33x) for an MCLK frequency of 1 MHz-reduces the size of the power supply to a minimum. Five different LPMs are implemented. The nominal supply currents lAM are shown for the MSP430C33x. The supply voltage is 5 V and the temperature range is from TA =-40 to 85°C. 4-116 o LPMO: the CPU is switched off, the 32-kHz oscillator (ACLK) the main clock MCLK (with enabled loop control) and the peripherals are active. lAM =120 IIA o LPM1: the CPU is switched off, ACLK, peripherals, and MCLK (with disabled loop control) are active. lAM = 120 IIA. o LPM2: the CPU and MCLK are switched off, ACLK and peripherals are active. lAM = 1811A. o LPM 3: the CPU is switched off, ACLK is active, the basic timer, the watchdog, and the interrupt hardware can be active (if enabled). lAM =5.211A. Digital Motor Control D LPM4: all parts of the MSP430 are off, only the RAM and the interrupt hardware are powered. lAM =0.4 f.,IA. The motor control software can use these low-power modes to reduce the power consumption to a minimum after the completion of the necessary calculations and control functions. 4.11.1.2 The 16-81t Tlmer_A The features of the MSP430 TimecA are very important for the pulse width modulation necessary for the DMC (see Section 6.3, The Timer_A, for explanations of the possibilities of this timer. 4.11.1.3 The Universal Timer/Port Module MSP430 family members that do not contain the Timer_A, contain at least the Universal Timer PortfModule (UTPM), a combination of two 8-bit timers with a common control unit and inputs and outputs. The UTPM is primarily thought as an ADC but it is also able to handle timing tasks that are not too complex. To get an interrupt request after a certain number of MCLK or ACLK cycles it is only necessary to load the negated number of cycles into the count registers TPCNT1 and TPCNT2. When the 16-bit counter (used with MCLK) or one of the 8-bit counters (used with ACLK) overflows to zero, the corresponding interrupt flag (RC2FG or RC1 FG) is set and an interrupt is requested. This method allows precise timings for TRIAC control or PWM control in the range of 128 Hz to 4000 Hz (repetition rate). This frequency range allows the replacement of PWM-control arrangements realized by relays, a solution sometimes needed in automotive applications. The UTPM can be used for: D Low-frequency pulse width modulation (see Section 3.6.4, PWM DAC With Universal Timer/Port Module); up to two independent PWM outputs are possible. D Measurement of the MCLK frequency when used without a crystal (see Section 6.5.8, Use Without Crysta~ D TRIAC-triggering: time measurement starting with the zero crossing of the acvoltage . D Other time measurements Application Examples 4-117 Di?itaJ Motor Control TPSSELi CMP--o ACLK--o MCLK--o-L...I.(:>-"'-. carry: MCLK--o" SeCRC2FG-Flag Even Count ACLK MCLK MCLK 0 0 1 1 MSBData LSBData Figure 4-71. Block Diagram of the UTPM (16-Bit Timer Mode) Figure 4-72 shows the generation of a low-frequency PWM with the UTPM alone. The timing for the period and for the pulse width is made by it. If the ACLK frequency is used for the timing. then two PWM outputs with up to 256-Hz repetition rate are possible. The resolution for this case is 128 steps. The formula for the period t of the PWM frequency is: t = at1 + at2 = n1 + n2 felk The formulas for the pulse width at1 and the corresponding value n1 are (the negative value of n1 is loaded hito TPCNTx): at1 = f1-elk - n1 = felk x at1 n2 and ~t2 are calculated the same way as n1 and ~t1. OFFh ,---~""",-,..r.---"--:::oII----~i ~~~-~-~-~~~~~I-~~-­ ~2~-----+---~~--~--~~------- Oh ~-----~-~------~----~-----At2 =n2/ACLK Ati = ni/ACLK fcI: Interrupt Latency and RC2FG RC2FG RC2FG RC2FG Interrupts SW Execullon Time " Figure 4-72. Low-Frequency PWM-Timing generated With the Universal Timer/Port Module 4-118 Digital Motor Control Figure 4-73 shows a solution that is synchronized by the basic timer (only one PWM timing is shown). Its interrupt (here with 256 Hz) sets the enabled PWM outputs and loads TPCNT1 and TPCNT2 with the corresponding negated clock cycles. The PWM outputs are reset by the interrupt software of the UTPM. The software is described in the Section 3.6.4. PWM DAC With the Universal Timer/Port Module). i \4- f (112 56 Hz) ~ OFFh .........---+--=*----+---:~I_--~1 .........---~~~---~~~I_--~ fTCNTx = 32768 Hz 128 Steps Resolullon 256 Hz Repetition Rete Oh~~--+--~~---+-~~~-- !.ti !.t1 !.t1 = n1lACLK t = n1/fBT Output "---.,,;=---+'---11.-----+1---11--- Id: Interrupt Latency and SW r execution Time Basic T. RCxFG Basic T. RCxFG Interrupts Figure 4-73. Low Frequency PWM Timing by Universal Timer/Port Module and Basic Timer 4.11.1.4 The Basic Timer Additional to the timers mentioned previously a third timer exists that is responsible for the time base (date and time). This timer runs completely independent of the other timers and outputs frequencies (0.5 Hz to 65536 Hz) derived from the crystal (ACLK) or the system clock generator (MCLK). This way the limer_A and the UTPM are completely free for real time operations. 4.11.1.5 The Watchdog Timer This 15-bit timer can be used for simple timer tasks or for security purposes. If it is not reset during a selectable time interval. then the watchdog timer resets the MSP430. This allows to reinstall the lost system integrity. The watchdog timer is switched on during the powerup and is active immediately. 4.11.2 Digital Motor Control With Pulse Width Modulation (PWM) Two modes of the limer.fi-the Up Mode and the Up/Down Mode-are developed especially for PWM generation. These two modes are used with all hardware proposals of this section. Application Examples 4-119 D/git~1 Motor Control 4.11.2•. 1 Single Output Stages If only one direction of rotation is necessary, or the change of the direction of rotation can be made with a relay having change over contacts, then a single output stage can be used. The direction of rotation of the motor is changed by a relay that switches the polarity of the field winding. For only one direction of rotation, this relay is omitted and the field winding is connected in a fixed way. All of the examples shown can use the high-frequency PWM (> 15kHz) or the low-frequency PWM (100 Hz and higher). The formulas for the coming circuit proposals are: V m = nCCRx V - --Y!!L x n nCCRO x motor'" nCCRx - Vmotor CCRO Where: Vm Vmotor nCCRx nCCRO Mean voltage at the motor M Voltage of the motor power supply M Content of Compare Register x Content of Compare Register 0 (Period Register) If the Up Mode of the Tlmer_A is used, then nCCRO must be substituted by nccRo+1. Single Output Stage With a Bipolar Power Transistor Figure 4-74 shows a single output stage with an npn power transistor. The PWM signal generated by Tlmer_A is amplified by two inverters and connected to the base of the power transistor. The inverters used must be able to drive the relatively high base current of the power transistor. Eventually several inverters need to be connected in parallel at the outputs, where serial resistors force an equal current distribution. Figure 4-74 shows such a driver stage at the lower right-hand corner. A simple configuration with only a pnp and an npn transistor is possible. This driver stage is shown In Figure 4-74 at the low- . er left-hand corner. The EEPROM connected to the MSP430 contains the characteristic of the controlled motor. 4-120 Digital Motor Control - 3t.fSlilB 5V VCC CINI--.... TP.1 HI(/V-. TP.O Dlracllon 01 Rotallon OV PossIble Pre-DrIvers: . ~- , '" OV Figure 4-74. Transistor Output Stage Allowing Both Directions of Rotation o Applicable for o Advantages • • DC motors, universal motors Minimum component count for only one direction of rotation Single Output Stage With a MOSFET Power Transistor Instead of npn power transistors it is possible to use power MOSFETs or IGBTs. Figure 4-75 shows a circuit with a dual MOSFET TPIC2202 and the appropriate MOSFET driver SN75372. An MSP430C33x controls two PWM outputs. If the calculations for the control of the motors are not too complex then it is possible to control up to four motors with a single MSP430C33x. If a change of the rotation direction is needed then a relay can be used as shown in Figure 4-74. The temperature of the motors can be observed with a temperature sensor, e.g., an NTC sensor. Figure 4-75 shows the circuitry needed for the connecApplication Examples 4-121 Digital Motor Control tion of two temperature sensors to the ADC inputs of the MSP430C33x. The motor temperatures are measured in appropriate time intervals to be sure, that typical circumstances are present. In case of a overly high motor temperature, the microcomputer switches off the MOSFET power transistor and switches on a fault indication LED. The observation of the motor current is realized with an operational amplifier working as a comparator. The circuitry shown allows eight different thresholds, a number that can be mOdified easily if neCessary. The control ports P3.x switch between the high state and the high-impedance state to get eight different thresholds (corresponding to eight different temperatures). OY I' ov -L Motor Temperatura TP.3 CIN Fault LED TP.2 Ports TP.1 TP.O Ports WInlrpl TA1 TP.x PorI4 TA2 MSP430x33x PO.7,NMI vas YSS PO.O P3.1 P3.2 5 P3.3 R Number 01 Revolutions ~________~~~Ar-f~~OY 1 - -_ _ _ _.:!!4R!JVV\r---l CUnent Comparison Figure 4-75. Control for Two MOSFET Output Stages o Applicable for • o DC motors, permanently excited dc motors Advantages • Control for two motors with minimum chip count The MOSFETs shown in Figure 4-75 allow up to 7.5-A continuous current simultaneously for both transistors. The TPIC2202, having only one source ter4-122 Digital Motor Control minai, allows only the measurement of the sum of both motor currents. If it is necessary to observe the motor currents independently, then the TPIC5201 can be used. This dual power MOSFET features two source terminals. For motor currents up to 3 A, the 15-V supply for the SN75372 is not necessary, a 5-V supply is sufficient for switching on of the MOSFETs. 4.11.2.2 H-Brldge Output Stages An H-bridge means the fourfold expense for power drivers compared to a single output stage. But if integrated drivers are used, the resulting expense is often lower than with a single output stage because the change of the direction of rotation is included with the H-bridge. H-Brldges for Low Motor Voltages For voltages up to 36 V, TI offers several solutions. Into this range belong the automotive sector and industrial control applications working with 24-V supply voltage. Output Stage With a MOSFET BrIdge Motor control applications working with relatively low voltages can use the Texas Instruments H-bridge TPIC5424. This device is able to switch currents up to 3 A at a maximum voltage of 60 V. The complete circuit diagram is shown in Figure 4-76. The gate voltage necessary for the turn-on of the upper MOSFETs of the bridge is generated by a bootstrap circuit. This gate voltage must be at least 5 V higher than the motor voltage. The MSP430 generates this support voltage using two capacitors and the low impedance power driver BT1. Three simple solutions are possible for the generation of the higher gate voltage: o o o PWM-output TA3 is used with the full PWM frequency (e.g. 19.2 kHz) PWM-output TAO is used with the divided PWM frequency (e.g. 9.6 kHz for 19.2 kHz). This is due to the only possible output mode for the period register, CCRO: Toggle/Toggle Mode. This way has the advantage that no other timer output is needed. Figure 4-76 illustrates this solution. One of the available output frequencies of the XBUF output is used: ACLK, ACLK/2 or ACLKl4 corresponding to 32.768 kHz, 16.384 kHz or 8192 Hz. Solutions 2 and 3 have the advantage of an always usable output voltage. They are independent of the PWM output driving the electric motor. Application Examples 4-123 Digital Motor Control Note: The power inverter shown, BT1, can be replaced by some parallelec:l---flot used otherwise-output ports of the MSP430C33x. They are toggled by a , software routine, driven by the interrupts . of the period register CCRO. A possible driver circuit for a pulldown outpLit is shown on the upper left-hand corner in Figure 4-76: the additional npn transistor lowers the output impedanceforthe positive supply voltage 12 V.ln this way the supply voltage VCC2 (18 V), which is needed for the output voltage of the SN75372, is generated. The two lower MOSFETs of the H-bridge are driven in a static manner from the MSP430 with 5-V signals. This is possible because the TPIC5424 is designed for logic drive signals (0 to 5 V). As shown in Figure 4-76, the TPIC5424 has integrated all the necessary protection diodes on-chip, therefore, no external components are needed. The signals at the MOSFET gates are shown in Figure 4-76 in the lower right-hand corner. An exceedingly high motor current is detected by the overcurrent detection circuit. If a fixed voltage level, according to a maximum current value, is exceeded (e.g. by a blocking of the motor or by a current flow through one of the. Hbridge halves), the comparator output switches off the lower drivers T2 and T4 and the additionally requested PO.O or NMI interrupt (highest priority) takes steps to switch off the output stages completely. The overcurrent detection can be realized with more than one level as shown in Figure 4-75. The motor temperature can be measured the same way as shown in Figure 4-75. o Applicable for • o 4-124 Permanently excited dc motors Advantages • Few components necessary • Both directions of rotation possible Digital Motor Control Parts Select MSP430x33x PO.l PO.2 5V TA2 r--\,;j;1j=~ Pl.x HM.......>--~~---.----tJ Pl.y rMJj:---111=:!=~=~_J Pol14 Vee pone VSS -----c i ~ Vec 5V 74HCOO TAl LINI 1.-____-1 HINI TA2 L1N2 L...-____-I TA3 VS2~~~------_+--~----~_e~ ~~--------..._4~ HIN2 VSl L1N3 L03~----------+--l------~_+__. 1.-____--1 HIN3 LOI ~-------I--t PO.O I -____--...J FAULT L021---------~::;:...---l---' vs~--~------~~~~--<~_e------~~~ Vss OV ITRIP 5V Overcurrent Adjustment r-~----------~----~------~------OV Figure 4-82. PWM Motors Control for High Motor Voltages 4.11.2.4 Low-Frequency Pulse Width Modulatfon . The PWM examples demonstrated in the circuits of this section are primarily thought for high repetition rates (16 kHz and more) but a lot of motor control applications do not need these high repetition rates. For these applications the same hardware proposals can be used with an output controlled by the Universal Timer/Port Module. If fed by the ACLK (32 kHz), it allows for example the following combinations: o o o 128-Hz repetition rate with a resolution of 256 steps or 256-Hz repetition rate with a resolution of 128 steps 512-Hz repetition rate with a resolution of 64 steps Application Examples 4-135 DiVltal Motor Control Other combinations are possible too. If the MCLK is used as input frequency then the repetition rates and the resolution can be even higher, but the interrupt latency time plays an increasing role due to the software-based structure of this timer module: the PWM output is controlled by an interrupt handler arid not by a hardware module as with the Timer_A. The characteristics of this kind of control are very similar to the TRIAC control due to the low repetition rates. This way of motor control can substitute the PWM-control solutions realized with relays, as it is implemented in some automotive applications. More details of the PWM generation are described in Section 3.6.4, PWM DAC With the Universal Timer/Port Module. o Applicable for • All motors controllable by TRIACs • DC motors 4.11.2.5 Bandwidth of the MSP430 Solutions for PWM Control Figure 4-83 shows the bandwidth of solutions the MSP430 family offers for PWM control systems; starting from a minimum system with a MSP430C312 up to a maximum system using a MSP430C337. The minimum system with the MSP430C312 gets its information concerning the motor control (reference speed, direction of rotation, on/off) normally from a host via the I/O terminals or the SW/HW UART (RS232 link). It allows relatively slow PWM frequencies (",1 kHz). The maximum system with the MSP430C337 is shown in the following. Its capabilities allow complete system control, not just the motor handling. The PWM control for a Single-phase motor normally does not use 100% of the MSP430 CPU. This being known, many functions of the host computer can be taken over by the MSP430 (e.g., when used in a tumbler or a dish washer controller). This is especially true for versions of the MSP430 having large memories and many 1/0 lines. 4-136 Digital Motor Control 5V VCC 27+4 LCDIOutput II0s Select/Common PortO MSP430C312 Sensors SW/HW-UART ADC TP.y PO.1, PO.2 TP.x Frequency Out ----------__----------------_4--0V 5V UART LCDIOutputs Sensors Temperature Speed TA414----t Currant TA11------1~ Current Compo TA2 Power Stagas II0s TA3,-"'1-_..,..-.....J Keys Display LEOs Lamps Counter Frequency Out Relay Drivers ----------~----------------_e--OV Figure 4-83. Minimum System and Maximum System Using the MSP430 Family In Figure 4-83 all components not absolutely needed are omitted. The hardware proposals shown are not only usable for the motor type named in the text, but also for other motor types when the needed hardware changes are made (e.g. the adding of a Hall sensor (position indication sensor) for a brushless dc motor). If needed the application shown can be completed with one or more of the following features: o Temperature sensors for the measurement of the motor temperature(s) o Temperature sensors for the driver Ie Application Examples 4-137 Digital Motor Control o o o Tachometer for the measurement of the motor speed or the rotor position Inputs for light sensors (safety. movement. flame observation etc.) Analog inputs for the measurement of the motor voltage (improvement of control) o Connections to a host via the USART (SPI or SCI). HW/SW-UART or ports o Some of the possibilities shown in Figure 4-83 (keys. LEOs. relays. LCD etc) Caused by the numerous peripherals of the MSP430 family. all of these previous functions can be implemented easily and cheaply. 4.11.3 Digital Motor Control With TRIACs With the help of a TRIAC (TRiode for ac) the following electric motor types can be controlled: o o o o o Universal motors DC motors (connected via a bridge rectifier. See Figure 4-84) Capacitor motors Single-phase asynchronous motors Single-phase synchronous motors The timing forthe TRIAC control Is possible with the Universal Timer/Port Module and the Timer_A. Both can deliver the timing in the range from 0.5 ms to 20 ms with the needed resolution. 4.11.3.1 Motor Connection and Control The electric motor can be connected to ac directly or via a bridge rectifier. Both possibilities are shown in Figure 4-84. It is possible to control ac motors as well as de motors with a TRIAC. 4-138 Digital Motor Control 230VAC Zero Crossing 5V Zero Crossing 5V MSP430C32x PO.O C R R -*----~~--------~~~~OV Figure 4-84. TRIAC Control for AC Motors and DC Motors The RC combination switched in parallel to the TRIAC (see Figure 4-84) prevents the turn-on of the TRIAC in case the voltage changes too fast (large dvl dt). Switching ac transients, therefore, do not cause errors. Otherwise, this RC combination greatly reduces switching noise (EMV). With the circuitry of the left hand side of Figure 4-84, the current through the TRIAC can be measured in the positive and negative direction. The current source of the MSP430 shifts the signed input voltage of the TRIAC current into the unsigned range of the 14-bit ADC. The zero point of the ADC can be calibrated during periods without TRIAC current. 4.11.3.2 TRIAC Control A TRIAC normally cannot be controlled directly from a microcomputer. Two factors cause this: o A normal microcomputer output cannot provide the necessary current for the TRIAC gate. The gate current is near 100 mAo o During the triggering of the TRIAC, the TRIAC gate generates a voltage that can pull the microcomputer output above or below the supply voltages, Vcc with respect to Vss. This can lead to destruction of the output, to latch-up, or to a hang up of the software. Both of the previous mentioned disadvantages are eliminated when a simple transistor stage is added between the microcomputer output and the TRIAC gate. o The current amplification of the transistor provides the necessary gate current using the limited output current of the microcomputer Application Examples 4-139 ~Igital Motor Control o The voltage range of the transistor collector withstands even strong voltage peaks generated by the TRIAC gate. Depending on whether a negative or positive gate current is used, an npn- or a pnp-tr'ansistor is used. Both possibilities are shown in Figure 4-85. The superior circuit arrangement depends on the gate characteristics of the TRIAC used. The gate current needed is normally lower if a negative-going gate trigger pulse is used. Overcurrent Detector Figure 4-85. Positive and Negative TRIAC Gate Control The TRIAC gate can be controlled in a static or in a dynamic manner. 4-140 o Static Gate Control: a long gate pulse switches on the TRIAC safely. The disadvantage of this method is the high gate current that is needed. o Dynamic Gate Control: a sequence of short pulses (duration approximately 10 IJ.S) switches on the TRIAC. If the first pulse does not have enough energy, one of the following pulses switches the TRIAC on safely. This method needs little energy and lessings the load on the power supply. One of the MSP430 timers can be left running in PWM mode or the setting/resetting by software can also do this job. Digital Motor Control ~ Dynamic tdelay,'--y IIIIIII Control Typically 5 to 8 Pulsea -+------~~------------~----------~~------static Control:...+-----I'-'".J.-..I-----~-L----~.J..f__J.--- Voltage Figure 4-86. Static and Dynamic TRIAC Gate Control The time tdelay in Figure 4-86 represents the time delay measured from the zero croSSing of the ac voltage to the triggering of the TRIAC. The conduction angle is defined in this way. The sequence of software steps is different for the Timer_A and the Universal Timer/Port Module. Universal Timer/Port Module o The time tdelay is calculated by the MSP430 software depending on the control algorithm o The negated number of cycles (MCLK or ACLK) corresponding to the result ~elay is loaded into the counter registers TPCNT1 and TPCNT2 after the zero crossing of the ac voltage o The timer requests an interrupt after the elapsed time tdelay (TPCNT2 overflows). o The called interrupt handler finally triggers the TRIAC, which switches the ac voltage to the load. Application Examples 4-141 Digital Motor Control Tlmer_A (Continuous Mode) o The time tdelay is calculated by the MSP430 software depending on the , control algorithm o The number of cycles (MCLK or ACLK) corresponding to the result tdelay is added to one of the compare registers CCRx after the zero crossing of the ac voltage o The output unit x is programmed to the mode that outputs the desired trigger pulse o The CCRx requests an interrupt after the elapsed time tdelay (CCRx equals the timer register). o The output unit x triggers the TRIAC, which switches the ac voltage to the load. . o If dynamic gate control is used, the called interrupt handler outputs several trigger pulses by software or by using the PWM capability of Timer_A. 4.11.3.3 Control Algorithms The value to be controlled (speed/velocity, current consumption, or torque) is influenced with the conduction angle of the TRIAC. This conduction angle (see Figure 4-86) is defined by tdelay, the time the TRIAC triggering is delayed with reference to the zero crossing of the ac voltage. For the control algorithms (that need to run in real time) two different methods are used: o Normal calculation of the algorithm: For this method, the MSP430c33x is well suited very because of its hardware multiplier on-chip. This allows a very-high calculation speed. (10 to 20 times higher than possible with an 8-bit CPU. o Use of tables (especially with very high control speeds): For this method, the MSP430 Is also very well suited because of its addressing modes, indirect, indirect autoincrement, and indexed, allow for a very simple and fast access to table values. With TRIAC controls, normally everything necessary for the controlling is calculated directly. For de machines, PIO control is possible without the use of characteristics because of their linear behavior. Exception: With asynchronous machines most often a voltage/frequency or a currentlfrequency characteristic method is used that uses description tables. These are located in the ROM (normalized form) or in an "external memory. 4-142 Digital Motor Control 4.11.3.4 Cost Reduction To lower the cost of the complete system, two possibilities exist. They are described in the following two sections. Nonregulated Voltage for the TRIAC Control To minimize the cost for the power supply, it is possible to split the parts for the supply of the MSP430 and for the TRIAC control. The TRIAC control does not need a regulated voltage supply, so this voltage can be supplied directly from the charge capacitor Cch. Figure 4-87 illustrates this method. This solution has another advantage; the two supplies are separated completely. The power part interferes with the control part very little. The npn transistor can be replaced by an unused driver on the board. Non-Regulatad Voltage TP.x To The AC Voltage MSP430 Cch vss OV Figure 4-87. Nonregulated Voltage for the TRIAC Control Use Without a Crystal Despite the relatively low cost of a 32-kHz crystal, it can be advantageous to leave this component out."The TRIAC control requires the measurement olthe ac frequency. This is required to know the exact time of the zero crossing of the ac voltage. If no crystal is used, the DCO frequency can be controlled by the measurement of a full ac period with one of the MSP430 timers. The formula for the calculation of the MCLK frequency fMCLK out of the timer value nand the ac frequency fac is: fMCLK = n x k x fac Where: fMCLK Output frequency of the DCO Application Examples [Hz] 4-143 pii!!tal Motor Control fae n k AC frequency [Hz] Measurement result in the timer register Predivider constant of the timer used (1, 2, 4, 8) The measured DCC frequency fMCLK can be adjusted to the desired value by taking measurements in regular time intervals. The calculated value of fMCLK is used as a time base for the TRIAC triggering. More details are given in Section 6.3.8.7, MSP430 Operation Without Crystal. 4.11.3.5 Bandwidth of the MSP430 Solutions for. TRIAC Control Figure 4-88 shows the available bandwidth the MSP430 family offers. Starting from a minimum system with an MSP430C312 up to a maximum system using the MSP430C337 a lot of solutions are possible. For the application ofthe MSP430 for a TRIAC motor control the same considerations are valid as made before for the PWM applications. It is possible with an MSP430 to control more than one electric motor. The second motor can also be controlled as shown with a TRIAC-then the TRIAC control circuit is simply doubled-or the TAx output of the MSP430C33x is used for the PWM control of the second motor. 4-144 Digital Motor Control 5V 230 V AC Sensors 110 Ports pone MSP430C312 LCDOutpul8 TP.y t--VIIV---l HWISW-UART MCLK,ACLK ------~------------~~~- OV 5V USART HWISW-UART Sensors EEPROMs 110 pone Keyboard Display (LCD) LEOS Lamps Relals Driver Ext. Memories Gates Jumpers --r---~----------~~~--~--~-OV Countar Input Figure 4-88. Minimum System and Maximum System With the MSP430 Family In Figure 4-88, all circuitry not needed to demonstrate the application is omitted. 4.11.4 Motor Measurements The methods shown for the measurement of the needed values like temperature, speed/velocity, etc are valid for PWM and TRIAC controls. 4.11.4.1 Overc:urrent Detection Many applications make it necessary to detect increased motor current and to start provisions when this occurs. An example for this is the blocking of a motor. Independent, if the high current consumption is detected by a threshold comparison or by a current measurement In any case, the software has to take Application Examples 4-145 Digital Motor Control steps against the overcurrent with the switch-off of the motor and the preventing of further gate triggering or by switching off the PWM output. Threshold Detection MSP430 family members that do not have an ADC on-Chip must simplify the overcurrent detection to the detection of a passed-over threshold value. A simple operational amplifier is used, it compares the voltage generated by the motor current over a shunt with the calculated threshold. If this fixed threshold i& reached, an interrupt is requested. Figure 4-89 shows this method of overcurrent detection on its upper side. The threshold itself is defined by the two resistors at the inverting input of the operational amplifier. If the voltage at the shunt resistor gets higher than this threshold, the positive edge of the operational amplifier output generates an interrupt signal. If one threshold is not sufficient because the motor current needs to be better defined, a variable threshold, as shown in Figure 48-9 on the lower side, can be used. The MSP430 defines the desired threshold by the switching of the resistors 2R and 4R. If the outputs use the high, the low, and the high-impedance states, then 9 different thresholds are possible with this circuit. The NMI input (non-maskable interrupt) can be used also for the overcurrent detection. No disabling is possible and the fastest response is assured. 4-146 Digital Motor Control PO.o Overcurrent DM~or__; -__~-r-r ______~~~~ Figure 4-89. Overcurrent Detection With Single and Multiple Thresholds Current Measurement MSP430 family members having an on-chip ADC (MSP43DC32x). can measure the current of both half-waves of the motor current. This allows a much better judgment of the behavior of the motor system than is possible with a simple threshold comparison. The voltage at the shunt. which is proportional to the motor current. is shifted into the range of the ADC (AVss to SVcc) with the voltage drop of Ics at Rv. Ics is the output current of the MSP430 current source. The voltage at the shunt is measured with one of the ADC inputs AD to A5. The resolution at these analog inputs is 305ILV for a supply voltage of 5 V. If this is not sufficient. a simple amplifier is used. The zero point can be measured during periods with zero current. Figure 4-90 shows the measurement of the motor current. Application Examples 4-147 Digital Motor Control 230VAC Voltage Measurement 230VAC . 3V 2.5V --2V A1:~ Zero Crossing C R 3.5 V ~~~-----.----~--~~-.-+~ ~O.5V Vsh: ---.;;:r- 0 V ---O.5V OV Current Measurement Figure 4-90. Motor Voltage Measurement and Current Measurement 4.11.4.2 Voltage Measurement Figure 4-90 shows, at the left-hand side, how to measure the ac voltage (or another voltage) if needed. The diode prevents a negative voltage at the analog input AO. In this way, only the positive half wave can be measured. If both half waves are needed, the same way as shown for the motor current path and can be used. The voltage drop of Ics at resistor Rv shifts the signed input voltage into the range of the ADC. 4.11.4.3 Zero Crossing Detection The detection of the zero crossing time of the ac voltage is very important with the TRIAC control because the zero crossing time represents the reference point for the phase control. The absolutely accurate zero crossing time is not necessary to get because in any case a certain minimum voltage must be reached at the TRIAC to hold it in the on-state. Figure 4-91 shows a simple circuit for this purpose. Via a resistor with a high resistance, the ac is connected to an interrupt input of the MSP430. This interrupt input is protected by a Zener diode (3.5 V), which protects against positive or negative overvoltages. The two edges of the square wave input signal give a very good indication for the positive and the negative zero crossing of the ac voltage. The time error of the zero crossing is due to this circuit arrangement and is approximately 60 lIS. 4-148 D!g~al Mot?' Control ov ..J.- Motor Temperature CIN COM 1---' TP.2 1--'\1(J'v_ SEL TP.l HNv-' TP.O MSP430 >---+--1 PO.O P003 2.7 V ov ~~--------'---r==~====~~~~~~~~~~~!=~~~o~v~ Figure 4-91. Support Functions for the TRIAC Control A second possibility for the detection of the zero crossing is shown on the lefthand side of Figure 4-91. In case of a heavy disturbed ac voltage, the operational amplifier used as a Schmitt trigger gives an uhdisturbed zero crossing signal. 4.11.4.4 Measurement of the Motor Speed If the control of an electric motor's speed is desired, a tachometer or something similar is necessary at the motor's shaft. The output signal of this tachometer is connected directly to an interrupt input of the MSP430 or is amplified with a simple operational amplifier when the output signal is t~o low. The second method is shown in Figure 4-91. With the capture latches the TImer_A provides, very precise timing measurements are possible. 4.11.4.5 SupelVls/on of the Motor Temperature To avoid the overheating ofthe motor, a temperature sensor (e.g. an NTC sensor) can be connected to MSP430 family members that have an ADC on-chip. In Figure 4-91 , this possibility is shown for the analog input A1. Other MSP430 members can use the Universal Timer/Port Module as an ADC (see Figure 4-91). The software has to take steps when a high temperature is detected (e.g. tum-off of the motor, tum-on of an error indication, and other things). Application Examples 4-149 Digital Motor Co~trol 4.11.4.6 Change of the Rotation Direction In Figure 4-92, it is shown how the rotation direction can be changed for a universal motor (single-phase series commutator motor). The field winding is changE!d with a relay having two change over contacts. The same way the motor winding can be changed over. 230VAC 5V VCC If0 Ports LCD, Outputs HWfSW·USART Direction 01 Rotation Figure 4-92. Change of the Direction of Rotation for a Universal Motor 4.11.5 Conclusion The application examples shown for the MSP430 family demonstrate the excellent suitability of this microcontroller for the digital control of electric motors. This is true for PWM control as well,as for TRIAC control. The numerous onchip hardware modules like an ADC, I/O ports, and other helpful peripherals also ease the task. The total software compatibility of the MSP430 family members allows its use in software development. Table 4-15 gives an overview of the capabilities of the MSP430 sub-families: Table 4-15. Capabilities of the MSP430 Sub-Families CAPABILITY 20kHz PWM Control MSP430x31x No MSP430x32x No MSP430x33x Yes Slow PWM Control « 1kHz) Yes Yes Yes TRIAC Control Yes Yes Yes Single Phase PWM Motor Control Yes Yes Yes Three Phase PWM Motor Control No No Voltage/Current Measurement Yes Yes Yes No Voltage/Current Comparison Temperature Measurement No Yes yeS Yes Yes Speed Measurement Yes Yes Yes 4-150 Yes Chapter 5 Software Applications 5-1 5.1 Integer Calculation Subroutines Integer routines have important advantages compared to all other calculation subroutines: o o o Speed: Highest speed is possible especially when no loops are used ROM space: Least amount of ROM space is needed for these subroutines Adaptability: With the following definitions it is very easy to adapt the subroutines to the actual needs. The necessary calculation registers can be located in the RAM or in registers. The following definitions are valid for all of the following integer subroutines. They can be changed as needed. Integer Subroutines Definitions: Software Multiply IRBT .EQU R9 IROPl .EQU R4 First operand IROP2L .EQU R5 Second operand low word IROP2M .EQU R6 Second operand high word IRACL .EQU R7 Result low word IRACM .EQU R8 Result high word ; Bit test register MPY Hardware Multiplier ResLo .EQU O13Ah ResHi .EQU O13Ch HW_MPYer: Result reg. LSBs Result register MSBs SumExt .EQU O13Eh Sum Ext. Register All multiplication subroutines shown in the following section permit two different modes: 5.1.1 o The normal multiplication: the result of the multiplication is placed into the re~ult registers o The multiplication and accumulation function (MAC): the result of the multiplication is added to the previous content of the result registers. Unsigned Multiplication 16 x 16-Bits The following subroutine performs an unsigned 16 x 16-bit multiplication (label MPYU) or multiplication and accumulation (label MACU). The multiplication 5-2 subroutine clears the result registers IRACL and IRACM before the start. The MACU subroutine adds the result of the multiplication to the contents of the result registers. The multiplication loop starting at label MACU is the same one as the one used for the signed multiplication. This allows the use of this subroutine for signed and unsigned multiplication if both are needed. The registers used are shown in the Figure 5-1 : o 15 Bit rest Register Multiplicand R6IROP2M R5IROP2L Multiplier R81RACM R71RACL Accumulsted Result Figure 5-1. 16 x 16 Bit Multiplication - Register Use EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES) without CALL: ; TASK MACU MPYU EXAMPLE ;------------------------------------------------------------MINIMUM 132 134 OOOOOh x OOOOOh - OOOODDODDh MEDIUM 148 150 DA5A5h x D5A5Ah = 03A763E02h MAXIMUM 164 166 DFFFFh x OFFFFh = OFFFEOOOlh UNSIGNED MULTIPLY SUBROUTINE: IROPI x IROP2L -> IRACM/IRACL USED REGISTERS IROPl, IROP2L, IROP2M, IRACL, IRACM, IRBT MPYU CLR IRACL CLR IRACM o o -> LSBs RESULT -> MSBs RESULT UNSIGNED MULTIPLY AND ACCUMULATE SUBROUTINE: (IROPI x IROP2L) + IRACMilRACL -> IRACMiIRACL MACU L$002 CLR IROP2M MSBs MULTIPLIER MOV #1,IRBT BIT TEST REGISTER BIT IRBT,IROPI TEST ACTUAL BIT Software Applications 5-3 L$01 JZ L$01 IF 0: DO NOTHING ADD IROP2L,IRACL IF 1: ADD MULTIPLIER TO RESULT ADDC IROP2M,IRACM RLA IROP2L RLC IROP2M MULTIPLIER x 2 RLA IRBT NEXT BIT TO TEST JNC L$002 IF BIT IN CARRY: FINISHED RET If the hardware multiplier is implemented then the previous subroutines can be substituted by MACROs. For source and destination, all seven addressing modes are possible. If register indirect or register indirect with 8utoincrement addressing modes are used to address the result, a NOP is necessary after the MACRO call to allow the completion of the multiplication. The ~umExt Register contains the carry after the MAC instruction; 0 (no carry) or 1 (carry occurred). Macro Definition for the unsigned multiplication 16 x 16 bits MPYU . MACRO argl,arg2 MOV argl,&0130h MOV arg2,&0138h .ENDM Unsigned MPY 16x16 Result in ResHilResLo Multiply the contents of two registers MPYU IROP1, IROP2L CALL the MPYU macro MOV ResLo,R6 Fetch LSBs of result MOV ResHi,R7 Fetch MSBs of result Multiply the operands located in a table, R6 points to MOV #ResLo,R5 Pointer" to LSBs of result MPYU @R6+,@R6 CALL the MPYU macro NOP MOV 5-4 NOP: allow completion of MPYU @R5+,R7 Fetch LSBs of result MOV @R5,R8 Fetch MSBs of result Macro Definition for the unsigned multiplication and accumulation 16 x 16 bits . MACRO argl,arg2 Unsigned MAC 16x16 MOV argl,&0134h Carry in SurnExt MOV arg2,&0138h MACU .ENDM Result in SumExtlResHilResLo Multiply and accumulate the contents of two registers 5.1.1.1 MPYU R5,R6 Initialize SumExtlResHilResLo MACU IROP1,IROP2L Add IROPl x IROP2 to result ADC &SumExt,RAM Add carry to RAM extension Run Time Optimized Unsigned Multiplication 16 x 16-Blts If the operands ofthe multiplication subroutine are shorter than 16 bits, the pre" vious multiplication subroutine MPYU can be optimized during run time The multiplication stops immediately after the operand IROP1 equals zero. This indicates that the operand with leading zeroes should be in IROP1. This run time optimized subroutine can be used instead of the normal subroutine. (The subroutine was developed by Leslie Mable/UK). EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES) without CALL: TASK MACU MPYU IROPl IROP2 ;------------------------------------------------------------MINIMUM 18 20 OOOOOh x OOOOOh = MEDIUM 90 92 OOOFFh x OFFFFh = OOOFEFFOlh 170 172 OFFFFh x OFFFFh = OFFFEOOOlh MAXIMUM OOOOOOOOOh UNSIGNED MULTIPLY SUBROUTINE (Run time optimized): IROPl x IROP2L -> IRACMIIRACL USED REGISTERS IROP1, IROP2L, IROP2M, IRACL, IRACM Software Applications 5-5 MPYU CLR IRACL CLR IRACM o -> o -> LSBs RESULT MSBs RESULT UNSIGNED MULTIPLY AND ACCUMULATE SUBROUTINE: (IROP1 x IROP2L) + IRACMIIRACL -> IRACMllRACL MACU' CLR IROP2M MSBs MULTIPLIER L$002 BIT #1, IROP1 TEST ACTUAL BIT (LSB) L$01 JZ L$Ol IF 0: DO NOTHING ADD IROP2L,IRACL IF 1: ADD MULTIPLIER TO RESULT ADDC IROP2M,IRACM RLA IROP2L RLC IROP2M Double MULTIPLIER IROP2 RRC IROP1 Next bit of IROP1 to LSB JNZ L$002 If IROP1 = 0: finished RET 5.1.1.2 Fast Unsigned Square Function For some applications, a fast square function is necessary. Two different solutions are given: o o For 16-bit unsigned numbers without rounding For 14-bit unsigned numbers with rounding. This version is adapted to the output of the ADC of the MSP430C32x family. . Both use table processing; an offset to a table containing the squared input numbers is built. The given cycles include the move of the operand into R5. Fast unsigned squaring for a 16 bit number. The upper 16 bits of the result are moved to RS. No rounding is used. 7 cycles MOV.B DATA+1,RS RLA RS Number x 2 (word table address) MOV SQTAB(RS),RS MSBs~2 MSBs to R5 to RS Squared value in R5 Fast unsigned squaring for a 14 bit number: The upper 16 bits of the result are added to a buffer SQSUM. Rounding is used. 18 cycles. If registers are used for the sum: 12 cycles ADC result to R5 MOV &ADAT,R5 ADD #80h,R5 Round high byte SWPB R5 MSBs to LSBs RLA.B R5 Number x 2 (word table address) ADD SQTAB(R5),SQSUM Add ADC SQSUM+2 Add carry to SQSUM MSBs~2 Continue Table with squared values. Length may be adapted to the maximum possible input number. SQTAB . word ($-SQTAB) * ($-SQTAB)/4 0 x 0 . word ($-SQTAB) * ($-SQTAB)/4 1 x 1 . word ($-SQTAB)* ($-SQTAB)/4 2 x 2 ~ 0 1 = 4 . word ($-SQTAB) * ($-SQTAB)/4 OFFh x OFFh . word OFFFFh Max. for 0100h x 0100h = OFE01h 5.1.2 Signed Multiplication 16 x 16-Bits The following subroutine performs a signed 16 x 16-bit multiplication (label MPYS) or multiplication and accumulation Oabel MACS). The multiplication subroutine clears the result registers IRACL and IRACM before the start. The MACS subroutine adds the result of the multiplication to the contents of the result registers. The register used is the same as with the unsigned multiplication. Therefore, Figure 5-1 is also valid. EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES) without CALL: TASK MACS MPYS EXAMPLE i------------------------------------------------------------MINIMUM 138 140 OOOOOh x OOOOOh MEDIUM 155 157 OA5A5h x 05A5Ah OEOIC3E02h MAXIMUM 172 174 OFFFFh x OFFFFh 000000001h = OOOOOOOOOh SIGNED MULTIPLY SUBROUTINE: IROPI x IROP2L -> IRACMIIRACL USED REGISTERS IROP1, IROP2L, IROP2M, IRACL, IRACM, IRBT Software Applications 5-7 MPYS CLR IRACL CLR IRACM o o -> LSBs RESULT -> MSBs RESULT SIGNED MULTIPLY AND ACCUMULATE SUBROUTINE: (IROP1 x IROP2L) + IRACMIIRACL -> IRACMIIRACL MACS L$OOl TST IROP1 JGE L$OOl MULTIPLICAND NEGATIVE ? SUB IROP2L,IRACM YES, CORRECT RESULT REGISTER TST IROP2L MULTIPLIER NEGATIVE ? JGE MACU SUB IROP1,IRACM ; YES, CORRECT RESULT REGISTER ; THE REMAINING PART IS EQUAL TO THE UNSIGNED MULTIPLICATION MACU L$OO2 L$Ol CLR IROP2M MSBs MULTIPLIER MOV #l,IRBT BIT TEST REGISTER BIT IRBT,IROP1 TEST ACTUAL BIT JZ L$Ol IF 0: DO NOTHING ADD IROP2L,IRACL IF 1: ADD MULTIPLIER TO RESULT ADDC IROP2M,IRACM RLA IROP2L RLC IROP2M MULTIPLIER x 2 RLA IRBT NEXT BIT TO TEST JNC L$OO2 IF BIT IN CARRY: FINISHED RET If the hardware multiplier is implemented then the previous subroutines can be substituted by MACROs. For source and destination, all seven addressing modes are possible. If register indirect or register indirect with autoincrement addressing modes are used to address the reSUlt, then a NOP is necessary after the MACRO call to allow the completion olthe multiplication. The SumExt Register contains the sign of the result in ResHi and ResLo; OOOOh (positive result) or OFFFFh (negative result). Macro Definition for the signed multiplication 16 x 16 bits MPYS 5-8 . MACRO arg1,arg2 MOV arg1,&0132h MOV arg2,&0138h Signed MPY 16x16 .ENDM Result in SumExtlResHilResLo Multiply the contents of two registers MPYS IROPl,IROP2 MOV &ResLo,R6 CALL the MPYS macro Fetch LSBs of result MOV &ResHi,R7 Fetch MSBs of result MOV &SumExt,R8 Fetch Sign of result Multiply the operands located in a table, R6 points to MOV #ResLo,RS Pointer to LSBs of result MPYS @R6+,@R6 CALL the MPYS macro MOV @RS+,R7 Fetch LSBs of result MOV @RS+,R8 Fetch MSBs of result MOV @RS,R9 Fetch sign of result NOP NOP: allow completion of MPYS Macro Definition for the signed multiplication and accumulation 16 x 16 bits. The accumulation is made in the RAM: MACHi, MACmid and MAClo. If more than 48 bits are used for the accumulation, the SumExt register is added to all further RAM extensions (here shown for only one) . MACS . MACRO argl,arg2 Signed MAC 16x16 MOV argl,&0132h Signed MPY is used MOV arg2,&0138h ADD &ResLo,MAClo ADDC &ResHi,MACmid Add MSBs to result ADDC &SumExt , MAChi Add SumExt to MSBs Add LSBs to result .ENDM Multiply and accumulate signed the contents of two tables MACS 2(R6),@RS+ CALL the MACS macro Accumulation is yet made Software Applications 5-9 5.1.2.1 Fast Signed Square Function For some applications, a fast signed square function is necessary (e.g. if the RMS value of an input signal needs to be calculated). Two different solutions are given: o o For 16-bit signed numbers without rounding For 14-bit signed numbers with rounding. This version is adapted to the output of the ADC of the MSP430C32x family. Both use table processing; an offset to a table containing the squared input numbers is built. The given cycles include the move of the operand into R5. Fast signed squaring for a 16 bit number. The upper 16 bits of the result are moved to RS. No rounding is used. 10-12 cycles L$l MOV.B DATA+1,R5 MSBs of number to RS TST.B RS Check sign of input number JGE L$l Positive sign INV.B RS Negative sign: INC.B RS Use absolute value RLA RS Number x 2 (word table address) MOV SQTAB(R5),RS MSBs 2 from table to RS h Squared value in. RS Squaring for a signed 14 bit value: Change the unsigned ADC value (0 to 3FFFh) to a signed value by the subtraction of the measured zero point of the system: MOV &ADAT,RS ADC result to.RS SUB VALO,RS Subtract measured O-point Fast signed squaring for a 14 bit number. The upper 16 bits of the result are added to a buffer SQSUM. Rounding is used. If registers are used for the sum: lS-17 cycles 5-10 RLA RS ADD IIBOh,R5 Round to high byte BIC 1I0FFh,RS Delete lower byte One bit more resolution L$l JGE L$l INV RS Absolute value of ADC result INC RS Complement + increment SWPB RS MSBs to LSBS RLA.B RS Number x 2 (word table address) ADD SQTAB(RS),SQSUM Add MSBs A 2 to SQSUM ADC SQSUM+2 Add carry Sign? Continue Table with squared values. Length may be adapted to the maximum possible input number. SQTAB . word ($-SQTAB) * ($-SQTAB)/4 o x 0 = 0 . word ($-SQTAB)*($-SQTAB)/4 1 x 1 1 . word ($-SQTAB) * ($-SQTAB)/4 2 x 2 4 .word ($-SQTAB) * ($-SQTAB)/4 07Fh x 07Fh . word ($-SQTAB) * ($-SQTAB)/4 OaOh x OaOh The errors for a single squaring are in the range of 1%. But, if rounding Is used and several squared inputs are summed-up, the resulting error gets much smaller. For example, if a sinusoidal input voltage is measured in distances of 15°, then an error of less than 0.24% results. If the previous method is used for the measurement of RMS values, then for a decision, it usually is not necessary to calculate the square root out of the accumulated squared inputs. It is much faster to use the accumulated value itself. 5.1.3 Unsigned Multiplication 8 x IJ.Bits The following subroutine performs an unsigned 8 x 8-bit multiplication (label MPYU8) or multiplication and accumulation (label MACU8). The multiplication subroutine clears the result register IRACL before the start. The MACU subroutine adds the result ofthe multiplication to the contents of the result register. The upper bytes of IROP1 and IROP2L must be zero when the subroutine is Software Applications 5-11 called. The MOV.B instruction used for the loading ensures these bits are cleared. The registers used are shown in the Figure 5-2: 0 15 00 RS 00 R4 00 RS " R7 Bit Test Reglater IRBT Multiplicand IROP1 Multiplier IROP2l Accumulated Result IRAel Figure 5-2. 8 x 8 Bit Multiplication - Register use EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES) without CALL: TASK MACU8 MPYU8 EXAMPLE ;------------------------------------------------------------MINIMUM 58 59 OOOh x OOOh OOOOOh MEDIUM 62 63 OA5h x 05Ah 03A02h MAXIMUM 66 67 OFFh x OFFh = OFE01h UNSIGNED BYTE MULTIPLY SUBROUTINE: IROP1 x IROP2L -> IRACL USED REGISTERS IROPl, IROP2L, lRACL, IRBT MPYU8 CLR IRACL o -> RESULT UNSIGNED BYTE MULTIPLY AND ACCUMULATE SUBROUTINE: (IROP1 x IROP2L) +IRACL -> IRACL MAcue MOV #l,IRBT BIT TEST REGISTER L$OO2 BIT IRBT,IROP1 TEST ACTUAL BIT IF 0: DO NOTHING L$Ol JZ L$Ol ADD IROP2L,IRACL IF 1: ADD MULTIPLIER TO RESULT RLA IROP2L MULTIPLIER x 2 RLA.B IRBT NEXT BIT TO TEST JNC L$OO2 IF BIT IN CARRY: FINISHED RET 5-12 If the hardware multiplier is implemented, the previous subroutines can be substituted by MACROs. For source and destination, all seven addressing modes are possible. If register indirect or register indirect with autoincrement addressing modes are used to address the result, a NOP is necessary after the MACRO call to allow the completion of the multiplication. If byte instructions are used for loading the multiplier registers, the high byte is cleared like a CPU register. Macro Definition for the unsigned multiplication 8 x 8 bits MPYU8 . MACRO argl,arg2 Unsigned MPY 8x8 MOV.B arg1,&0130h OOxx to 0130h MOV.B arg2,&0138h .ENDM OOyy to 0138h Result in ResLo. ResHi 0 Multiply the contents of two registers (lOW bytes) MPYU8 IROP1,IROP2L CALL the MPYU8 macro MOV &ResLo,R6 Fetch result (16 bits) Macro Definition for the unsigned multiplication and accumulation 8 x 8 bits MACU8 . MACRO arg1,arg2 Unsigned MAC 8x8 MOV.B arg1,&0134h OOxx MOV.B arg2,&0138h .ENDM OOyy Result in SumExtlResHilResLo Multiply and accumUlate the low bytes of two registers MACU8 5.1.4 IROP1,IROP2 CALL the MACU8 macro Signed Multiplication 8 x 8-Bits The following subroutine performs a signed 8 x 8-bit multiplication (label MPYS8) or multiplication and accumulation (label MACS8). The multiplication subroutine clears the result register IRACL before the start, the MACS8 sub. routine adds the result ofthe multiplication to the contents ofthe result register. Software Applications 5-13 The register usage is the same as with the unsigned 8 x 8 multiplication. Therefore, Figure 5-2 Is also valid. The part starting with label MACU8 is the same as used with the unsigned multiplication. EXECUTION TIMES FOR REGISTER CONTENTS (CYCLES) without CALL: TASK MACSB MPYSB EXAMPLE i------------------------------------------------------------MINIMUM 64 65 OOOh x OVOh - OOOOOh MEDIUM 75 76 OA5h x 05Ah = OE002h MAXIMUM B6 B7 OFFh x OFFh = OOOOlh SIGNED BYTE MULTIPLY SUBROUTINE: IROPI x IROP2L -> IRACL USED REGISTERS IROPl, IROP2L, IRACL, IRBT MPYSB CLR IRACL o -> RESULT SIGNED BYTE MULTIPLY AND ACCUMULATE SUBROUTINE: (IROPI x IROP2L) +IRACL -> IRACL MAcse L$lOl MULTIPLICAND NEGATIVE ? TST.B IROPI JGE L$lOl NO SWPB IROP2L YES, CORRECT RESULT SUB IROP2L, IRACL SWPB IROP2L RESTORE MULTIPLICATOR TST.B IROP2L MULTIPLICATOR NEGATIVE ? JGE MACUB SWPB IROPl SUB IROP1,IRACL SWPB IROPl YES, CORRECT RESULT THE REMAINING PART IS THE UNSIGNED MULTIPLICATION MACUB MOV #l,IRBT BIT TEST REGISTER L$002 BIT IRBT,IROPl TEST ACTUAL BIT 5-14 L$Ol JZ L$Ol ADD IROP2L,IRACL IF 0: DO NOTHING IF 1: ADD MULTIPLIER TO RESULT RLA IROP2L MULTIPLIER x 2 RLA.B IRBT NEXT BIT TO TEST JNC L$002 IF BIT IN CARRY: FINISHED RET If the hardware multiplier is implemented, the previous subroutines can be substituted by MACROs. For source and destination, all seven addressing modes are possible. If register indirect or register indirect with autoincrement addressing modes are used to address the result, a NOP is necessary after the MACRO call to allow the completion of the multiplication. if byte instructions are used for loading the multiplier registers, the high byte is cleared like a CPU register. Macro Definition for the signed multiplication 8 x 8 bits MPYS8 . MACRO argl,arg2 MOV.B argl,&0132h OOxx SXT &0132h Extend sign: OOxx or FFxx MOV.B arg2,&013Bh OOyy SXT &013Bh Extend sign: 09yy or FFyy .ENDM Signed MPY 8x8 Result in SumExtlResHilResLo Multiply the contents of two registers signed (low bytes) MPYS8 IROP1,IROP2 MOV &ResLo,R6 Fetch result (16 bits) MOV &ResHi,R7 Only sign: 0000 or FFFF CALL the MPYSB macro Macro Definition for the signed multiplication and accumulation 8 x 8 bits. The accumulation is made in the RAM: MACHi, MACmid and MAClo. If more than 48 bits are used for the accumulation, the SumExt register is added to all further RAM extensions MACS8 . MACRO arg1,arg2 Signed MAC 8x8 MOV.B argl,&0132h MPYS is used Software Applications 5-15 Extend sign: OOxx or FFxx SXT &0132h MOV.B arg2, &0138h OOyy SXT &0138h Extend sign ADD &ResLo,MAClo Accumulate LSBs 16 bits ADDC &Reslii,MACmid ADDC &SumExt, MAChi Add SumExt to MSBs .ENDM Multiply and accumulate signed the contents of two byte tables MACS8 2{R6),@RS+ CALL the MACS8 macro Accumulation is yet made 5.1.5 Unsigned Division 32116-Blts The subroutine performs an unsigned 32-bit by 16-bit division. If the result does not fit into 16 bits, the carry is then set after return. If a valid result is obtained, the carry is reset after a return. The. register usage is shown in Figure 5-3. The subroutine was developed by Mr. Leipold/L&G. IROP2L IROP2M Remelnder 15 Dividend 0 IROP1 Divisor IRACL Result IRBT Counter Figure 5-3. Unsigned Division - Register Use ; EXECUTION CYCLES FOR REGISTER CONTENTS (without CALL): ; DIVIDE CYCLES EXAMPLE ;------------------------------------------------------~-------------------------- 5-16 242 Oxxxxxxxxh OOOOOh - OFFFFh C = 1 237 03A763E02h OSASAh = OASASh C - 0 240 OFFFE0001h OFFFFh = OFFFFh C - 0 USED REGISTERS IROP1, IROP2L, IRACL, IRBT, IROP2M UNSIGNED DIVISION SUBROUTINE 32-BIT BY 16-BIT IROP2MIIROP2L IROP1 -> IRACL RETURN: CARRY 0: OK DIVIDE DIV1 DIV2 REMAINDER IN IROP2M CARRY - 1: QUOTIENT> 16 BITS CLR IRACL CLEAR RESULT MOV #17, IRBT INITIALIZE LOOP COUNTER CMF IROP1,IROP2M JLO DIV2 SUB IROP1, IROP2M RLC IRACL JC DIV4 Error: result> 16 bits DEC IRBT Decrement loop counter JZ DIV3 Is 0: terminate w/o error RLA IROP2L RLC IROP2M JNC DIV1 SUB IROP1,IROP2M SETC JMP DIV2 DIV3 CLRC No error, C DIV4 RET Error indication in C = 0 A 32-bit divided by 32-bit numbers (XDIV) is given in the square root section. 5.1.6 Signed Division 32116-Blts The subroutine performs a signed 32-bit by 16-bit division. If the result does not fit into 16 bits, the carry is then set after a return. If a valid result is obtained, the carry is reset after a return. The register IRACM contains the extended sign (OOOOh or OFFFFh) of the signed result in IRACL. The register usage is shown in the Figure 5-4: Software Applications 5-17 15 lSi IROP2M Remalncler lsi IRACM Dividend IROP2L 0 15 IROP1 Divisor IRACL Reeuh IRBT Counter Extended Sign Figure 5-4. Signed Division - Register Use ; EXECUTION CYCLES FOR REGISTER CONTENTS (without CALL): ;DIVIDE CYCLES EXAMPLE ;--------------------------------------------------------------------------------MINIMUM 15 Oxxxxxxxxh OOOOOh - Oyyyyh C - 1 268 OE01C3E02h 05A5Ah OA5A5h C 258 000000001h OFFFFh OFFFFh C = 0 o USED REGISTERS IROP1, IROP2L, IROP2M, IRACL, IRBT SIGNED DIVISION SUBROUTINE 32-BIT BY 16-BIT IROP2MIIROP2L IROP1 -> IRACL RETURN: CARRY 0: OK DIVS DIVS1 5-18 REMAINDER IN IROP2M CARRY = 1: QUOTIENT> 16 BITS CLR IRACM Sign of result TST IROP2M Check sign of dividend JGE DIVS1 INV IROP2M INV IROP2L Is neg.: I dividend I INC IROP2L ADC IROP2M INV IRACM Invert sign of result TST IROP1 Check sign of divisor. C = JEQ DIVSERR Divisor is 0': error. C 1 JGE DIVS2 Sign is neg.: I divisor I INV IROP1 1 DIVS2 INC IROPl INV IRACM Invert sign of result CALL #DIVIDE Call unsigned division JC DIVSERR C - 1: error TST IRACM Test sign of result JZ DIVS3 INV IRACL INC lRACL Is neg.: negate result DIVS3 CLRC No error occured: C - 0 DIVSERR RET Error: C - 1 5.1.7 Shift Routines The results of the previous subroutines (MPY, DIV) accumulated in IRACMI IRACL have to be adapted to different numbers of bits after the decimal point because they are too large to fit into 32 bits. The following subroutines can do this function. If other types of number shifting is necessary, the subroutines can be constructed as shown for the 6-bit shifts (subroutine SHFTRS6). No tests are made for overflow. Signed shift right subroutine for IRACM/IRACL Definitions see above SHFTRS6 CALL #SHFTRS3 Shift 6 bits right signed SHFTRS3 RRA IRACM Shift MSBs, bitO -> carry RRC IRACL Shift LSBs, carry -> bitlS SHFTRS2 RRA lRACM RRC IRACL SHFTRSI RRA IRACM RRC IRACL RET Unsigned shift right subroutine for IRACM/lRACL SHFTRU6 CALL SHFTRU3 CLRC #SHFTRU3 Shift 6 bits right unsigned Clear carry RRC IRACM Shift MSBs, bitO -> carry, 0 -> bit15 RRC IRACL Shift LSBs, carry -> bitlS Software Applications 5-19 SHFTRU2 CLRC SHFTRUl RRC lRACM RRC IRACL CLRC RRC lRACM RRC IRACL RET Signed/unsigned shift left subroutine for lRACM/lRACL SHFTL6 CALL #SHFTL3 Shift 6 bits left SHFTL3 RLA lRACL Shift LSBs, bitO -> carry RLC lRACM Shift MSBs, carry -> bit15 RLA lRACL SHFTL2 SHFTLl RLC lRACM RLA lRACL RLC lRACM RET 5.1.8 Square Root Routines The square root of a number is often needed in computations. Two different methods are given: . o o A very fast method for 32-bit integer numbers A normal method for 32-bit numbers that can have a fractional part 5. 1.B. 1 Square Root for 32·8It Integer Numbers The square root of a 30-bit integer number is calculated. The result contains 15 correct fractional bits. The subroutine uses the method known from the finding of a square root by hand. This method is much faster than the widely known NEWTONIAN method and only 720 cycles are needed. This subroutine was developed by Jllrg MOiler Software-Art GmbHlZurlch. The C program code needed is also shown: unsigned long y, h; int i; h = x; x = y 5-20 = 0; for (i = 0; i < 32; i++) II x «= 1; X ist eigentlich 2*x II 4*x + 1 X++i i f (y < x) x -= 2; else y -= x; x++; y «= 1; II «= 2 i f (h & Minus) y++; h «= 1; y «= 1; i f (h & Minus) y++; h «= 1; return Xi Square Root of a 32-bit number. x_MSB .equ R4 x_LSB .equ R5 y_MSB .equ R6 y_LSB .equ R7 h~SB .equ Ra h_LSB .equ R9 i .equ R10 Call: Result: 32-bit-nurnber Range for x: a <= in x~SB (16 bit integer part) x_LSB (16 bit fraction) x <= 40000000h Range for result: 0 <= SQRT <- aooO.OOOOh Max. Error: OOOO.0002h Calculation Time: 720 cycles (t = 720/MCLK) Software Applications 5-21 Examples: sqrt (10000000h) = 4000.0000h Sqrt sqrtlO sqrt (2710h) sqrt (2h) Mov x~SB,~SB Mov x_LSB,h_LSB Clr x~SB Clr xJ,SB Clr y~SB Clr y_LSB Mov #32,1 OOOO.0064h 000l.6a09h = 92681 SetC R1c Sqrtl2 = x «= 1; x++; x_LSB Rlc x~SB Sub x_LSB,y_LSB Subc x_MSB,y_MSB y.l -= x.l; Jhs Sqrtl2 Add x_LSB,y_LSB Addc x_MSB,y_MSB y.l += x.l; Sub #2,x_LSB x.l-=2;} Inc x_LSB' i f (y.l & Minus) x.l++; «= 2 Rla h_LSB R1c h_MSB Rlc y_LSB Rlc y_MSB Rla h_LSB R1c h~SB Rlc y_LSB Rlc y_MSB Dec i Jne SqrtlO «= 1 «= 1 Ret 5.1.8.2 Square Root for 32-Bit Numbers The following subroutine uses the Newtonian-approximation method for calculating the square root. The number of iterations depends on the length of the 5-22 operand. The subroutine was developed by A. MiihlhoferlTlO. The general formula is: !(A=x Xn+I=.!...(m-l)xXn+~) m I m X. - Where m =2 (square root) .[A = X x'+l=ix(x.+~) x. 2 xo='% To calculate AlXn a division is necessary. This is done with the subroutine XOIV. The result of this division has the same integer format as the divisor Xn. This makes an easy operation possible. Ah .EQU RB Al .EQU R9 ; Low word of A XNh .EQU RIO ; High word of result XNl .EQU Rll ;Low word of result ; High word of A Square Root The valid range for the operand is from OOOO.0002h to 7FFF.ffffh EXAMPLE: SQR(2)=1.6a09h SQR SQR...,l SQR(7fff.ffffh) B5.04f3h SQR(OOOO.0002h) O.016ah .EQU $ MOV Ah,XNh set XO to A/2 for the first MOV Al,XNl approximation RRA XNh XO=A/2 RRC XNl CALL #XDIV R12xR13=A/Xn ADD R13,XNl Xn+l=Xn+A/Xn ADDC R12,XNh Software Applications 5-23 SQR_3 RRA XNh RRC XNl Xn+l-l/2(Xn+A/Xn) CMF XNh,Rl2 is high word of Xn+l = Xn JNE SQR_l no, another approximation CMF XNl,Rl3 yes, is low word of Xn+l = Xn JNE SQR_l no, another approximation yes, result is XNh.XNl RET Extended unsigned division RBIR9 / RlOIR1l XDIV L$36l L$363 L$364 5-24 = .EQU $ PUSH R8 PUSH R9 R121Rl3, remainder is in Rl41Rl5 PUSH RlO PUSH Rll Save operands onto the stack MOV 4/48,R7 Counter=48 CLR RlS Clear remainder CLR Rl4 CLR Rl2 CLR Rl3 RLA R9 RLC R8 RLC RlS RLC Rl4 Clear result Shift one bit of R81R9 to R141RlS CMP RIO,Rl4 JLO L$364 No JNE L$363 Yes CMP Rll,RlS Rll-RlS JLO L$364 No SUB Rll,RlS Yes, subtract SUBC RlO,R14 RLC Rl3 RLC Rl2 Is subtraction necessary? Shift result to Rl21Rl3 DEC R7 Are 48 loops over ? JNZ L$361 No POP Rll POP RIO POP R9 POP RS Yes, restore operands RET 5.1.9 Signed and Unsigned 32-Bit Compares The following examples show optimized routines for the comparison of values longer than 16 bits. They can be enlarged to any length (Le., 48 bit, 64 bit etc.). Comparison for unsigned 32-bit numbers: RIIIRI2 with R131R14 L$I CMP Rll, R13 Compare MSBs JNE L$l MSBs are not equal CMP R12, R.14 Equality: Compare LSBs too JLO LO Jumps are used for MSBs and LSBs JEQ EQUAL R13IR14 > Rll1RI2 LO R131R14 < Rll1R12 EQUAL RI31 R14 Rlll R12 The approach shown can be adapted to any number length, only additional comparisons have to be added: Comparison for unsigned 4S-bit numbers: RIOIRIIIR12 with R13 I R14 IRIS L$l CMP RIO,R13 Compare MSBs JNE L$l MSBs are not equal CMP Rll,R14 Equality: Compare MSBs-l too JNE L$I MSBs-l are not equal CMP R12,R15 Equality: Compare LSBs too JLO LO Jumps are used for all words JEQ EQUAL R131R141R15 > RIOIRIIIR12 LO R131R141R15 < RIOIRIIIR12 EQUAL R131R141R15 RIOIRIIIR12 Software Applications 5-25 Comparison for signed 32-bit numbers: RllIRl2 with Rl31R14 CMP Rll,Rl3 Compare MSBs signed JLT LO JNE HI Rl3 < Rll Not LO, not EQUAL: only HI rests CMP Rl2,R14 Equality: Compare LSBs too JLO LO 'LSBS use unsigned jumps! JEQ EQUAL Not LO, not EQUAL: only HI rests HI Rl31Rl4 > RllIRl2 LO Rl31R14 < RIIIR12 EQUAL Rl31Rl4 = RIlIRl2 Comparison for signed 48-bit numbers: RlOIRllIRl2 with Rl3IR14IRl5 L$l CMP RIO,R13 JLT LO Compare MSBs signed JNE HI Not LO, not EQUAL: only HI rests CMP Rll,R14 Equality: Compare MSBs-l too JNE L$l CMP Rl2,Rl5 MSBs-l are not equal Equality: Compare LSBs too JLO LO Used for MSBs-l and LSBs JEQ EQUAL Not LO, not EQUAL: only HI rests Rl3IR14IRl5 > RlOIRllIR12 HI LO R131Rl41R15 < RlOIRllIR12 EQUAL R131R14IR15 = RI0lRllIR12 5.1.10 Random Number Generation The linear congruential method is used (Introduced by D. Lehmer in 1951). The advantages of this method are speed, code simplicity, and ease of use. However, if care is not taken in choosing the multiplier and increment values, the results can quickly degenerate. This algorithm produces 65,536 unique numbers with very good correlation. Therefore, the random numbers repeat in the same sequence every 65,536. Within this sequence, only the LSB exhibits Ii repeatable pattern every 16 calls. The linear congruential method has the following form: Rndnum n = (Rndnum n- 1 X MULT), + INC(modM) 5-26, Where: Rndnum n Rndnum n_1 MULT INC M Current random number Previous random number Multiplier (unique constant) Increment (unique constant) Modulus (word width of MSP430 = 16 bits = 64K) Many hours of research have been done to identify the optimal choices for the constants MULTand INC. The constant used in this implementation are based on this research. If changes are made to these numbers, extreme care must be taken to avoid degeneration. The following text is a more detailed look at the algorithm and the numbers used: o M: M is the modulus value and is typically defined by the word width of the processor. The linear congruential algorithm returns a random number between 0 and 65,536 and is NOT internally bounded. If the user requires a minimax limit, this must be coded externally to this routine. The result is not actually divided by 65,536. The result register is allowed to overflow, thus implementing the modulus. o SEED: The first random number in the sequence is called the seed value. This is an arbitrary constant between 0 and 64K. Zero can be used. This is OK if the code is allowed 3 calls to warm up before the numbers are considered valid. The number 21,845 was used in this implementation because it is 1/3 of the modulus (65,536). o MULT: Based on random number theory, this number should be chosen such that the last three digits are even-2-1 (such as xx821 , x421 , etc.). The number 31,821 was used in this implementation. o INC: In general, this constant can be any prime number related to M. Two values were actually tested in this implementation: 1 and 13,849. Research shows that INC should be chosen based on the following formula: Software Applications 5-27 (Using M=65,536 leads to INC=13,849) The following code describes the first equation. Three subroutines are used to generate random numbers. Furthermore, the initialization of corresponding constants and of a RAM-variable storing the random number is included. The symbol names of the 1st equation are strictly used in the code underneath. The first time, an initialization routine INIRndnum must be called. Then a subroutine Rndum 16 is called to calculate the random numbers as oiten as needed. The code necessary and the description of the subroutine MPYU can be found in Section 5.1.1, UnSigned Multiplication 16 x 16-blts. INITIALIZE CONSTANTS FOR RANDOM NUMBER GENERATION SEED .set 21845 Arbitrary seed value (65536/3) MULT .set 31821 Multiplier value (last 3 INC .set 13849 1 and 13849 have been tested HW~PY .set o 1: HW-MPYer on chip Digits are even-2-1) ALLOCATION RANDOM NUMBER IN RAM-ADDRESS 200h .bss Rndnum,2,0200h SUBROUTINE: INITIALIZE RANDOM NUMBER GENERATOR: Load the SEED value and produce the 1st random number INIRndnum .equ MOV $ Uses Rndnum16 #SEED,Rndnum Initialize generator SUBROUTINE: GENERATES NEXT RANDOM NUMBER 0: 169 cycles HW~PY = HW~PY - 1: Rndnum16 .equ .if 5-28 26 cycles $ HW~Y=O No MPYer MOV Rndnum,IROP2L Prepare. multiplication MOV #MULT, IROP1 Prepare multiplication CALL ADD #MPYU HNC,IRACL Call unsigned MPY (5.1.1) Add INC to low word of product Overwrite old random number with low word of new product MOV .else MPYU MOV ADD IRACL,Rndnum Rndnum, #MULT &ResLo, Rndnum #INC,Rndnum .endif RET Result to Rndnum and IRACL HW MPYer on chip Rndnum x MULT Low word of product Add INC to low word Random number in Rndnum EXAMPLE: Use of the Random Generator (1st call and succeeding calls). First call: produce the 1st random number CALL HNIRndum ; Initialize generator Second and all other calls to get the next random number CALL #Rndnum16 ; Next random number to register ; IRACL and location Rndnum Algorithm from TMS320DSP Designer's Notebook Number 43 Random Number Generation on a TMS320C5x. 7/94 5.1.11 Rules for the Integer Subroutines Despite the fact that the subroutines shown previously can only handle integer numbers, it is possible to use numbers with fractional parts. It is necessary only to define for each number where the virtual decimal point is located. Relatively simple rules define where the decimal point is located for the result. For calculations with the integer subroutines, it is almost impossible to remember where the virtual decimal point is located. It is good programming practice to indicate in the comment part -of the software listing where the decimal point is currently located. The indication can have the following form: N.M where N M Worst-case bit count of integer part (allows additional assessments) Number of bits after the virtual decimal point Software Applications 5-29 The rules for determining the location of the decimal point are simple: o Addition and subtraction: Positions after the decimal point have to be equal. The position is the same for the result. o Multiplication: Positions after the decimal point can be different. The two positions are added to get the result's position after the decimal point. o Division: Positions after the decimal point can be different. The two positions are subtracted to get the result's position. (Dividend - divisor) Table 5-1. Examples for the Virtual Decimal Point First Operand NNN.MMM NNN.M NNN.MM NNNN.MMMM NNN.M NNN.MM NNN.M NNNN.MMMMM Operation + x : + x : Second Operand NNNN.MMM NN.MMM NN.MM NN.MMM NNNN.M NN.MMM NN.M NN.M Result NNNN.MMM NNNNN.MMMM NNN.MM NN.M NNNN.M NNNNN.MMMMM NNN.M NN.MMMM If two numbers have to be divided and the result needs n digits after the deci- mal pOint, the dividend has to be loaded with the number shifted appropriately to the left and zeroes filled into the lower bits. The same procedure can be used if a smaller number is to be divided by a larger one. EXAMPLES for the division: Table 5-2. Rules for the Virtual Decimal Point First Operand Operation Second Operand Result (Shifted) NNNN.OOO NNNN.OOO NNNN.OOO O.MMMOOO 5-30 : : : : NN NN.M N.MM NN.M NN.MMM NN.MM NNN.M O.MMMMM EXAMPLE for a source using the number indication: MOV #01234h,IROP2L Constant 12.34h loaded 8.8 MOV R15,IROP1 Operand fetched 2.3 CALL #MPYS Signed MPY 10.11 CALL #SHFTRS3 Remove 3 fraction bits 10.8 ADD #00678h,IRACL Add Constant 6.78h 10.8 ADC lRACM Add carry 10.8 Software Applications 5-31 Table Processing 5.2 Table Processing One of the development targets of the MSP430 was the capability of processing tables because software can be written more legible and more functional when using tables. The addressing modes, the instruction set, and the word! byte structure make the MSP430 an excellent table processor. The arrangement of information in tables has several advantages: o .Good visibility o Simplifies changes: enlargements and deletions are made easily o Low software overhead: Short programs o High speed: Fastest way to access data Generally, two ways exist of arranging data in tables: o Data is arranged in blocks, each block containing the complete information of one item o Data is arranged in several tables, each table containing one or two kinds of information for all items. Max. Pressure MPY I EEPROM Max. Pressure Item 0 MelI. Pressure Hemn Block 0 Offset Max. Pressure MPY 1EEPROM Block 1 MPY EEPROM MPY EEPROM I Item 0 Offset Mex. Pressure MPY I EEPROM Hemn Offset Hem 0 Offset Hemn Block n Offset Block Arrangement Of Date Deta In Several Tebles Figure 5-5. Data Affangement in Tables EXAMPLE: A table arranged in blocks is shown. Some examples for random access are given. The addressed tables refer to Figure 5-6 ;Block Arrangement of data TABLE 5-32 . WORD 2095 Maximum pressure item 0 Table Processlnq TEEPR . BYTE 16 EEPROM start address TMPY .BYTE 3 Multiply constant TOFFS . WORD 014S6h Offset correction value TABN . WORD 3084 Maximum pressure item 1 . WORD 2010 . BYTE 37 Maximum pressure item N EEPROM start address . BYTE 3 Multiply constant . WORD 004S6h Offset correction value Access examples for the above block arrangement: RS points to the 1st word of a block (max. pressure) Examples how to access the other values are given: MOV @RS,R6 MOV.B TEEPR-TABLE(RS),R7 EEPROM start to R7 CMP.B TMPY-TABLE(RS),R8 Same constant as in R8? MOV &ADAT,R9 ADC result to R9 ADD TOFFS-TABLE(RS),R9 Correct ADC result ADD lFTABN-TABLE,RS Address.next item's block Copy max. pressure to R6 Copying of block arranged data to registers MOV @RS+,R6 MOV.B @RS+,R7 EEPROM start to R7 MOV.B @RS+,R8 MPY constant to R8 MOV @RS+,R9 Offset to R9 Copy max. pressure to R6 RS points to next item's block now EXAMPLE: A table arranged in several tables is shown. Some examples for random access. are given. The addressed tables refer to Figure 5-5 Arrangement of data in several tables TMAXPR . WORD 209S Maximum pressure item 0 Software Applications 5-33 Table Processing TEEMPY TOFFS WORD 3084 Maximum pressure item 1 . WORD 2010 Maximum pressure item N .BYTE 16,3 EEPROM start, MPY constant . BYTE 37,3 item 1 .BYTE 37,114 item N . WORD 014S6h Offset correction value . WORD 004S6h item N Access examples for the above arrangement: RS contains the item number x 2: (word offset) Examples with identical functions as for the block arrangement shown in the example before 5.2.1 MOV TMAXPR(RS),R6 Copy max. pressure to R6 MOV.B TEEMPY(RS),R7 EEPROM start to R7 CMP.B TMPY+1(RS),RS Same constant as in RS? MOV &ADAT,R9 ADC result to R9 ADD TOFFS(RS), R9 Correct ADC result INCD RS Address next item Two Dimensional Tables The output value of a function often depends on two (or more) input values. If there is no algorithm for such a function, then a two (or more) dimensional table is needed. Examples of such functions are: o The entropy of water depends on the inlet temperature and the outlet temperature. An approximation equation of the twelfth order is needed for this problem if no table is used. o The ignition angle of an Otto-motor depends on the throttle opening and the motor revolutions per minute. Figure 5-6 shows a function like the one described. The output value T depends on the input values X and Y. Table Processing T Figure 5-6. Two-Dimensional Function A table contains the output values T for all crossing points of X and Y that have distances of ~ and IlY respectively. For every point in between these table points, the output value can be calculated. Software Applications 5-35 Table Processing W - o - - - AX ---~ Figure 5-7. Algorithm for Two-Dimensional Tables The calculation formuias are: f(X, Yb) = X-~ - - - x (T10- TOO)+ Xa + 1-Xa Ll f(X, Yb+ 1) ;:: f(X, Y) = X-~ TOO = --;--X x (T10- TOO)+ TOO X-Xa - - x (T11- T01)+ T01 flX Y-Yb - - x (f(X, flY Yb+ 1)-(f(X, Yb»+ f(X, Yb) These formulas need division. There are two possible ways to avoid the division: o To choose the values for !J.X and flY in such a way that simple shifts can do the divisions (!J.X =0.25, 0.5, 1, 2, 4 etc.) o To use adapted output values T' within the table T'xy;:: Txy flXflY Table Processing This adaptation leads to: f(X, Yb) ~ = f(X, Yb+ 1) .1.Y f(X, Y) (X - Xa) x (T'10 - T'OO)+ T'OO = (X - Xa) = (Y _ Yb)X x (T'11 - f(X, Yb T' 01)+ T'01 + 1) _ f(X, Yb»)+ f(X, Yb) X A Y AY AY AY The output value f(X,Y)is now calculated with multiplications only. EXAMPLE: A 2-dimensional table is given . .1.X and .1.Yare chosen as multiples of 2. The integer subroutines are used for the calculations Note: The software shown is not a generic example. It is tailored to the input values given. If other .1.X and .1.Y values are used. the adaptation parts and masks have to be changed. ITEM Detta Input value lonnat Starting value X V 2 4 8.2 7.1 0 0 XO rasp. VO COMMENT AX and AV Bits before/alter decimal point End value 42 56 XM resp. YN Input value (RAM. reg) XiN YIN Assembler mnemonic Two dimensional table processing ; XIN .EQU R15 unsigned X value, register or RAM YIN .EQU R14 unsigned Y value, register or RAM XM .EQU 42 Number of X rows YN .EQU 56 Number of Y columns XCL .EQU 7 Mas"k for fraction and dX YCL .EQU 7 Mask for fraction and dY XAYB .EQU R13 Rel. address of (XA,YB), register ZCFLG .EQU 0 Flag: 0: 2-dim 1: 3-dimensional Address definitions for the 4 table points: Software Applications 5-37 TI!,bIe Processing TOO .EQU TABLE (XA,YB) TOI .EQU TABLE+2 (XA,YB+1) TABLE+2(XAYB) TIO .EQU TABLE+(YN*2) (XA+I,YB) TABLE+(YN*2) (XAYB) Tll .EQU TABLE+(YN*2)+2 (XA+1,YB+I) TABLE+(YM*2)+2(XAYB) TABLE (XAYB) Table for two dimensional processing. Contents are signed numbers. TABLE . WORD 0101Sh, ... 073A7h (XO,YO) (XO,Yl) ... (XO,YN) . WORD 02222h, ... OBE21h (Xl,YO) (XI,Yl) ... (X1,YN) . WORD OA730h, ... 06BD1h (XM,YO) (XM,Y1) ... (XM,YN) Table calculation software 2-dimensional. Approx. ,700 cycles Input value X in XIN, Input value Y in YIN Result T in lRACL, same format as TABLE contents Calculation of YB out of YIN. One less adaption due to word table. Relative address of (XO,YB) to lRACL TABCAL2 CLR I RACK 0 -> Hi result register MOV YIN,IRACL Y -> Lo result register RRA IRACL Shift out fraction part 7.0 RRA lRACL Adapt to dY = 4 6.0 BIC #l,IRACL Word address needed 7.1 Calculation of XA out of XIN. One less adapt ion due to word table. Relative address of' (XA,YB) to IRACL (TOO) 5-38 MOV XIN,IROPI X ->"Multiplicand B.2 RRA IROPI Shift out fraction part B.l RRA IROP1 Adapt to dX = 2 B.O BIC #I,IROP1 Word address needed MOV IIYN,IROP2L Max., Y (YN) to multipl. 5.0 Table Processing CALL tMACS ReI address (XA,YB) 13.0 MOV IRACL,XAYB to storage register 13.0 .IF ZCFLG If 3-dimensional calculation ADD OFFZC,XAYB Add offset for actual table .ENDIF ReI. address of ZC Calculation of f(X,YB) = (XIN-XA)/dX x (T10-TOO) + TOO MOV XIN,IROP1 build (XIN - XA) 8.2 AND tXCL,IROPl Fraction and dX rests 1.2 MOV T10(XAYB),IROP2L T10 -> IROP2L 16.0 SUB TOO(XAYB),IROP2L T10 - TOO 16.0 CALL #MPYS (XIN - XA)(T10 - TOO) 17.2 CALL #SHFTRS3 :dX, to integer 15.0 ADD TOO (XAYB) , IRACL (XIN-XA) (TlO-TOO)+TOO 15.0 PUSH IRACL Result on stack Calculation of f(X,YB+l) (XIN-XA)/dX x (T11-TOl) + T01 (XIN-XA) still in IROP1 MOV Tl1(XAYB),IROP2L TIl -> IROP2L SUB TOl(XAYB),IROP2L TIl - TOI 16.0 CALL #MPYS (XIN - XA)(TII - TOl) 17.2 CALL #SHFTRS3 :dX, to integer 15.0 ADD TOl(XAYB), IRACL (XIN-XA) (Tll-TOl)+TOl 16.0 15.0 Calculation of f(X,Y) = (YIN-YB)/dY' x (f(X,YB)-f(X,YB+l) + f(X,YB) MOV YIN, IROPI build (YIN - XB 7.1 AND tYCL,IROPl Fraction and dX rests 2.1 SUB @SP,IRACL f(X,YB+l)-f(X,YB) 16.0 MOV IRACL,IROP2L Result to multiplier CALL #MPYS (YIN-YB) (f .. -f .. ) 18.1 CALL #SHFTRS3 :dY, to integer 16.0 Software AppHcations 5-39 Table Processing @SP+,IRACL ADD RET ; (YIN-YB) (f .. -f .. )+f .. 15.0 ; Result T in lRACL 16.0 The table, used with the previous example uses unsigned values for X and Y (the upper left hand table of Figure 5-8 shows this). If X or Y or both are signed values, the structure of the table and its entry paint have to be changed. The following examples in Figure 5-8 show how to do that. YO YN .. _ _ _ _ _ _--1 XO Y-N-1 YO YN 1 - - -...... - - - - 1 XO '--_ _ _ _ _...... XM ....._ _....._ _ _,.,XM X Unsigned Y Unsigned Location Of Address TABLE • YO X Unsigned Y Signed YN YO Y-N-1 YN X-M-1 ..--------t XO ....._ _ _ _ _- - ' XM X-M-1 ------4 1 - - -.. ~ X Signed Y Unsigned ____ ~ ______ ~ X Signed Y Signed Figure 5-8. Table Configuration for Signed X and Y The previous tables are shown in assembler code: ; X unsigned, Y unsigned TABLE . WORD OlOlSh, ... 073A7h (XO ,YO) ... (XO, YN) • WORD 02222h, ... 08E2lh (Xl,YO) ... (Xl,YN) . WORD OA73h, ... 068Dlh (XM, YO) ... (XM, YN) X unsigned, Y signed 5-40 XO XM Table Processing TABLE . WORD 030l7h, ... 093A2h (XO,Y-N-l) ... (XO,Y-l) . WORD 02233h, ... 0872lh (XO,YO) ... (XO,YN) . WORD 030l7h, ... 093A2h (Xl,Y-N-l) ... (Xl,YN) . WORD OOl73h, ... 0785lh (XM,Y-N-l) ... (XM,YN) X signed, Y unsigned TABLE . WORD 030l7h, ... 093A2h (X-M-l,YO) ... (X-M-l,YN) . WORD 080l2h, ... OB3Clh (X-M,YO) ..... (X-M,YN) . WORD 040l9h, ... OD3A3h (X-l,YO) ... (X-l,YN) . WORD 02233h, ... 0872lh (XO,YO) .... (XO,YN) . WORD 030l7h, ... 093A2h (Xl,YO) .... (Xl,YN) . WORD OOl73h, ... 07851h (XM,YO) .... (XM,YN) X signed, Y signed TABLE . WORD 030l7h, ... 093A2h (X-M-l,Y-N-l) (X-M-l,YN) . WORD 08012h, ... OB3Clh (X-M,Y-N-l) ... (X-M,YN) . WORD 04019h, ... OD3A3h (X-l,Y-N-l) ... (X-l,YN) . WORD 02233h, ... 0872lh (XO,Y-N-l) .... (XO,Y-l) . WORD 02233h, ... 0872lh (XO,YO) ....... (XO,YN) . WORD 030l7h, ... 093A2h (Xl,Y-N-l) .... (Xl,YN) . WORD 00173h, ... 0785lh ; (XM, Y-N-l) .... (XM, YN) The entry label TABLE always points to the word or byte with the coordinates (XO,YO). 5.2.2 Three-Dimensional Tables If the output value T depends on three input variables X, Y and Z. a three dimensional table is necessary for the crossing pOints. Eight values TOOO to T111 are used for the calculation of the output value T. Software Applications 5-41 Table Pf0C6ss/ng The simplest way is to compute these figures is to calculate the output values for both two-dimensional tables f(X,Y,Zc) and f(X,Y,Zc+ 1) with the subroutine TABCAL2. The two results are used for the final calculation: = f(X, Y, Z) . Z_Zc x (f(X, Y, Zc + t) - (f(X, Y, Zc) )+ f(X, Y, Zc) ZC+t-ZC The following figure shows this method. The output values Txxx are calculated for Zc and for Zc+ 1. Out of these two output values, the final value fIX, Y,Z), is calculated. . .,. .1 0 . .,. . " fIX, V,Z) z-L.c----~Z--~ZC+1 Figure 5-9. Algorithm for a Three-Dimensional Table EXAMPLE: f1. three-dimensional table is given. AX and flY and AZ are chosen as multiples of 2. The integer subroutines are used for calculations. x y Z 2 4 AX,AY,/lZ. Input value fonnat 8.2 7.1 256 0 Starting value 0 42 XIN 0 56 YIN 0 214_1 XC, YO,ZO rrEM Delta End value Input value (RAM, register) XIN YIN 5-42 .EQU R15 .EQU R14 ZIN ·COMMENT Bits after decimal point XM,YN,ZP Assembler mnemonic unsigned X value, register or RAM unsigned Y value, register or RAM Table Processing ZIN .EQU R13 XM .EQU 42 unsigned Z value, register or RAM Number of X rows YN .EQU 56 Number of Y columns XCL .EQU 7 Mask for fraction and dX YCL .EQU 7 Mask for fraction and dY Mask for deltaZ ZCL .EQU OFFh XAYB .EQU R12 ReI. address of (XA,YB), register ZCFLG .EQU 1 Flag: 0: 2-dim. OFFZC .EQU Rll Relative offset to actual (XO,YO,ZC) 1: 3-dim. Table Three dimensional table TABL3D . WORD 01015h, ... 073A7h (XO,YO,ZO) ... (XO,YN,ZO) . WORD 02222h, ... 08E21h (XM,YO,ZO) ... (XM,YN,ZO) . WORD OA730h, ... 068D1h (XO,YO,Zl) ... (XO,YN,ZI) . WORD OlOA5h, ... 09BA7h (XM,YO,ZI) ... (XM,YN,ZI) . WORD 02BC2h, ... 08E4Ih (XO, YO, ZP) ... (XO, YN, ZP) . WORD OA980h, ... 023D1h ; (XM,YO,ZP) ... (XM,YN,ZP) Table calculation software 3-dimensional Input values: X in XIN, Y in YIN, Z in ZIN Result is located in IRACL, same format as TABLE content Calculation of ZC out of ZIN. One less adapt ion due to word table. TABCAL3 MOV ZIN,IROP1 Z -> Operand register SWPB IROPI Use only upper byte (dZ -256) MOV.B IROPI,IROPI Adapt to dZ = 256 14.0 6.0 Calculation of ,relative address of (XO,YO,ZC) to IRACL Corrected for word table Software Applications 5-43 Table Processing MOV #YN*2*XM,IROP2L CALL #MPYU Table length for dZ ReI address (XO,YO,ZC) 13.0 MOV lRACL,OFFZC to storage register 13.0 Calculation of f(X,Y,ZC):·The table block for ZC is used CALL #TABCAL2 f(X,Y,ZC) -> lRACL PUSH IRACL Save f(X,Y,ZC) 16.0 Calculation of f(X,Y,ZC+I): The table block for ZC+I is used ADD #YN*2*XM,OFFZC ReI. adress (XO,YO,ZC+1) CALL #TABCAL2 f(X,Y,ZC+1) -> lRACL 16.0 6.8 Calculation of f(X,Y,Z) MOV. ZIN,IROP1 build (YIN - XB AND nCL,IROP1 Fraction and dZ rests 0.8 SUB @SP,IRACL f(X,Y,ZC+l)-f(X,Y,ZC) 16.0 Result to multiplier MOV lRACL,IROP2L CALL #MPYS CALL #SHFTRS6 CALL #SHFTRS2 ADD @SP+,IRACL RET (ZIN-ZC) (f .. -f .. ) :dZ, to integer 16.8 16.2 16.0 (ZIN-ZC) (f. .-f .. )+f. . . Result in IRACL 15. ° Signal Averaging and Noise C~?c:"ation 5.3 Signal Averaging and Noise Cancellation If the measured signals contain noise, spikes, and other unwanted signal components, it may be necessary to average the ADC results. Six different methods are mentioned here: 1) Oversampling: Several measurements are added-up and the accumulated sum is used for the calculations. 2) Continuous Averaging: A circular buffer is used for the measured samples. With every new sample a new average value can be calculated. 3) Weighted summation: The old value and the new one are added together and divided by two afterwards. 4) Wave Digital Filtering: Complex filter algorithms, which need only small amounts of calculation power, are used for the signal conditioning. 5) AeJection of Extremes: the largest and the smallest samples are rejected from the measured values and the remaining samples are added-up and averaged. 6) Synchronization of the measurements to hum The advantages and disadvantages of the different methods are shown in the following sections. Oversampling 5.3.1 Oversampling is the simplest method for the averaging of measurement results. N samples are added-up and the accumulated sum is divided by N afterwards or is used as it is with the following algorithm steps. It is only necessary to remember that the accumulated value is N-times too large. For example, the following formula, used for a single measurement, needs to be modified when N samples are summed-up as shown: V normal = Slope x ADC + Offset ~ V oversample= L ( Slope x ADC + Offset) N EXAMPLE: N measurements have to be summed-up in SUM and SUM+2. The number N is defined in A6 SUMLO .EQU R4 LSBs of sum SUMHI .EQU R5 MSBs of sum Software Applications 5-45 S/g~1 Averaging and NOiS? Cancellation OVSLOP CLR SUMLO CLR SUMHI liip Init of registers MOV U6,R6 Sum-up 16 samples of the ADC CALL #MEASURE Result in ADAT ADD &ADAT,SUMLO LSD of accumulated sum ADC SUMBI MSD DEC R6 Decr. "N counter: 0 reached? JNZ OVSLOP Yes, 16 samples in SUMBIISUMLO o Advantages • o Simple programming Disadvantages • High current cons.umption due to number of ADC conversions • Low suppression of spikes etc. (by N) 5.3.2 Continuous Averaging A very simple and fast way for averaging digital signals is continuous averaging. A circular buffer is fed at one end with the newest sample and the oldest sample and is deleted at the other end (both items"share the same RAM location). To reduce the calculation time, the oldest sample is subtracted from the actual sum and the new sample is added to the sum. The actual sum (a 32-bit value containing N samples) is used by the background. For calculations, it is only necessary to remember that it contains the accumulated sum of N samples. The same rule is valid for oversampling. 5-46 Signal Averaging and Noise Cancellation The characteristic of this averaging is similar to a comb filter with relatively good suppression of frequencies that are integral multiples of the scanning frequency. The frequency behavior is shown in the following figure. 0.0625 0.125 0.25 0.5 ---+ Input Frequency Seen Frequency -10 40 1 Attenuation dB Figure 5-10. Frequency Response of the Continuous Averaging Filter o o Advantages • Low current consumption with only one measurement • Fast update of buffer • Good suppression of certain frequencies (multiples of scan frequency) • Low-pass filter characteristic Disadvantages • RAM allocation: N words are needed for the circular buffer EXAMPLE: An interrupt driven routine (e.g. from the ADC, which Is started by the basic timer) that updates a circular buffer with N items is shown. The actual sum CFSUM is calculated by subtracting of the oldest sample and adding of the newest one. CFSUM and CFSUM+2 contain the sum of the latest N samples. N .BQU 16 ; Circular buffer with N items .BSS CFSTRT,N*2 ; Address of 1st item .BSS CFSUM,4 Accumulated sum 32 bits Software Applications 5-47 CFHND .BSS CFPOI,2 Points to next PUSH RS Save RS MOV CFPOI,RS Actual address to RS CMP #CFSTRT+(N*2),RS Outside circ. buffer? JLO L$300 No MOV IICFSTRT,R5 Yes, reset pointer (= oldest) item The oldest item is subtracted from the sum. The newest item overwrites the oldest one and is added to the sum L$300 SUB @RS,CFSUM Subtract oldest item from CFSUM SBC CFSUM+2 MOV &ADAT,O(RS) Move actual item to buffer ADD @RS+,CFSUM Add latest ADC result to CFSUM ADC CFSUM+2 MOV RS,CFPOI Update pointer POP RS Restore RS RETI 5.3.3 Weighted Summation The weighted sum of the measurements before and the current measurement result are added and then divided by two. This gives every measurement result a certain weight. Table 5-3. Sample Weight MEASUREMENT TIME WEIGHT 10 0.5 0.25 0.125 0.0625 0.03125 2""2 .BSS SESUM,4 Summing-up buffer SESUM,2 N<-2 Sample count used -2 . ELSE .BSS 5-50 Signal Averaging and Noise Cancellation .ENDIF SEHND .BSS SEHI,2 .BSS SELO, 2 Largest ADC result Smallest ADC result .BSS SECNT,l Counter for N+2 CLR SESUM Initialize buffers .IF N>2 CLR SESUM+2 .ENDIF MOV.B #N+2,SECNT Sample count +2 to counter MOV #OFFFFh,SELO ADCmax -> SELO CLR SEHI ADCrnin -> SEHI N+2 measurements are made and summed-up in SESUM SELOOP CALL #MEASURE ADC result to &ADAT MOV &ADAT,R5 Copy ADC result to R5 ADD R5,SESUM . IF N>2 ADC SESUM+2 Use 2nd sum buffer if N>2 .ENDIF L$l L$2 CMP R5,SEHI JHS L$l No MOV R5,SEHI Yes, actualize SEHI CMP R5,SELO Result < SELO? JLO L$2 No MOV R5,SELO Result > SEHI? DEC.B SECNT Counter - 1 JNZ SELOOP N+2 not yet reached N+2 measurements are made, extremes are subtracted now from summed-up result. Return with N-times value in SESUM SUB SELO,SESUM Subtract lowest result .IF N>2 Necessary if N>2 SBC SESUM+2 Software Applications 5-51 Signal Averaping and Noise Cancellation .ENDIF SUB SEHI,SESUM Subtract highest result . IF N>2 Necessary if N>2 SBC SESUM+2 .ENDIF RET 5.3.6 Synchronization of the Measurement to Hum If hum plays a role during measurements then a synchronization to the ac frequency can help to overcome this problem. Figure 5-11 shows the influence of the ac voltage during the measurement of a single sensor. The necessary number of measurements (here 10 are needed) is split into two equal parts, the second part is measured after exactly one half of the period Tac of the ac frequency. The hum introduced to the two parts is equal but has different signs. Therefore the accumulated influence (the sum) is nearly zero. i ACVoltage V1 -V1 Figure 5-11. Reduction of Hum by Synchronizing to the AC Frequency. Single Measurement If the basic timer is used forthe timing then the following numbers of basic timer interrupts can be used. 5-52 Signal Averaging and Noise Cancellation Table 5-4. Basic Timer Frequencies for Hum Suppression AC Frequency fac Basic Timer Frequency fBT Number of BT lnterrupts k 50Hz 4096Hz 60Hz 2048Hz 41 17 Time Error 8t Residual Error er mu mex. 0.097% 0.61% -0.39% -2.45% The formulas to get the above errors are: e, = (TBT X2k-l)X100 TAc er = sin( TBT X2kX21t)X1OO TAc where: at er TBT Tac k Maximum time error due to fixed basic timer frequency (in %) Maximum remaining Influence of the hum (in %) compared to a measurement without hum cancellation Period of basic timer frequency (1lfBT) Period of ac (1lfaC> Number of basic timer interrupts to reach Tad2 respective of Tac If difference measurements are used, the two measurements to be subtracted should be made with a delay of exactly one ac period. Both measurements have the same influence from the hum and the result, the difference of both measurements, does not show the error. This measurement method is used with heat meters, where the temperature difference of the water inlet and the water outlet is used for calculations. t ACVoltage V1 Figure5-12. Reduction of Hum by Synchronizing to the AC Frequency. Differential Measurement Software Applications 5-53 Signal Averaginlj ,and Noise Cancellatlo:' Ifthe basic timer is used for the timing then the following numbers of basic timer interrupts can be used. Table 5-5. Basic Timer Frequencies for Hum Suppression AC Frequency fac Time "rror 8t max. Baale Timer Frequency Number of Interrupts fBT . k . Residual Error et mex. 50Hz 2048Hz 41 0.097% 0.61% 60Hz 1024Hz 17 -0.39% -2.45% The formulas to get the previous results are: TBr ) xJOO et = ( --xk-J TAc er = sin( TBr TAC X k x 21t) x ZOO The software needed for the modification of the Basic Timer frequency without the loss of the exact time base is shown in Section 6.1.1, Change of the Basic Timer Frequency. 5-54 Real-Time Applications 5.4 Real-Time Applications Real-time applications for microprocessors are defined often as follows: o The controlling processor is able, under worst case conditions, to finish the necessary control algorithms before the next sample of the control input arrives. The architecture of the MSP430 is ideally suited for real time applications due to its system clock generation. The system clock MCLK of the CPU is not generated by a second crystal, which needs a lot of time until it is oscillating with the nominalfrequency. But, by the multiplication ofthe frequency ofthe 32-kHz crystal that is oscillating continuously. 5.4.1 Active Mode The active mode shows the fastest response to interrupts because all of the internal clocks are operating at their nominal frequencies. The active mode is recommended when the speed of the MSP430 is the critical factor of an application. 5.4.2 Normal Mode Is Low-Power Mode 3 (LPM3) This mode is used for battery-driven systems where the power consumption plays an overwhelming role. Battery lifetimes over ten years are only possible when the CPU is switched off whenever its processing capability is not needed. Despite the switched-off CPU, the MSP430 is at the start address of the interrupt handler within eight MCLK cycles; the system clock oscillator is then working at the correct frequency. This means true real-time capability, no delay due to the slow coming-up of the main oscillator crystal (up to 400 ms) is slowing down the system behavior. See Section 6.5, The System Clock Generator, for the details of the programming. 5.4.3 Normal Mode is Low-Power Mode 4 (LPM4) The low power mode 4 is used if there are relatively long time elapses between two interrupt events. The power consumption goes below 0.1 mA if this mode is used All oscillators are switched off and only the RAM and the interrupt hardware are powered. Despite this inactivity the MSP430 CPU is at the start of the interrupt handler within eight cycles of the programmed DCC tap. See Section 6.5, The System Clock Generatorfor the details of the speed-up of the CPU. Software Applications 5-55 Real-Time Applications 5.4.4 Recommendations for Real-Time Applications o Switch on the GIE bit (SR.3) as soon as possible. Within the interrupt handlers, only the tasks that do not allow interruption should be completed first. This allows nested interrupts and avoids the blocking of other interrupts. o Interrupt handlers (foreground) should be as short as possible. All calculations should be made in the background part of the program. The communication between these two software parts is made by status bytes. See Section 9.2.5, Flag Replacement by Status Usage. o o Use status bytes and calculated branches. o 5-56 The interrupt capability of the 1/0 ports makes input polling superfluous. Any change of an input is seen immediately. Use of the ports this way is recommended. Disabling and enabling of the peripheral interrupts during the software run is not recommended. Additional interrupt requests can result from these manipulations. The use of status bytes is recommended instead. They inform the software if an interrupt is valid or not. If not, it is neglected. General-Purpose Subroutines 5.5 General-Purpose Subroutines The following, tested software examples can be of help during the software development phase. The examples can not fit into any application, but they can be modified easily to the user's needs. 5.5.1 Initialization For the first power-on, it is necessary to clear the internal RAM to get a defined basis. If the MSP430 is battery powered and contains calibration factors or other important data in its RAM, it is necessary to distinguish between a cold start and a warm start. The reason for this is the possibility of initializations caused by electromagnetic interference (EM I). If such an erroneous initialization is not checked for legality, EMI influence could destroy the RAM content by clearing the RAM with the initialization software routine. Testing can be done by comparing RAM bytes with known content to their nominal value. These RAM bytes could be identification codes or non-critical test pattems (e.g. A5h, FOh). If the tested RAM locations contain the correct pattern, a spurious signal caused the initialization and the normal program can continue. If the tested RAM bytes differ from the nominal value, the RAM content is destroyed (e.g. by a power loss) and the initialization routine is invoked. The RAM is cleared and the peripherals are initialized. The cold start software contains the waiting loop for the DCO, which is needed to set it to the correct frequency. See Section 6.5, The System Clock Generator, and Section 6.6, The RESET Function. Initialization part: Check if Cold Start or Warm Start: RAM location 0200h decides kind of initialization: Cold Start: content differs from OASFOh Warm Start: content is OASFOh INIT CMP #OASFOh,&0200h Test content of &200h JEQ EMIINI Correct content: No reset Control RAM content differs from OASFO: RAM needs to be cleared, peripherals needs to be initialized MOV #0300h,SP Init. Stack Pointer CALL #RAMCLR Clear complete RAM MOV #OASFOh,&0200h Insert test word Software ApplicationS 5-57 System frequency MCLK is .set to 2.048MHz MOV.B MOV.B #64-1,&SCFQCTL iFN_2,&SCFIO 64 x 32kHz - 2.048MHz DCa current for 2MHz Waiting loop for the DCO of the FLL to settle: 130ms L$1 CLR INC RS RS 3 x 6SS36us JNZ L$1 186ms EMI caused initialization: Periphery needs to be initialized: Interrupts need to be enabled again EMINI 5.5.2 RAM clearing Routine The RAM is cleared starting at label RAMSTRT up to label RAM END (inclusive). Definitions for the RAM block (depends on MSP430 type) RAMSTRT .EQU 0200h ; Start of RAM RAMEND .EQU 02FEh ; Last RAM address (return address) ; Subroutine for the clearing of the RAM block RAMCLR CLR RS Prepare index register RCL CLR.B RAMSTRT(RS) 1st RAM address INC RS Next address CMF #RAMEND-RAMSTRT+1,RS RAM cleared? JLO RET 5.5.3 RCL No, once more Yes, return Binary to BCD Conversion The conversion of binary to BCD and vice versa is normally a time consuming task. Five divisions by ten are necessary to convert a 16-bit binary number to BCD. The DADO instruction reduces this to a loop with five instructions. 5-58 Gener~/-Purpose Subro'!ines THE BINARY NUMBER IN R12 IS CONVERTED TO A 5-DIGIT BCD NUMBER CONTAINED IN R14 AND R13: R141R13 BINDEC L$1 MOV U6,R15 LOOP COUNTER CLR R14 o -> RESULT MSD CLR R13 o -> RESULT LSD RLA R12 Binary MSB to carry RESULT x2 LSD DADD R13,R13 DADD R14,R14 DEC R15 JNZ L$1 RET MSD THROUGH? ; YES, RESULT IN R141R13 The previous subroutine can be enlarged to any length ofthe binary partsimply by the adding of registers for the storage of the BCD number (a binary number with n bits needs approximately 1.2 x n bits for BCD format). If numbers containing fractions have to be converted to BCD, the following algorithm can be used: 1) Multiply the binary number as often with 5 as there are fractional bits. For example if the number looks like MMM.NN, then multiply it with 25. Ensure that no overflow will take place. 2) Convert the result of step 1 to BCD with the (eventually enlarged) subroutine BIN DEC. The BCD result is a number with the same number of fractional digits as the binary number has fractional bits. EXAMPLE: The hexadecimal number OA8Bh has the binary formal MMM.NNN. The decimal value is therefore 337,375. The steps to get the BCD number are: 3) OA8Bh is to be multiplied by 53 or 12510 due to its 3 fractional bits. OA8Bh x 12510 ~0525DFh 4) 0525DFh has the decimal equivalent 337,375. The correct BCD number with 3 fractional digits. To convert the previous example, the basic subroutine BINDEC needs to be enlarged. Two binary registers are necessary to hold the input number. THE BINARY NUMBER IN R121R11 IS CONVERTED TO AN B-DIGIT BCD NUMBER CONTAINED IN R14 AND R13: R141R13 Max. hex number in R121R11: 05F5EOFFh (999999999) Software Applications 5-59 ~neraI-Putp088 Subroutines BINDEC L$l MOV #32,R15 LOOP COUNTER CLR R14 0 -> RESULT MSD CLR R13 0 -> RESULT LSD RLA Rll MSB of LSBs to carry RLC R12 Binary MSB to carry DADD R13,R13 RESULT x2 LSD DADD R14,R14 DEC R15 JNZ L$l RET 5.5.4 MSD THROUGH? YES, RESULT IN R141R13 BCD to Binary This subroutine converts a packed 16-bit BCD word to a 16-bit binary word by multiplying each digit with its decimal value (100,10 1, ...). To reduce code length, the HORNER scheme is used as follows: R5 = XO+1O(Xl+10(X2+lOX3) The packed BCD number contained in R4 is converted to a binary number contained in R5 BCDBIN SHFT4 5-60 MOV #4,R8 CLR R5 CLR R6 RLA R4 SHIFT LEFT DIGIT INTO R6 RLC R6 THROUGH CARRY RLA R4 RLC R6 RLA R4 RLC R6 RLA R4 RLC R6 ADD R6,R5 LOOP COUNTER ( 4 DIGITS ) CLR R6 DEC R8 THROUGH ? JZ END YES MPYlO END 5.5.5 RLA RS NO, MULTIPLICATION WITH 10 MOV RS,R7 DOUBLED VALUE RLA RS RLA RS ADD R7,RS JMP SHFT4 VALUE X 8 NEXT DIGIT RET RESULT IS IN RS Keyboard Scan A lot of possibilities exist for the scanning of a keyboard, which also includes jumpers and digital input signals. If more input signals exist than free inputs, scanning is necessary. The scanning outputs can be I/O-ports and unused segment outputs, On. The scanning input can be I/O ports and analog inputs, An, switched to the function of digital inputs, If I/O ports are used for inputs, wake-up by input changes is possible. The select line(s) of the interesting inputs (keys, gates etc.) are set high and the interrupt(s) are enabled for the desired signal edges. If one of the desired input signal changes occurs, an interrupt is given and wake-up takes place. Figure 5-13 shows a keyboard with 16 keys. 32kHz dD~' LCD COM SEL -v' """" Ox/PO•• :: :: MSP430 OyIPD.b OzlPO.c OkIPO.d An/PO.w Am/PO.X Ao/PO.y Ap/PO.z 3'f561B _ _ 1!!i3 ... ri+- 0= 0 0 0 0 0 0 0 0 .. 0 0 0 0 0 0 Figure 5-13. Keyboard Connection to MSP430 Figure 5-14 shows some possibilities for connecting external signals to the MSP430: .Software Applications 5-61 General-Purpose SubroutInes o The first row contains keys. The decoupling diode in the row selection line prevents a pressed key from shorten other signals. If more than one key can be activated simultaneously, then all keys need to have a decoupling diode. o The second row contains diodes. This is a simple way to identify the version used to a system. o The third row selects digital signals coming from peripherals with outputs that can be switched to high-Impedance mode. o The fourth row uses an analog switch to connect digital signals to the MSP430. The output of a CMOS gate and the output of a comparator are shown. The rows containing keys need to be debounced. If a change is seen at these inputs, the information is read in and stored. A second read is made after 10 ms to 100 ms, and the Information read is compared to the first one. If both reads are equal, the information is used. Otherwise, the procedure is repeated. The basic timer can be used for this purpose. LCD 3'i561B MSP430 --~ XC AnlPO.w AmlPO.x AOIPO.'I AplPO.z X # X # X # X # Figure 5-14. Connection of Different Input Signals 5-62 4018 1B 1A 2B 2A 3B 3A 4B 4A General-Purpose S~b~outines 5.5.6 Temperature Calculations for Sensors Several sensors can be connected to the MSP430. Chapter 2, The Analog-toDigital Converters, describes the different possible ways of doing this. Independent of the ADC or sensor type used, a binary number N is finally delivered from the ADC that represents the measured value K: K = f(N) where: K N Measured value (temperature, pressure etc.) Result of ADC The function f(N) is normally non-linear for sensors, and, therefore, a calculation is needed to get the measured value K. The linearization of sensors by resistors is described in Section 4.7.1, Sensor Connection and Linearization. Two methods of how to represent the function, f(N), are described: o o 5.5.6.1 Table processing Algorithms (linear, quadratic, cubiC or hyperbolic equations) Table Processing for Sensor Calculations The ADC measurement range used is divided into parts, each of them having a length of 2M bits. For any multiple of 2M the output value K is calculated and stored In a one-dimensional table. This table is used for linear interpolation to get the values for ADC results between two table values. Figure 5-15 shows such a non-linear sensor characteristiC. o I aN J Nm ADCValueN Figure ~ 15. Nonlinear Function K = f(N) Soffware Applications 5-63 General-Purpose Subroutines Steps for the development of a sensor table: 1) Definition of the external circuitry used at the ADC inputs (see Chapter 2, The Analog-to-Digital Converters) 2) Definition of the output format of the table contents (bits after decimal pOint, M.N) 3) Calculation of the voltage at the analog input Ax for equally spaced (aN) ADC values n 4) Calculation of the sensor resistances for the previous calculated analog input voltages 5) Calculation of the input values K (temperature, pressure etc.) that cause these sensor resistances 6) Insertion of the calculated input values K in the format defined with 2. into the table EXAMPLE: A sensor characteristic is described In a table TABLE. The ADC results are divided in distances Llli = 128 starting at value NO =256. The output value K is content of this table. The ADC result is corrected with offset and slope coming from the calibration procedure. DN .BSS OFFSET,2 .BSS SLOPE,2 Slope from calibration .EQU 128 Delta N Offset from calibration 10.0 1.10 Table contains signed values. The decimal point may be anywhere TABLE . WORD 02345h, ... ,00F3h ; KO, Kl, ... KM TABCALI MOV &ADAT,IROP1 ADC result N to IROP1 14.0 ADD OFFSET,IROP1 Correct offset 10.0 MOV SLOPE,IROP2L Slope 1.10 CALL #MPYS (ADC+OFFSET)xSLOPE 15.10 15.0 Corrected ADC value in IRACMllRACL. CALL #SHFTLS6 Result to lRACM MOV lRACM,XIN Copy it General-Purpose Subrou,tines_ =------~-----~=~~~------~----~.--. Calculation of NA address. One less adaptation due to word table (2 bytes/item). ; K MOV XIN,IROP1 N -> Multiplicand SWPB !ROP1 Adapt to deltaN BIC.B #1, IROP1 Even word address needed SUB #2,IROP1 Adapt to NO MOV TABLE(IROP1),R15 KA from table MOV TABLE+2(IROP1),R14 KA+l from table = = 128 15.0 14.0 8.0 256 (2 x deltaN) «XIN-KA)/deltaN) x (KA+1 - KA) + KA SUB R15,XIN XIN - KA MOV R14,IROP2L KA+1 SUB R15,IROP2L KA+1 - KA) MOV XIN,IROP1 XIN - KA CALL #MPYS (XIN CALL #SHFTRS6 /deltaN CALL #SHFTRS1 del taN ADD R15, IRACL + KA, result in IRACL ~ KA) x (KA+1 - KA) = 2~7 RET 5.5.6.2 Algorithms for Sensor Calculations If the sensor characteristic can be described by a function, K = f(N), then no table processing is necessary. The value K can be calculated out of the ADC result N. The coefficients an and bn can be found with PC computer software (e.g. MATH CAD) , with formulas by hand, or by the MSP430 itself. Thesecategories are for example: Linear Equation K alX N +ao Quadratic Equation Software Applications 5-65 GenefB;I-Purpose SiJbroutines Cubic Equation Root Equation K = oo±,JbIXN +bo Hyperbolic Equation K bI --+00 N+bo Steps for the development of a sensor algorithm: 1) Definition of the hardware circuitry used at the ADC inputs (See Chapter 2, The ADC, for the different possibilities) 2) Definition of the format of the algorithm (floating point: 2- or 3-word package, integer software: bits after decimal point M.N) 3) Definition of a value for K to be measured (temperature, pressure etc.) 4) Calculation of the nominal sensor resistance for the previous chosen valueofK 5) Calculation of the voltage at the analog input Ax for this sensor resistance (See Chapter 2, The ADC, for the formulas used with the different circuits) 6) Calculation of the ADC result N for this input voltage at analog input Ax 7) Repetition of steps 3 to 6 depending on the algorithm used: twice for linear equations, three times for quadratic, hyperbolic and root equations, four times for cubic equations. 8) Decision of the sensor characteristic: look for best suited equation. 9) Calculation of the coefficients an and bn out of the calculated pairs of values Kn and the ADC result Nn. See Section 5.5.6.3, CoefficientCalculation for the Equations. EXAMPLE: A quadratic behavior is given for a sensor characteristic: K = Cl2xN 2 +aIxN+oo with N representing the ADC result. The corrected ADC result (see the previous text) is stored In XIN. The three terms are stored in the ROM locations· A2, A1 and AO. 5-66 General-Purpose Subroutines A2 . WORD 07FE3h Quadratic term +-0.14 Al . WORD 00346h Linear term +-0.14 AO . WORD 01234h Constant term +-15.0 QUADR MOV XIN,IROP1 Corrected ADC result Factor A2 MOV A2,IROP2L CALL #MPY ADD Al,IRACL ADC IRACM ; 14 .0 +-0.14 14.14 XIN x A2 (XIN x A2) + Al +-0.14 ; Carry to HI reg ; To IRACM 14.1 (XIN x A2) + Al -> IROP2L 14.1 CALL #SHFTL3 MOV IRACM,IROP2L CALL #MPYS (XIN x A2) + AI') x XIN 28.1 CALL #SHFTL2 Result to IRACM 15.0 ADD AO,IRACM Add AO 15.0 The signed 16-bit result is located in IRACM. RET The Horner-scheme used above can be expanded to any level. It is only necessary to shift the multiplication results to the right to ensure that the numbers always fit into the 32-bit result buffer IRACM and IRACL The terms A2, A1, AO can also be located in RAM. If lots of calculations need to be done, then the use of the floating point package should be considered. See Section 5.6, The Floating Point Package, for details. 5.5.6.3 Coefficient Calculation for the Equations With two pairs (linear equation), three pairs (quadratic, hyperbolic and root equations), or four pairs (cubic equations) of Kn and Nn, the coefficients an and bn can be calculated. The formulas are shown in the following. where: Kn Calculation result for the ADC result Nn (e.g. temperature, pressure) Nn Input value for the calculation e.g. ADC result an Coefficient for the Nn value of the polynoms bn Coefficients for the hyperbolic and root equations Software Applications 5-67 General-Purpose Subroutines Linear equation: K alxN+ao ao KIXN2-K2X NI N2-NI Quadratic Equation: (K2 -K1)-al x(N2-N1) N;-Nf = al ao (K2 -K1)X(N; -N;)-(K3-K2)X(N; -Nf) (N2-N1)X (N; -N;)=(N3-N2)X (N; -Nf) Cubic Equation: The equations forthe four coefficients an are too complex. Shift the calculation task to the calibration PC and use MATHCAD or something similar to it. Root Equation: (N2 -N1)X(K; -Kf}-(N3 -NI)X(K; -Kf) ao = O.5x (N2-NI)X(K3 -K1}-(N3 -N1)X(K2-K1) 5-66 General-Purpose Subroutines Hyperbolic Equation: bi --+ao N+bo K (N j XK3 -NIKt)X (N2 -NI )-(N2 X K2 -NI XKJ)X(N j -NI ) bo (N j -NJ )X(K2 -KJ )-(N2 -NJ)X(K j -KJ ) (KJ-ao) x (NJ + bo) ao = (Nj XK3 -NJKt)+boX(Kj -KJ ) Nj-N J EXAMPLE: the sensor used has a quadratic characteristic R = d2XK2 + d1 xK + do. This means, the value K is described best by the root equation (inverse to the quadratic characteristic of the sensor): K = ao±.JblxN+bo where the sensor resistance R is replaced by the ADC result N. During the calibration with the values for Kn 0, 200, and 400, the following ADC Results, Nn, were measured: ADCValueN n Calc.Value Kn ('C, hP, VI K1 0 N1 K2 200 N2 4196 4430 K3 400 N3 4652 With the previous numbers the coefficients ao' bo and b1 can be calculated: ao 0.5 X (4430-4196)x (400 2 _0 2}-(4652-4196)X (200 2 _0 2) (4430-4196)x (400-0)-(4652-4196)x (200-0) (200 2 - 0 2}- 2 x 4000 x (200 - 0) 4430-4196 = 4000 -6666.6667 bo = (0-4000)2 - (-6666.6667) x 4196 = 43.97371E6 With the above calculated coefficients, the negative root value is to be used: K = ao-.JbJxN +bo Software Applications 5-69 _G~neraJ-Purpose Subroutines 5.5.7 Data Security Applications If consumption data is transmitted via telephone lines or sent by RF then it is normally necessary to encrypt this data to make it completely unreadable. For these purposes the DES (Data Encryption Standard) is used more and more, and is becoming the standard in Europe also. The next ~o sections show how to implement the algorithms of this standard and how the encrypted data can be sent by the MSP430. 5.5.7.1 Data Encryption Standard (DES) Routines The DES works on blocks of 64 bits. These blocks are modified in several steps and the output is also a block with 64 totally-scrambled bits. It is not the intention of this section to show the complete DES algorithm. Instead, a subroutine is shown that is able to do all of the necessary permutations In a very short time. The subroutine mentioned can do the following pennutations (the tables mentioned refer to the booklet Data Encryption Algorithm from ANSI): o o o o o Initial Permutation: 64-bits plain text to 64-bit encrypted text via table IP 32-bit to 48-bit permutation via table E 48-bit to 32-bit permutation via tables S1 to S8 32-bit to 32-bit permutation via table P Inverse initial Permutation: 64-bits to 64-bit via table IP-1 The permutation subroutine is written In a code and time optimized manner to get the highest data throughput with the lowest ROM space requirements. For each kind of permutation a description table is necessary that contains the following information for every bit to be permuted: 5 7 I I Rep. Bit EOT Where: Rep. Bit EOT 5-70 3 o 2 +POSIUO~ Repetition Bit: The actual bit is contained twice in the output table. The next byte (with Rep. =0) contains the address for the second insertion. This bit is only used during the 32-bit to 48-bit permutation End of Table Bit: This bit is set in the last byte of a permutation table General-Purpose Subroutines Byte Index The byte address 0 to 7 inside the output block Bit Position The bit address 0 to 7 inside the output byte The following figure shows the permutation of bit i. The description table contains at address i the information: Repetition Bit =0: The bit i is to be inserted into the output table only once EOT = 0 Bit i is not the last bit in the description table Byte Index =3: The relative byte address inside the output table is 3 (PTOUT+3) Bit Position =5: The bit position inside the output byte is 5 (020h) Bit Position 7 Bit Address 5 III 0101 3 I 5 0 0 11 3 III 641 64 Description Teble Input Table Output Teble 7 Byte Index Figure 5-16. DES Encryption Subroutine Note: The bit numbers used in the DES specification range from 1 to 64. The MSP430 subroutines use addresses from 0 to 63 due to the computer architecture. The software subroutines for the previously described permutations follow. The subroutines PERMUT and PERM_BIT are used for all necessary permutations (see previous). The subroutines shown have the following needs: o The initialization of the subroutine PERMUT decides which permutation takes place. The address of the actual description table is written to pointer register PTPOI. o Permutations are always made from table PTIN (input table) to table PTOUT (output table). o Only 1s are processed during the permutation. This saves 50% of proceSSing time. The output buffer is therefore cleared initially by the PERMUT subroutine. Software Applications 5-71 General-Purpose Subroutines o The output buffer must start with an even address (word instructions are used for clearing) Main loop for a permutation run, Tables with up to 6,4 bits are permuted to other tables, Definitions for the permutation software PTPOI ,EOO R6 Pointer to description table PTBYTP ,EOO R7 Byte index input table Bit counter inside input byte ,EOO Ra ,BSS PTIN,a Input table 64 bits ,BSS PTOOT,a Output table 64 bits EOT ,EOO 040h End of table indication bit REP ,EOO OaOh Repetition bit PTBITC Call for the "Initial Permutation", Description table is starting at label IP (64 bytes for 64 bits), MOV #IP,PTPOI Load description table pointer CALL #PERMOT Process Initial Permutation Permutation subroutine, Table PTIN is permuted to table PTOOT PERMOT CLR PTBYTP Clear byte index input table CLR PTOOT Clear output table a bytes CLR PTOOT+2 CLR PTOOT+4 CLR PTOOT+6 PERML CLR PTBITC Bit counter (bits inside byte) L$502 RRA,B PTui (PTBYTP) Next input bit to Carry JNC L$500 If bit = 0: No activity nec, L$501 CALL #PERM_BIT Bit L$500 INC PTPOI Incr, description table pointer TST,B -l(PTPOI) REP bit set for last bit? IN L$501 Yes, process 2nd output bit 5-72 = 1: Insert bit to output General-Purpose Subroutines One input table bit is processed. Check if byte limit reached INC.B PTBITC Incr. bit counter CMP.B #8,PTBITC Bit 8 (outside byte) reached? JLO L$502 INC.B PTBYTP Yes, address next byte BIT.B #EOT,-l(PTPOI) End of desc. table reached? JZ PERML No, proceed with next byte RET Permutation subroutine for one bit: A set bit of the input is set in the output depending on the information of a description table pointed too by pointer PTPOI 20 cycles + CALL (5 cycles) PERM_BIT .EQU $ MOV.B @PTPOI,R4 Fetch description word MOV R4,R5 Copy it BIC.B #REP+EOT,R4 Clear Repetition bit and EOT RRA.B R4 Move Index Bits to LSBs RRA.B R4 to form byte index to PTBIT RRA.B R4 AND.B #07h,R5 Mask out index for output table BIS.B PTBIT(R5),PTOUT(R4) Set bit in output table 1,2,4,8, 10'h, 20h, 40h, 80h Bit table RET PTBIT .BYTE Description Table for the Initial Permutation. 64 bits of the input table are permuted to 64 bits in the output table (IP-l table contains these numbers) IP .BYTE 40-1 Bit 1 -> position 40 . BYTE 8-1 Bit 2 -> position 8 Software Applications 5-73 Ge.~eral-Purpose Subroutines . BYTE EOT+25-1 ; Bit 64 -> pos. 25, End of table Description Table for the Expansion Function E. 32 bits of the input table are permuted to 48 bits in the output table E .BYTE REP+2-1 Bit 1 -> position 2 and 48 . BYTE 48-1 Bit 1 -> position 48 . BYTE 3-1 Bit 2 -> pos. 3 .BYTE REP+1-1 Bit 32 -> pOSition 1 and 47 .BYTE EOT+47-1 Bit 32 -> pos. 47, End of table Processing time for a 64-bit block: The most time consuming parts for the encryption are the permutations. All other operations are simple moves or exclusive ORs (XOR). This means that the number of pennutations multiplied with the number of cycles per bit gives an estimation of the processing time needed. Every bit needs 43 cycles to be permuted. The necessary number of permutations is: 1) 2) 3) 4) 5) 6) 7) Initial Permutation 32-bit to 48-bit permutation 48-bit to 32-bit permutation 32-bit to 32-bit permutation Inverse initial Permutation: Key permutations choice 1 Key permutations choice 2 Sum of permutations 64 16x48 16x32 16x32 64 56 16x48 2744 Number of cycles typically (2744 x 43 x 0.5) 58996 cycles 32 ones in block maximum (2744 x 43) 117992 cycles 64 ones in block For a block with 64 bits approximately 59 ms are needed with an MCLK of 1 MHz. ROM space: The needed ROM space can be divided into the following parts: 1) Main program (approx.) 2) Subroutines 3) Tables for permutations 5-74 400 bytes 100 bytes 570 bytes . General-Purpose Subroutines 1070 bytes Sum of bytes The complete DES encryption software fits into 1K bytes. 5.5.7.2 Output Sequence for 19.2-kHz B/phase Space Code The encrypted information is normally output with a Biphase Code. Figure 5-17 shows such a modulation. At the beginning of a bit, a level change occurs. A zero bit has an additional level change in the middle of the bit, a one bit has the same information during the whole bit. o o o o Information BI·Phase Space Figure 5-17. Biphase Space Code The output sequence is written for PO.4 (as shown in Section 4.4, Heat Allocation Counte". This means that no constant of the constant generator can be used. If PO.O, PO.1, PO.2, or PO.3 are used, the instructions that address the ports are one cycle shorter and the delay subroutines have to be adapted. The following output sequence is written with counted instructions per bit due to the normal use of batteries (Vee =3V) for these applications. This means the maximum MCLK is 2.2 MHz. If the supply voltage is 5 V, MCLK frequencies up to 3.3 MHz are possible. These high operating frequencies allow the use of interrupt driven output sequences. The interrupt approach makes strict real time programming necessary. Any interrupt handler must be interruptible (EINT is one of the first instructions of any interrupt handler). Hardware examples are shown in Section 4.8, RF Readout. OUTl92 OUTPUTS THE RAM STARTING AT " RAMS TART " BITWISE IN BI-PHASE-CODE. EVERY 040h ADDRESSES A SCAN IS MADE TO READ PO.l WHERE THE WATER FLOW COUNTER IS LOCATED. THE 4 SCAN RESULTS ARE ON THE STACK AFTER RETURN FOR CHECKS NOPs ARE INCLUDED TO ENSURE EQUAL LENGTH OF EACH BRANCH. Software Applications 5-75 Gen~ral-purpose Subroutines All interrupts must be disabled during this output subroutine! CALL #NOPx MEANS x CYCLES OF DELAY. MCLK = IMHz OUTPUT .EQU OlOh PORT .EQU Ollh PORTO 0200h Start of output info RAMSTART .EQU PO.4: RAMEND .EQU 0300h End of output info SCAND .EQU 040h Scan delta (addresses) Rw .EQU R15 Register allocation Rx .EQU R14 Ry .EQU R13 Rz .EQU R12 OUT192 ; BIC.B #OUTPUT,&PORT Reset output port MOV #RAMSTART,Ry WORD POINTER MOV #RAMSTART+SCAND,Rw NEXT SCAN ADDRESS FETCH NEXT WORD AND OUTPUT IT WORDLP CYCLES MOV #l6,Rz BIT COUNTER 2 MOV @Ry,Rx FETCH WORD 5 CHANGE OUTPUT PORT 5 OUTPUT NEXT BIT: Change output state BITLOP XOR.B #OUTPUT,&PORT CHECK IF NEXT SCAN OF WATER FLOW IS NECESSARY: Ry >= Rw CMP Rw,Ry JHS SCAN NOP 1 YES 2 NO 5 NOP NOP NOP NOP SCAN BITT 5-76 JMP BITT ADD #SCAND,Rw NEXT SCAN ADDRESS 2 PUSH &PORT PUSH INFO OF PORT 5 RRC Rx NEXT BIT TO CARRY 1 2 General-PufPOS,e~Subroutines JNC BIT BIT OUTO OUTO BIT o 2 1: OUTPUT PORT IS CHANGED IN THE MIDDLE OF BIT CALL #NOP9 XOR.B #OUTPUT,&PORT JMP CHECK 9 CHANGE OUTPUT PORT 5 2 0: OUTPUT PORT STAYS DURING COMPLETE BIT CALL #NOP16 OUTPUT STAYS HI 16 END OF LOOP: CHECK IF COMPLETE WORD OR END OF INFO CHECK DEC Rz 16 BITS OUTPUT? 1 JZ L$1 YES 2 CALL #NOP15 NO, NEXT BIT 15 JMP BITLOP :2 COMPLETE WORD OUTPUT: ADDRESS NEXT WORD L$1 ADD #2,Ry POINTER TO NEXT WORD :2 CMP #RAMEND,Ry RAM OUTPUT? 2 JEQ' COMPLET NO, NEXT WORD 2 YES· 2 NOP NOP JMP COMPLET WORDLP :2 ; 4 SCANS ON STACK NOP Subroutines: The Subroutine inserts defined numbers of cycles when called. The number xx of the called label defines the number of cycles including CALL (5 cycles) and RET NOP16 NOP NOP15 NOP NOP14 NOP NOPl3 NOP CALL #NOPxx needs 5 cycles Software Applications 5-77 General-Purpos~ Subroutines NO!?12 NO!? NO!? 11 NO!? NO!?10 NO!? NO!? 9 NO!? NO!? 8 RET RET needs 3 cycles 5.5.8 Status/Input Matrix A few subroutines are described that handle the inputs coming from keys. signals etc. They check. Ifthe Inputs are valid. for the given status ofthe program. 5.5.8.1 Matrix with Few Valid Combinations The following subroutine checks if for a given program status an input (e.g .• via the keyboard) is valid or not; and. if valid. which response is necessary. This solution is recommended if only few valid combinations exist out of a large possible number (see Figure 5-18). 1"1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 ~I :1 I o H I tiJ11111111 2 3 4 5 6 7 8 9 10 11 12 Input - - . Figure 5-18. Matrix for Few Valid Combinations o o 5-78 I Call • Input number in R5 • Status in R4 Return • R4 ~ 0: Input not valid (not included in the table) • R4 # 0: task number in R4 13 14 rl 15 General-Purpose Subroutines CALL Mav STATUS,R4 Program status to R4 MaV INPUT,R5 New input to RS CALL #STIMTRX Check validity R4 contains info STIMTRX L$3 MaV.B STTAB(R4), R4 Start of table for status ADD #STTAB,R4 Table address to R4 CMP.B @R4+,RS New input included in table? JEQ L$2 Yes, output it INC R4 No, skip response byte TST.B 0(R4) End of status table? (0) JNE L$3 No, try next input CLR R4 Yes, end of table reached RET L$2 MaV.B Input invalid, return with R4 @R4,R4 RET 0 Input valid, return with task number in R4 Table with relative start addresses for the status tables STTAB . BYTE STO-STTAB,STl-STTAB,ST2-STTAB, ... STIS-STTAB Status tables: valid inputs,response, .. ,0 (uP to 15 inputs) STO . BYTE INS,AKTOO,O Status 0 table STI .BYTE IN1,AKTOl,IN4,AKT03,0 Status 1 table ST2 . BYTE INlS,AKTOO,IN6,AKT06,O Status 2 table STIS . BYTE INS,AKT02,0 Status 3 to 14 Status IS table With a small change, the. task to do is also executed within the subroutine: CALL Mav STATUS,R4 MaV INPUT,RS New input ;to R5 CALL #STIMTRX Check validity and execute task Program status to R4 R4 = 0: invalid input STIMTRX MaV.B STTAB(R4),R4 Start of table for status Software Applications 5-79 Gener~tP~'f..OSe Subr0ut.ines L$3 ADD #STTAB,R4 CMP,B @R4+,R5 New input included? JEQ L$2 Yes, proceed INC R4 No, skip task address TST,B 0(R4) End of status table? (0) JNE L$3 No, try next input CLR R4 End of table reached RET L$2 to R4 Input invalid, return with R4 MOV,B @R4,R4 Input valid, go to task ADD R4,PC offset to AKTOO in R4 AKTOO 0 Task 00 RET AKT01 Task 01 RET AKT06 Task 06 RET AKT03 Task 03 RET Table with relative start addresses for the status tables STTAB ,BYTE STI-STTAB,ST2-STTAB", ,ST15-STTAB Status tables: valid inputs,task-table_start,O STI ,BYTE IN5,AKTOO-AKTOO,0 ST2 ,BYTE INl,AKT01-AKTOO,IN4, AKT03-AKTOO,0 ST3 ,BYTE INI5,AKTOO-AKTOO,IN6,AKT06-AKTOO,O ST15 ,BYTE IN5,AKT02-AKTOO,0 ; Status 1 table· Status 4 to 14 Status 15 table 5.5.8.2 Matrix WIth Valid Combinations Only The following subroutine executes the tasks belonging to the 16 possible STATUS/INPUT combinations. The handler start addresses must be within 254 bytes relative to the label STTAB, The number of combinations can be enlarged to any value. 5-80 Gene!al-Purpose Subroutines o o Call • Input number in RAM byte INPUT (four possibilities 0 to 3) • Program status in RAM byte STATUS (four possibilities 0 to 3) Return • No information returned CALL CALL #STIMTRX STIMTRX MOV.B STATUS,R4 ; Program status OOxx MOV.B INPUT,RS ;.Input (key, Intrpt,) Oyy RLA R4 RLA R4 OxxO -> OxxOO ADD R5,R4 Build MOV.B STTAB(R4),R4 Offset of Start of table STTAB ; Execute task for input STATUS x 4: OOxx -> OxxO ta~le offset: Oxxyy ADD R4,PC Handler start to PC . BYTE AKTOO-STTAB Action STATUS 0, INPUT . BYTE AKTOl-STTAB Action STATUS 0, INPUT = 1 . BYTE AKT02-STTAB,AKT03-STTAB,AKT04-STTAB,AKTOS-STTAB .BYTE AKT12-STTAB,AKT13-STTAB,AKT14-STTAB,AKT1S-STTAB = 0 Aotion handlers for the 16 STATUS/INPUT xy combinations AKTOO Handler for task 0,0 RET AKT01 Handler for task 0,1 RET Tasks 02 to 31 AKT32 Handler for task 3,2 RET AKT33 Handler for task 3,3 RET The next subroutine also executes the tasks belonging to the 16 possible STATUSIINPUT combinations. Here the handler start addresses can be located in the complete 64K-byte address space. The number of STATUSIINPUT combinations can be enlarged to any value. Software Applications 5-81 G8n8raJ-P~rpos8 Subroutl".86 o o Call • Input number In RAM byte INPUT (five possibilities 0 to 3) • Program status in RAM byte STATUS (four possibilities 0 to 3) Return • No information returned CALL CALL #STIMTRX STIMTRX MOV STATUS,R4 MOV INPUT,R5 Input (key, Intrpt) Oyy RLA R4 OOxx -> OxxO STTAB ; Execute task for input Program status OOxx RLA R4 OxxO -> OxxOO ADD R5,R4 Oxxyy table offset RLA R4 To word addresses MOV STTAB(R4) ,PC Offset of Start of table . WORD AKTOO Action STATUS - 0, INPUT . WORD AKTOl Action STATUS . WORD AKT33 = 0 0, INPUT - 1 Action handlers AKT02 to AKT32 Action STATUS = 3, INPUT = 3 The Floating-Point Package 5.6 The Floating-Point Package Floating-point arithmetic is necessary if the range of the numbers used is very large. When using a floating-point package, it is normally not necessary to take care if the limits of the number range are exceeded. This is due to a number ratio of about 1078 If comparing the largest to the smallest possible number (remember: the number of smallest particles in the whole universe is estimated to 1084). The disadvantages are the slower calculation speed and the ROM space needed. A floating-point package with 24-bit and 40-bit mantissa exists for the MSP430. The number range, resolution, and error indication are explained as well as the conversion subroutines used as the interface to binary and binarycoded-decimal (BCD) numbers. Examples are given for many subroutines and applications, like the square root, are included in the software example chapter. The floating-point package makes use ofthe RISC architecture ofthe MSP430 family. During the initialization of the subroutines, the arguments are copied into registers R4 to R15 and the complete calculations take place there. After the completion of the calculation, the result is placed on top of the stack. 5.6.1 General The floating-point package (FPP) consists of 3 files supporting the .FLOAT format (32 bits) and the .DOUBLE format (48 bits): o o o FPPDEF4.ASM: the definitions used with the other two files FPP04.ASM: the basic arithmetic operations add, subtract, multiply, divide and compare CNV04.ASM: the conversions from and to the binary and the BCD format Notes: The file FPP04.ASM can be used without the conversions, but the conversion subroutines CNV04.ASM need the FPP04.ASM file. This is due to the common completion parts contained in FPP04.ASM. The explanations given for the FPP version 04 are valid also for the FPP version 03. The only difference between the two versions is the hardware multiplier that is included in the version 04. Other differences are mentioned in the ajoining sections. FPP4 is upward compatible to FPP3. The assembly time variable DOUBLE defines which format is to be used: Software Applications 5-83 !.!'e. Floating-Point Package DOUBLE=O: DOUBLE .. 1: Two word format .FLOAT with 24-bit mantissa Three word format .DOUBLE with 40-bit mantissa The assembly time variable SW_UFLOW defines the reaction after a software underflow: SW_UFLOW = 0: Software underflow (result is zero) is not treated as an error SW_UFLOW .. 1: Software underflow is treated as an error (N is set) The assembly time variable HW_MPY defines if the hardware multiplier is used or not during the multiplication subroutine: HW_MPY = 0: HW_MPY = 1: No use, the multiplication is made by a software loop The 16 x 16 bit hardware multiplier is used The FPP supports the four basic arithmetic operations, comparison, conversion subroutines and two register save/restore functions: FLT_ADD FLT_SUB FLT_MUL FLT_DIV FLT_CMP FLT_SAV FLT_REC CNV_BINxxx CNV_BCD_FP CNV_FP_BIN CNV_FP_BCD Addition Subtraction Multiplication Division Comparison Saving of all used registers on the stack Restoring of all used registers from the stack Binary to floating point conversions BCD to floating point conversion .Floating point to binary conversion Floating point to BCD conversion 5.6.2 Common Conventions The use of registers containing the addresses of the arguments saves time and memory space. The arguments are not affected by the operations and can be located either in ROM or RAM. Before the call for an operation, the two pointers RPARG and RPRES are loaded with the address(es) of the most significantword MSW ofthe argument(s). After the return from the call, both pOinters and the stack pointer, SP, point to the result.(on the stack) for an easy continuation of arithmetical expressions. 5-84 The Floating-Point Package Note: The result of a floating point operation is always written to the address the stack pointer (SP) points to when the subroutine is called. The address contained in register RPRES is used only for the addressing of Argument 1. The results of the basic arithmetic operations (add, subtract, multiply and divide) are also contained in the RAM address@SPorO(SP), and the registers RESULT_MID and RESULT_LSB after the return from these subroutines. Using these registers for data transfers saves program space and execution time. Between FPP subroutine calls, all registers can be used freely. The result of the last operation is stored on the stack. See previous note. If, at an intermediate stage of the basic arithmetic operations, a renormalizalion shift of one or more bit positions to the left is required, then valid bits are available for the shift into the low-order bit positions during renormalization. These bits are named guard bits. With some other FPPs having no guard bits, zeroes are shifted in, which means a loss of accuracy. The registers that hold the pointers are called: o RPRES Pointer to Argument 1 and Result o RPARG Pointer to Argument 2 and Result The following choices can be used to address the two operands: 1) RESULTNEW =@(RPRES)@(RPARG) 2) RESULTNEW = @(RPRES) RESULTOLD 3) RESULTNEW = RESULTOLD @(RPARG) o To 1: RPRES and RPARG both point to the·arguments for the next operation. This is the default and is independent of the address pointed to either a new argument or a result. The result of the operation is written to the address in the SP. o To 2: RPRES points to the argument 1, RPARG still points to the result of the last operation residing on the top of the stack (TOS). This calling form allows the operations (argument 2 - result) and (argument 2 / result) . .0 To 3: RPARG points to argument 2, RPRES still points to the result of the last operation residing on the top of the stack. This calling form allows the operations (result - argument 2) and (result / argument 2). Software Applications 5-85 The Floating-Point Package ' ' ' ' OJ! t"''' ~ :!l;:':U:~ ;:,::; Note: Formulas 2 and 3 are not equal. they allow use of the result on the TOS in two ways with division and subtraction. No time is needed and no ROM-consuming moves are necessary if the result is the divisor or the subtrahend for the next operation. Common to these subroutines is: 1) The pointers RPARG and RPRES point to the addresses of the input numbers. They always pOint to the MSBs of these numbers. 2) The input numbers are not modified. except the last result on the stack. if it is used as an operand. 3) The result is located on the top of the stack (TOS). the stack pOinter. RPARG. and RPRES point to the most significant word of the result 4) Every floating point number represents a valid value. No invalid combinations like Not a Number, Denormalized Number, or Infinity exist. In this way. the MSP430 FPP has a larger range than other FPPs and allows a higher speed with less memory used. This is because no unnecessary checks for invalid numbers are made. 5) Every floating point operation outputs a valid floating point number that can be used immediately by other operations. 6) If a result is too large (exceeds the number range). the signed maximum number is ·output. An error indication is given in this case (see Table 5-6. Error Indication). 7) The CPU registers used are modified within the FPP subroutines. but do not contain valid data after a return from the subroutine. This means. they can be used freely between the FPP subroutines for other purposes. 5.6.3 The Basic Arithmetic Operations The FPP is designed for fast and memory saving calculations. So register instructions are ideally suited for this operation. A common save and recall routine for the registers used at the beginning and the end of an arithmetical expression is an additional option. The subroutines FLT_SAV and FLT_REC should be applied as shown in the following examples. 5.6.3.1 Addition o 5-86 FLT_ADD: The floating point number pointed to by the register RPARG is added to the floating point number pointed to by the register RPRES. The The Floating-Point Package 25th bit (41 st bit in case of DOUBLE format) of the calculated mantissa is used for rounding. It is added to the result. RESULT on TOS =@(RPRES) + @(RPARG) o Errors: Normal error handling. See Section 5.6.3.5, Error Handling, for a detailed description. o Output: The floating point sum of the two arguments is placed on the top of the stack. The stack painter pOints to the same location as it did before the subroutine call. The stack pointer, RPRES, and RPARG pOint to the MSBs of the floating point sum. If an error occurred (N = 1 after return), the result is the number that best represents the correct result: 0 resp. ±3.4 x 1038. o DOUBLE EXAMPLE: The floating point number (.FLOAT format) contained in the ROM starting at address NUMBER is added to the RAM location pointed to by R5. The result is written to the RAM addresses RES and RES+2 (LSBs). .EQU 0 MOV R5,RPRES MOV #NUMBER,RPARG Address of Argument 2 CALL #FLT_ADD Call add subroutine Address of Argument 1 in R5 IN ERR_HND Error occurred, check reason MOV @RPRES+,RES Store FPP result (MSBs) MOV @RPRES+,RES+2 LSBs Continue with program 5.6.3.2 Subtraction o FLT_SUB: The floating point number pointed to by register RPARG is subtracted from the floating point number pOinted to by register RPRES. With proper loading of the two input pOinters, it is possible to calculate (Argument1 - Argument2) and (Argument2 - Argument1). The 25th bit (41 st bit In case of DOUBLE format) of the calculated mantissa is used for rounding and is subtracted from the result. RESULT on TOS =@(RPRES) - @(RPARG) o Errors: Normal error handling. See Section 5.6.3.5, Error Handling, for a detailed description. o Output: The floating point difference of the two arguments is placed on top of the stack. The stack pointer points to the same location as it did before the subroutine call. Software Applications 5-87 The Floating-Point Package The stack pointer, RPRES, and RPARG point to the MSBs of the floating point difference. If an error occurred (N .. 1 after return), the result is the number that best represents the correct result; 0 resp. ±3.4 x 1038. o DOUBLE EXAMPLE: The floating point number (.DOUBLE format) contained in the ROM locations starting at address NUMBER is subtracted from RAM locations pointed to by R5. The result is written to the RAM addresses pointed to by R5• . EQU 1 MOV RS,RPRES Address of Argumentl in RS MOV #NUMBER,RPARG Address of Argument2 CALL #FLT_SUB «RS)) - IN ERR_HND Error occurred, check reason . MOV @RPRES+,O(RS) Store FPP result (MSBs) MOV @RPRES+,2(RS) MOV @RPRES,4(RS) (NUMBER) -> TOS LSBs Continue with program 5.6.3.3 Multiplication o FLT_MUL: The floating point number pointed to by the register RPARG is multiplied by the floating point number pointed to by the register RPRES. The 25th and 26th bit (41 st and 42nd bit in case of DOUBLE format) ofthe calculated mantissa are used for rounding. If a shift is necessary to getthe MSB ofthe mantissa setthen the LS8-1 is shifted into the mantissa and the LS8-2 is added to the result. Ifthe MSB ofthe mantissa is set, only the LS8-1 Is added to the result. The multiplication subroutine returns the same result regardless of whether. the hardware multiplier is used (HW_MPY = 1) or not (HW_MPY = 0). RESULT on TOS = @(RPRES) x @(RPARG) o Errors: Normal error handling. See Section 5.6.3.5, Error Handling, for a detailed description. o Output: The floating point product of the two arguments is placed on the top of the stack. The stack pointer pOints to the same location as it did before the subroutine call. The stack pOinter, RPRES, and RPARG point to the MSBs of the floating point product. If an error occurred (N = 1 after return), the result is the number that best represents the correct result; 0 resp. ±3.4 x 1038. o 5-88 SpeclaICases:OxO=O OxX.O XxO=O The Floating-Point Package o DOUBLE EXAMPLE: The result of the last operation, a floating point number (.FLOAT format) on the top of the stack, is multiplied by the constant Tt. .EQU 0 MOV #PI,RPARG CALL #FLT_MUL «RPRES) ) x (PI) -> TOS IN ERR_END Error occurred, check reason . FLOAT 3.1415926535 Constant PI Address of constant PI Continue with program PI 5.6.3.4 Division o FLT_DIV: The floating point number pointed to by the register RPRES is divided by the floating point number painted to by the register RPARG. With proper loading of the two input pointers, it is possible to calculate (Argument1 I Argument2) and (Argument21 Argument1). The 25th bit (41 st bit in case of DOUBLE format) of the calculated mantissa is used for rounding and is added to the result. RESULT on TOS= @(RPRES) @(RPARG) o Errors: Normal error handling. See Section 5.6.3.5, Error Handling, for a detailed description. Division by zero is indicated also. o Output: The floating paint quotient of the two arguments is placed on the top of the stack. The stack pointer points to the same location as it did before the subroutine call. The stack pointer, RPRES, and RPARG paint to the MSBs of the floating point quotient. If an error occurred (N = 1 after return), the result is the number that best represents the correct result. For example, the largest number that can be represented if a division by zero was made. o Special Cases: 010 =0 OIX =0 -X/O = max. neg. number +X/O = max. pas. number o EXAMPLE: The floating point number (.DOUBLE format) contained in the ROM locations starting at address NUMBER is divided by the RAM locations pointed to by R5. The result is written to the RAM addresses pointed to by R5. Software Applications 5-89 The Floating-Poin! P~~e DOUBLE .EQU 1 MOV R5,RPARG Address of dividend MOV #NUMBER,RPRES Address of divisor CALL #FLT_DIV (NUMBER) / IN ERR_HND Error occurred, check reason MOV @RPRES+,O(R5) Store FPP result (MSBs) MOV @RPRES+,2(RS) MOV @RPRES,4(R5) «RS» -> TOS LSBs Continue with program Examples for the Basic Arithmetic Operations The following example shows the following program steps for the .FLOAT format: 1) The registers used R5 to R12 are saved on the stack. 2) Four bytes are allocated on the stack to hold the results of the operations. 3) The address to a 12-<1igitBCD-buffer is loaded into pointer RPARG and the BCD-to-floating point conversion is called. The resulting floating point number is written to the result space previously allocated. 4) The resulting floating point number is multiplied with a number residing in the memory address VAL3. RPARG pOints to this address. 5) To the last result, a floating point number contained in the memory address VAL4 is added 6) The final result is converted back to BCD format (6 bytes) that can be displayed in the LCD. 7) The final result is copied to the RAM addresses BCDMSD, BCDMID and BCDLSB. The three necessary POP instructions correct the stack pointer to the value after the save register subroutine. 8) The registers used, R5 to R12, are restored from the stack. The system environment is exactly the same now as before the floating point calculations. DOUBLE .EQU o Use .FLOAT format Normal program CALL 5-9.0 Save registers RS to Rl2 The Floating-Point Package SUB #4,SP MOV #BCDB,RPARG Load address of BCD-buffer CALL #CNV_BCD_FP Convert BCD number to FP Allocate stack for result Calculate (BCD-number x VAL3) + VAL4 MOV #VAL3,RPARG Load address of slope CALL #FLT_MUL Calculate next result MOV #VAL4,RPARG Load address of offset· CALL #FLT_ADD Calculate next result CALL #CNV_FP_BCD Convert final FP result to BCD IN CNVERR Result too big for BCD buffer POP BCDMSD BCD number MSDs and sign POP BCDMID BCD digits MSD-4 to LSD+4 POP BCD LSD BCD digits LSD+3 to LSD CALL #FLT_REC Stack is corrected by POPs Restore registers R5 to R12 Continue with program VAL3 . FLOAT -1.2345 . VAL4 . FLOAT 14.4567 CNVERR Slope Offset Start error handler The next example shows the following program steps for the .DOUBLE format: 1) The registers used, R5 to R15, are saved on the stack. 2) Six bytes are allocated on the stack to hold the results of the operations. 3) The ADC buffer address of the MSP430C32x (14-bit result) is written to RPARG and the last ADC result converted into a floating point number. The resulting floating point number is written to the result space previously allocated. 4) The resulting floating point number is multiplied with a number located at the memory address VAL3. RPARG pOints to this address. 5) To the last result, a floating point number contained in the memory address VAL4 is added. 6) The final result is converted back to binary format (6 bytes) and can be used for integer calculations. Software Applications 5-91 The Floating-Point Package 7) The resulting binary number is copied to the RAM addresses BINMSD, BINMID, and BINLSB. The three necessary POP instructions correct the stack pointer to the value after the save register subroutine. 8) The registers used, R5 to R15, are restored from the stack. The system environment is now exactly the same as it was before the floating point calculations. DOUBLE .EQU ; Use .DOUBLE format 1 Normal program CALL Save registers R5 to R15 SUB lI6,SP Allocate stack for result MOV lIADAT,RPARG Load address of ADC data buffer CALL lICNV_BIN16U Con.vert unsigned result to FP Calculate (ADC-Result x VAL3) + VAL4 MOV #VAL3,RPARG Load address of slope CALL #FLTJIDL Calculate next result MOV #VAL4,RPARG Load address of offset CALL #FLT_ADD Calculate next result CALL lICNV_FP_BIN Convert final FP result to binary POP BINMSD Store MSBs of result and s-ign POP BINMID Store MIDs and LSBs POP BINLSD Stack is corrected by POPs CALL #FLT_REC restore registers R5 to R15 Continue with program VAL3 . DOUBLE 1.2E-3 Slope 0.0012 VAL4 . DOUBLE 1.44567E1 Offset 14.4567 5.6.3.5 Error Handling Errors during the operation affect the status bits in the status register SR. If the N-bit contained in the status register is reset to zero, no error occurred. If the N-blt is set to one, an error occurred. The kind of error can be seen in Table 5-6. The columns .FLOAT and .DOUBLE show the returned results for each error. 5-92 The Floating-Point Package Table 5-6. Error Indication Table Error Status .DOUBLE .FLOAT No error N-O xxxx,xxxx xxxx,xxxx,xxxx Overflow positive Overflow negative N=1, C=1, Z=1 N-1, C.1, Z=O FF7F,FFFF FFFF,FFFF FF7F,FFFF,FFFF FFFF,FFFF,FFFF Underflow N-1, C.O, Z=O 0000,0000 0000,0000,0000 Divide by zero Dividend positive Dividend negative Na1, C=O, Z=1 FF7F,FFFF or FFFF,FFFF FF7F,FFFF,FFFF or FFFF,FFFF,FFFF Software underflow is only treated as an error if the variable SW_UFLOW is set to one during assembly. 5.6.3.6 Stack Allocation Before calling an operation 4 (resp. 6) bytes on the stack have to be reserved for the result. The following return address of the operation occupies another 2 bytes. The subroutines need one subroutine level during the calculations for the common initialization subroutine. The allocation in Figure 5-19 is shown for the use of FLT_SAV. t- Addressn Addressn·4 Addrassn-ll Addrass n·12 Addrassn-18 Address n·20 Addrass n·24 R12 Rll R5 R8 R7 R8 RS Rl0 Return FLT_SAY RllllUltLSBs RIlllUItMSBs Retum FLT·xxx SP During MAIN Program Addrassn Addrassn"" Addrassn-8 Addrassn-12 Addrassn-18 Addrass n-2O ~ SP Alter Retum ~ SP During FLT_xxx Addral8 n·24 Addrass n-28 Addrass n-32 R15 R14 RS RS R7 R8 RS Rl0 Rl1 R12 R13 Retum FLT SAY ResuhLSBs RIlllUItMIDs ResullMSBs Retum FLT-xxx t- SP During MAIN Program tt- SP Altar Retum SP During FLT_xxx Figure 5-19. Stack Allocation for .FLOAT and .DOUBLE Formats The FPP-subroutines correctly work only when the previous allocation is provided. This means the SP points to the return address on the stack. If the FPPsubroutines are called inside of a subroutine, a new result area must be allocated because the return address of the calling subroutine is now at the location the SP pOints to. The return address is overwritten in this case. The following example shows the correct procedure: Software Applications 5-93 The Roatlng-Polnt Package SUBR SUB #(ML/8)+1,sP Allocate new result area MOV @RPARG+,O(SP) Fetch argument 2 to new MOV @RPARG+,2(SP) result area .if DOUBLE=l MOV @RPARG,4(SP) .endif MOV SP,RPARG MOV txx, RPRES Point to argument 1 CALL tFLT_xxx Use new result area for calc. MOV @SP+,result Free allocated stack MOV @SP+,result+2 Store result, correct SP .if DOUBLE=l MOV @SP+,result+4 Point again to argument 2 Continue with calculations . end i f RET Note that it is strongly recommended that conscientious housekeeping be provided for SP to avoid stack overflow. 5.8.3.7 Number Range and Resolution E = exponent of the floating point number. See Section 5.6.5, Internal Data Representation for more information . .Float Format 2-23) Most positive number FF7F,FFFF 2127 x (2 - = 3.402823 x 1038 Least positive number 0000,0001 2-128 x (1 + 2-23) = 2.938736 x 10-39 Zero 0000,0000 0 =0.0 Least negative number 0080,0000 _2-128 = -2.938736 x 10-39 Most negative number FFFF,FFFF _2127 x (2 - 2-23) = -3.402823 x 1038 = 119.2093 x 10-9 2E Resolution .DOUBLE Format Most positive number 5-94 FF7F,FFFF,FFFF 2127 x (2 - 2-39) = 3.402824 x 1038 The Floating-Point Package Least positive number 0000,0000,0001 2-128 x (1 + 2-39) Zero 0000,0000,0000 0 =2.938736 x 10-39 =0.0 Least negative number 0080,0000,0000 _2-128 = -2.938736 x 10-39 Most negative number FFFF,FFFF,FFFF _2127 x (2 - 2-39) = -3.402824 x 1038 = 1.818989 x 10-12 x 2E Resolution 5.6.4 Calling Conventions for the Comparison The comparison subroutine works much faster than a floating subtraction. Only the signs are compared in a first step to find out the relation of the two arguments. When the signs of the two operands are equal, the mantissas are compared. After the comparison, the status bits of the status register (SA) hold the result: The registers RPRES and RPARG point to the same location the SP pOints to (for the FPP version 3 they were not defined). Table ~7. Comparison Results Relations Status Argument 1 > Argument 2 C.l, Z.O Argument 1 < Argument 2 C=O,z,.O Argument 1 = Argument 2 C=1,Z=1 The calling and use of the returned status bits is shown in the next example: MOV #ARG1,RPRES point to Argument 1 MSBs MOV #ARG2,RPARG Point to Argument 2 MSBs CALL #FLT_CMP Comparison: result to SR JEQ EQUAL Condition for program flow JHS ARG1_GTJ.RG2 ARGl is greater than ARG2 ARGl is less than ARG2 EQUAL ARGl and ARG2 are equal ARG1_GT_ARG2 ARGl is greater than ARG2 Other possibilities after the return CALL Comparison: result to SR Software Applications 5-95 The Floating-Point Package ARGl is greater/equal ARG2 JHS ARGI is less than ARG2 CALL #FLT_CMP JNE ARGl_NE_ARG2 Comparison: result to SR @RPRES not equal to @RPARG ARGI is equal to ARG2 CALL #FLT_CMP Comparison: result to SR JLO ARGl_LT_ARG2 ARGI is less than ARG2 ARGI is greater/equal ARG2 5.6.5 Internal Data Representation The following description explains both the FLOAT and the DOUBLE formats. The two floating point formats consist of a floating point number whose: o o 8 most significant bits represent the exponent 24 (or 40 in the case of DOUBLE format) least significant bits hold the sign and the mantissa. 16 31 Exponent e7 eO o 15 Mantissa 18m I m22 32 47 FLOAT mO 31 16 15 o Exponent~__ ~______ ~~~__~______M__an_tl_8_~______~______________~1 DOUBLE 18m I e7 eO mO m3S Figure 5-20. Floating Point Formats for the MSP430 FPP Where: Sm mx ex x Sign of floating point number (sign of mantissa) Mantissa bit x Exponent bit x Valence of bit The value N of a floating point number is 5-96 The Floating-Point Package Note: The only exception to the previous equation is the floating zero. It is represented by all zeroes (32 if FLOAT format or 48 if DOUBLE format). No negative zero exists, the corresponding number (0080,0000) is a valid non-zero number and is the smallest negative number. A frequently asked question is why the MSP430 floating point format does not conform to the widely used IEEE format. There are two main reasons why this is not the case: 1) The MSP430 is often used in a real time environment where calculations need to be completed before the next input data are present. 2) Battery-supplied applications make calculations quickly to produce longer battery lifes (up to 10 years for example). These two main reasons make a run-time optimized floating point package necessary. The format of the floating-point number plays an important role in reaching this target. S.B.S.1 o With the MSP43O-format, every floating-point number represents a valid value. No invalid combinations like Not a Number, Denormalized Number, or Infinity exist. This way the MSP430 FPP has a larger range than other FPPs. This allows a higher speed with the smallest memory usage. This eliminates the need for unnecessary checks for invalid numbers. o The exponent of the IEEE-format is located in two bytes because of the location of the sign in the MSB of the floating point number. With the MSP430-format, the exponent resides completely within the high byte of the most significant word and can, therefore, use the advantages of the byte-oriented architecture of the MSP430. No shifts and no bit handling are necessary to manipulate the exponent. ComputatIon of the MantIssa M 22 M = 1 + 2,(m; x 2 1- 23 ) FLOAT 2;-39 ) DOUBLE Format i=O 38 M 1 + 2,(m; X Format ;=0 The result of the previous calculation is always: 2>M~ 1 Software Applications 5-97 The Floating-Point Package Because the M8B of the normalized mantissa is always 1, a most significant non-sign bit is implied providing an additional bit of precision. This bit is hidden and called hidden bit. The sign bit is located at this place instead: 8m - 0: positive Mantissa 8m .. 1: negative Mantissa Note: The mantissa of a negative floating point number is NOT represented as a 2's-complement number, only the sign bit (8m) decides if the floating-point number is positive or negative. 5.6.5.2 Computation of the Exponent E 7 E = I(e{ x 2i) {=o 128 The M8B of the exponent indicates whether the exponent is positive or negative. M8B of exponent = 0: The exponent is negative M8B of exponent = 1: The exponent is positive The reason for this convention is the representation of the number zero. This number is represented by all zeroes. 5.6.6 Execution Cycles In the following evaluation the variables x . float 3.1416 ; Resp . . double 3.1416 Y . float 3.1416*100 ; Resp . . double 3.1416*100 are the base for the calculations. The shown cycles include the addressing of one operand and the subroutine call itself: MOV tX,RPRES Address 1st operand MOV tY,RPARG Address 2nd operand CALL *FLT_xxx X Y Result on TOS Table 5-8 shows the number of cycles needed for the previously shown calculations: 5-98 The Floating-Point Package Table 5-8. CPU Cycles needed for Calculations Operation Addition X+V Subtraction X-V Multiplication XxV 5.B.7.1 .DOUBLE 184 207 199 1n 395 Comment 692 Software Loop Multiplication XxV 153 213 Hardware MPVer Division XIV X-V 405 756 37 41 Comparison 5.6.7 .FLOAT Conversion Routines General To allow the conversion of integer numbers to floating point numbers and vice versa, the following subroutines are provided (both for .FLOAT and .DOUBLE format): CNV_BCD_FP CNV_FP_BIN CNV_FP_BCD Convert 16-bit, 32-bit, or 40-bH signed and unsigned integer binary numbers to the floating point formal. See Section 5.6.7.2, Binary to Floating Point Conversions. Convert a signed 12-digit BCD number to the floating point format Convert a floating point number to a signed 5 byte integer (40 bits) Convert a floating point number to a signed 12-digit BCD number Common to these subroutines is: 1) The pointer RPARG points to the address of the input number 2) The input number is not modified, except when it is the result of the previous operation on the TOS 3) The result is located on the top of the stack (TOS) , SP, RPARG, and RPRES point to the most significant word of the result 4) Only integers are converted. See Section 5.6.7.3, Handling af Naninteger Numbers, for the handling of non-integer numbers 5) The result is normally calculated using truncation, except when rounding is specified. The assembly-time variable SW_RND defines which mode is to be used. SW_AND =0: Truncation is used, the trailing bits are cut off SW_AND = 1: Rounding is used, the first unused bit is added to the number See Section 5.6.7.4, Rounding and Truncation, for details. Software Applications 5-99 The F~tlng-POint Package 6) The subroutines can be used for 2-word (.FLOAT format) and 3-word (.DOUBLE format) floating point numbers. The assembly time variable DOUBLE defines which mode is to be used: DOUBLE =0: Two word format .FLOAT DOUBLE =1: Three word format .DOUBLE 7) All conversion subroutines need two (three) allocated words on the top of the stack. These words contain the result after the completed operation. A simple instruction is used for this allocation. It is the same allocation that is necessary anyway for the basic arithmetic operations. The possible instructions follow: ML FPL or or .egu .egu SUB SUB SUB SUB For . FLOAT. ML = 40 for . DOUBLE Length of one FP number .FLOAT format allocation .DOUBLE format allocation For both formats For both formats 24 (ML/B)+l #4,SP #6,SP #(ML/B)+l,SP #FPL,SP 8) The FPP04.ASM package is needed. The completion routines of this file are used too 5.6.7.2 Conversions The possible conversions are described in detail in the follOwing sections. Input and output format~, error handling and number range are given for each conversion. Binary to Floating Point Conversions Binary numbers, 16-bit, 32-bit, and 40-bit long, are converted to floating pOint numbers. The subroutine call used defines if the binary number is treated as a signed or an unsigned number. No errors are pOSSible, the N-bit of SR is always cleared on return. Six different conversion calls are provided: CNV_BIN16 The 16-bit number, RPARG points to, is treated as a 16-bit signed number (see Figure 5-21. Range: 15 Addressn ~I~I -32768 to + 32767 o _______________--,M~f--- Sign Figure 5-21. Signed Binary Input Buffer Format 16 Bits 5-100 (08000h to 07FFFh) RPARG The Ftoating-P~I~! Package CNV_BIN16U The 16-bit number, RPARG points to, is treated as a 16-bit unsigned number (see Figure 5-22). Range: Oto + 65535 (OOOOOh to OFFFFh) o 15 ~ Addressn M f - - - - RPARG Figure 5-22. Unsigned Binary Input Buffer Format 16 Bits CNV_BIN32 The 32-bit number, RPARG points to, is treated as a 32-bit signed number (see Figure 5-23). Range: -231 to +231 - 1 o 15 Addressn+2 (08000,OOOOh to 07FFF,FFFFh) 1-"1'"""---------------11____ ~ Address n RPARG Sign Figure 5-23. Signed Binary Input Buffer Format 32 Bits CNV_BIN32U The 32-bit number, RPARG points to, is treated as a 32-bit unsigned number (see Figure 5-24). Range: 0 to 232 - 1 o 15 Addreasn+2 Addressn (OOOOO,OOOOh to OFFFF,FFFFh) __- __ ~~ ~-----------------L-S-B~~ ~ ~ Sign Figure 5-24. Unsigned Binary Input Buffer Format 32 Bits CNV_BIN40 The 48-bit number, RPARG points to, is treated as a 40-bit signed (unsigned number) (see Figure 5-25). Range signed: -24 0 +1 to +240 - 1 (OFFOO,OOOO,OO01 h to OOOFF,FFFF,FFFFh) Software Applications ~1 01 The Floating-Point Package Range unsigned:· 0 to +240 - 1 (OOOOO,OOOO,OOOOh to OOOFF,FFFF,FFFFh) 15 ~_: ~_: ='=1. ___ 8_lg_n_B_yte _ _ _-"'_ _ _ _ o __ __'liIt--- RPARG Figure 5-25. Binary Number Format 48 Bit The previous conversion subroutines convert the 16-bit, 32-bit, or 48-bit numbers to a sign extended 48-bit number contained in the registers BIN_MSB, BIN_MID, and BIN_LSB. Depending on the call (signed or unsigned) used, the leading bits are sign extended or cleared. The resulting 48-bit number is converted afterwards. This allows an additional subroutine call: CNV_BIN The 48-bit signed number contained in the registers BIN_MSB to BIN_LSB (3 words) is converted to a floating point number (see Figure 5-26). Range signed: _240 +1 to +240 - 1 (OFFOO,OOOO,0001 h to OOOFF,FFFF,FFFFh) Range unsigned: 0 to +240 - 1 (OOOOO,OOOO,OOOOh to OOOFF,FFFF,FFFFh) o 15 LSBs Sign Byte MSBs Figure 5-26. Binary Number Format 48 Bit Note: Input values outside of the 40-bit range, shown previously, do not generate error messages. The leading bits are truncated and only the trailing 40-bits , are converted to the floating point format. 5-102 The Floating-Point Package Errors: No error is possible, the N-bit of SR is always cleared on return. Output: The output depends on the floating point format chosen. The format is selected with the assembly time variable DOUBLE. .FLOAT The two-word floating point result is written to the top of the stack. The SP, RPRES, and RPARG point to the MSBs of the floating point number. .DOUBLE The three-ward floating point result is written to the top of the stack. The SP, RPRES, and RPARG point to the MSBs of the lIoating point number. EXAMPLE: The 32-bit signed binary number contained in RAM locations BINLO and BINHI (MSBs) is converted to a three-word floating point number. The result is written to the RAM addresses RES, RES+2 and RES+4 (LSBs). DOUBLE .EQU 1 MOV #BINHI,RPARG Define .DOUBLE format Address of binary MSSs CALL #CNV_BIN32 Call conversion subroutine MOV @RPRES+,RES store MSBs of result MOV @RPRES+,RES+2 MOV @RPRES,RES+4 Store LSBs of result Binary Coded Decimal to Floating Point Conversion Binary coded decimal numbers (BCD numbers), 12 digits in length, are converted to floating point numbers. The MSB of the MSD word contains the sign of the BCD number: . MSB '" 0: positive BCD number MSB '" 1: negative BCD number 15 o Address n+4 Addresan+2 Addressn Sign Figure 5-27. BCD Buffer Format Software Applications 5-103 The Floating-Point Package CNV_BCD_FP 'The 12-cJigit number (contained in 3 words, see Figure 5-27), RPARG points to, is converted to a floating point number. -8 x 1011 +1 to +8 x 1011 _1 Range: Errors: No error is possible, the N-blt of the Status Register Is always cleared on return. If non-BCD numbers are contained in the BCD-buffer, the result will be erroneous. If the MSD of the input number is greater than 7, then the input number is treated as a negative number. Output: A floating point number on the top of the stack: .FLOAT The two-word floating point result is written to the top of the stack. The stack pointer SP, RPRES and RPARG point to the MSBs of the floating point number• .DOUBLE The three-word floating point result is written to the top of the stack. The stack pointer SP, RPRES arid RPARG point to the MSBs of the floating point number. EXAMPLE: The signed BCD number contained in the RAM locations starting at label BCDHI (MSDs) is to be converted to a two word floating point number. The result is to be written to the RAM addresses RES, and RES+2 (LSBs). DOUBLE .EQU MOV CALL MOV MOV 0 #BCDHI,RPARG #CNV~CD_FP @RPRES+,RES @RPRES,RES+2 Define .FLOAT format Address of BCD MSDs Call conversion subroutine Store FP result (MSBS) LSBs Continue with program Floating Point to Binary Conversion The floating point number pointed to by register RPARG is converted to a 40-bit signed binary number located on the top of the stack after conversion (see Figure 5-28). o 15 LSBs Addre88n+4 Addre88n+2 Addressn SIGN BYTE (0 OR FF) Figure 5-28. Binary Number Format 5-104 MSB. SP,RPARG The Floating-Point Package CNV_FP_BIN The floating point number at the address in RPARG is converted to a 40-bit signed binary number. Range signed: -240 +1 to + 240 - 1 (OFFOO,OOOO,0001 h to OOOFF,FFFF,FFFFh) Errors: If the absolute value of the floating point number is greater than 240-1, then the N bit in the status register is set to one. Otherwise, the N bit is cleared. The result, put on top of the stack, is the largest signed binary number (saturation mode). Output: A 40-bit signed, binary number at the top of the stack. The sign uses a full byte• .FLOAT SP, RPRES, and RPARG point to the MSBs of the three-word binary result. An additional word is inserted. It is the responsibility of the calling software to correct the stack by one level upwards after the result is read . •DOUBLE SP, RPRES, and RPARG point to the MSBs of the three-word binary result. EXAMPLE: The floating point number (.DOUBLE format) contained in the RAM locations starting at label FPHI (MSBs) is converted to a 40-bit signed binary number. The result is written to the RAM addresses RES, RES+2, and RES+4 (LSBs). DOUBLE .EQU 1 MOV CALL #FPHI,RPARG #CNV_FP_BIN IN MOV MOV ERR_HND @RPRES+,RES @RPRES+,RES+2 Store binary result (MSBs) MOV @RPRES,RES+4 LSBs Continue with program Address of FP MSBs Call conversion subroutine IFP number I is too big Floating Point to Binary-Coded Decimal Conversion The floating point number at the address in RPARG is converted to a signed 12-cJigit BCD number located on the top of the stack after conversion (see Figure 5-27). The MSD of the result has a maximum value of 7 because the sign bit uses the MSB position. CNV]P_BCD The floating point number at the address in RPARG Is converted to a 12-digit signed BCD number. Software Applications 5-105 Range: Errors: Three errors, at different stages of the conversion, are possible. These errors set the N-bit in the status register: • The exponent value of the floating point number is greater than 39, which represents an absolute value greater than 1.0995 x 1012 • The absolute value ofthe floating point number is greater than 8x1011_1 • The absolute value is greater than 1 x 1012 Otherwise, the N bit is cleared. The result, on the top of the stack, is the largest signed BCD number in case of an error; Output: A 12-c1igit signed BCD number at the top of the stack (see Figure 5-27). .FLOAT SP, RPRES, and RPARG point to the MSDs of the three-word BCD result. An additional word is inserted. It is the responsibility of the calling software to correct the stack by one level upwards after the reading of the result. .DOUBLE SP, RPRES and RPARG point to the MSDs of the three-word BCD result. EXAMPLE: The floating point number (.FLOATformat) contained in RAM locations starting at label FPHI (MSBs) is converted to a 12-digit BCD number. The result is written to RAM addresses RES, RES+2, and RES+4 (LSDs) . DOUBLE . EQU 0 MOV #FPHI,RPARG Address of FP MSBs CALL #CNV_FP_BCD Call conversion subroutine IN ER~HND IFP number I is too big MOV @SP+,RES Store BCD result (MaDs) MOV @SP,RES+2 SP is corrected MOV 2 (SP), RES+4 LSDs Continue with program ERR_HND 5-106 Correct error here The Floating-Point Package 5.6.7.3 Handling of Non-Integer Numbers The conversion subroutines handle only integer numbers when converting to or from floating point numbers. The reasons for this restriction are: 1) The stack grows if non-integer handling is included 2) The necessary program code of the conversion software grows larger 3) The integration of non-integer numbers is easier outside ofthe conversion subroutines 4) The execution time grows longer due to the necessary successive divisions or multiplies by 10. This cannot be tolerated in real time environments. Binary to Floating-Point Conversion If the location of the decimal point in the binary or hexadecimal number is known, the correction of the result is as follows: The resulting floating point number is divided by the constant 2n for binary numbers or 16m for hexadecimal numbers (with m = 0.25 n). This is made simply by subtracting n from the exponent of the floating-point number. Overflow or underflow is not possible due to the restricted range of the binary input (_240 +1 to +240 -1) compared to the range of the floating-point numbers (-1032 to +1032 ). EXAMPLE: The binary 32-bit signed number contained in the RAM locations starting at label BINHI (MSBs) is converted to a floating-point number (.DOUBLE format). The virtual decimal point of the binary input number is 5 bits left to the LSB. This means the integer input number is 32-times too large. For example, the binary butter contains 1011000 (8810) but the real number is 10.11000 (2.7510: 88/32 = 2.75) MOV #BINHI,RPARG CALL #CNV_BIN32 Address of binary buffer MSBs Call conversion subroutine SUB.B #S,leSP) Correct result's expo by 2 A S Continue with corrected number Binary-Coded Decimal (BCD) to Floating-Point Conversion If the location of the decimal point in the BCD number is known, the correction of the result is as follows: The resulting floating-point number is divided by the constant 1on after the conversion. Overflow or underflow is not possible due to the restricted range ofthe Software Applications 5-107 The Floating-Point Package BCD input number (-8 x 1011 +1 to +8 x 1011 -1) compared to the range of the floating-point numbers (-1032 to +1032). EXAMPLE: The BCD number contained in the RAM locations starting at label BCDHI (MSDs) is converted to a floating-point number (.FLOAT format). The virtual decimal point of the BCD input number is 3 digits left to the LSD. This means the integer input number is 1000-times too large. For example, the BCD buffer contains 123456 and represents the number 123.456 DOUBLE .EQU 0 MOV #BCDHI,RPARG Address of BCD buffer MSDs CALL #CNV_BCD_FP Call conversion subroutine MOV #FLT1000, RPARG Address of constant 1000 CALL #FLT_DIV Correct result by 1000 Continue with corrected input FLT1000 . FLOAT 1000 Correction constant 1000 If the location of the decimal point relative to the number's end is contained in a byte DPL (content> 0) the following code can be used. DOUBLE LOOP .EQU 1 MOV #BCDHI,RPARG Address of BCD buffer MSDs CALL #CNV_BCD_FP Call conversion subroutine Divide result by 10 as often - MOV #DBL10,RPARG CALL #FLT_DIV as DPL defines DEC.B DPL DPL - 1 JNZ LOOP Repeat as often as necessary Continue with corrected input DBL10 .DOUBLE 10 Correction constant 10 Floating Point to Binary Conversion If the binary result should contain n binary digits after the deci!T1al point then the following procedure may be used. The floating-point number is multiplied by the constant 2" before the conversion call. This is made simply by adding of n to the exponent of the floatingpoint number. Overflow can occur if the floating-point number is very large. A very large floating-point number cannot be converted to binary format. EXAMPLE: The floating-point number contained In the RAM locations starting at label FPHI (MSBs) is to be converted to a binary number (.FLOAT format). Four fractional bits of the resulting binary number should be included in the ra5-108 The F/o~t;rig-Po;nt Package suit. This means the result needs to be 16-times larger. For example, the floating-point number is 12.125 and the resulting binary number is 110000102 (C216) not only 11002 (C16)' DOUBLE .EQU MOV °FPHI,O(SP) MOV FPHI+2,2(SP) LSBs to TOS+2 ADD.B U,l(SP) Correct exponent by 2A4 MOV SP,RPARG Act. pointer (if not yet done) CALL iCNV_FP_BIN Call conversion subroutine MSBs of FP number to TOS Result includes 4 add. bits If the floating point number to be converted can be modified then a simplified code can be used. MOV #FPHI,RPARG Address of FP number MSBs ADD.B U,l(RPARG) Correct exponent by 2A4 CALL #CNV_FP_BIN Call conversion subroutine Result includes 4 add. bits Floating Point to BlnBry Coded DecImal Conversion If the BCD result of this conversion contains n digits after the decimal point, the following procedure can be used. The floating-point number is multiplied by the constant 10n before the conversion call. Overflow can occur if the floating-point number is very large. A very large floating-point number cannot be converted to BCD format due to the buffer length limit (12 digits maximum). EXAMPLE: The floating-point number contained in the RAM locations starting at label FPHI (MSBs) is converted to a BCD number (.DOUBLE format). Two fractional digits should be included in the BCD result. This means the BCD result needs to be 100-times larger. For example, the floating-point number is 12.12510, the resulting BCD number written to the TOS is 121210 (SW_RND = 0) respective 121310 (SW_RND = 1) not only 1210. DOUBLE . EQU 1 MOV iFPHI,RPARG Address of FP number (MSBS) MOV #DBL100,RPRES Address of constant 100 CALL #FLT_MUL FP number x 100 -> TOS CALL #CNV_FPJlIN Call conversion subro~tine Software Applications 5-109 The Flcating-Point Package Result includes 2 add. digits DBL100 5.6.7.4 .DOUBLE 100 Constant 100 Rounding and Truncation Two different modes for conversions can be selected during the assembly of the conversion subroutines. Truncation: Intermediate results of the conversion process are used as they are independent of the status of the next lower bits. This is the case if SW_RND =0 is selected during assembly. Rounding: Intermediate results of the conversion process are rounded depending on the status of the 1st bit not included in the current result (LSB-1). If this bit is set (1), the intermediate result is incremented. Otherwise, the result is not affected. If a carry occurs during the incrementing, the exponent is also corrected. Rounding is used if SW_RND = 1 is selected during assembly. Rounding is applied (when SW_RND =1) at the following conversion steps: Binary to Floating Point: .FLOAT: the MSB of the truncated word is added to the 24-bit mantissa .DOUBLE: all 40 Input bits are Included, no rounding is possible BCD to Floating Point: like with the binary to floating point conversion Floating Point to Binary: the 2-1 bit (the bit representing 0.5) of the floating point number is added to the binary Integer result Floating Point to BCD: The 2-1 bit (the bit representing 0.5) of the floating point number is added to the binary integer that is converted to a BCD number. If rounding Is specified during assembly (SW_RND =1), the ROM code of the conversion subroutines is approximately 26 bytes larger than with truncation selected (SW_RND =0). 5.6.7.5 Execution Cycles To illustrate how long data conversion takes, the required cycles for each conversion are given for the converted values 1 and the largest possible value (8 x 1011 -1 for BCD conversions and 240 -1 for binary conversions). The cycle count is given for the .FLOAT and for the .DOUBLE format and rounding is used. 5-110 The Floating-Point Package The cycle count for each conversion includes the loading of the pointer RPARG, the subroutine call and the conversion itself. Table 5-9. Execution Cycles of the Conversion Routines Conversion CNV BIN40 CNV BCD FP .FLOAT1 .FLOATmax .DOUBLE1 418 67 422 .DOUBLEmax 71 1223 890 1227 894 CNV_FP_BIN 535 67 531 63 CNV FP BCD 1174 706 1170 701 5.6.8 Memory Requirements of the Floating Point Package The memory requirements of an implemented floating-point package depend on the routines used and the precision applied. The following values refer to a completely implemented package. Truncation is used with the conversion routines. The given numbers indicate bytes. Table 5-10. Memory Requirements without Hardware Multiplier Package .FLOAT .DOUBLE Basic Arithmetic Operations 604 696 Conversion Subroutines 342 338 Complete FPP 946 1034 Table 5-11. Memory Requirements with Hardware Multiplier .FLOAT .DOUBLE Basic Ar~hmetic Operations 638 786 Conversion Subroutines 342 338 Complete FPP 980 1124 Package 5.6.9 Inclusion of the Floating-Point Package Into the Customer Software This section shows how to insert the floating-point package into the user's software. The symbolic definition of the working registers makes it necessary to include the FPP-definition file (FPPDEF4.ASM) before the customer's software. Otherwise, the assembler allocates an address word for every use of one of the working registers during the first pass of the assembler. During the second assembler pass, this proofs to be wrong and the assembler run fails. The two files FPP04.ASM and CNV04.ASM need to be located together as shown in the following examples. This is due to the common parts that are connected with jumps. The constant DOUBLE decides which FPP version is generated. It is assumed that the FPP files are located in a directory named c: \fpp . If this is not the case, then the name of this directory is to be used. Software Applications 5-111 The Floating-Point Package . text OeOOOh ROM/EPROM start address STACK .egu 0600h Initial value for SP DOUBLE Use .DOUBLE format FPP .egu 1 SW_UFLOW .egu 0 Underflow is no 'error SW_RND .egu 1 Use rounding for conversions HW..-MPY .egu 1 Use the hardware multiplier . copy c:\fpp\fppdef4.asm FPP Definitions . copy c:\fpp\fpp04.asm FPP file . copy c:\fpp\cnv04.asm FPP Conversions Customer software starts here START MOV #STACK,Si? Allocate stack User's SW starts here Power-up ~tart address: . sect "RstVect",OFFFEh . word START ; Reset vector A second possibility is shown in the following. The FPP is located after the user's software: . text OEOOOh ROM start address STACK .egu 0300h Initial value for SP DOUBLE .egu 0 Insert .FLOAT format FPP SW_UFLOW .equ 1 Underflow is an error SW_RND .egu 0 No rounding for conversions HW..-MPY .egu 0 No hardware multiplier . copy c:\fpp\fppdef4.asm Customer software starts here 5-112 FPP Definitions The Floating-Point Pa~e START MOV #STACK,SP Allocate stack . copy c:\fpp\fpp04.asm End of user's software Copy FPP file . copy c:\fpp\cnv04.asm Copy conversions Power-up start address: . sect "RstVect",OFFFEh . word START Reset vector 5.6.10 Software Examples The following subroutines for mathematical functions use the same conventions like the basic arithmetic functions described previously. o o RPARG points to the operand X for single operand functions (InX, eX) o The result of the operation is placed on the top of the stack, RPARG, RPRES and SP pOint to the result. RPRES points to the first operand (base) and RPARG to the second one if two operands are used (e.g. for the power function ab) 5.6.10.1 Square Root Subroutine The following subroutine shows the use of the floating-point package for the calculation of the square root of a number X. The NEWTONIAN approach is used: x.+/ = O.5x (:t. + x) x. The subroutine uses the RPARG register as a pOinter to the number X and places the result on the top of the stack. The algorithm used for the first estimation - exponentl2 and different correction for even and odd exponents - leads to the worst case estimation errors of +8% and -13%. This relatively exact estimations lead to only four iteration loops to get the full accuracy. The number range of X for the square-root function contains all positive numbers including zero. Negative values for X return the previous result on the top of the stack and the N bit set as an error indication. Software Applications 5-113 The Floating-Point Package The calculation errors for the square-root function are shown in the following table. They indicate relative errors. Table 5-12. Relative Errors of the Square Root Function X .FLOAT .DOUBLE Comment Smallest FPP number +3.Ox10-39 6.8><10-8 0.0 0 0 1.0 6.0 0 +5.4xlQ-9 0 +1.3x1Q-12 8.0 +3.4xl038 +6.7xl0-8 +4.6xlQ-9 +1.3xlQ-12 +2.2x1Q-11 Zero Largest FPP number Calculation times: .FLOAT with hardware multiplier: 2300 cycles 4 iterations .FLOAT without hardware multiplier: 2300 cycles (no multiplication used) .DOUBLE with hardware multiplier: 4000 cycles 4 iterations .DOUBLE without hardware multiplier: Square Root Subroutine XAO.S Call: MOV #addressX, RPARG CALL 4000 cycles Result on TOS - (@RPARG)AO.S RPARG points to address of X Call the square root function RPARG, RPRES and SP point to result XAO.S. N-bit for error Range: 0 -< X < 3.4xlOA+38 Errors: X < 0: N - 1 Result: previous result Stack: FPL + 2 bytes Calculates the square root of the number X, RPARG points to. SP, RPARG and RPRES point to the result on TOS FLT_SQRT .equ $ 5-114 TST.B o(RPARG) Argument negative? IN SQRTJRR Yes, return with N = 1 The Floating-Point Package MOV @RPARG+,2(SP) MOV @RPARG+,4(SP) ,if DOUBLE-l MOV @RPARG+,6(SP) Copy X to result area ,endif CLR HELP ,if DOUBLE=l TST 6(SP) JNE SQO Check for X 0 ,endif SQO TST 4(SP) JNE SQO TST 2(SP) JEQ SQ3 X PUSH #4 Loop count (4 iterations) pusa FPL+4(SP) Push X on stack for Xn PUSH FPL+4(SP) = 0: result 0, no error ,if DOUBLE=l PUSH FPL+4(SP) ,endif 1st estimation for XAO,s: exponent even: 0,5 x fraction + 0,5 exponent odd: fraction ,or, O,30h exponent/2 RRA,B l(SP) JC SQl Exponent even or odd? RRA,B @SP Exponent is even: Exponent/2 JMP SQ2 0,5 + 0,5 x fraction SQl BIS,B 030h,0(SP) Exponent is odd: correction SQ2 XOR,B #040h,1(SP) Correct exponent SQLOOP MOV SP,RPARG Pointer to Xn MOV SP,RPRES ADD #FPL+4,RPRES Pointer to X Software Applications 5-115 The Floatinf"~oint P~age . SUB #FPL,SP Allocate stack for result CALL #FLTJlIV X/xn ADD #FPL,RPARG Point to xn CALL #FLT....ADD X/xn + xn DEC.B l(RPRES) 0.5 x (X/xn +xn) = xn+l MOV @SP+,FPL-2(SP) xn+l -> xn MOV @SP+,FPL-2(SP) .if DOUBLE-l MOV @SP+,FPL-2(SP) .endif DEC FPL(SP) JNZ SQLOOP Decrement loop counter MOV @SP+,FPL+2(SP) N = 0 (FLTJ.DD) MOV @SP+,FPL+2(SP) Rpot to result space .if DOUBLE-l MOV @SP+,FPL+2(SP) .endif SQ3 ADD #2,SP Skip loop count BR #FLT_END To completion part #FN,HELP Root of negative number: N = 1 SQRT_ERR MOV JMP SQ3 5.6.10.2 Cubic-Root Subroutine The cubic root of a number is calculated the same as the square root, using the Newtonian approach. The formula for the cubic root of X is: Xn+l = .!~Xn 3 + .!.) x; The subroutine uses the RPARG register as a pointer to the number X and places the result on the top of the stack. The algorithm used for the first estimation - exponentl3 and a constant fraction value ±1.4 - leads to worst case estimation errors of +40% and -37%. This estimation leads to four (.FLOAT) or five (.DOUBLE) iteration loops to get the full accuracy. The number range of X for the cubic-root function contains all numbers including zero. No error is possible. 5-116 The Floating-Point Package The calculation errors for the cubic-root function are shown in the following table. They indicate relative errors. Table 5-13 Relative Errors of the Cubic Root Function .FLOAT 1.2xlo-a 0 1.7xl0-7 0 -1.7xl0-7 0 -1.2xlo-a X -3.4028xl ()38 -1.0 -2.9387xl0-39 0.0 +2.9387xl0-39 +1.0 +3.4028xl ()38 Comment .DOUBLE +2.2xl0-13 Most negative number 0 -3.8xl 0-13 0 +3.8xl0-13 -1.0 Least negative number Zero Least positive number +1.0 Most positive number 0 -2.2xl 0-13 Calculation times: .FLOAT with hardware multiplier: 5000 cycles .FLOAT without hardware multiplier: 6100 cycles .DOUBLE with hardware multiplier: 10200 cycles .DOUBLE without hardware multiplier: 12600 cycles Cubic Root Subroutine XA1/3 Call: MOV Result on TOS #addressX, RPARG CALL = 4 iterations 5 iterations (@RPARG)Al/3 RPARG points to X Call the cubic root function RPARG, RPRES, SP point to result Result on the top of the stack Formula: xn+l = 1/3(2xn + X x xnA-2) Range: No errors possible Errors: Stack: 2 x FPL + 2 bytes Calculates the cubic root of the number X, RPARG points to. SP, RPARG and RPRES point to the result on TOS Software Applications 5-117 Th,; ~/oatlng-Poi..nt Package @RPARG+,2(SP) MOV @RPARG+, 4 (SP) . . if DOUBLE-1 MOV @RPARG+,6(SP) Copy X to result area . end if .if DOUBLE=l TST 6(SP) Check for x - ° JNE CBO .endif TST 4(SP) JNE CBO TST 2(SP) JEQ CB3 CBO x = 0: result 0 .equ $ .if DOUBLE-O Loop count PUSH #4 .FLOAT #5 .DOUBLE 5 iterations PUSH FPL+4(SP) Push X on stack for Xn PUSH FPL+4(SP) 4 iterations .else PUSH . end if .if DOUBLE=l PUSH FPL+4(SP) .endif 1st· estimation for DCL$l 5-118 X~1/3: exponent/3, fraction +-1.4 MOV.B l(SP) ,RPARG Exponent of X OOxx AND #OeOh,O(SP) Only sign of X remains ADD #Oe034h,0(SP) +-1.4 for 1st estimation TST.B RPARG Exponent's sign? IN DCL$2 positive DEC.B l(SP) Neg. exp.: exponent - 1 ADD.B #3,RPARG Add 3 until OaOh is reached IN CBLOOP OaOh is reached, The Floating-Point Package JMP DCL$l DCL$3 INC.B l(SP) Pos. exp.: exponent + 1 DCL$2 SUB.B #3, RPARG Subtr. 3 until oaOh is reached IN DCL$3 Continue MOV SP,RPARG Point to xn MOV SP,RPRES CBLOOP Continue SUB #FPL,SP Allocate stack for result CALL #FLT_MUL xn"2 ADD #2*FPL+4,RPRES Point to A CALL #FLT_DIV X/xn h 2 xn·x 2 INC.B FPL+l(SP) ADD #FPL,RPARG Point to 2xn CALL #FLT_ADD X/xn h 2 + 2xn MOV #FLT3,RPARG 1/3 x (X/xnh2 + 2xn) CALL #FLT_DIV MOV @SP+,FPL-2(SP) MOV @SP+,FPL-2(SP) .if DOUBLE=l MOV @SP+,FPL-2(SP) xn+1 xn+1 -> xn . end i f DEC FPL(SP) JNZ CBLOOP Decr. loop count MOV @SP+,FPL+2(SP) Result to result area MOV @SP+,FPL+2(SP) Cubic root to result space .if DOUBLE=l MOV @SP+,FPL+2(SP) .endif CB3 FLT3 ADD #2,SP CLR HELP No error BR #FLT_END Normal termination .if DOUBLE-l . DOUBLE 3.0 Skip loop count Constant for cubic root .else FLT3 . FLOAT 3.0 Software Applications 5-119 The Ff?Btlng-Polnt Package .endif 5.6.10.3 Fourth-Root Subroutine The fourth root of a number is calculated by calling the square root subroutine twice. EXAMPLE: the fourth root is calculated for a number residing in RAM at address NUMBER (MSBs). The fourth root is written to RESULT. The previous result on TOS must not be overwritten. SUB #ML/8+1,SP Allocate work area MOV ·#NUMBER,RPARG Address of NUMBER to RPARG CALL tFLT_SQRT Square root of NUMBER on TOS IN ERROR NUMBER is negative Fourth root on TOS CALL #FLT_SQRT MOV @SP+,RESULT 4th root MSBs MOV @SP+,RESULT+2 Correct SP to previous result .if DOUBLE=l MOV @SP+,RESULT+4 LSBs for DOUBLE .endif 5.6.10.4 Other Root Subroutines Using the same calculations shown previously, higher roots can also be calculated using the Newtonian approach. The generic formula for the mth root out of A is: X.+l = .!...«m-l)x. m + x:A_J To get short calculation times - which means only few iterations are necessary - the choice of the first estimation xo is very important. For the above formula a good first iteration Xo is (M = mantissa, E = exponent): xo = (M-1) (-m-- + 1) X 2 E1m 5.6.10.5 Calculet/ons WIth Intermedlste Results If a calculation cannot be executed simply and has intermediate results, a new result space is used. This is done by subtracting 4 (.FLOAT) or 6 (.DOUBLE) from the stack pointer. 5-120 The Floating-Point Package EXAMPLE: The following function for e is to be calculated. The example is valid for both formats: e = axb FPL - c d .equ (ML/8)+1 Length of a FPP number SUB #FPL,SP Allocate result space 0 (RSO) MOV #a,RPRES Address argument 1 MOV #b,RPARG Address argument 2 CALL #FLT_MUL a x b -> RSO SUB #FPL,SP Allocate result space 1 (RSl) MOV #c,RPRES Address c MOV #d,RPARG Address d CALL #FLTJ)lV c/d -> RSl ADD #FPL,RPRES Address (a x b) in RSO CALL #FLT_SUB e - MOV @SP+,FPL-2(SP) Result e to RSO MOV @SP+,FPL-2(SP) Overwrite (a x b) with e .if DOUBLE-l MOV @SP+,FPL-2(SP) (a x b) - c/d -> RSl LSBs for DOUBLE .endif Housekeeping is made, SP pOints to RSO again, but not RPARG and RPRES EXAMPLE: The multiply-and-add (MAC) function for e shown in the following is calculated. The example is written for both formats: en+1 = axb + en SUB #ML/8+l,SP Allocate result space MOV h,RPRES Address argument 1 MOV #b,RPARG Address argument 2 CALL #FLT_MUL a x b MOV #e,RPARG Address e CALL #FLT_ADD (a x b)+ e Software Applications 5-121 MOV @RPARG+,e Actualize e with result MOV @RPARG+,e+2 MIDs or LSBs .if DOUBLE-l MOV @RPARG+,e+4 LSBs' .endif SP and RPRES still point to the result, RPARG may be used for the next argument address. 5.6.10.6 Absolute Value of a Number If the absolute value of a number is needed, this is done by simply resetting the sign bit of the number. EXAMPLE: the absolute value of the result on the top of the stack is needed. BIC I result I on TOS #080h,O{SP) 5.6. 10.7 Change of the Sign of a Number If a sign change is necessary (multiplication by -1), this is done by simply inverfing the sign bit of the number. EXAMPLE: the sign of the result on the top of the stack is changed. XOR #080h,O{SP) ; Negate result on TOS 5.6.10.8 Integer Value of a Number The integer value of a floating-point number can be calculated with the subroutine FLT_INTG in the following example. The pointer RPARG is loaded with the address of the number. The result is then placed on the top of the stack. No error is possible. Numbers below one are returned as zero. The subroutine can handle .FLOAT and .DOUBLE formats. Calculate the integer value of the number RPARG points to. Result: on top of the stacK. RPARG, RPRES and SP point to it Call MOV #number, RPARG CALL Address to RPARG Call subroutine Result on TOS FLT_INTG MOV.B MOV 5-122~ 1 (RPARG) ,COUNTER Exponent to COUNTER @RPARG+,2{SP) MSBs and Exponent The Floating-Point Package MOV @RPARG+,4(SP) .if DOUBLE-l LSBs . FLOAT MOV @RPARG,6(SP) LSBs . DOUBLE MOV #OFFFFh,ARG2_MSB Mask for fractional part .if DOUBLE=l MOV #OFFFFh,ARG2_MID .endif .endif INTGLP MOV #OFFFFh,ARG2_LSB JMP L$30 CLRC Shift 0 in always RRC.B ARG2-.MSB .if DOUBLE=l RRC ARG2_MID Shift mask to next lower bit .endif L$30 RRC ARG2_LSB DEC COUNTER Shift as often as: CMP #OaOh,COUNTER SHIFT COUNT JHS INTGLP BIC ARG2_MSB,2(SP) .if DOUBLE-l BIC ARG2-.MID,4(SP) BIC ARG2_LSB,6(SP) = EXPONENT - 07Fh Mask out fracto part For .DOUBLE format .else BIC ARG2_LSB,4(SP) For .FLOAT format MOV SP,RPARG Both pointer to result's MSBs ADD #2,RPARG MOV RPARG,RPRES .endif RET ; Return with Integer on TOS EXAMPLE: the integer value of the floating pOint number residing at address VOL1 is placed on TOS. MOV #VOLl,RPARG Load pointer with address CALL #FLT_INTG Calculate integer of VOLl Software Applications 5-123 The Floating-Point Package Integer on TOS 5.6.10.9 Fractional Part of a Number The fractional part of a floating-point number can be calculated with the subroutine FLT]RCT in the following example. The pointer RPARG is loaded with the address of the number. The result Is placed on the top of the stack. No error is possible. The subroutine can handle both floating-point formats. The subroutine calls the subroutine FLT_INTG shown previously. Integer values or very large numbers return a zero value due to the given resolution. The Floating-Point Package EXAMPLE: the fractional part of the floating-point number R5 points to is placed on TOS. MOV R5,RPARG Load pointer with address CALL #FLT_FRCT Calculate fractional part Fractional part on TOS 5.6.10.10 Approximation of Integrals Simpson's Rule states that the area A limited by the function f(x), the x-axis, Xo and xN is approximately: yO f---Jr -+x Figure 5-29. Function ((x) The subroutine SIMPSON, in the following code, processes N+1 inputs pointed to by register RPARG and computes the area A after the measurement of sample N. The result is written back to the RAM location A. This integration method can be used for the calculation of the apparent power with electronic electricity meters. The absolute values of current and voltage are added up and are multiplied afterwards. . Subroutine for the approximation of integrals. Samples yO to yN are processed and stored in location A. Nmax = 254 (if larger, a word has to be used for INDEXn) Software Applications 5-125 The F~t;ng-Polnt P~e Call: CLR.B INDEXn Before 1st call: n - 0 LOOP MOV #sample, RPARG Address of yn CALL #SIMPSON Process sample yn eMP.B #N+l,INDEXn YN processed? JLO LOOP No, proceed Yes, integral in A Max. index (must be even) .equ 8 .if DOUBLE=O A .equ 0200h summed up value (integral) INDXn ,equ 0204H Index n (0 to N) FLT3 . float 3.0 . float 0.32 Difference h: yn+1 - yn N h .else A .equ 0200h Summed up value (integral) INDXn .equ 0206H Index n (0 to N) FLT3 . double 3.0 . double 0.32 Difference h: yn+1 - yn h .endif SIMPSON SUB #(ML/8)+1,SP Allocate new workspace MOV @RPARG+,O(SP) Fetch yn MOV @RPARG+,2(SP) .if DOUBLE=l MOV @RPARG,4(SP) .endif YEVEN 5-126 CMP.B #O,INDXn JEQ YO CMP.B iN, INDXn JEQ YN 1st value yO? Last value yN? BIT n,INDXn JZ YEVEN INC.B l(SP) Odd: value x 4 INC.B l(SP) ,Even: value x 2 MOV #A,RPARG Fetch summed-up value A MOV SP,RPRES New sample yn on TOS Odd or even n? The Floating-Point Package YN YO CALL lfFLT_ADD Add it'to A JMP YO Store added result in A MOV #A,RPARG Last value yN: calculate MOV SP,RPRES New sample yn on TOS CALL #FLTj.DD Add last result to A To constant 3.0 MOV #FLT3,RPARG CALL #FLT_DIV Divide summed-up value by 3.0 MOV #h,RPARG Multiply with distance h CALL #FLT_MUL MOV @SP+,A Store result to A MOV @SP+,A+2 and correct stack .if DOUBLE-l MOV @SP+,A+4 .endit INC.B INDXn Next n RET Return with integral in A EXAMPLE: The function f(x) described by the calculated results on top of the stack is integrated using Simpson's rule .. CLR.B INDXn Initialization: INDXn = 0 INTLOP Calculation, result on TOS CALL #SIMPSON Process samples yO to yN CMP.B #N+l, INDXn Last sample yN processed? JLO INTLOP No, continue Yes, result in A 5.6. 10. 11Statistlcal Calculations The mean value, the standard deviation, and the variance of measured samples can be calculated with the following subroutines. , o o STAT_INITclears the RAM locations used for data gathering. STAT_PREP adds the input sample to the RAM location SUMYi, the squared input sample to SUM2Yi and increments the sample counter N. Software Applications 5-127 Th~ Floating-Point ".ackage o STAT_CALC calculates mean, standard deviation, and variance from these three values and writes them back to the RAM locations used for data recording. i=N ~> Mean Value = .!::LN I=N Variance = StandardDeviation = = i=1 i=l N-J i=1 N N 1=1 I=N LYI 2 -MeanValuex LYI IVariance x V N N-J RAM locations for the input samples: N .equ 0200h Number of input samples (binary) SUMYi .equ N+(ML/8)+1 Summed-up samples yi SUM2Yi .equ SUMYi+(ML/8)+1 Sum of squared samples yi The same RAM-locat'ions are used for the three results: MEANV .equ N STDDEV .equ SUMYi Standard Deviation after return SUM2Yi Variance after return VARIANCE .equ FLTl .if DOUBLE-l . DOUBLE 1.0 .else FLTl . FLOAT . end i f 5-128 1.0 Mean Value after return Floating 1. 0 The Floating-Point Package STAT_INIT initializes the RAM-locations for statistics STAT_INIT CLR N Clear sample counter CLR SUM2Yi Clear sum of squared samples CLR SUM2Yi+2 .if DOUBLE=l CLR SUM2Yi+4 .endif CLR SUMYi CLR SUMYi+2 .if DOUBLE=l CLR SUMYi+4 Clear sum of input samples . end if RET STAT_PREP sums-up the sample pointed to by RPARG in SUMYi (summed-up yi) and in SUM2Yi (summed-up squared yi) . The binary sample counter N is incremented STAT_PREP PUSH RPARG Save address of input sample SUB #(ML/B)+1,SP Allocate stack space Copy input sample address MOV RPARG,RPRES CALL #FLTJ«JL (yi)A2 MOV #SUM2Yi,RPRES Add (yi)A2 to SUM2Yi CALL #FLT_ADD (yi)A2 + SUM2Yi MOV @SP,SUM2Yi Sum back to SUM2Yi MOV 2(SP),SUM2Yi+2 .if DOUBLE=1 MOV 4(SP),SUM2Yi+4 .endif MOV (ML/B)+1(SP),RPARG MOV #SUMYi,RPRES CALL #FLTj.DD ; Fetch sample address Add yi to SUMYi MOV @SP+,SUMYi Summed-up yi MOV @SP+,SUMYi+2 House keeping .if DOUBLE=1 MOV @SP+,SUM2Yi+4 Software Applications 5-129 The Floating-Point Package . end i f ADD #2,SP Remove sample address INC N Increment N RET STAT_CALC calculates the Mean Value, the Variance and the Standard Deviation from the N samples input to the subroutine STAT_PREP. The three calculated statistical values are stored in: Mean Value: N Variance: SUM2Yi Standard Deviation: STAT_CALC SUMYi SUB #(ML/8)+1,SP ; Allocate stack space MOV #N,RPARG CALL #CNV_BIN16U Binary to FPP on TOS SUB # (ML/8)+1 ,SP To save N on stack MOV #SUMYi,RPRES Summed-up yi/N CALL #FLT_DIV Mean Value on TOS Store Mean Value MOV @SP,MEANV MOV 2(SP),MEANV+2 .if DOUBLE=l MOV 4 ( SP) ,MEANV+4 Convert N to FP-format .endif The Mean Value on TOS is used for the calculation of the Variance: Variance = (Sum(yiA2) - Mean Value x Sum(yi)/N)/N 5-130 MOV #SUMYi,RPARG CALL #FLTJIDL MOV #SUM2Yi,RPRES To Sum(yiA2) CALL #FLT_SUB Sum(yiA2) ADD # (ML/8)+l,RPARG Point to N CALL #FLT.J>IV Varia!'ce on TOS MOV @SP,VARIANCE Store Variance Mean Value x Sum(yi) - MY x Sum(yi) TheF~~P~ntPackage MOV 2(SP),VARIANCE+2 .if DOUBLE=l MOV 4(SP),VARIANCE+4 .endif The Variance on TOS is used for the calculation of the standard Deviation: Std Dev. ~ SQUROOT(Variance x N/(N-l) ADD #(ML/8)+l,RPARG Point to N CALL #FLT_MUL Variance x N MOV @SP+,STDDEV Store value for later use MOV @SP+,STDDEV+2 .if DOUBLE=l MOV @SP+,STDDEV+4 .endif MOV #FLTl,RPARG Build N-l MOV SP,RPRES point to N CALL #FLT_SUB N-l on TOS MOV #STDDEV,RPRES point to (Variance x N) CALL #FLT_DIV Variance x N/(N-l) CALL #FLT_SQRT StdDev = SQROOT(Var x N/(N-l» MOV @SP+,STDDEV store Standard Deviation MOV @SP+,STDDEV+2 .if MOV DOUBLE~l @SP+,STDDEV+4 .endif RET EXAMPLE: The normal calling sequence for the statistical calculations is shown In the following. The input samples are contained in the ADC-result registerADAT. STATLOP CALL #STAT_INIT Initialization: clear used RAM MOV #ADAT, RPARG Set pointer to ADC-result CALL #CNV_BINl6U Convert ADC-result to FP on TOS CALL #STAT_PREP Process samples yl to yN Continue Software Applications 5-131 The Floating-POfnt Package CMP.B #xx,N yN processed? JLO STATLOP No, next sample N samples are pre-processed: Calculate Mean Value, Variance, and Standard Deviation out of SUMYi, SUM2Yl and N CALL Call calculation subroutine Results in"sample locations 5.6.10.12 Complex Calculations Complex numbers of the form (a + jb) can be used in calculations also. The four basic arithmetic operations are shown for complex numbers. Pointers RPARG and RPRES are used in the same way as with the normal FPP subroutines. They point to the real parts of the complex numbers used for input and to the result on the TOS after the completion of the subroutine. The real and imaginary part of a complex number need to be allocated in the way shown in Figure 5-30 (shown for .FLOAT format). Stack Usage: The subroutines need up to 36 bytes (.DOUBLE) or 28 bytes (.FLOAT) of stack space (complex division). Not included in this numbers is the initially allocated result space. No error handling is provided. It is assumed that the numbers used stay within the range of the floating-point package. Stack COnfiguration AcIdr8as n SP During MAIN Program Add..... n-4 Irna Ina Part MS8s Add..... !HI Real Part Return CMPLX-xxx Addre18 n·12 AdditIOn Result Space AcIdr8as~x~__________~I_ l ....: SP Alter Return RAM/ROM COnfiguratIOn '= ~_ ~ AcIdr8as n+8 Imaginary Part Add..... n+4 MS8s ",M_ Figure 5-30. Complex Number on TOS and in Memory (.FLOAT Format) FPL .equ (ML/B)+l ; Length of an FP-number (bytes) ; Complex calculation is made with the complex numbers RPARG 5-132 The Floating-Point Package and RPRES point to. Call: MOV #argl,RPRES MOV #arg2,RPARG Address argument1 Address argument2 CALL #CMPLJCxxx Calculate arg1 op arg2 Result on TOS. Pointed to by SP, RPARG and RPRES Complex Subtraction: (a + jb) - (c + jd). @RPRES - @RPARG. Stack Usage: 16 bytes (.DOUBLE) CMPLX_SUB MOV JMP 12 bytes (.FLOAT) #OFFFFh,HELP Define subtraction CL$1 To common part Complex Addition: (a + jb) + (c + jd). @RPRES + @RPARG Stack Usage: 16 bytes (.DOUBLE) 12 bytes (.FLOAT) CMPLX....ADD CLR HELP Define addition CL$1 PUSH RPRES Save argument pointer .if DOUBLE=l PUSH lO(RPARG) LSBs imaginary part d PUSH 8 (RPARG) MIDS imaginary part d PUSH 6 (RPARG) The coming words depend on PUSH 4 (RPARG) DOUBLE PUSH 2 (RPARG) LSBs real part c .endif PUSH @RPARG MSBs real part c TST HELP Addition or subtraction? JZ CA Subtraction: the complex number (c + jd) is negated CA XOR #080h,O(SP) XOR #080h,FPL(SP) MOV SP,RPARG Point to c CALL IIFLT_ADD Add real parts (a + c) Negate real part c .; Negate imaginary part d Software Applications 5-133 Th~ :Ioating-Point Package MOV @SP+,2*FPL+2(SP) To real storage MOV @SP+,2*FPL+2(SP) Housekeeping .if DOUBLE=l MOV @SP+,2*FPL+2(SP) .endif MOV SP,RPARG MOV FPL(SP),RPRES Point to d Restore RPRES ADD IIFPL,RPRES To imaginary part b Add imaginary parts (b + d) CALL #FLT~D MOV @SP+,2*FPL+2(SP) To imaginary storage MOV @SP+,2*FPL+2(SP) Housekeeping .if DOUBLE=l MOV @SP+,2*FPL+2(SP) .endif ADD #2,SP Skip saved RPRES JMP CMPLX_RT Result on TOS Complex Division: (a + jb)/(c + jd). @RPRES/@RPARG The Complex Division uses the inverted divisor and the multiplication afterwards: (a + jb)/(c + jd) - (a + jb) x l/(c + jd) with: l/(c + jd) - (c " ~ jd)/(C A 2 + ·d A 2) Stack Usage: 36 bytes (.DOUBLE) CMPLXJ)IV PUSH 5-134 RPRES 28 bytes (.FLOAT) Save RPRES (dividend a + jb» PUSH RPARG Save RPARG (divisor·c + jd) SUB #FPL,SP Allocate result space MOV RPARG,RPRES Fetch real part c CALL #FLT_MUL c 2 A SUB #FPL,SP Allocate result space MOV 2*FPL(SP),RPARG Fetch imaginary part d ADD #FPL, RPARG MOV RPARG,RPRES Copy address of d CALL tFLT_MUL dA2 ADD #FPL,RPARG to c A 2 The Floating-Point Package CALL #FLT_ADD c A 2 + dA 2 PUSH FPL(SP) Copy c A 2 + d A 2 PUSH FPL(SP) .if DOUBLE-1 PUSH FPL(SP) .endif MOV SP,RPARG MOV 3*FPL(SP), RPRES To (c2 +d2) Pointer to (c + jd) ADD #FPL,RPRES Address d CALL flFLT_DIV d/(c A 2 + d A 2) imago part XOR flOBOh,O(SP) -d/(c A 2 + d2) MOV @SP+,2*FPL-2(SP) store imaginary part MOV @SP+,2*FPL-2(SP) to final location .if DOUBLE=l MOV @SP+,2*FPL-2(SP) .endif MOV SP,RPARG MOV 2*FPL(SP),RPRES To copy of c A 2 + d A 2 To (c + jd) CALL #FLT_DIV c/(c A 2 + d2) Prepare the interface to the multiplication and call it: RPARG pOints to l/(c + jd) RPRES points to CDIVL yet made by FLT_DIV (a + jb) MOV 2*FPL+2(SP),RPRES ; CALL #CMPLX_MUL (a +jb) x l/(c +jd) MOV #FPL, HELP Result to final location MOV @SP+,2*FPL+4(SP) DEC HELP JNZ CDIVL JMP CMPLX_RET address of (a + jb) To common housekeeping Complex Multiplication: (a + jb}x(c + jd). @RPRES x @RPARG ;(a + jb)x(c + jd) = ac + jad + jbc - bd ; Stack Usage: 24 bytes (.DOUBLE) 1B bytes (.FLOAT) Software Applications 5-135 The F1:?!tlng-Polnt Package CMPLXJIDL PUSH PUSH RPRES Save pointer to (a + jb) RPARG Save pointer to (c + jd), real Part ac - bd SUB #FPL,SP CALL #FLTJ4UL a x c SUB #FPL,SP Allocate result space for b x d MOV 2*FPL(SP),RPARG To c + jd MOV 2*FPL+2 ('SP) , RPRES To a + jb ADD #FPL,RPARG To jd ADD #FPL,RPRES To jb CALL #FLTJIDL jb x jd ADD #FPL,RPRES To a x c CALL #FLT_SUB (a x c) - (b x d) MOV @SP,FPL(SP) Store ac - bd MOV 2(SP),FPL+2(SP) .if DOUBLE~l MOV 4(SP),FPL+4(SP) Allocate result space for a x c -bd .endif Imaginary Part j(ad + be) 5-136 MOV 2*FPL(SP),RPARG To c + jd MOV 2*FPL+2(SP),RPRES To a + jb ADD #FPL,RPARG To jd CALL a x d SUB #FLTJIDL #FPL,SP Allocate result space for b x c MOV 3*FPL(SP),RPARG To c + jd MOV 3*FPL+2(SP),RPRES To a + jb ADD #FPL,RPRES To b CALL #FLTJIDL b xc ADD #FPL,RPARG To a x d CALL #FLTJDD ad + bc MOV @SP+,4*FPL+4(SP) To imaginary result MOV @SP+,4*FPL+4(SP) .if DOUBLE-l MOV @SP+,4*FPL+4(SP) .endif ADD #FPL,SP To real result MOV @SP+,FPL+4(SP) To real result MOV @SP+,FPL+4(SP) .if MOV DOUBLE=l .@SP+,FPL+4(SP) .endif RPARG, RPRES and SP point to the real part of the result on the TOS CMPLX_RET ADD #4,SP CMPLX_RT MOV SP,RPARG ADD #2,RPARG MOV RPARG,RPRES Skip pointers RET EXAMPLE: The complex number at address CN1 is divided by a complex number at address CN2. The result (on TOS) is added to a RAM value CST3 and stored there. SUB #2*FPL,SP Allocate result space MOV #CN1,RPRES Address of CNl MOV #CN2,RPARG Address of CN2 CALL #CMPLX..J)IV CN1/CN2 -> TOS MOV #CST3,RPARG Address of CST3 CALL #CMPLX.-ADD CN1/CN2 + CST3 -> TOS MOV @RPARG+,CST3 Store result in CST3 MOV @RPARG+,CST3+2 Save result space MOV @RPARG+,CST3+4 MOV @RPARG+,CST3+6 .if DOUBLE-l MOV @RPARG+,CST3+8 Software Applications 5-137 The Package , Floating-Point . MOV@RPARG+,CST3+10 .endif Continue wi·th complex calc. ADD #2*FPL,SP Terminate complex calc. 5.6.10.13 Trigonometric and Hyperbolic Functions Four subroutines are shown for the calculation of ~he sine, cosine, hyperbolic sine, and hyperbolic cosine. All four subroutines use the same kernel, only the initialization part is different for each of them. Expansion in series is used for the calculation. The formulas are (X is expressed in radians): Sine function: n X2n-1 sin X = " ( 1)n+1 k(2n-l)/ - Cosine function: cos X n = x2n L-x(-lr o (2n)! Hyperbolic sine function: • n smhX = X2n-1 L(2n-1!) 1 Hyperbolic cosine function: coshX= • x Lo (2n)! 2• The number r.ange for X is ±2n: for all four functions. Outside of this range, the error increases relatively fast due to the fast growing terms of the sequences (x2n and x2n+1). If the trigonometric functions have to be calculated for numbers outside of this range, two possibilities exist: o 5-138 Sine and cosine: addition or subtraction of 2n: until the number X is back in the range ±2n:. The subroutine FLT_RNG can be used for this purpose. The Floating-Point Pac:.~?e o Hyperbolic sine and cosine: increase of the software variable Nmax (normally 30.0. see the following software) that defines the number of iterations. If this variable is changed to 120.0 (60 iterations). the deviations in the range 10-12 (.DOUBLE format) or. 10-6 (.FLOATformat) are possible for X input values up to 65. The input number that delivers results near the maximum numbers ±1038• Note: The following subroutines are optimized for ROM space and accuracy. but not for run time. They are not intended as part of a floating point package. but as a place to begin if needed. The calculation errors for the trigonometric functions are shown in the following table. They indicate absolute errors; the difference to the correct values. Table 5-14. Angle X Errors of the Trigonometric Functions .FLOAT ±7t Sin 0 -21 x 10-9 3.8 x 10-9 ±21t -1.3 x 10-6 0 ±1cI2 .DOUBLE Cos -20 x 10-9 -64 x 10-9 -225 x 10-9 2xl0-6 Sin - Cos 0 0 0 -SOx 10-12 0 0 0 0 The errors of the hyperbolic functions are shown in the following table. They indicate relative errors. The differences to the correct values are related to the correct values. Table 5-15. Errors of the Hyperbolic Functions Angle X 0 ±JrI2 ±7t ±211: .FLOAT .DOUBLE Hyperbolic Sine Hyperbolic Cosine Hyperbolic Sine Hyperbolic Cosine 0 85 x 10-9 55 x 10-9 34 x 10-9 0 160 x 10-9 100 x 10-9 218 x 10-9 0 -126 x 10-12 -242 x 10-12 -153x 10-12 0 255 x 10-12 -474x-10-12 -309 x 10-12 Calculation times (Nmax = 30.0: 15 iterations). The number of cycles is the same one for all four functions: .FLOAT with hardware multiplier: 18000 cycles .FLOAT without hardware multiplier: 26000 cycles .DOUBLE with hardware multiplier: 28000 cycles Software Applications 5-139 The Floating-Point Package .DOUBLE without hardware multiplier: 42000 cycles Sine, Cosine, Hyperbolic Sine, Hyperbolic Cosine of X (radians) Call: MOV #addressX, RPARG RPARG points to operand X CALL # FPP.-xxx ; Call the function RPARG, RPRES, SP point to result Range: -2xPi < X < +2xPi for larger numbers FAST loss of accuracy Stack allocation: (4 x FPL + 4) words are needed (Basic FPP Functions are included) Initialization for the trigonometric and hyperbolic functions +--------------+-------+-------+--------+-----~--+ 1 INIT 1 'sin X 1 cos X 1 sinh X 1 cosh X I. +--------------+-------+-------+--------+--------+ Sign Mask 1 n qaoh OaOh OOOh OOOh 1.0 0.0 1.0 0.0 1.0 X 1.0 1.0 X 1.0 Series Term X Result Area X 1 +--------------+-------+-------+--------+--------+ FPL .equ (ML/a)+l Length of FPP numbers (bytes) Floating Point Sine Function: Result on TOS - SIN(@RPARG) Prepare the stack with the initial constants #80h JMP Sign mask (toggle) SINc Hyperbolic Sine Function: Result on TOS SINc PUSH #OOh Sign mask (always pos.) #0 n: 1 .if DOUBLE=! 5-140 SINH(@RPARG) The Floating-Point Package PUSH #0 .endif PUSH .if #oaOOOh .FLOAT 1.0 DOUBLE~l PUSH 4 (RPARG) Series term: X .endif PUSH 2 (RPARG) PUSH @RPARG JMP TRIGCOM To cormnon part Floating Point Cosine Function: Result on TOS COS(@RPARG) Prepare the stack with the initial constants taOh JMP Sign mask (toggle) COSc Hyperbolic Cosine Function: Result on TOS = COSH(@RPARG) FLT_COSH PUSH #OOh Sign mask (always pos.) COSc # n: 0 PUSH .if DOOBLE~l PUSH #0 .endif PUSH . if tOOh .FLOAT 0.0 DOUBLE~l PUSH #0 Series term: 1.0 .endif PUSH #0 PUSH #OaOOOh .FLOAT 1.0 Cormnon part for sin X, cos X, sinh X and cosh X The functions are realized by expansions in series TRIGCOM .equ $ Software Applications 5-141 The Floating-Point p'~e .if DOUBLE=l PUSH 4 (RPARG) Push X onto stack (gets XA2) PUSH 2 (RPARG) XA2 is calculated once PUSH @RPARG MOV RPARG,RPRES Both pOinters to X CALL #FLT_MUL XA2 to actual stack Copy series term to result space .endif ADD #FPL, RPARG MOV @RPARG+,3*FPL+4(SP) MOV @RPARG+,3*FPL+6(SP) ; is X or 1.0 .if DOUBLE-l MOV @RPARG+,3*FPL+8(SP) .endif SUB #FPL,SP MOV SP,RPRES Result space for calculations The actual series term is multiplied by XA2/(n+l)x(n+2) to get the next-series term TRIGLOP MOV #FLT2,RPARG Address of .FLOAT 2.0 ADD #3*FPL,RPRES' Address n CALL #FLT_ADD n + 2 MOV @RPARG+,3*FPL(SP) (n+2) -> n MOV @RPARG+,3*FPL+2(SP) .if DOUBLE=l MOV @RPARG+,3*FPL+4(SP) .endit Build (n+l)x(n+2) for next term. (n+2)A2 - (n+2) 5-142 (n+l)x(n+2) MOV RPRES, RPARG CALL #FLT_MUL (n+2)A2 ADD t3*FPL,RPARG Point to old n CALL #FLT_SUB (n+2)A2 -(n+2) = (n+l)x(n+2) Both point to (n+2) The Floating-Paint Package The series term is divided by (n+l)x{n+2) ADD #2*FPL,RPRES Point to series term CALL #FLT_DIV Series term/{n+l)x{n+2) ADD #FPL,RPARG Point to xh2 CALL #FLTJWL ST x Xh2/{n+l)x{n+2) IN TRIGERR Error, status in SR and HELP The sign of the new series term is modified dependent on the sign mask. 0: always positive 080h: alternating + XOR 4*FPL{SP),O{SP) Modify sign with sign mask MOV @RPARG+,2*FPL{SP) Save new series term MOV @RPARG+,2*FPL+2{SP) .if DOUBLE=l MOV @RPARG+,2*FPL+4{SP) .endif ADD #3*FPL+4,RPARG Point to result area CALL #FLT-ADD Old sum + new series term MOV @RPARG+,4*FPL+4{SP) MOV @RPARG+,4*FPL+6{SP) ; Result to result area .if DOUBLE=l MOV @RPARG+,4*FPL+8{SP) .endif Check if enough iterations are made: iterations Nmax/2 CMP Nmax,3*FPL{SP) Compare n with Nmax JLO TRIGLOP Only MSBs are used Expansion in series done. Error indication (if any) in HELP The completion part of the FPP is used TRIGERR ADD #4*FPL+2,SP Housekeeping: free stack BR #FLT_END To completion part of FPP Software AppHcatlons 5-143 The Floating-Point Package .if FLT2 DOUBLE~l .DOUBLE 2.0 constant 2.0 .else FLT2 . FLOAT 2.0 .endif Nmax . FLOAT 30.0 ; Iterations x 2 (NSBs used only) 5.6.10.14 Other Trigonometric and Hyperbolic Functions With the previous calculated four functions (sin, cosin, hyperbolic sin, and hyperbolic cosin), five other important functions can be calculated: tangent, cotangent, hyperbolic tangent, hyperbolic cotangent, and exponential functions. tan X = sinX cot X cos X eX = = cosX sin X X· L -;;! tanhX =sinhX -- coth X cosh X = cosh X sinh X = sinh X+ cosh X To calculate one of the five functions, the two functions it consists of are calculated and combined. The errors ofthe five functions can be calculated with the errors ofthetwo functions used and are shown in Table 5-14 and Table 5-15: o tan X, cot X, tanh X and coth X: the resulting error is the difference of the two errors o exp X: the resulting error is the sum of the two errors Calculation times (Nmax = 30.0: 15 iterations). The number of cycles is the same one for all five functions: .FLOAT with hardware multiplier: 36000 cycles .FLOAT without hardware multiplier: 52000 cycles .DOUBLE with hardware multiplier: 56000 cycles .DOUBLE without hardware multiplier: 84000 cycle$ The same software kernel is used for all five functions. The number contained in R4 decides which function is executed. The range for all five functions is ±27t. For larger numbers a relatively fast loss of accuracy occurs. 5-144 The Floating-Point Package Tangent of X (radians) Call: MOV #addressX, RPARG RPARG points to operand X CALL #FLT_TAN Call the tangent function RPARG, RPRES, SP point to result Offset for tan X Go to common handler Cotangent of X (radians) Call: MOV #addressX, RPARG CALL #FLT_COT RPARG points to operand X Call the cotangent function RPARG, RPRES, SP point to result #2,R4 Offset for cot X TRCCOMl Go to common handler Hyperbolic Tangent of X (radians) Call: MOV CALL iaddressX, RPARG RPARG points to operand X #FLT_TANH Call the hyperbolic tangent RPARG, RPRES, SP point to result FLT_TANH MOV Offset for tanh X JMP Go to common handler Hyperbolic Cotangent of X (radians) Call: MOV #addressX, RPARG CALL #FLT_COTH RPARG points to addres·s of X Call the hyperbolic cotangent RPARG, RPRES, SP point to result Offset for coth X Go to common handler Software Applications 5-145 The Floating-Point PacksfP! Exponential function of X (ex) Call: MOV #addressX, RPARG CALL iFLT_EXP RPARG points to operand X Call the exponential function RPARG, RPRES, SP point to result #8,R4 Of.fset for exp X Common Handler for tan, cot, tanh, coth and exponent function Range: -2xPi < X < +2xPi. For larger numbers FAST loss of accuracy TRI_COM1 .equ $ MOV @RPARG+,2(SP) MOV @RPARG+,4(SP) .if DOUBLE-1 MOV @RPARG,6(SP) Copy X to result space .endif SUB #FPL,SP SUB U,RPARG Point to X again CALL FT1(R4) Calculate 1st function IN TERR2 Error: error code in HELP SUB #FPL,SP Allocate cosine result space ADD #FPL+2,RPARG Point to X CALL FT2(R4) Calculate 2nd function AI1.ocate new result space ADD #FPL,RPRES Point to result of 1st function CALL FT3(R4) 1st result .OP. 2nd result MOV @SP+,2*FPL(SP) Final result to result area MOV @SP+,2*FPL(SP) .if DOUBLE=l MOV @SP+,2*FPL(SP) .endif TERR2 FT1 5-146 ADD #FPL,SP Skip 1st result BR #FLT_END Error code in HELP .word FLT_SIN tan = sin/cos 1st function The Floating-Point Package FT2 FT3 . word FLT_COS cot - cos/sin . word FLT_SINH tanh . word FLT_COSH coth - cosh/sinh . word FLT_COSH exp . word FLT_COS tan = sin/cos . word FLT_SIN cot - cos/sin = * sinh/cosh cosh + sinh . word FLT_COSH tanh = sinh/cosh . word FLT_SINH coth - cosh/sinh . word FLT_SINH exp . word FLT.J)IV tan . word FLT_DIV cot = cos/sin . word FLT_DIV tanh . word FLT_DIV coth = cosh/sinh . word FLT_ADD exp = 2nd function cosh + sinh sin/cos 3rd function sinh/cosh = cosh + sinh If the argument X for trigonometric functions is outside of the range ±21t then the subroutine FLT_RNG may be used. The subroutine moves the angle X into the range ±It. Subroutine FLT_RNG moves angle X into the range -Pi < X < +Pi Call: MOV #addressX, RPARG RPARG points to operand X CALL #FLT_RNG Call the function RPARG, RPRES, SP point to result Range: -lOOxPI < X < +100xPI FLT - RNG loss of accuracy increases with X PUSH @RPARG Save sign of X on stack AND #080h,O(SP) Only sign remains SUB #FPL,SP Reserve space for JAn x Pi .if DOUBLE-1 PUSH 4 (RPARG) X on stack .endif PUSH 2 (RPARG) PUSH @RPARG BIC #080h,O(SP) IXI remains Software AppHcations 5-147 The Floating-Point :~e. FR1 MOV FLT2PI,FPL(SP) MOV FLT2PI+2,FPL+2(SP) 2xPi to stack .if DOUBLE=l MOV FLT2PI+4,FPL+4(SP) .endif 'CMP JHS @SP,FLTPI Pi - IXI FR2 Pi > IXI: range process done Successive approximation by subtracting 2An x2Pi FR3 INC.B FPL+1(SP) CMP @SP,FPL(SP) 2Pi x 2 2 An·x 2Pi - IXI 2"'n x 2Pi < IXI JLO FR3 DEC.B FPL+1(SP) 2""n x MOV SP,RPRES Address IXI MOV SP,RPARG ADD #FPL,RPARG CALL #FLT_SUB Address 2 An x 2Pi IXI - 2 .... n x 2Pi JMP FR1 Check if in range now 2Pi > IXI divide by 2 Move.X (now between -Pi and +Pi) to old result space FR2 XOR 2*FPL(SP),O(SP) Correct sign of X MOV @SP+,2*FPL+2(SP) Result to old RS MOV @SP+,2*FPL+2(SP) .if DOUBLE-1 MOV @SP+,2*FPL+2(SP) .endif ADD #FPL+2,SP BR iFLT_END To return address of FLT_RNG .if DOUBLE=l FLTPI .DOUBLE 3.141592653589793 Pi FLT2PI .DOUBLE 3.141592653589793*2 2xPi .else FLTPI 5-148 . FLOAT 3.141592653589793 Pi The Floating-Point Package FLT2PI . FLOAT 3.141592653589793*2 2xPi .endif 5.6.10.15 Faster Approximations for TrIgonometric Functions If the calculation times of the previous iterations are too long and the high accuracy is not needed (e.g. for the calculation of pulse widths for PWM), tables or cubic equations can be used. The table method is described in the MSP430 Software User's Guide (literature number SLAUE11). With the following four definition points, a cubic approximation to the sin curve is made. The range is 0 to 1tI2. All other angles must be adapted to this range. X1:= 0.0000000000 SIN X1:= 0.0000000000 (0°) X2:= 0.3490658504 SIN X2:= 0.3420201433 (20°) X3:= 1.2217304760 SIN X3:= 0.9396926208 (70°) X4:= 1.5707963270 SIN X4:= 1.0000000000 (90°) The resulting multiplication factors are: SIN X = -0.11316874 X3-o.063641170 XII2 +1.01581976 X The following results and errors are obtained with the previous factors: X=O, SIN X = 0.000000000 0.00% (0°) X=1t!12 SIN X =0.259548457 +0.28% (15°) X .. 1tI6 SIN X = 0.498189297 -0.36% (30°) X:=1tI4 SIN X = 0.703738695 -0.47% (45°) X:=1tI3 SIN X .. 0.864012827 -0.23% (60°) X:= 51t112 SIN X .. 0.966827870 +0.09% (75°) X:=1tI2 SIN X .. 1.000000000 0.00% (90°) The error of the previous approximation is within ±a.5% from 0 to 27t. Calculation times: .FLOAT with hardware multiplier: 880 cycles .FLOAT without hardware multiplier: 1600 cycles .DOUBLE with hardware multiplier: 1150 cycles .DOUBLE without hardware multiplier: 2550 cycles Software Applications 5-149 The Floating-Point Package • 4W u. JtI Sine Approximation: Sin X = A3xX~3 + A2xX~2 + AlxX + AO Input range for X: 0 =< X =< Pi/2 The terms Ax are stored in a table starting with the cubic term MOV #X,RPARG Address of X (radians) MOV #A3,R4 Address of cubic term for sine CALL # HORNER Cubic approximation .equ $ R4 points to cubic term .if DOUBLE=l Store X on stack PUSH 4 (RPARG) for later use Use approximated value Sin X HORNER .endif PUSH 2 (RPARG) PUSH @RPARG SUB #FPL,SP. Locate new result space MOV R4,RPRES Address cubic term A3 CALL #FLT_MUL XxA3 ADD #FPL,R4 Address quadratic term A2 MOV R4,RPRES CALL #FLT...AJ)D ADD #FPL,RPARG to X CALL #FLTJroL X~2xA3 ADD #FPL,R4 Address linear term Al MOV R4,RPRES XxA3 + A2 CALL #FLT...AJ)D X~2xA3 ADD #FPL,RPARG to X + XxA2 + XxA2 + Al CALL #FLT_MUL X~3xA3 ADD #FPL,R4 Address constant term AO + X~2xA2 + XxAl MOV R4,RPRES CALL #FLT_ADD X~3xA3 MOV @SP+,2*FPL(SP) Copy to result area .if DOUBLE=l MOV @SP+,2*FPL(SP) + X~2xA2 + XxAl + AO .endH MOV ADD 5-150 @SP+,2*FPL(SP) '#FPL,SP SP to return address The Floating-Point Package BR ; Use standard FPP return Multiplication factors for the Sine generation (0 to Pi/2) SIN X = -0.11316874 X3-0.063641170 .if DOUBLE-1 X~2 +1.01581976 X A3 . DOUBLE -0.11316874 cubic term A2 . DOUBLE -0.063641170 quadratic term A1 . DOUBLE 1.01581976 linear term AO . DOUBLE 0.0 constant term .else A3 . FLOAT -0.11316874 cubic term A2 . FLOAT -0.063641170 quadratic term A1 . FLOAT 1.01581976 linear term AO . FLOAT 0.0 constant term .endif Note: The HORNER algorithm (used previously) can be used for several other purposes. It is only necessary to load the register R4 with the starting address of the appropriate block containing the factors (address A3 with the previous example). I 5.6.10.16 The Natural Logarithm Function The natural logarithm of a number X is calculated with the following formula: InX = :t I (X-l)" X (_l)n-I n The number range of X for the natural logarithm contains all positive numbers except zero. Values of X less than or equal to zero return the largest negative number (-3.4x1 038) and the N bit set as an error indication. The calculation errors for the natural logarithm function are shown in the following table. They indicate relative errors. The errors of the .DOUBLE routine are estimated: no logarithm values greater than 12 digits were available. Table 5-16 shows the relative large errors - especially for the .FLOAT format - for input values X very near to 1.0. This is due to the (X -1) operation necessary for the calculation. Algorithms used should avoid the calculation of the logarithm of numbers very close to 1.0. Software Applications 5-151 Table 5-16. Relative Errors of the Natural Logarithm Function X .FLOAT .DOUBLE Comment 2.938736Xl0-39 -1.5Xl0-7 -4.5Xlo-12 Smallest FPP number 1.00 0 O. 1.0001 -3.5Xl0-5 -1.4Xl0-8 Missing resolution 1.00001 +5.2Xl0-3 -aXl0-8 at results near zero 1.000001 +6.7Xl!l4 +2.4Xlo-7 See above 1.95 +1.5Xlo-7 +5Xlo-12 loS +3.6Xl0-8 +1.5Xlo-11 1012 +3.6X10-8 +4.5X1o-12 3.402823X1 ()38 +1.5Xl0-7. +4.5X1o-12 Largest FPP number Calculation times: .FLOAT with hardware multiplier: 13000 cycles .FLOAT without hardware multiplier: 16000 cycles .DOUBLE with hardware multiplier: 34000 cycles .DOUBLE without hardware multiplier: 43000 cycles Natural Logarithm Funotion: Result on TOS - LN(@RPARG) Call: RPARG points to operand X MOV #addressX,RPARG CALL #FLT_LN 13 iterations 22 iterations Call the function lnX RPARG, RPRES and SP point to lnX Range: +2.9x10~-38 Errors: X - 0: X < 0: < X < +3.4x10~38 N = 1, C = 1, Z N = 1, C = = 1, Z - 0 0 Result: -3.4E38 Resul t: -3.. 4E38 Stack usage: 3 x FPL + 6 bytes #0 N binary (divisor, power) .if DOUBLE=1 PUSH 5-152 4 (RPARG) Push X onto stack The Floating-Point P~e . end if PUSH 2 (RPARG) PUSH @RPARG Check for the legal range of X: MOY #FLTO,RPRES CALL #FLT_CMP JHS LNNEG °< X Check valid range: °< X X is negative If X is 1.0 then 0.0 is used for the result MOY #FLT1,RPRES CALL #FLT_CMP JEQ LN1PO Check i f X= 1 X is 1: result is 0.0 The exponent of X is multiplied with ln2. Then In1.5 is added to correct the division by 1.5. Result is base for final result SUB #FPL,SP Reserve working space MOY.B 1 (RPARG) ,HELP Copy exponent of X XOR .BOh,HELP Correct sign of exponent SXT HELP MOY HELP,O(SP) MOV SP,RPARG CALL #CNV_BIN16 Exponent to FP format MOV #FLN2,RPARG To ln2 exp x ln2 CALL #FLT_MUL MOV #FLN1P5,RPARG To In1. 5 CALL #FLT_ADD exp x ln2 + ln1.5 MOV @RPARG+,2*FPL+4(SP) MOV @RPARG+,2*FPL+6(SP) ; To result area .if DOUBLE=l MOV @RPARG+,2*FPL+B(SP) .endif Software Applications 5-153 !he Floating-Point Package The mantissa of x is converted into the range -0.33 to +0.33 to get fast convergion ADD flFPL',SP MOV SP,RPRES RPRES points to X MOV.B flSOh,l(SP) 1. 0 =< X < 2.0 To . FLOAT 1. 5 Back to X MOV #FLTlPS, RPARG CALL flFLT.J)IV 2/3 =< X < 4/3 MOV #FLTl,RPARG To . FLOAT 1. 0 CALL #FLT_SUB -1/3 =< X < +1/3 .if DOUBLE-l PUSH #0 .endif PUSH #0 PUSH FLTl .if DOUBLE=l PUSH N (FLT1.0) on stack #0 .endif LNLOP PUSH #0 PUSH SUB <, FLTl tlFPL,SP Working area .equ $ MOV SP,RPRES To XAN ADD #2*FPL,RPRES MOV SP,RPARG ADD #3*FPL,RPARG To X CALL #FLTJroL r(N+l) New XA(N+1) _> XAN MOV @RPARG+,2*FPL(SP) MOV @RPARG+, 2*FPL+2 (SP) .if DOUBLE=l MOV .endif CALL 5-154 @RPARG+,2*FPL+4(SP) RPARG points to N The Floating-Point Package INC LN1 4*FPL(SP) Incr. binary N BIT #l,4*FPL(SP) N even? JNZ LNl XOR #80h,0(SP) ; Yes, change sign of XAN/N ADD #4*FPL+4,RPARG Point to result area CALL #FLT_ADD Old result + new one MOV @RPARG+,4*FPL+4(SP) New result to result area MOV @RPARG+,4*FPL+6(SP) .if DOUBLE~l MOV @RPARG+,4*FPL+8(SP) . end i f Float N is incremented MOV #FLT1,RPARG To . FLOAT 1. ADD #FPL,RPRES To N CALL #FLT.-ADD MOV @RPARG+,FPL(SP) MOV @RPARG+,FPL+2(SP) ° N+l to N area .if DOUBLE=l MOV @RPARG+,FPL+4(SP) .endif Check if enough iterations are made LNE LN1PO LNNEG CMP #LNIT,4*FPL(SP) Compare with nec. iterations JLO LNLOP HELP = ADD #4*FPL+2,SP Housekeeping: free stack BR #FLT_ENO To completion. Error in HELP X-I: result ° ° ADO #FPL+2,SP BR #RESO ADO #FPL+2,SP X <= 0: -3.4E38 result MOV #OFFFFh,2(SP) MSBs negative = Software Applications 5-155 BR #DBL_OVERFLOW .if DOUBLE=l FLTO . DOUBLE 0.0 0.0 FLTI . DOUBLE 1.0 1.0 FLTIP5 . DOUBLE 1.5 1.5 FLNIP5 . DOUBLE 0.405465108107 101.5 FLN2 . DOUBLE 0.6931471805599 102.0 LNIT .equ 22 Number of iterations .else FLTO . FLOAT 0.0 FLTI . FLOAT 1.0 FLTIP5 . FLOAT 1.5 FLNIP5 . FLOAT 0.405465108107 FLN2 . FLOAT 0.6931471805599 LNIT .equ 13 .eodif To calculate the logarithm of X based to the number 10 the following sequence may be used: MOV #addressX, RPARG CALL #FLT_LN MOV #FLTMOD,RPARG CALL #FLT_MUL Address of X ; ; Calculate loX 10X/lo10 = 10gX 10gX on TOS FLTMOD .if DOUBLE=O . FLOAT 0.4342944819033 10g10/1010 0.4342944819033 10g10/1010 .else FLTMOD . DOUBLE .eodif 5.6.10.17 The Exponential Function The exponential function eX is calculated. The number range of X is: -88.72 :5 X:5 +88.72. Values of X outside of this range return zero (X < -88. 72) respective the largest positive number (+3.4x1 038) and the N bit set as an error indication. The calculation errors for the exponential function are shown in the following table. They indicate relative errors. 5-156 The Floating-Point Package Table 5-17. Errors of the Exponential Function X -88.72 .FLOAT .DOUBLE Result -9.4X1o-7 -4.5X1O-11 2.9470911X1Q-39 -12.3456 -1.7X1o-S -1.5X1o-11 4.348846154014X1o-S 0.0 2""41 0 0 -4.5X1o-13 -4.5X1o-13 1.0 1.0 -4.5X1o-11 Most positive FPP number 2-25 -30X10-9 +88.72 -2.8X1o-S 1.0+29.8X10-9 Calculation times: .FLOAT with hardware multiplier: 3200 cycles .FLOAT without hardware multiplier: 5100 cycles .DOUBLE with hardware multiplier: 4500 cycles .DOUBLE without hardware multiplier: 7500 cycles Call: Result on TOS e~X. Exponential Function: ~ e~(@RPARG) MOV #addressX,RPARG RPARG points to operand X CALL #FLT_EXP Call the expo function RPARG, RPRES, SP point to result Range: -88.72 < X < +88.72 Errors: X> +88.72: N X < -88.72: N = 1, C = 1, Z 1, C = 0, Z N - 0, C Stack usage: 1 ~ = x, Z 0 =x Result: 0.0 if SW_UFLOW = 1 Result: 0.0 if SW_UFLOW - 0 3 x FPL + 4 bytes @RPARG+,2(SP) MOV Result: +3.4E38 Copy X to result area @RPARG+,4(SP) .if DOUBLE=l MOV @RPARG,6(SP) .endif Software Applications 5-157 The Floating-Point Package • l1li11 Check if X is inside limits: -BB.72 < X< +BB.72 MOV 2 (SP) ,COUNTER MSBs, exp and sign of X SIC tOBOh,COUNTER CMP tOB631h,COUNTER JLO EXP_L3 IXI IXI > 88.721 ln3.4xlOA3B=BB.72 IXI is in range JNE EXP_RNGOUT X > B8.72 .or. X < -B8.72: error CMP 1I07217h,4(SP) Check LSBs JHS E;XP_RNGOUT LSBs show: IXI > B8.72 Prepar.e exponent of result: N EXP_L3 (B631h,721Bh) = X/ln2 (rounded) MOV SP,RPRES SUB #FPL,SP New working area ADD t2,RPRES To X (result area) MOV IIFLTLN2I,RPARG To 2/1n2 (allows MPY) CALL CALL IIFLTJ(UL lICNV_FP_BIN 2 x X/ln2 -> binary 2 x X/ln2 .if DOUBLE-l SUB lI2,SP LSBs contain N ADD #FPL-2,RPARG To N lIFPL,RPARG To binary N .else ADD .endif EXPLl N is at correct place yet RRA @RPARG /2 for rounding JNC EXPLl No carry, no rounding TST o (RPARG) Sign of N IN EXPLl INC o(RPARG) Round N CALL #CNV_BINl6 N -> FPP format Xn Calculation of g: g = X - Xn*(Cl + C2) 5-158 MOV #EXPC, RPARG Cl + C2 CALL #FLTJ(UL Xn*(Cl + C2) The Floating-Point Package ADD 'FPL+4, RPRES To X CALL 'FLT_SUB 9 = X - Xn*(Cl + C2) Calculation of mantissa R(g): R(g) = 0.5 + g*P(Z)/(Q(z) - g*P(z» SUB .FPL,SP CALL .FLTJroL Calculation of g*P(Z): g*P(z) g*(pl*z + pO) SUB .FPL,SP MOV #EXPPl,RPARG To pl, RPRES points to z CALL #FLTJroL pl*z Area for g*P(z) MOV #EXPPO, RPARG To pO CALL #FLT_ADD pl*z + pO ADD #2*FPL,RPARG To 9 CALL #FLTJroL g*P(z) = g*(pl*z + pO) MOV @SP+,2*FPL-2(SP) Store g*P(z) MOV @SP+,2*FPL-2(SP) .if DOUBLE=l MOV @SP+,2*FPL-2(SP) .endif Calculation of Q(z): Q(z) = (ql*z + qO) Q(z) = (q2*z + ql)*z + qO .FLOAT format .DOUBLE format SUB #FPL,SP Area for Q(z) .if DOUBLE=l Quadratic equation MOV #EXPQ2,RPARG To q2 ADD #FPL,RPRES To z CALL #FLT_MUL q2*z MOV #EXPQ1,RPARG TO ql CALL #FLT_ADD q2*z + ql #EXPQ1,RPARG To ql .else MOV Linear equation Software Applications 5-159 The Floating-Point Paclcage .endif ADD IIFPL,RPRES To CALL #FLT_MUL (q2*z + q1)*z MOV #EXPQO,RPARG To qO CALL IIFLTJ,DD (q2*z + q1)*z + qO or q1*z + qO Z resp. q1*z Result mantissa R(g) = 0.5 + g*P(z)/(Q(Z) - g*P(z» CALL ADD #2*FPL,RPARG #FLT_SUB Q(z) - g*P(z) To g*P(z), RPRES to Q(z) ADD #2*FPL,RPRES To g*P(z) CALL #FLT_DIV g*P(z)/(Q(z) - g*P(z» MOV #FLTOPS, RPARG To 0.5 CALL #FLT_ADD R(g)=O.S + g*P(z)/(Q(z)-g*P(z» MOV @SP+,3*FPL+2(SP) store R(g) to result area MOV @SP+,3*FPL+2(SP) .if DOUBLE-1 MOV @SP+,3*FPL+2(SP) .endif Insert exponent N+l to result ADD #2*FPL,SP To binary N @SP+,3(SP) Add N + 1 to exponent of result SETC ADDC.B N + 1 To normal return, HELP = 0 X is out of range: test if overflow (+) or underflow (-) EXP_RNGOUT TST.B 2(SP) EXP_OVFL Yes, error: handling in FPP04 BR #DBL':'UNDERFLOW Underflow: depends on SW_UFLOW EXP_OVFL BR .if FLTLN2I 5-160 Overflow? (sign positive) JGE #DBL_OVERFLOW DOUBLE=l .double +1.4426950408889634074*2 2/ln2 The Floating-Point ~a7!age EXPC c1+c2 .double +0.693359375-2.1219444005469058277E-4 EXPP1 .double +0.595042549776E-2 EXPPO .double ;p1 0.24999999999992 ;pO EXPQ2 .double +0.29729363682E-3 ;q2 EXPQ1 .double +0. 5356751764522E-1 ;q1 FLTOP5 .equ EXPQO .double +0.50000000000000E+0 both are 0.5 $ qO .else +1.4426950408889634074*2 FLTLN21 . float EXPC . float +0. 693359375-2.1219444005469058277E-4 EXPP1 . float +0.00416028863 EXPPO . float 0.24999999950 EXPQ1 . float +0.04998717878 FLTOP5 .equ $ EXPQO . float +0.50000000000 both are 0.5 .endif 5.6.10.18 The Power Function The power function AB is calculated. The number range for A and B is: 2.9 x 10-39 ~A ~ 3.4x 1Q38 -88.72 ~ B x InA ~ + 88.72 For the error handling, see the header of the software. The used formula is: The calculation errors for the power function are shown in the following table. They indicate relative errors. Table 5-18. Relative Errors of the Power Function X .FLOAT .DOUBLE Result 11 0 0 1.0 (3.4X1038)0 0 0 1.0 (5.5X1 Q4D)2 -aX1o-7 0 3.025X1 Q-39 1.0000788 -4.X1Q-O -9X1o-1O 1.0061768 1.000071267513 -6.5% -7X1o-7 3.4027X1038 Software Applications 5-161 The Roating-Point Package 05 o o 0.0 0.1-0 -1.3Xl0-7 -1.6Xl0-10 105 The previous table shows the large errors for small bases raised by very large exponents. This Is due to the natural logarithm function. Calculation times: Power Function: Call: .FLOAT.wlth hardware multiplier: 17000 cycles .FLOAT without hardware multiplier: 20000 cycles . .DOUBLE with hardware multiplier: 40000 cycles .DOUBLE without hardware multiplier: 50000 cycles Result on TOS = A~B. MOV lIaddressA,RPRES MOV iaddressB,RPARG CALL (@RPRES)~(@RPARG) RPRES points to operand A RPARG pOints to operand B Call the power function RPARG, RPRES and SP point to AAB Range: 2.9x10~-39 < A< 3.4x10~+38 -88.72 < Bx1nA < +88.72 A < 0: Errors: N - 1, C = 1, Z = O· B x 1nA > +88.72: N = 1, C = 1, Z - 1 Result: -3.4E38 Result: +3.4E38 B x lnA < -88.72: N = 1, C N = = 0, Z = B x lnA > 3.4E38: stack: Error handling of multiplication FPL + 4 + (3 x FPL + 8) bytes FLT_PQWR .equ $ .if DQUBLE=1 TST 4 (RPRES) JNZ PWRL1 .endif 5-162 0: Result: 0.0 i f SW_UFLOW = 1 0, C - x, Z - x: Result: 0.0 if SW_UFLOW - 0 Check if A = 0 The Floating-Point Package TST PWRLl PWERR 2 (RPRES) A # 0 JNZ PWRLl TST o (RPRES) JZ POWRO PUSH RPARG Save pointer to exponent B SUB #FPL,SP Working area A 0: result - 0 MOV RPRES,RPARG Pointer to base A CALL #FLT_LN InA IN PWERR A is negative MOV FPL(SP),RPARG Pointer to exponent CALL #FLT_MUL BxlnA B is too large. HELP # 0 IN PWERR CALL #FLT_EXP e~(BxlnA) MOV @SP+,FPL+2(SP) To result area MOV @SP+,FPL+2(SP) .if DOUBLE=l MOV @SP+,FPL+2(SP) = AAB .endif POWRO ADD #2,SP Skip exponent pointer BR #FLT_END Error code in HELP BR #RESO A 0: A~B = 0 Software Applications 5-163 Battery..Checlf and Power Fall Detection 5.7 Battery Check and Power Fall DetectIon The detection of the near loss of the supply voltage is shown for battery driven and for ac-powered MSP430 systems. Described in the following section are several methods of how to check if the voltage of a battery or an accumulator is above the minimum supply voltage of the MSP43D-system. Possibilities are given for the family members having the 14-bit ADC on-chip and also for the members without it. Three ways, with different hardware, are given to detect power fail situations for ac-driven systems. For all examples, applications, schematics, diagrams, and proven software code are given for a better understanding. 5.7.1 Battery Check In microcomputer systems driven by a battery or an accumulator it is necessary to detect when the lowest usable supply voltage is reached. A battery check executed In regular time intervals ensures that the supply voltage Is stili sufficient. If the lowest acceptable voltage is reached, normally with an added security value, a warning can be given with the LCD. The deciSion algorithms used can be very different: o o 5.7.1.1 Simple checks; if the low threshold is reached or not Sophisticated methods using the speed of the voltage reduction (IN/At) dependent on the discharge behavior of the actual battery or accumulator type. For even better estimations the temperature of the battery can also be taken into account. Battery Check With the 14-Blt ADC Due to the ratiometric measurement principleofthe·ADC, the measured digital value of a constant, known reference voltage is an indication of the supply voltage of the MSP430C32x. The measured value is inversely proportional to the supply voltage Vcc. Figure 5-31 shows the connecting of the voltage reference for all three explained variants. Using the auto mode of the ADC, the digital result, N, for an analog input voltage Vin is: N =INTlvin x 214 VSVcc 5-164 Battery Check and Power Fail Detection With a reference voltage Vref (Vin) of 1.2 V, the supply voltage Vcc (exactly VSVcc) can be measured in steps of approximately 0.3 mV near the voltage VCCmin =2.5 V. Note: If the other analog parts connected to the SVcc-terminal cause a voltage drop that cannot be neglected, it is recommended that the reference diode be connected to an unused TP-output or an O-output. Otherwise, the resulting voltage drop corrupts the result and the calculated value for Vcc is too small. 32kHz rlD~' sVcc. TP.x To Other Analog Parts R=82kn MSP43OC32x A3 ~~ LMx85-1.2 VREF = 1.236 V AVss DVss I OV DVcc I 3V Figure 5--31. Connection of the Voltage Reference Battery Check With a Reference Measurement To get the reference for later battery checks, a measurement of the reference voltage (Vref) is made with Vcc =VCCmin. The result is stored in RAM. If the battery should be tested, another measurement is made and the result is compared to the stored value. The result of the comparison determines the status of the battery. o If the actually measured value exceeds the stored one, then Vcc < VCCmln and a battery low indication Is given by software. o If the actually measured value is lower than the stored one, then Vcc > VCCmin Software Applications 5-165 Battery Check and Power Fail Detection EXAMPLE: The battery check with a reference measurement is shown for the analog input A3 (see Figure 5-31). During the calibration, a reference measurement is made with the lowest tolerable Vee (VCCmin). The battery check is then made in regular time intervals (in this example, every hour). RAM storage for the ADC value measured for Vref with Vccmin ADVref .EQU 02021i ADC value for Vref' at Vccmin Vccmin (+ security value) is adjusted. A certain code at PortO or a temporary jumper between an input and an output leads to this software part CALL #MEAS_A3 Vref connected to A3 MOV &ADAT,ADVref Store reference ADC value One hour elapsed: check if Vcc is above Vccmin. CALL #MEAS_A3 CMP ADVref,&ADAT (ADAT) - (ADVref) JLO VCCok Vcc > Vccmin Vref connected to A3 The actual vcc is lower than Vccmin. Indicate 'Battery LoW" in the LCD. CALL Output warning with LCD VCCok Continue program \ Measurement subroutine for analog input A3. Result in ADAT #ADIFG,&IFG2 MOV L$lOl BIT.B #ADIFG,&IFG2 JZ L$lOl RET 5-166 ; Reset ADC flag ADIFG #ADCLK2+RNGAUTO+CSOFF+A3+VREF+CS,&ACTL CONVERSION COMPLETED? IF Z=l: NO Yes, return. Result in ADAT Battery Check and Power Fail Det~i~Jn o o Advantages • Very precise definition of one voltage • Small amount of software code • Different reference elements possible without software modifications Disadvantages • Calibration necessary • Relation to only one supply voltage value is known (calibration voltage) Battery Check With the Calculation of the Voltage If no reference measurement during a calibration phase is possible, the value of the supply voltage Vee can be determined by calculation. The formula is: Vee = 214 x Vref N With: N Vref ADC result of the measurement of Vref Voltage of the reference diode IV] EXAMPLE: The actual supply voltage (Vcc) needs to be checked. The previous formula is used for the calculation after the measurement of the reference voltage (Vref). The MSP430 floating point package (32-bit .FLOAT version) is used for all calculations. The hardware is shown in Figure 5-31. FPL .equ (ML/B)+l Length of FPP number ; Normal program sequence One hour elapsed: eheek if Vee is above Veemin or not. CALL #FLT_SAV Save FPP registers on stack SUB #FPL,SP Allocate stack for result CALL #MEASj.3 Measure ref. diode at A3 (N) MOV #ADAT,RPARG Address of ADC result CALL #CNV_BINl6U Convert ADC result N to FP Calculate Vcc = 2~l4 x Vref/(ADC-Result) Software Applications 5-167 Battery Check and Power Fail Detection BATT_ok MOV IIVref,RPRES Load address of Vref voltage CALL IIFLT_DIV Calculate vref/N (N on TOS) ADD.B U4,l(RPRES) Vee MOV tVCCmin, RPARG Compare Vee to VCCmin CALL tFLT_CMP Vee - VCCmin JHS BATT_ok Vee> VCCmin: ok CALL #BATT_LOW Give "Battery Low" Indication ADD #FPL,SP Correct SP (result area) CALL #FLT_REC = 2Al4 x Vref/N (exp+l4) Restore FP registers Continue with program Vref . FLOAT 1. 235 Voltage of ref. diode 1. 235V VCCmin . FLOAT 2.5 Vcemin MSP430: 2.5V o Advantages • o Battery voltage is known (trend calculation possible) Disadvantages I!I Error of the reference element is not eliminated • Calculation takes time Battery Check With a Fixed Value for Comparison This method uses a fixed ROM4:>ased value for the decision; If Vcc is sufficient or not. According to the data sheet of the LMx85-1.2, the typical voltage of this reference diode is 1.235 V with a maximum deviation of ±0.012 V. Therefore, the fixed comparison value (Nref) for the minimum supply voltage (VCCmin) can be calculated: Nrej= INTlvref x 214 Vccmin With VCCmin = 2.5 V and Vref = 1.235 V ± 0,012 V: Nref = INTI(1.235±0,012 V) X214 1 =8093 ±78 2.5 V To ensure that the voltage of the battery is above VCCmin, the reference value should be set to: 5-168 Battery Check and Power Fail Detection Nref =8093 - 78 = 8015 Every measured value below 8015 indicates that the battery voltage is higher than the calculated value, even under worst-case conditions. If the measured value is above 8015, a Battery Low warning should be given. EXAMPLE: The battery check with a fixed value for comparison is executed. The hardware needed is shown in Figure ~1. The comparison value is stored in ROM at address VCCmin. One hour elapsed: check if Vcc is above Vccmin or not. Vref connected to A3 CALL #MEAS-.A3 CMP VCCmin,&ADAT (ADAT) - (VCCmin) JLO VCCok Vcc > Vccmin The actual Vcc is lower than Vccmin. Output "Battery Low" to the LCD. CALL Output warning to the LCD Continue program VCCok ROM storage for the calculated ADC value: Vref at Vccmin. (worst case value) . VCCmin . WORD 8015 o ADC value 1.235V at 2.5V Advantages • o 5.7.1.2 Small amount of software code Disadvantages • Error of the reference element is not eliminated • Fixed reference element • Relation to only one supply voltage value is known Battery Check With an External Comparator With an operational amplifier used as a comparator, a simple battery check can be implemented for MSP430 family members that do not have the 14-blt ADC. Figure ~2 shows two possibilities: Software Applications 5-169 ~~ttery Check and Power fail Detection 1) On the left, a simple Go/No Go solution. The voltage at PO.7 is high, when Vcc is above VCCmin and is low when Vcc is below this voltage. The threshold voltage VCCmin is: . VCCmin = Vref X (R1 + 1) R2 2) On the right, a circuit that allows the comparison of the battery voltage (Vee) to three different voltage levels; two of them can be determined, the third results from the calculated resistor values for R1, R2 and R3. This allows to distinguish four ranges of the supply voltage: o o o o Vee < Vthmin The supply voltage is below the lowest threshold Vthmin < Vce < Vthmid The supply voltage is between Vthmin and Vthmid Vthmid < Vee < Vth max The supply voltage is between Vthmid and Vth max Vth max < Vcc The supply voltage is above the maximum threshold .-----------1 r--4_---~ R1 621<0 TP.1 r l - - - - - I TP.O TP.O MSP430 R3 680110 R1 62110 MSP430 PO.7 PO.7 R2 56110 R2 56110 y------~ vss VREF=1.2V '-4.......- -.....-1 Vss Vee vee ov OV 3V Figure 5-32. Battery Check With an External Comparator The three different threshold levels are: o Resistor R3 is switched off (TP.1 is switched to Hi-Z): Vthmid =Vrefx (R1 +1) R2 5-170 3V . Battery Check and Power Fail Detection o R3 is switched to Vee by TP.1 : R111R3 Vth min =Vrefx (--+1) R2 o R3 is switched to Vss by TP.1 : Vthmax = Vref x R1- + 1) (R211R3 If the comparator's output (Vout) is high, Vee is above the selected threshold voltage, if Vout is low, then Vee is below this voltage. The calculation of the resistors R1 to R3 starts with the desired threshold voltage (Vthmld), R1 and R2 are derived from it. Then, the low threshold voltage (Vthmin) defines the value of R3. The 3rd threshold (Vth max) results from the other two threshold voltages. The resistor values shown in Figure 5-32 define the following threshold values: Vthmin =2.52 V (calculated with second step) Vthmid =2.66 V (calculated first) Vth max =2.78 V (results from the other two thresholds) EXAMPLE: With the hardware shown in Figure 5-32 (circuit on right side), the "actual battery voltage (Vce) Is compared to three different thresholds. This allows the differentiation of four different ranges for Vec. For any of the four supply levels, different actions are started at the appropriate labels (not shown). Dependent on the speed of the MSP430 and the comparator used, NOPs may be necessary between the setting of the TP-ports and the bit test instructions BIT.B. One hour elapsed: check the range Vcc falls in now. BIS.B #TPO+TP1,&TPD TP.O and TPl active high BIS.B #TPO+TP1,&TPE Comparison with Vthmin BIT.B #P07,POIN Comparator output JZ BATTlo Vee < Vthmin BIC.B #TP1,&TPE TP.l to HI-Z BIT.B #P07,POIN Comparator output Software Applications 5-171 Battery Check and Power Fail Detection Vthmin < Vee < Vthmid JZ BA1:'Tmiq BIC.B #TP1,&TPD TP.l active to Vss BIS.B UP1,&TPE Check Vthmax BIT.B #P07,POIN Comparator output JNZ BATThi Vee > Vthmax Vthmid < Vee < Vthmax o o Advantages • Four ranges defined (more ranges are possible if desired) • Very fast software • Different reference elements are possible without software change Disadvantages • Hardware effort (except if an unused operational amplifier of a quadpack can be used) 5.7.1.3 Battery Check ·Wlth the Universal Timer/Port Module The Universallimer/Port module allows a relatively aeeurate measurement of the battery voltage (Vcc). The principle (see Figures 5-33 and 5-34) is as follows: the capacitor (e), also used for the other measurements, is chargedup to the vohage (Vref) of the reference diode. e is then discharged with Rref and the time tref until ve reaches the lower threshold VIT- of the Input elN is measured. Afterwards, e is charged-up fully to the supply voltage (Vcc) and the discharge time (tVee) is also measured. Vee is then: tVee-tref Vee Vref x e 1: With: Vee Vref tref tVcc "t VIT5-172 Actual supply voltage of the MSP430 M Voltage of the reference diode M lime to discharge C from Vref to VIT- [s] lime to discharge e from Vee to VIT- [s] lime constant for discharge: "t = Rref x C [s] Lower threshold voltage of input elN [V] Battel'}' Check and Power Fall Detection Figure 5-33. Discharge Curves for the Battery Check With the Universal Timer/Port Module Two hardware possibilities are shown in Figure 5-34: o The left side uses the existing ADC hardware for the battery check too. o The right side uses different battery check hardware. This avoids any influence from the battery check and creates precise ADC-measurement hardware. See the application report, Voltage Measurement with the Universal Timer/ Port Module, in Chapter 2 for more information. Here a formula is given that Is independent of the time constant (t). Software Applications 5-173 Battery Check and P?w,er Fall Detect!?n o32kHz TP.1 TP.2 TP.O RREF MSP430 RD ClN TP.5 Vss Vss c RD Ballary Check Separated From Measurement Pert Battery Check CombIned With Measurement Part OV 3V Figure 5-34. Battery Check With the Universal Timer/Port Module The conditions to be met for the reference voltage (Wef) are: Vref > VT- Vref must be higher than the lower threshold voltage VT- of the input CIN at VCCmax Vref < VCCmin Only voltages above Vref can be measured The previous conditions mean for an MSP430 system supplied with 3 V: Vref = 1.5 V to 2.5 V. The measurement sequence like shown in Figure 5-33 is described for the left-side circuitry of Figure 5-34 (the following sequence of numbers refer to the Conversion States of Figure 5-33): 1) Switch outputs TP.1 to TP.3 to HI-Z 2) Charge capaCitor C with resistor (Rref) until input CIN gets high (or up to Vee). then switch-off Rref (TP.1 is set to HI-Z) 3) Discharge capacitor C with the reference diode and Rd to Vref (TP.3 is set to LO): Discharge time: td > 5 x Rd x C. Set TP.3 to HI-Z. 4) Discharge capacitor C from Vref to VIT- with Rref (TP.1 set to LO). Measure discharge time tref' 5) Charge capacitor C with Rref to Vcc (tcharge > 5 x Rref x C) 6) Discharge capacitor C from Vcc to VIT- with Rref (TP.1 set to LO). Measure discharge time (tVcc) 5-174 Battery Check and Power Fail o.etec!i0n 7) Calculate Vcc with the formula shown previously For the supply voltage range of a 3-V system (Vee = 2.5V to 3.5V) and a reference voltage of Vref =2.3 V, the exponential part of the equation can be replaced by a linear function: tVee-tre/ ) +0.97 Vee=Vre/x ( 1.29x 't If the Universal TimerlPort Module is used in an ADC application with high accuracy (like a heat volume counter) then the battery-check circuitry should be connected to other I/0s as shown in Figure 5-34 on the right side. This way the measurement of the sensors cannot be influenced by the battery-check circuitry. The software shown in the application report, Using the MSP430 Universal Timer/Port Module as an Analog-to-Dlgltal Converter in Chapter 2, can also be used for the battery check with only a few modifications. o o Advantages • Minimum hardware effort if measurement part exists anyway • Supply voltage is known after the measurement Disadvantages • Slow measurement 5.7.2 Power Fall Detection AC driven systems need a much faster indication of a power-down situation than battery-driven systems. It is a matter of milliseconds, not of hours ordays. Therefore, other methods are used. Three of them are described in the following text. o The non-regulated side of the power supply is observed. If the voltage (VC) ofthe charge capacitor falls below a certain level (VCmin), an interrupt is requested. o The voltage at the secondary side of the ac transformer is observed. A sufficient level change there resets the watchdog. If the secondary voltage is too low or ceases, an interrupt is requested. o The non-regulated side of the power supply is observed with a TLC7701. The output of this supply voltage supervisor requests an NMI interrupt or resets the microcomputer. Software Applications 5-175 Battery Check and Power Fail Detection The interrupt requested by the previous three solutions is used to start the necessary emergency actions: o Switching-off all loads to lengthen the available time for the emergency actions o Reduction of the system clock MCLK to 1 MHz to be able to use Vcc down to VCCmin o o Storage of all important values into an external EEPROM Use of LPM3 finally to bridge the power failure eventually The three hardware proposals can be used with all members of the MSP430 family. The power-fail detection is also called ac-low detection. It issues the ae-Iow signal. 5.7.2.1 Power-Fall Detection by Observation of the Charge Capacitor Here the voltage level of the charge capacitor (Cch) is observed. If the voltage level of this capaCitor falls below a certain voltage level (VCmin), an interrupt is requested. With the circuit shown in Figure 5-35, VCmin is: (R3+ 1) R4 Vee x ---=R:-::'1-- (R2 +1) R1, R2, R3 and R4 are chosen in a way that delivers the desired threshold voltage (VCmin)' The regulated supply voltage (Vcc) is used as a reference. The NMI (non-maskable interrupt) can be used to get the fastest possible response. The remaining time (trem) for actions after a power-fail interrupt is approximately: itT Cch trem=\yCmin -Vccmin -Vr ) X-lAM Where: trem Cch lAM .VCmin VCCmin Vr 5-176 Approximate time from interrupt to the reaching of VCCmin [s1 Capacity of the charge capacitor [F] Supply current of the MSP430 system (medium value) [A1 Voltage at the charge capaCitor that causes ac-low interrupt M Lowest supply voltage for the MSP430 M Dropout voltage (voltage difference between output and input) of the voltage regulator for function M Battery Check and,Power ~a!1 Eelection ~-....---"'::"":--I vCC MSP430 po.o, NMI AC vz ------~--~~L---~~~-----~vss ov Figure 5-35. Power Fail Detection by Observation of the Charge Capacitor With the following component values for the hardware shown in Figure 5-.35, trem for emergency tasks can be calculated with the following formula. CCH =50 /LF. VCCrnln = 2.5 V, Vr = 1 V, lAM = 2 mA, Vz =10 V, VCrnin =7 V trem = (7V -2.5V -lV)x 50JlF = 87.5ms 2mA This remaining time trem =87.5 ms allows between 14000 and 87500 instructions (dependent on the addressing modes) for the saving of important values .in an EEPROM and other emergency tasks. Note: The capacitor power supply shown in Figure 5-.35 is used only to demonstrate this hardware possibility. A normal transformer supply as shown with the other hardware examples can also be used. . Software Applications 5-177 ~a!tery Check and Power Fail Detection The equations shown previously are only valid if the dropout voltage (Vr) of the used voltage regulator (Vr = VC - Vee) is relatively low. Vr must be: Vr < VCO _ Vreg X VCO VCmin Where: VCO Lowest voltage at Cch that outputs low voltage to the MSP430 input Vreg Nominal output voltage of the voltage regulator [V] M If this condition for Vr Is not possible, then another approach is necessary. Figure 5-37 shows a circuitry that is independent of the previously described restriction. 1-_ _ _5;;...v;.......-j vee MSP430 PO.O,NMI AC R3 --------~----~~--~--~~----~vss Figure 5-37. Power-Fail Detection by Observation of the Charge Capacitor The threshold voltage level (VCmin) for the interrupt Is : R2 VCmln =Vrefx ( -+1) R3 The time remaining (trem) for emergency tasks can be calculated: . Cch trem= (VCmin - VC'inin - Vr)x-- lAM If brown outs are a serious problem, the hardware proposal shown in Figure 5-37 can be used with the RESET/NMI terminal as described in Section 5.7.2.3, Power-Fail Detection with a Supply Voltage Supervisor. Instead of the inverted RESET output of the TLC7701, the output of the operational amplifier is used. 5-178 Battery Check and Power Fail Detection EXAMPLE: The interrupt handler and its initialization is shown for the powerfail detection by observation of the charge capacitor with a comparator. After the completion of the emergency tasks, a test is made to check if the supply voltage is still low. If not, the software restarts at label PF_INIT. Otherwise, LPM3 is entered to eventually bridge the power failure. The basic timer checks with its interrupt handler In regular intervals for an indication that the voltage is above Vemin again. The hardware shown in Figure 5-35 is used. SYSTAT contains the current system status: calibration, normal run, power fail aso. SYSTAT .BQU 0200h ; System status byte The program starts at label INIT if a power-up occurs INIT Normal initialization The program restarts at label PF_INIT if the supply voltage returns before Vccmin is reached (short power fail) #0300h,SP Restart after power fail Special initialization Initialization: Prepare PO.O for power fail detection. BIS.B #POIFGO,&IBI BIS.B #POO,&POIES Intrpt for trailing edge BIC.B #POIFGO,&IFGl Reset flag (safety) Enable PO.O interrupt Continue with initialization BINT MAINLOOP MOV.B Enable GIB #NORMAL,SYSTAT Start normal program PO.O Interrupt Handler: the voltage VC at Cch fell below a minimum voltage Vcmin. Switch off all loads and interrupts except Basic Timer interrupt. #PD,&ACTL ADC to Power down Software Applications 5-179 Battery Check and Power Fail Deteeti~n MOV.B 1I32-1,&SCFQCTL MCLK back to IMHz' BIC.B 1I0ICh,&SCFIO DCO current source to IMHz CLR.B &TI?D Reset all TI?-ports Store values to EEI?ROM All tasks are done, return to I?F_INIT if vcc is above Vccmin otherwise go to LI?M3 to bridge eventually the power fail time BIT.B #I?OO,&POIN Vcc above Vcmin again? JNZ I?F_INIT Yes, restart program MOV.B #PF,SYSTAT System state is 'Power Fail" BIS #CPUoff+GIE+SCG1+SCGO,SR JMI? Set LPM3 ; Continue here from BT Basic Timer Interrupt Handler: a check is made for power fail: if actual, only the return of vcc is checked. If Vcc is above VCmin, LPM3 is terminated by modification of stack info BT_HNDLR CMP.B lIPF,SYSTAT System in "Power Fail" state? JNE BT$l No, normal system states BIT.B #POO,&POIN Yes: Vcc above VCmin again? JZ BT_RTI No, return to LI?M3 BIC #CI?Uoff+SCG1+SCGO,O(SI?) ; Yes, leave LI?M3 RETI BT$1 5-180 Normal Basic Timer handler . SECT "INT_VECO",OFFE2h . WORD BT_HNDLR . SECT "INT_VECI",OFFFAh . WORD POO_HNDLR I?O.O Inrtpt Vector . WORD 0 NMI not used . WORD INIT Reset Vector Basic Timer Vector Battery Check and Pow?r Fail. Detection o . 0 Advantages • Precise due to the use of the +5V regulator voltage for reference purposes • Fast response to charge losses Disadvantages • Hardware effort (except an unused operational amplifier of a multiple pack can be used) 5.7.2.2 Power-Fall Detection WIth the Watchdog The ac-Iow detection can also be made with the internal watchdog. The watchdog is reset twice by one half-wave of the ac voltage (Vtr). If this does not occur, due to a power fail, the watchdog initializes the system. The reason for the system reset can be checked during the initialization routine and the necessary emergency actions taken. See the introduction of this section for details of these actions. The advantage of this method is the unnecessary operational amplifier, the difficulty is to react to brown-out conditions. The ac voltage is still active but too low for an error-free run. If a brown out can be excluded or is impossible due to the hardware design, the watchdog solution is a very cheap and reliable possibility for ac-Iow detection. If the restricted interval possibilities (only eight discrete time intervals) of the watchdog timer cannot satisfy the system needs, the watchdog timer can be .used as a normal timer and the needed interval built by summing-up shorter intervals with software. 5V VTR vcc 1 MQ MSP430 VPO.O AcJl1 PO.O,NMI '----------<.-------<.----1 Vss Figure 5-38. Power-Fail Detection With the Watchdog Software Applications 5-181 Battery Check and Power Fail Detection With the component values shown in Figure 5-38, a square wave out of the ac voHage (Vtr) is reached (the MSP430 inputs have Schmitt-trigger characteristics). The voltages Vtr+ and Vtr- atthe transformer output (Vtr) that switch the input voltage at the NMI (or PO.x) input are +7 V and +2 V, respectively. If these two voltage thresholds are carefully adapted to the actual environment, brown-out conditions can also be handled very safely. The equation for trem is: trem 0 edge Continue with initialization EINT Enable interrupt MAINLOOP Start normal program here NMI Interrupt Handler: an oscillator fault or the trailing edge of the TLC7701 caused interrupt due to the low input voltage VC. Check first the cause of the interrupt. The load is reduced to gain time for emergency actions. NMI_HNDLR BIT.B #OFIFG,IFG1 Oscillator fault? JNZ OSCFLT Yes, proceed there BIC.B #03Fh,&TPD Switch off all TP-outputs BIS lIPD,&ACTL ADC Power down MOV.B lI32-1,&SCFQCTL MCLK back to lMHz BIC.B lI01Ch,&SCFIO DCO drive to lMHz Switch off other loads Store values to ,EEPROM All tasks are done: switch RESET/NMI to RESET function. CPU stops until next power-up sequence. If the TLC7701 output is high again (mains back) the program restarts at INIT MOV lIOSAOOh+CNTCL,&WDTCTL BR #INIT ; PC is set to INIT ; Short power fail: Vcc high Software App'ications 5-187 . SECT "INT_VEC1",OFFFCh . WORD NMI vector . WORD Reset Vector o Advantages • o Disadvantages' • 5.7.3 Extremely safe: can handle any environment with the appropriate software and hardware combination Hardware effort (TLC7701 needed) Conclusion The concepts shown for battery check and power-fail detection are only possible due to the MSP430's hardware features: o Battery-driven systems can be realized only with microcomputers that need only a very low supply current o In ac-driven systems, the available security of MSP430 systems is due to three unique MSP430 features: 1) The low current consumption allows the remaining charge of the (relatively small) charge capacitor to be used for a lot of emergency tasks in case of a power fail 2) The high speed of the CPU allows to finish all these necessary emergency tasks during the remaining time from power-fail detection to the reaching of the lowest usable supply voltage. 3) The wide supply voltage range (+5.5 V down to +2.5 V) increases the time remaining for these tasks. These three features together allow relatively simple hardware solutions for MSP430 systems, especially the use of small charge capacitors. 5-188 Chapter 6 On-Chip Peripherals 6-1 The Basic Timer 6.1 The Basic Timer The basic timer is normally used as a time base; it is programmed to interrupt the background program at regular time intervals. Table 6-1 shows all possible basic timer interrupt frequencies that can be set by the control bits in byte BTCTl (address 040h). The values shown are for MClK =1.048 MHz. Table 6-1. Basic Timer Interrupt Frequencies SSEL--G SSEL=1 IP2 IP1 IPO 0 0 0 16348 HZ 64Hz 1524288 Hz) 64HZ 0 0 1 8192HZ 32Hz [262144 Hz) 32HZ 0 1 0 4096HZ 16Hz [131072 Hz) 16HZ 0 1 1 2048HZ 8Hz 65536 Hz 8HZ 1 0 0 1024HZ 4Hz 32768 Hz 4HZ 1 0 1 512HZ 2Hz 16348 Hz 2HZ 1 1 0 256HZ 1 Hz 8192 Hz 1 HZ 1 1 1 128HZ 0.5 Hz 4096 Hz 0.5 HZ Note: DIV=O DIV=1 DIV=O Interrupt frequencies shown in [brackets) exceed the maximum allowable frequency and cannot be used. Example 6-1. Basic Timer Control ; DEFINITION PART FOR THE BASIC TIMER BTCNT2 .EQU 047h Basic Timer Counter2 (O.ss) BTCTL .EQU 040h BASIC TIMER CONTROL BYTE: SSEL .EQU OSOh 0: ACLK 1: MCLK RESET .EQU 040h 0: RUN 1: RESET BT DIV .EQU 020h 0: fBT1-fBT 1: fBT1=12SHz FRFQ .EQU OOSh LCD FREQUENCY DIVIDER IP .EQU 00lh BT FREQUENCY Selection bits IE2 .EQU 001h INTERRUPT ENABLE BYTE 2: BTIE .EQU OSOh BT INTERRUPT ENABLE BIT 6-2 DIV=1 .BSS TlMER,4 O.ss COUNTER .BSS BTDTOL,l LAST READ BT VALUE The Basic Timer INITIALIZATION FOR 1 SECOND TIMING: 32768:(256x128)=1 Input frequency ACLK: SSEL = 0 Input division by 256: DIV - 1 Add. input division by 128: IP - 6 LCD frequency FRFQ = 3 = 128Hz: Initialization part HLD .EQU 040h 1: Disable BT MOV.B #(DIV+(6*IP)+(3*FRFQ»,&BTCTL ; 1s interval BIS.B #BTIE,&IE2 ; ENABLE INTRPT BASIC TIMER INTERRUPT HANDLER BASIC TIMER The register BTCNT2 needs to be read twice BTHAN PUSH R5 SAVE USED REGISTER L$300 MOV.B &BTCNT2,R5 READ ACTUAL TIMER VALUE CMP.B &BTCNT2,R5 ENSURE DATA INTEGRITY JNE L$300 READ AGAIN IF NOT EQUAL R5 CONTAINS ACTUAL TIMER VALUE, BTDTOL CONTAINS LAST VALUE READ. THE DIFFERENCE IS ADDED TO 'THE 1S COUNTER PUSH.B BTDTOL SAVE LAST TIMER VALUE MOV.B R5,BTDTOL ACTUAL VALUE -> LAST VALUE ACTUAL - LAST VALUE ->'R5 SUB.B @SP+,R5 ADD R5,TIMER 16-BIT DIFFERENCE ADC TIMER+2 Carry to high word POP R5 Restore R5 ~O COUNTER RETI . SECT "Int_Vect",OFFE2h • WORD BTHAN Basic Timer Interrupt Vector On-Chip Peripherals 6-3 The Basic TImer 6.1.1 Change of the Basic Timer Frequency If the basic timer is used as a time base (for example as a base for a clock), then it is necessary to compensate If the frequency is changed during the normal rUI1. The necessary operations are different for changing from a faster frequency to. a slower one than for the reverse operation. The timer register where the interrupts are counted needs to be implemented for the highest used basic timer frequency. Slow to fast change: The change should be done only inside the basic timer interrupt routine. The status is to be changed to the new time value. Fast to slow change: The change should only be done inside the basic timer interrupt routine. Afterward, all bits of the software timer register that represent the higher basic timer frequencies shOUld be reset to zero. This is the correct time for the lower frequency. Example 6-2. Basic Timer Interrupt Handler A basic timer interrupt handler that works with two frequencies, 1 Hz and 8 Hz, is shown below. All necessary status routines are shown. The handler may be used for all other possible frequency combinations as well. The background software changes the status according to the needs. HIF .EQU 8 Hi frequency is 8Hz LOF .EQU 1 Lo frequenqy is 1Hz LOBIT .EQU HIF/LOF LSB position of low frequency .BSS TIMER,2 16-bit timer register .BSS BTSTAT,1 status byte PUSH R5 Save R5 MOV.S STSTAT,RS R5 contains status (0, 2, 4, 6) BR STTAB(R5) Got to appropr. routine BT_INT STTAS CHGT8 . WORD ST1HZ STO: 1Hz interrupt • WORD ST8HZ ST2: 8Hz interrupt . WORD CHGT8 ST4: Change to 8Hz interrupt . WORD CHGT1 ST6: Change to 1Hz interrupt MOV.B #2,BTSTAT Change to 8Hz interrupt BIC.S #IP2+IP1+IPO,&BTCTL ; Clear frequ. bits BIS.S #IP1+IPO,&STCTL ; Set 8Hz, use BT1HZ for INCR. The BasIc Timer BT1HZ ADD #LOBIT,TIMER POP RS Incr. bit 3 of the 125ms timer RETI BTBHZ No change of status INC TIMER POP RS Incr. bit 0 of the 125ms timer RETI CHGT1 No change of status INC TIMER Incr. bit 0 (evtl. carry) BIC #LOBIT-1,TIMER Reset 8Hz bits to zero MOV.B #O,BTSTAT New status: 1Hz interrupt BIC.B #IP2+IP1+IPO,&BTCTL Clear frequ. bits BIS.B #DIV+IP2+IP1,&BTCTL Set 1Hz POP RS RETI . SECT nInt_Vectn,OFFE2h . WORD BT_INT Basic Timer Interrupt Vector 6.1.2 Elimination of Crystal Tolerance Error For normal measurement purposes, the accuracy of 32768 Hz crystals is more than sufficient. But, if highly accurate timing has to be maintained for years, then it is necessary to know the frequency deviation from the exact frequency of the crystal used (together with the oscillator). An example for such an application is an electricity meter that must change the tariff at given times each day without any possibility of synchronizing the internal timer to a reference. The time deviations for two crystal accuracies (+ 1 Hz and +10 ppm) are shown in Table 6-2. The data in the table indicates the amount of time required to accumulate a given time error. Table 6-2. Crystal Accuracy =± 1 S DEVIATION .. ± 1 m 32768 Hz, ± 1 Hz 9.10 hours 22.7Sdays DEVIATION ± 1 h 3.74 years 32768 Hz, ± 10 ppm 27.77 hours 69.44 days 11.40 years ACCURACY DEVIATION On-Chip Peripherals = 6-5 The Basic Timer If these time deviations are not acceptable, then a calibration and correction are necessary: 1) The crystal frequency is measured and the deviation stored in the RAM or EEPROM. All other interrupts have to be disabled during this measurement to get correct results. 2) The measured time deviation of the crystal is used for a correction that takes place at regular time intervals. The crystal frequency can be measured during the calibration with a timing signal of exactly 10 or 16 seconds at one of the ports with interrupt capability. The MSP430 counts its Internal oscillator frequency, ACLK, during this time with one of the timers (8-bit timer or 16-bit timer) and gets the deviation to 32768 Hz. The deviation measured is added at appropriate time intervals (32768 s x 10 or 32768 s x 16) to the timer register that counts the seconds. 3~56'B AO Temperature --~ calibration I - - - - - - f Unit Rgure 6-1. Crystal Calibration If necessary, the temperature behavior of the crystal can also be taken into account. Figure 6-2 shows the typical temperature dependence of a crystal. TO is the nominal frequency at a particular temperature. Above and below this temperature, the frequency is always lower (negative temperature coefficient). The frequency deviation increases with the square of the temperature deviation (-0.035 ppm/oC2 for the example) . . 6-6 The Basic Timer O~--~~--~~~--~--~~---­ ~.5 +----::I~--------~~ Crystal Temperature OC -7 Frequency Deviation ppm Figure 6-2. Crystal Frequency Deviation With Temperature The quadratic equation that describes this temperature behavior is approximately (To =+19°C): Ilf :::: -O.035x(T-19Y Where: Ilf T Frequency deviation in ppm Crystal temperature in °C To use the equation shown above, simply measure the crystal temperature (PC board temperature) every hour and calculate the frequency deviation. These deviations are added up until an accumulated deviation of one second is reached. The counter for seconds is then incremented by one and one second is subtracted from the accumulated deviation, leaving the remainder in the accumulation register. Example 6-3. Quadratic Crystal Tempe;ature Deviation Compensation The crystal temperature is measured each hour (3600 s) and calculated. The result - with the dimension ppm/l 024 - is added up in RAM location PPMS. If PPMS reaches 1024, one second is added to seconds counter SECONDS and PPMS is reduced by 1024. The numbers atthe right margin show the digits before and after the assumed decimal point. On-Chip Peripherals 6-7 The Basic Timer Quadratic temperature compensation after each hour: tcorr = -I (T-19)A2 x -0.035ppml x t Tmax = To+40C, Tmin - To-40C To .SET 19 Turning point of temperature PPM .SET 35 -0.035ppm/(T-To)A2 .BSS .BSS PPMS,2 RAM word for adding-up deviation SECOND, 2 RAM word for seconds counting TIMCORR CALL #MEASTEMP POP IROP2L Result to IROP2L 6.4h T - To Copy result (always pos.) 12.8 IT-ToI A2 Adapt IT-ToI A2 12.2 SUB #(To*10h),IROP2L MOV I'ROP2L,IROPl CALL CALL #MPYS ADC MOV lRACL #SHFTRS6 lRACL,IROP2L ;Meas. crystal temperature Rounding IT-ToI A2 -> IROP2L tcorr = 3600 x -0.035 x lE-6 x (T-19)A2 L$006 MOV CALL,' # (36*PPM) , IROPl iMPYS CALL #SHFTLS6 12.2 s/h 36 x PPM/1E4 ms/h Signed multiplication lRAC contains: 36s x PPM x 4 (To-T)A2 x 1E-7 - 36s x PPM x 4 (To-T)A2 x lE-4 6.4h 6.4h s/h ms/h to lRACM lRACM contains: tcorr - 4 x dT x 36 x PPM/l024 Correction: 0.25 x lE-7 x 1024 - 1/39062.5 L$200 6-8 ADD lRACM,PPMS Add-up deviation CMp #39062,PPMS One second deviation reached? JLO L$200 INC SECONDS SUB RET #39062,PPMS ; Yes, add one second and adjust deviation counter The Basic nmer 6; 1.3 Clock Subroutines The following two subroutines provide 24-hour clocks - one using decimal counting (RTCLKD) and one using hexadecimal Counting (RTCLK). These subroutines are called every second by the basic timer handler. SBC .BOU 0200H Byte for counting of seconds MIN .BOU 0201H Byte for counting of minutes HOURS .BOU 0202H Byte for counting of hours Subroutine provides a decimal clock: 00.00.00 to 23.59.59 RTCLKD RTRBTD SBTC Entry every second DADC.B SBC Increment seconds CMP.B #060H,SBC One minute elapsed? JLO RTRETD No, return (C CLR.B SBC Yes, clear seconds (C DADC.B MIN Increment minutes with set carry CMP.B #060H,MIN JLO RTRETD CLR.B MIN DADC.B HOURS CMP.B #024H,HOURS JLO RTRBTD CLR.B HOURS RET = 0) = 1) 00.00.00 Return to caller C - 1: one day elapsed Subroutine provides a hex clock: 00.00.00 to 17.3B.3B RTCLK INC.B SBC CMP.B #60,SEC Increment seconds JLO RTRBT One minute elapsed? Entry point every second CLR.B SEC No, return to caller INC.B MIN Yes, clear seconds CMP.B #60,MIN Increment minutes JLO RTRET On-Chip Peripherals 6-9 The Basic Timer RTRET CLR.B MIN INC.B HOURS CMP.B #24,HOURS JLO RTRET CLR.B HOURS RET 00.00.00 C = 1: one day elapsed The next subroutine increments the date with each call. The handling of leapyears is included. The data is stored in binary format. DAY .EQU 0203h Day of month 1 - 31 (byte) MONTH .EQU 0204h Month 1 - 12 (byte) YEAR .EQU 0206h Year 1990 - 2399 (word) DATE PUSH RS Save RS INC.B DAY To next day of month MOV.B MONTH,RS Look for length of month MOV.B MT-1(RS) ,RS NOFEB DATRET CMP.B #2,MONTH JNE NOFEB BIT i3,YEAR JNZ NOFEB February now? Yes, Leap Year? INC RS Yes, 29 days for February CMP.B RS,DAY One month elapsed? JLO DATRET No MOV.B III ,DAY Yes, start with 1st day INC.B MONTH of next month CMP.B- #13 ,MONTH Year over? JLO DATRET No MOV.B IIl,MONTH Yes, start with 1st month INC YEAR of next year POP RS Restore RS RET Table with the length of the 12 months 6-10 The Basic Timer MT 6.1.4 . BYTE 31+1,28+1,31+1,30+1,31+1,30+1 January to June .BYTE 31+1,31+1,30+1,31+1,30+1,31+1 July to December The Basic Timer Used as a 16-Bit Timer The two 8-bit registers BTCNT1 and BTCNT2 may be connected together and used as a simple 16-bit timer counting the ACLK. This 16-bit value can be used for time measurements by calculating the difference of two readings. The problem is that the two registers cannot be read with just one instruction, so BTCNT1 can overflow between the two readings and deliver an incorrect result. The following software corrects this possible error. If the LSBs change during the register read, then a second reading is made. This second register read is likely correct because of the relatively long time interval (30.5115). If interrupts between the readings can occur, then the interrupt can be disabled with the DINT instruction. BTCTL .equ 040h Basic Timer1 Control Register DIV .equ 020h Clock for BTCNT2 is ACLK/256 BTCNTl .equ 046h LSBs of Basic Timerl BTCNT2 .equ 047h MSBs of Basic Timerl MOV.B #DIV+xx,BTCTL Define BT as a l6-bit counter MOV.B &BTCNT1,R5 Read LSBs of Basic Timer1 OOyy MOV.B &BTCNT2,R6 Read MSBs OOxx CMP.B &BTCNTl,R5 LSBs still the same? JNE L$l No, read once more, 30.Sus time SWPB R6 Yes, prepare l6-bit result xxOO ADD R5,R6 Correct result in R6 now: xxyy L$l If the result of the first reading is important, then the following subroutine may be used. The 16-bit value is read and corrected if an overflow to 0 may have happened between the reading of the low and high bytes. Read-out of the Basic Timer running as a l6-bit timer MOV.B &BTCNT1,R5 Read LSBs OOyy MOV.B &BTCNT2,R6 Read MSBs OOxx CMP.B R5,&BTCNTl BTCNTl still >= R5? JHS L$l Yes, no overflow On-Chip Peripherals 6-11 The Basic Timer Transition from OFFh to 0 occurred with LSBs, read actual MSB, it now has the value +l. L$1 6-12 MOV.B &BTCNT2,R6 Read actual MSBs DEC.B R6 MSB - 1 is correct SWPB R6 MSBs to high byte ADD R5,R6 16-bit value to R6: xxyy OOxx xxOO The Watchdog Timer 6.2 The Watchdog Timer The internal watchdog of the MSP430 family may be used as a simple timer or as a watchdog that ensures system integrity. The watchdog function is enabled after power-on reset or a system reset. This means that if there are difficulties after the start-up of the MSP430, the watchdog will reset the system as often as it is needed for it to start successfully. The watchdog mode is described in this chapter. 6.2.1 Supervision of One Task With the Watchdog In Section 5.7.2.2 Power Fail Detection With the Watchdog, an example is given of how to use the watchdog forthe supervision of a power fail task only. This example shows the necessary hardware and the software needed to detect an impending power failure. As long as ac line voltage is present, an interrupt occurs for each polarity change of the ac line. These interrupts reset the watchdog, preventing it from timing out. If the line voltage falls below a certain level or fails completely, these interrupts disappear and the watchdog is not reset. When the watchdog times out, it initializes the MSP430 system. 6.2.2 Supervision of Multiple Tasks With the Watchdog Normally, the watchdog can only supervise one task at a time. If this task does not reset the watchdog, the MSP430 is initialized by the watchdog. In complex systems, more than one function needs to be supervised to assure correct system functionality. This is possible with a small software effort - each supervised function sets a bit in a RAM byte if it runs correctly. The mainloop then resets the watchdog only if all bits are set. This approach can be enlarged to any number of supervised functions if more than one byte is used. Example 6-4. Watchdog Supervision of Three Functions A system running with MCLK =3 MHz uses the watchdog for the supervision of three functions. o Power Fall - by the checking of the 60 Hz AC line (see section Battery Check and Power Fail Detection for details) o Function 1 - a check is made if the software reaches this background part regularly o Function 3 - a check is made if this interrupt handler is called regularly On-Chip Peripherals 6-13 The Watchdog Timer Each supervised function sets a dedicated bit in RAM byte WOB in intervals less than 10.66 ms (power-up value of the watchdog with MCLK =3 MHz) if everything is functioning normally. The mainloop checks this byte (WOB) and resets the watchdog ONLYif all three bits are set (07h). If one of the functions fails. the watchdog is not reset and will therefore reset the system. HARDWARE DEFINITIONS ACTL .EQU 0114h ACC CONTROL REGISTER: PD .EQU 1000h 1: ACC POWERED DOWN IFG2 .EQU 003h INTERRUPT FLAG REGISTER :2 POO .EQU 00lh PO.O Bit Address IEl .EQU OOOh Intrpt Enable Reg. 1 Addr. POIEO .EQU 004h PO.O Intrpt Enable Bit IFGl .EQU 002h Intrpt Enable Reg. 1 Addr. POIFGO .EQU 004h PO.O Flag Bit POlES .EQU 014h Intrpt Edge Sel. Reg. Addr. SCFQCTL .EQU 052h Sys Clk Frequ. Control Reg. SCFIO .EQU OSOh Sys Clk Frequ. Integr. Reg. WDTCTL .EQU 0120h Watchdog Timer Control Reg. WDTIFG .EQU 01h Watchdog flag CNTCL .EQU OOBh Watchdog Clear Bit WDB .EQU 020:2h RAM byte for functional bits .TEXT OEOOOh Software Start Address Watchdog reset and Power-up both start at label INIT. The reason for the reset needs to be known INIT BIT.B #WDTIFG,&IFGl Reset by watchdog? JNZ WD_RESET Yes; check reason Normal reset caused by RESET pin or power-up: lnit. system 6-14 The Watchdog Timer INITl BIS.B #8,&SCFIO Switch DCO to 3MHz drive ' MOV.B #96-1,&SCFQCTL FLL to 3MHz MCLK MOV #05AOOh+CNTCL,&WDTCTL ; Define watchdog BIS.B #POIEO,&IEl Enable PO.O interrupt BIS.B #POO,&POIES To trailing edge BIC.B #POIFGO,&IFGl Reset flag (safety) Continue initialization CLR.B WDB Clear Functional Bits #MAINLOOP Go to MAINLOOP EINT BR Enable GIE Reset is caused by watchdog: check reason and handle individually WD_RESET MOV.B JAB WDB,R5 MOV.B TAB(R5),R5 SXT R5 ADD RS,PC Build handler address Offsets may be negative! . BYTE INITl-TAB . BYTE PF-TAB power fail and function 3 . BYTE FIF3-TAB Function 1 and 3 failed . BYTE F3-TAB Function 3 failed . BYTE PF-TAB Power fail and function 1 . BYTE PF-TAB Power fail ,BYTE FI-TAB Function 1 failed . BYTE INITI-TAB All bits set: hang-up All functions failed: hang-up Missing mains voltage means power fail. supply current is minimized to enlarge active time PF BlC.B #03Fh,&TPD Switch off all TP-outputs BIS #PD,&ACTL Power down ADC MOV.B #32-1,&SCFQCTL MCLK back to IMHz BlC.B #OlCh,&SCFIO DCO drive to IMHz Switch off other loads On-Ghip Peripherals 6-15 The Watchdog Timer ••• • Store values to EEPROM All tasks are done: LPM3 to bridge eventually the power fail BIS #CPUoff+GIE+SCG1+SCGO,SR JMP INITl ; Continue here eventually The handlers for all failures except power fail. Every failure can be handled individually Fl Function 1 failed F3 Function 3 failed FIF3 Function 1 and 3 failed Background: Main Loop. If RAM-byteWOB'contains 07h then the watchdog is reset: all 3 supervised functions are OK. MAINLOOP CMP.B JNE #07h,WOB Test WOB L$l WOB does not contain 7: continue MOV #OSAOOh+CNTCL,&WOTCTL ; All OK: reset watchdog CLR.B WOB L$l Clear WOB Continue Mainloop Function 1: if the software reaches this address, the supervision bit 1 is set in WOB. This indicates normal run BIS.B n,WOB Set supervision bit 1 Function 3: if the software reaches this interrupt handler, the supervision bit 3 is set in WOB. This indicates normal run INT_HNOLR BIS.B RETI 6-16 #4,WOB Set supervision bit 3 The Watchdog Timer The POO_HNDLR is called each the mains changes polarity. The bit 2 in WDB is set to indicate: "No Power Fail". POO_HNDLR BIS.B #2h,WOB XOR. B #POO, &POIES Set mains control bit Invert edge select for PO.O RET I . SECT "INT_VECl", OFFFAh . WORD POO_HNDLR PO.O Inrtpt Vector .WORD 0 NMI not used .WORD INIT Reset Vector The interrupt handler for the watchdog operation can be simplified if a strict priority exists for the processing steps. If, for example, the priority Is from power fail (highest priority), to function 3, and function 1 (lowest priority), then the watchdog handler may look like this: Reset is caused by watchdog: check reason and handle with priority from power fail to function 1. WD_RESET BIT.B JZ #2,WDB Power fail? PF Yes, prepare for it BIT.B U,WOB Function 3 failed? JZ F3 Yes, handle it Function 1 failed? BIT.B #l,WOB JZ Fl Yes, handle it JMP INITl Hang-up occurred (WOB 7) On-Chip Peripherals' 6-17 The TimecA 1:1 UN d 6.3 The nmer_A 6.3.1 Introduction . The 16-bit Timer_A is a relatively complex timer consisting of the 16-bit timer register and several capture/compare registers. All capture/compare registers are identical, but one of them (CCRO) is used for additional functions. The architecture of the Timer_A shows some similarity to the MSP430 CPU - both of them use the principle of orthogonality (equal features for all registers). The Timer_A, whose block diagram is shown in Figure 6-3, has several registers available for different tasks. These registers are described in Section 6.3.2 The Timer_A Hardware. Note: The software and hardware examples shown are related to the MSP430x33x family. Other MSP430 family members may use other I/O ports and addresses for the Timer_A registers and signals, Also, the number of capture/ compare registers may be different. The programming principle will stay unchanged; only address definitions need to be modified. It is recommended that the data book MSP430 Family Architecture Guide and Module Library (TI literature number SLAUE10B) be consulted. The hardware related information given there is very valuable and complements the information in this chapter. The architecture of the Timer_A is not restricted to the configuration shown in Figure 6-3. Different family members of the MSP430 family have different configurationsof the Timer_A: o The minimum configuration is the timer register block and the capture/ compare block o. This allows one timing but no pulse width modulation (PWM). o The next possible configuration is the timer register block and the capture/ compare blocks 0 and 1. This allows two independenttimings or one PWM timing. o The configuration Implemented in the MSP430x33x family allows up to five independent timings or three PWM signals and a capture input for the speed control (for a 3-phase digital motor control, for example). o Larger configurations are also possible - eight capture/compare blocks for very complex applications, for example. The upper limit for the number of capture/compare registers is only the overhead coming from the actualization of the registers .and the overhead from the interrupts, themselves. 6-18 CCI801 I TAOCCIOA ACLK --0 GND - - 0 VCC - - 0 TAO CCI811 I TA1CCl1A ACLK - - 0 GND - - 0 VCC --0 TA1 CCl821 I TA2CCI2A ACLK - - 0 GND - - 0 TA3 TA4 Figure 6-3. The Hardware of the 16-Bit Time,-A (Simplified MSP430x33x Configuration) On-Chlp Peripherals 6-19 The Tim81 A Applications for the Timer_A can be: o o 6-20 Generation of up to five independenttimings (MSP430x33x configuration) Frequency generation - using the output units, the internal generated timings can be output to the external periphery of the MSP430 o Generation of the timing for RF transmission (amplitude modulation, biphase code, biphase space modulation) for the transfer of metered data (gas meters, electric meters, heat allocation meters, etc.) o o o Realization of a software SPI Realization of a software UART Digital motor control (DMC) - the MSP430x33x is able to control a 3-phase electric motor with PWM in closed loop mode o o o o TRIAC control for electric motors and other power applications o DTMF generation - the DTMF frequency pairs can be generated by software and output by three external operational amplifiers for filtering and mixing. See the third part of this chapter for hardware and software details o Crystal replacement - the frequency locked loop (FLL) of the MSP430 may be locked to the ac line frequency instead of the 32-kHz frequency of a crystal. This eliminates the need for a crystal and provides a better adaptation to the ac line frequency (for DMC applications, for example) o o PWM generation with the output units Time measurement, period measurement, pulse width measurement Frequency measurement (using the capture mode for low frequencies) Analog-to-digital converter (ADC) - a single-slope ADC can be built using the capture mode. Normal 1/0 ports switch the reference resistors and sensors Real Time Clock (RTC) - if fed by the ACLK (32 kHz), the Timer-.A can be used as an ATC with all low power modes. Time intervals of up to two seconds In steps of 2-15 s are possible. 6.3.1.1 Definitions Used with the Application Examples HARDWARE DEFINITIONS TAIV .equ 12Eh TACTL .equ 160h Timer_A Vector Register Timer...A Control Register Bits of the TACTL'Register: TAIFG .equ 00lh TAlE .equ 002h Interrupt enable bit CLR .equ 004h Reset TAR and Input Divider Interrupt flag MSTOP ,equ OOOh Stop Mode MUP .equ 010h Up Mode MCONT .equ 020h Continuous Mode MUPD .equ 030h Up/Down Mode D1 .equ OOOh Input Divider: Pass D2 .equ 040h /2 D4 .equ 080h /4 D8 .equ OCOh ISTACLK .equ OOOh ISACLK .equ 100h ACLK ISMCLK .equ 200h MCLK ISINCLK .equ 300h I NCLK CCTLO . equ 162h Capture/Compare Control Reg . 0 CCTL1 . equ i64h Capture/Compare Control Reg . 1 /8 Input Selector:TACLK CCTL2 .equ 166h Capture/Compare Control Reg. 2 CCTL3 . equ 168h Capture/Compare Control Reg . 3 CCTL4 .equ 16Ah Capture/Compare Control Reg. 4 CCIFG .equ 00lh Interrupt flag COV .equ 002h Capture overflow flag Output bit Bits in the CCTLx Registers: OUT .equ 004h CCI .equ 008h Input signal CCIE .equ 010h Interrupt enable bit Output Mode: OMOO .equ OOOh OMSET .equ 020h set OMTR .equ 040h toggle/reset output only On-Chip Peripherals 6-21 The Tlmer_A OMSR .equ 060h set/reset OMT .equ OaOh toggle OMR .equ OAOh reset OMTS .equ OCOh toggle/set OMRS .equ OEOh reset/set CAP .equ lOOh Capture/Compare switch SCCl .equ 400h Synchronized CCl SCS .equ aOOh Async/sync switch Capture input: lSCCIA .equ OOOh ISCCIB .equ lOOOh CClxA lSGND .equ 2000h GND lSVCC .equ 3000h Vcc CMDlS .equ OOOh CMPE .equ 4000h CMNE .equ BOOOh falling edge CMBE .equ OcOOOh both edges CClxB Capture mode: disabled rising edge CCRO .equ l72h Capture/Compare Register 0 CCRl .equ l74h Capture/Compare Register 1 CCR2 .equ l76h Capture/Compare Register 2 CCR3 .equ l7Bh capture/Compare Register 3 CCR4 .equ l7Ah capture/Compare Register 4 TAR .equ Ol70h Timer Register TAO .equ DOBh Bit address TAO Port3: P3.3 TAl .equ OlOh Bit address TAl port3: P3.4 TA2 .equ 020h Bit address TA2 Port3: P3.S TA3 .equ 040h Bit address TA3 Port3: P3.6 TA4 .equ OaOh Bit address TA4 Port3: P3.7 P3SEL .equ OlBh Port3 Select Register P3DlR .equ OlAh Port3 Direction Register P30lJT .equ Oi9h Port3 Direction Register Definitions of other used peripherals SCFQCTL 6-22 .equ OS2h FLL Multiplier and Mod. Bit The Timer_A M .equ 080h SCFIO .equ OSOh Modulation Bit Current Switches FN_x, FLL FN_2 .equ 004h DCO Switch for 2MHz FN_3 .equ 008h DCO Switch for 3MHz SCFIl .equ OSlh Taps of DCO POFG .equ Ol3h PortO Flag Register Address POlE .equ OlSh PortO Interrupt Enable Reg. IEl .equ o Interrupt Enable Register POIE.O .equ 4 PO.O Interrupt Enable Bit Crystal Buffer Control CBCTL .equ OS3h CBE .equ OOlh Enable XBUF output CBACLK .equ OOOh ACLK is output at XBUF CBMCLK .equ 006h MCLK is output at XBUF BTCTL .equ 040h Basic Timer Control Register BTCNTl .equ 046h Basic Timer Counter 1 WDTCTL .equ l20h Watchdog Control Register CNCTL .equ 008h Reset Watchdog Bit HOLD .equ 080h Stop Watchdog GIE .equ 008h General Interrupt Enable CPUOFF .equ OlOh CPU-Off bit SCGO .equ 040h Low Power Mode Bits SCGl .equ 080h Bits in the Status Register SR 6.3:2 Timer_A Hardware TimecA has a modular structure, giving it considerable flexibility. At least one capture/compare block is necessary for all configurations, and an almost unlimited number of capture/compare blocks may be connected to the timer register block (see Figure 6-4). The general function ofthese blocks is described I;>elow. The user software controls the TimecA with the registers that are described there. Several registers control the function of Timer_A. Every capture/compare register (CCRx) has its own control register CCTLx and the timer register (TAR) is also controlled by its own control register TACTL. This section describes all registers contained in the TimecA. On-Chip Peripherals 6-23 Thenmer A The TimecA registers have two common attributes: a All registers, with the exception of the interrupt vector register (TAIV), can be read and written to a All registers are word-structured and should be accessed therefore by word instructions only. Byte addressing results in a nonpredictable operation. Example 6-5. Timer Register Low Byte If only the information contained in the low byte of the timer register Is wanted, then the following code sequence may be used: MOV &TAR,RS Read the complete TAR: yyxxh MOV.B RS,RS OOxxh to RS If only the high byte information of the timer register is wanted: MOV &TAR,RS Read the complete TAR: yyxxh SWPB RS Swap bytes: yyxxh -> xxyyh MOV.B RS,RS OOyyh to RS Table 6-3 shows the mnemonics and the hardware addresses of the Timer_A registers. Table 6-3. Timer_A Registers REOISTER NAME ABBREVIATION REGISTER TYPE ADDRESS INITIAL STATE TACTL Read/Wrlte 160h POR Reset TAR ReadlWrHe 170h POR Reset CaplCom Control Register 0 CCTLO ReadlWrtte 162h POR Reset Cepture/Compare Register D CCRD ReadlWrlte 172h POR Reset Cap/Com Control Register 1 CCTL1 Read/Write 164h POR Reset Capture/Compare Register 1 CCR1 ReadIWrHe 174h PORReset Cap/Com Control Register 2 CCTL2 ReadlWrite 166h PORReset Capture/Compare Register 2 CCR2 ReadlWrite 176h POR Reset Cap/Com Control Register 3 CCTL3 Read/Write 16Sh POR Reset Capture/Compare Register 3 CCR3 Read/Write 178h POR Reset CaplCom Control Register 4 CCTL4 ReadlWrite 16Ah PORReset Capture/Compare Register 4 CCR4 ReadlWrite 17Ah PORReset TAIV Read only 12Eh (PORReset) Timer....A control register Timer register Interrupt Vector Register Note: 6-24 Futureextensions - more capture/compare registers - will use the reserved addresses 16Ch. 16Eh. 17Ch. and 17Eh. The Timer A 6.3.2.1 The Timer Register Block The timer register block is the main block of the TImer_A. Even the simplest version contains this block, which includes the timer register (TAR). The timer register block consists of the following parts: o Input Multiplexer - selects the timer input signal out of four possible sources o Input Divider - selects the division factor for the timer input signal (1 , 2, 4,8) o o Timer Register TAR - a 16-bit counter o Timer Control Register TACTL - contains all control bits for the timer register Block o Timer Vector Register TAIV - contains the vector of the interrupt with the actual highest priority o Interrupt Logic Mode Control - selects one of the possible four modes (Stop, Continuous, Up, Up/Down) Data DC to MClK TAClK AClK MClK INClK -0---<0..11-, --0 Equo --0 --0 POR/ClR Paas 1/2 1/4 1/8 TIMOV Sst_TAIFG Tlm.rBuB MeO o 1 o 1 From COR Blocka _ _~nT----I.!!!!:=~~:!l Figure 6-4. The Timer Register Block On-Chip Peripherals 6-25 The Timer A 6.3:2.1.1 The Timer Register (TAR) The timer register (TAR) is the main register of the timer. The timer input frequency - selected from four different sources - is prescaled by the input divider (by a factor of 1, 2, 4, or 8) and counted with this 16-bit register. The timer register Information is distributed to all other registers via the 16-bit tmer bus. This register contains the counted information in all three timer modes (Figure 6-4). The timer register is incremented with the positive edge of Its input signal, timer clock. The CCIFG flags and the TAIFG flag are also set with the positive edge if the programmed conditions are true. The maximum resolution forthe limer_A is 1ifMCLKmax. This relates to a maximum inputfrequencyforthetimerregisterequaltofMCLKmax (currently 4 MHz, 250 ns resolution for the MSP430C33x). The 16 bits of the timer register can be cleared by two methods: CLR &TAR BIS .CLR,&TACTL o -> TAR, nothing else ; Clear TAR, lnp. Div. + .count dir The second method clears not only the timer register, but also the content of the input divider and sets the count direction of the timer register to upward. 6.3.2.1.2 The Tlmer_A Control Register TACTL The timer control register (TACTL) contains all bits that control the timer register (TAR) and its operation. The control bits are reset with the power-on reset (POR) signal but the power-up clear (PUC) signal dOes not affect them. This allows a continued limecA operation if the watchdog times out or the watchdog security key is violated. The timer control register (Figure 6-5) is a word register and should therefore be accessed· with word instructions only. TACTL Input Select 160h rw(0) rw(0) rw(0) rw(0) rw- (w)- rw- rw(0) (0) (0) (0) Figure 6-5. Timer Control Register (TACTL) If the operation of the limer_A needs to be modified - with the exception of the TAIFG and TAlE bits-then the limer_A should be halted during the modification of the control bits. After the change of the TACTL register, limecA is restarted. Without this procedure, unpredictable behavior Is possible. 6-26 The TimecA :Ml Example 6-6. The Timer_A Control Register TACTL The timer should be restarted in continuous mode. This is accomplished with two instructions. The first instruction defines the new state of the timer (except the mode), and stops it (Mode Control =00). The second instruction sets the mode control bits to continuous mode and restarts the timer operation. Input Selection: MCLK Input Divider: /4, cleared Interrupt: enabled, TAlE = 1, TAIFG = 0 MOV #ISMCLK+D4+CLR+TAIE,&TACTL; Define new state BIS #MCONT,&TACTL ; Restart continuous Mode The control bits of the Timer control register are explained below. Timer Interrupt Flag TAIFG This flag indicates a timer overflow event: the timer register TAR reached the value zero. The way to get the flag TAIFG set depends on the mode used: o Continuous Mode - TAIFG is set if the timer counts from OFFFFh to OOOOh. o o Up Mode - TAl FG is set ifthe timer counts from the CCRO value to OOOOh. Up/Down Mode - TAIFG is set if the timer counts down to OOOOh. See the The Timer Vector Register TA/V section for examples how to use the TAIFG flag. Timer Overflow Interrupt Enable Bit TAlE This bit enables and disables the interrupt for the timer interrupt flag TAIFG: TAlE = 0: Interrupt is disabled TAlE = 1: Interrupt is enabled An interrupt is requested only if the TAIFG bit, the TAlE bit, and the GIE (SR.3) bit are set. The sequence of the bit setting does not matter. If two out of the three bits (mentioned above) are 1, and the third is set afterward, an interrupt will be requested. On-Chip Peripherals 6-27 The TlmecA Example 6-7. Timer Overflow Interrupt Enable Bit TAlE Interrupt is enabled for the TAIFG flag. A pending interrupt is cleared. BIC #TAIFG,&TACTL Clear TAIFG flag BIS #TAIE,&TACTL Enable interrupt for TAIFG Timer Clear Bit CLR The timer register (TAR) and the input divider are cleared, after POR or if bit CLR is set by the software. The CLR bit is automatically reset by the hardware . and always read as O. The limer_A starts operation with the next positive edge of the timer clock. The counting starts in upward direction if it is not halted by cleared Mode Control bits. Example 6-8. Timer Clear Bit CLR Timer_A is restarted after the calibration process. It needs a complete reset: up/down mode, upward count direction, interrupt enabled, MCLK passed to the timer register, input divider cleared. MOV tISMCLK+Dl+CLR+TAIE,&TACTL; Define state BIS #MUPD,&TACTL ; Start Up/Down Mode BIt3 Not used. Read as O. To maintain software compatibility, this bit should NOT be set. Mode Control Bits The two mode control bits define the operation of the limer_A. Table 6-4 lists the four possible modes. See Section 6.3.3 The Timer Modes for a detailed description of the timer modes. " the mode control bits are cleared (stop mode), a restart of the timer operation is possible exactly at the point where the operation was halted, including the count direction information used with the up/down mode. Table 6-4. Mode Control Bits MODE CONTROL BITS 6-28 COUNT MODE Stop Mode COMMENT TImer is halted 0 1 2 Continuous Mode Count up to CCRO and restert at 0 Count up to OFFFFh and restart at 0 3 Up/Down Mode Count up to CCRO and back to 0, restart Up Mode The TimecA Example 6-9. Mode Control Bits limer_A is stopped and restarted in continuous mode. BIC iMUP+MCONT,&TACTL; Stop Timer_A BIS iMCONT,&TACTL Restart in Cont. Mode Input Divider Control Bits The two input divider control bits allow the use of a prescaled input frequency (timer clock) for the timer register (TAR). A prescaler may be necessary because of any of the following: D The MCLK frequency (up to 4 MHz) is too high for the task. D The MCLK frequency leads to an overflow of the timer register (TAR) during the necessary measurement periods. This makes a RAM extension of the TAR necessary. which takes time and occupies RAM space. D The resulting resolution is not necessary. D The resulting timer register contents lead to numbers that are too large during the calculations. D Power savings is important. If one the above reasons is true. then a prescaled input frequency should be used. The possible prescale factors are shown in Table 6-5. Table 6-5. Input Divider Control Bits COMMENT INPUT DIVIDER BITS MODE 0 1 Pass Input signal is passed to the Timer Register +2 Input signal is divided by 2 2 +4 Input signal Is divided by 4 3 +8 Input signal Is divided by 8 Example 6-10. Input Divider Control Bits The input divider is changed from pass mode (0) to divide-by-4 mode (2): BIC #MUP+MCONT,&TACTL ; stop Timer-A BIS #MUP+D4+CLR,&TACTL ; Continue in Up Mode On-Chip Peripherals 6-29 TheTimerJ, Input Selection Bits The three input selection bits select the input signal of the input divider. Four different sources are provided as shown in Table 6-6. The INCLK input may be used for a fourth input source with other family members. Table 6-6. Input Selection Bits (MSP430x33x - Source Depends on MSP430 Type) INPUT SELECT BITS SIGNAL 0 1 TACLK ACLK COMMENT Signal at the external pin TACLK is used ACLKisused 2 MCLK MCLKisused 3 INCLK MCLK for the MSP43OC33x 4-7 NfA Reserved for future expansion The highest timer resolution is possible with the internal MCLK signal: the full range of the MClK frequency may be used. If the external pin TACLK (P3.2 for the MSP430C33x) is selected, then the maximum input frequency is restricted due to the internal capacities of the signal path. See the specification for actual limits. Example 6-11. Input Selection Bits Tlmer_A is initialized. Continuous mode, interrupt enabled, ACLK - divided by 2 - routed to the timer register, timer register and input divider are cleared. MOV BIS #ISACLK+D2+CLR+TAIE,&TACTL #MCONT,&TACTL Define state ; Start timer: Cont. Mode Bit 11 to 15 Not used. Read as O. To maintain software compatibility, these bits should NOT be set to 1. 6-30 The Timer A 6.3.2.1.3 The Timer Vector Register TAIV .This 16-bit register contains an even vector ranging from 0 (no interrupt pending) via 2 (CCR1 interrupt) to 10 (timer overflow interrupt TIMOV). See Figure 6-6 and Table 6-7 for more information. I TAIV 12Eh 15 0 ~ I I I I I I I I I I I 0 0 0 0 0 0 0 0 0 0 0 l,nte:;uPI ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ v~or I H~~~H~ o 0 ~ Figure 6-6. Timer Vector Register (TAIV) If more than one interrupt is pending. then the vector with the highest priority is placed into the TAIV register. See figure 6-7. Table 6-7 illustrates the interrupt priority scheme of Timer_A: Table 6-7. Timer Vector Register Contents INTERRUPT PRIORITY Highest INTERRUPT SOURCE VECTOR ADDRESS VECTOR REGISTER CONTENTS Capture/Compare 0 CCIFGO OFFF2h NlA Capture/Compare 1 CCIFG1 OFFFOh 2 Capture/Compare 2 CCIFG2 OFFFOh Capture/Compare 3 CCIFG3 OFFFOh Capture/Compare 4 CCIFG4 OFFFOh OFFFOh Reserved NlA 4 6 8 10 12 No interrupt pandlng NlA 0 Timer OVerflow Lowest FLAG TAIFG The timer vector register allows a very fast response to the differenttimer interrupts. Its content is simply added to the program counter (PC). using a JMP table located directly after the ADD instruction: ADD &TAIV,PC RETI HTIMOV INTRPT with highest priority 0: No INTRPT pending JMP HCCR1 JMP HCCR2 4: CCIFG2 caused INTRPT JMP HCCR3 6: CCIFG3 caused INTRPT JMP HCCR4 2: CCIFG1 caused INTRPT 8: CCIFG4 caused INTRPT 10: TAIFG is reason On-Chip Peripherals 6-31 The Timer A If the corresponding interrupt handlers are out of the reach of JMPs (more than ±511 words), then a word table containing the handler start addresses may be used: TTAB MOV MOV . WORD . WORD . WORD . WORD . WORD . WORD TAIV contains vector: o - 10 Write handler address to PC 0: No INTRPT pending, RETI 2: CCIFG1 caused INTRPT 4: CCIFG2 caused INTRPT 6 : CCl;FG3 caused INTRPT 8 : CCIFG4 caused INTRPT 10: TAIFG is reason &TAIV,RS TTAB(RS} ,PC PRETI HCCR1 . HCCR2 HCCR3 HCCR4 HTIMOV A third (slower) method is to read the content of the register TAIV and to use the read value for the decision of where to proceed (the interrupt flag with the highest priority is reset by the MOV instruction): MOV CMP JEQ CMP JEQ &TAIV,RS #2,R5 HCCRl #4,RS HCCR2 , ; Actual vector to Check for CCIFG1 2: CCIFGl caused Check for CCIFG2 4: CCIFG2 caused a.s.o. R5. Reset flag interrupt INTRPT interrupt INTRPT The next software example shows a method that does not use the register TAIV. A normal skip chain is used. Only the software for blocks 0 and 1 is shown (this example makes the advantages of using the TAIV register obvious): BIT JNZ BIT JNZ tCCIFGO,&CCTLO MODO #CCIFG1,&CCTL1 MOD1 MODO BIC #CCIFGO,&CCTLO MOD1 BIC #CCIFG1,&CCTL1 Block 0: Flag set? Yes, serve it Block 1: Flag set? Yes, serve it Continue with skip chain Reset CCIFGO flag Start handler for block 0 Reset CCIFG1 flag Start handler for block 1 The capture/compare block 0 is not included in the TAIV register; it has its own interrupt vector located at address OFFF2h. The shorter interrupt latency time of register CCRO, makes it the preferred choice for the most time critical applications. The vector for the other Timer~ interrupts is located at address oFFFOh. 6-32 The Timer A Note: The timer vector register contains only the vectors of timer blocks with enabled interrupt (set CCIEx resp. TAlE bits). Blocks with disabled interrupt bits (reset CCIEx resp. TAlE bits) can be checked by software if their CCIFG resp. TAIFG flag is set and the flag must be reset by software too. See the skip chain example above . . No interrupt flag (CCIFGx or TAIFG) needs to be reset if the register TAIV is used. The act of reading of the timer vector register TAIV resets the interrupt flag automatically that determines the actual register content. The interrupt flag with the next lower priority level defines the timer vector register TAIV afterward. Note: Any access to the timer vector register (read or write) resets the interrupt flag with the highest priority. The timer vector register should be read only and the read data should be used to determine the interrupt handler with the highest priority. otherwise the data is lost. . On-Chip Peripherals 6-33 The Timer A Figure 6-7 shows the internal interrupt logic that controls the register TAIV. The five controlling inputs are shown. Priority Encoder CCII EQUI CAPI Timer Clock rg- ~ J S Sel --+- .I CCIEI (Interrupt Enable) ~rJ -s--S Sel --+- ooIFG2 _ J ) CCIE2 IRACC CCI3 EQU3 CAP3 Timer Clock -s--S Sel --+- CCIFG3 _ - J ) CCIE3 IRACC 0014 EQU4 CAP4 Timer Clock -s--- TImer'FFFF' -s--- S Sel --+- CCIFG4 _ - J CCIE4 , .I IRACC Time,='CCRO' Mode Time, Clock S Sel Vector Generator TAIFG (Flag) _ J ) ~ tj- ~ IRACC (Reset Flag) 4 Interrupt_Servlce_Rsquest 6 tJ ~ tJ-' '" I 1; - TAlE (Interrupt Enable) 4- 2 '-- IRACC (Interrupt Acknowledge) CCI2 EQU2 CAP2 Timer Clock TAIV Access CCIFGl (Flag) TAIV Contsnt (0-10) 8 10 '" Figure 6-7. Simplified Logic of the Timer Interrupt Vector Register 6-34 The Timer A 6.3.2.2 The Cspture/COmpBl'8 Register Blocks Figure 6-8 illustrates the capture/compare register block 1. The others, with the exception of the capture/compare register block 0, are identical The CCRO block has additional functions. See section The Period Register CCRO, below. OOISll I TA 1 COil A --<:>-<>"-, AOLKCOl1B - - 0 ,...----, Capture GND - - 0 Vco TAl --0 CCll OOMll 00M10 o 0 o 1 1 0 1 Disabled Positive Edge Negative Edge Both Edges 1b Other Capture/Compare BtockS Figure 6-8. Capture/Compare BLock 1 6.3.2.2.1 The Cspture/COmpBl'8 Registers CCRx These registers may be used individually as oompare registers or as capture registers. Any combination is possible. o 15 CCRx 17yh I I I I I I I I I I I 1 1- I I I rw-(O) rw-{O) rw-(O) rw-(O) rw-(O) rw-(O) rw-{O) I Figure 6-9. The Capture/Compare Registers CCRx o Compare Mode With Continuous Mode - the register CCRx contains the time information for the next interrupt. Within the interrupt handler, the time Information for the next interrupt is prepared. The number An (corresponding to the time interval at from the last interrupt to the next one) is added to CCRx. The interrupt latency time does not playa role in this method. See the example in section The Continuous Mode. The output units may be used to generate output changes at output pins TAx with an exactly defined timing, independent of interrupt latency times. o Compare Mode With Up Mode or Up/Down Mode - the capture! compare' register 0 is used as the period register with these two modes. On-Chip Peripherals 6-35 The Timer A The register CCRx contains the time interval between interrupts respective the pulse width of the output signal at TAx. The registers CCRx are modified depending on the result of the control calculations. If no pulse width change is necessary, the timing is repeated without CPU intervention. o Capture Mode With Continuous Mode - a register (CCRx) used with the capture mode, copies the timer register at the precise moment the selected capture conditions are satisfied. This allows very accurate measurements of timings independent of the interrupt latency time. If the time intervals to be captured are longer than 65536 timer register steps, then a RAM extension (TIMAEXT) is necessary. This RAM extension is incremented with the TAIFG interrupt and used with the calculations as shown below: n eapt = 65536 X next + 1I.rAR This means: with the continuous mode the RAM extension contains simply the extendedtimer bits 17 through 31. No correction or calculation is necessary. 6-36 o Capture Mode With Up Mode - this method of capturing is exactly the same as described above for the continuous mode. But the up mode uses only a part of the timer register range. If the time interval to be captured is longer than the content of the period register (CCRO), then a RAM extension (TIMAEXT) is necessary. This RAM extension is incremented with the CCIFGO or TAIFG Interrupt and used with the calculations as shown below: o Capture Mode With Up/Down Mode -this method of capturing is exactly the same as described above for the continuous mode. But the up/down mode uses only a part of the timer register range and this part is counted up and down. Therefore, the actual count direction should also be considered. If the time Interval to be captured is longer than the doubled content ofthe period register (CCRO), then a RAM extension (TIMAEXT) is necessary. This RAM extension is incremented with the CCIFGO interrupt and with the TAIFG interrupt. The LSB of the RAM extension (TIMAEXT) indicates the count direction. The RAM extension TIM32 must be initialized to zero. The TimecA LSB of TIMAEXT =0 - Timer register counts upwards LSB of TIMAEXT =1: Timer register counts downwards Where: ncapt next nCCRO nTAR Resulting cycle value for captured signals (> 16 bits) Content of the timer register RAM extension TIMAEXT Content of the period register CCRO Captured content of the timer register TAR (captured in CCRx) Figure 6-10 illustrates the logic used for the capture/compare registers. CClx Figure 6-10. Function of the Capture/Compare Registers (CCRx) On-Chip Peripherals 6-37 Thenmer A 6.3.2.2.2 The Capture/Compare Control RegIsters CCTLx Each capture/compare block has its own control word CCTLx. Figure 6-11 illustrates the organization ofthese control words - it is the same for all ofthem. The main bit of these registers is the CAP bit (CCTLx.8), which determines if the capture/compare block works in the capture mode or in the compare mode. CCTLx 162h to 16Ah rw(0) rw(0) rw- rw- rw- rw(0) (0) (0) (0) rw(0) rw(0) rw(0) rw- rw(0) (0) Figure 6-11. Timer Control Registers (CCTLx) The POR signal resets all bits of the registers (CCTLx), but the PUC signal does not affect them. This permits continuation with the same timing after a watchdog reset, if this is necessary. Capture/Compare Interrupt Flag CCIFG This flag indicates two different events depending on the mode in use: ill Capture Mode If set, it indicates that a timer register value was captured in the corresponding capture/compare register (CCRx). • Compare Mode If set, it indicates that the timer register value was equal to the data contained in the corresponding capture/compare register (CCRx). The signal EaUx is also generated. The CCI FGO flag is reset automatically when the interrupt request is accepted~ It is a single-source interrupt flag and its interrupt vector is located at address OFFF2h. The reset of the CCIFG1 to CCIFGx flags depends on: • The timer vector register TAIV is used The flag that determines the actual vector word (content of TAIV) is reset automatically after the register TAIV is read. • The timer vector register TAIV is not used The flags CCIFG1 to CCIFGx must be reset by the interrupt handler 6-38 The Timer_A If the interrupt capability is not enabled for a capture/compare block then the flag CCIFGx must be tested to check ifthe block x needs service. The CCIFG flag must be reset by software for this case: BIT #CCIFG,&CCTLx JZ NO_FLAG Flag set? No continue BIC #CCIFG,&CCTLx Yes, reset flag Execute task for block x Example 6-12. Capture/Compare Interrupt Flag CCIFG See the examples in section The Timer Vector Register TAIl/. Examples forthe treatment of the CCIFG flags are given there. Capture Overflow Flag COY This flag indicates two different events depending on the mode in use: • Compare Mode No function. The COY bit is always reset, independent of the state of the capture input. • Capture Mode The capture overflow flag COY is set if a second capture event occurred before the first capture sample was read out of the capture register (CCRx). The COY flag allows the software to detect the loss of synchronization and helps to reacquire synchronization. The COY flag Is not reset by the reading ofthe CCRx register and must be reset by software. Example 6-13. Capture Overflow Flag COV The interrupt handler of capture/compare block 2 - running in capture mode - checks first to see if a capture overflow occurred. HCCR2 BIT #COV,&CCTL2 Capture overflow ? JNZ COV2 Yes, handle it MOV &CCR2,CAPST02 Store valid captured value Proceed with task Error handler for Capture/Compare Block 2 On-Chip Peripherals 6-39 COV2 BIC #COV, &CCTL2 Reset overflow flag COy Check reason for overflow RET I Output Bit OUT The state of the output bit OUT defines the output signal (TAx) of output unit x if the output mode 0 (output only) is selected. See section The Output Units for details. The state of the output signal (TAx) is always indicated by this bit, independent of the output mode in use. A modification of the output signal is possible only if the output mode 0 is selected. The OUT bit allows the definition of the start condition for PWM. Example 6-14. Output Bit OUT The output unit 3 is not used currently by Timer_A. To place TA3 in a defined state, output mode 0 is used and output TA3 is reset. BIC #OEOh+OUT,&CCTL3; output only·to OUT3: 0 BIC #OEOh,&CCTL3 BIS #OUT,&9CTL3 If output TA3 should be set initially the following sequence is used: Output only to OUT3 ; Set OUT3 Capture/Compare Input Bit CCI The CCI bit allows to read the state of the selected capture input: the input signal (CClxA at pin TAx, ACLK, Vee or Vss) can be read independent of the selected mode. See figure 6-10 for details. Example 6-15. Capture/Compare Input Bit CCI The timer block 4 - running in capture mode - uses different software parts for the leading and the trailing edges of the input signal. The interrupt handler checks via the CCI4 bit which edge is the actual one. Initialization part: Capture both edges, TA4 input, synchronized capture, Capture Mode, interrupt enabled 6-40 The Timer A HCCR4 MOV #CMBE+ISCCIA+SCS+CAP+CCIE,&CCTL4 Initialize Interrupt handler Block 4 .equ $ BIT #CCI,&CCTL4 Input signal positive? JNZ TA4POS Yes: leading edge occurred No, handle trailing edge RETI TA4POS Handle leading edge RETI Capture/Compare Interrupt Enable Bit CCIE This bit enables and disables the interrupt for the capture/compare interrupt flag CCIFGx: CCIE =0: Interrupt is disabled CCI E = 1: Interrupt is enabled Interrupt Is requested only if the CCIFG bit, the corresponding CCIE bit, and the GIE bit (SR.3) are set. The sequence of the bit setting does not matter. If two out of the above-mentioned three bits are 1 and the third is set afterward, an interrupt will be requested. Example 6-16. Capture/Compare Interrupt Enable Bit CCIE The interrupt of timer block 2 is disabled. Now the interrupt should be enabled again. But if the CCIFG2 flag is set, no interrupt should occur. Ail other bits in register CCTL2 should retain their states. BIC ffCCIE,&CCTL2 Disable interrupt Block 2 Continue The interrupt for Timer Block 2 is enabled again. A pending interrupt is cleared BIC #CCIFG,&CCTL2 Reset CCIFG2 flag BIS ffCCIE,&CCTL2 Enable interrupt Block 2 On-Chip Peripherals 6-41 The Timer A Output Mode Bits These three bits define the behavior of the output unit x. Table 6-8 illustrates the influence ofthe signals EQUx and EQUO to the output signal TAx. The table shows the actions when timer register TAR is equal to CCRx or CCRO. Table 6-8 is valid for all timer modes. Table 6-8. Output Modes of the Output Units OUTPUT MODE 0 NAME TAR COUNTED UP TO CCRx Output only TAR COUNTED UP TO CCRO TAx is set according to bit OUTx (CCTLx.2) 1 Set Sets output No action 2 Toggle/Reset Toggles output Resets output 3 SetlReset Sets Output Resets output 4 Toggle Toggles output No action 5 Reset Resets output No action 6 7 Toggle/Set Toggles output Sets output Reset/Set Resets output Sets output See the examples given in the section The Output Units. Capture/Compare Select Bit CAP The CAP bit defines if the capture/compare block works in the capture mode or in the compare mode. This bit influences the function of nearly aU other control bits located in the same capture/compare control register. See figure 6-1 0 for an explanation of the used logic. CAP =0: The compare mode is selected CAP = 1: The capture mode is selected Example fr.17. Capture/Compare Select Bit CAP The use of this bit is explained with aU other control bits. Bit 9 Not used. Read as O. To maintain software compatibility this bit should NOT be set to 1. 6-42 The Timer A Synchronized Capture/Compare Input SCCI • Compare Mode TheSCCI bit is the output of a transparent latch. This latch is in transparent mode as long as the timer register TAR is equal to CCRx. The SCCI bit stores the selected capture input (ACLK, Vee, or Vss) when the timer register TAR becomes unequal to register CCRx. • Capture Mode The state of this bit is not defined. No EQUx signal is available in capture mode. ' Example 6-18. Synchronized Capture/Compare Input SCCI The timer bock 4 - running in capture mode - uses different software parts for the two possible states of the ACLK signal when the EQU4 Signal comes true. The Interrupt handler checks via the SCCI4 bit the state of the ACLK signal when CCR4 was equal to the timer register (TAR). The read information is shifted into a RAM word DATA. Initialization part: ACLK, Compare Mode, interrupt enabled Output Unit disabled, clear CCIFG HCCR4 MOV #ISCCIB+OMOO+CCIE,&CCTL4 ; Init. Timer_A MOV &CCR4,DATA Interrupt handler Block 4 BIT ACLK signal -> Carry JNZ #SCCI,&CCTL4 TA4POS RRC DATA Shift captured info in DATA ACLK was high during EQU4 Execute task for low input RET I TMPOS RRC DATA Shift captured info in DATA EXecute task for high input RETI Synchronization of capture Signal Bit SCS The capture signal can be read in asynchronous mode or synchronized with the selected timer clock. The SCS bit selects the mode to be used. See also Figure 6-10 for a depiction of the internal logic. On-Chip Peripherals 6-43 The Timer A • SCS=O The asynchronous capture mode sets the CCIFG flag immediately when the capture conditions are met (rising edge, falling edge, both edges) and also immediately captures the timer register. This mode may be used if the period of the captured data is much longer than the period of the selected timer clock. The captu'red data may be incorrect for high input frequencies at terminal TAx. • SCS=1 The synchronous capture mode - which is used normally - synchronizes the setting of the CCIFG flag and the capturing of the selected capture input with the selected timer clock. The captured data is always valid. Example 6-19. Synchronization of Capture Signal Bit SCS See Example for Capture Compare Input bit CCI. Capture/Compare Input Selection Bits These two bits select the input signal to be captured. The operation for the captured signal is different for capture mode and compare mode: • Compare Mode The selected Input signal is read and stored with the EQUx signal. See the description of the SCCI bit, above. • Capture Mode The selected input signal captures the timer register TAR into the capture/compare register CCRx when the conditions defined in the capture mode bits are met. See the description of the capture mode bits below. Table 6-9. Capture/Compare Input Selection Bits (MSP430x33x) INPUT SELECTION BITS INPUT SIGNAL 0 COMMENT Signal at the external pin TAx Is selected 1 CClxA CClxB 2 VSS For software capturing 3 VCC For software capturing ACLK is selected Capture Mode Selection Bits. These two bits select the capture operation for the input signal to be captured: TheTIme,-A • Compare Mode No function. • Capture Mode The content of the timer register TAR is stored in the capturel compare register CCRx when the capture condition is true forthe selected input signal. The capture conditions are listed in Table 6-1 O. Table 6-10. Capture Mode Selection Bits COMMENT CAPTURE MODE BITS 0 Capture mode is disabled 1 Capturing is done with the rising edge (0 to 1) 2 Capturing is done with the failing edge (1 to 0) 3 Capturing is done for both edges Example 6-20. Capture Mode Selection The capture/compare block 3 - running in capture mode - measures the period of the input signal CCI3A at terminal TA3. The measurement Is made continuously between two rising edges. The calculated period is stored in the RAM location PERIOD for the use by the background software. The actual value of CCR3 is stored in OLDVAL for the next calculation. Timer_A uses the continuous mode. Initialization part: Capture rising edge, TA3 input, synchronous capture, Capture Mode, interrupt enabled PERIOD .equ 0200h Calculated period OLDVAL .equ 0202h Storage of last pos. edge time MOV #CMPE+ISCCIA+CAP+CCIE+SCS,&CCTL3 .equ $ Interrupt handler Block 3 Captured TAR, rising edge HCCR3 Init. PUSH &CCR3 MOV @SP,PERIOD SUB OLDVAL,PERIOD New - old = period POP OLDVAL For next calculation RETI On-Chip Peripherals 6-45 . The TimscA 6.3.2.2.3 The Period Register CCRO The purpose of register CCRO changes with the used timer mode. o ContInuous Mode - If this mode Is used, CCRO is a capture/compare register exactly like the other four registers (CCR1 to CCR4). See section The TimecA Modes for details. o Up Mode or UpiDown Mode - with one of these modes selected, the register CCRO works as the perloQ register for the TImer_A, which defines the length of the timer period. Whenever the timer register (TAR) reaches the value of CCRO (EQUO =1), the following actions occur, depending on the mode in use: • UpMode The timer register is cleared with the next timer clock and restarts from the value O. This continues automatically without any software intervention ·necessary. See section The Timer_A Modes. • Up/Down Mode The timer register changes the count direction and starts to count down to 0 with the next timer clock. If 0 is reached, the timer register counts up again with the next timer clock until the value of CCRO is reached again. This continues automatically without any further software intervention necessary. See section The TimecA Modes. With the up mode or up/down mode selected, the EQUO signal is valid if the timer register (TAR) equals the period register (CCRO). or if it is greater than CCRO. This is not the case for the other registers (CCRx). The value 0 is not a valid content for the period register: the TImer_A blocks. The content of the period register CCRO is not modified normally. The timer period is a constant value (50 ~ for a repetition rate of 20 kHz - this means 200 cycles for a 4 MHz MCLK). But this value may also be modified if necessary. 6-46 6.3.3 Timer Modes limer_A provides three different operating modes as well as the stop mode: o Continuous Mode - the normal mode, except when high-speed PWM generation is necessary o o o Up Mode - used for high-speed, asymmetric PWM generation Up/Down Mode - used for high-speed, symmetric PWM generation Stop Mode - limecA is halted, all control bits retain their status One of the. advantages of Timer_A is the absolute synchrony of all timings and output signals. This is due to the single timer register (TAR) that controls all timings. This synchrony is very important for the interdependence of timings, for example, if the MSP43D is used with a 3-phase digital motor control application (OMC). The equations shown in the next sections use the following abbreviations: at t Time interval cretween two similar interrupts Time e.g. period of a PWM signal lpw Pulse width of a PWM signal M Cycle value added to a CCRx register (timer clock cycles) n Number - content of a register (CCRx) k Predivider constant of the input divider (1, 2, 4 or 8) fClK Input frequency at the input divider input of TimecA nCCRO Content of the period register CCRD [s1 [s1 Is] [Hz] The calculation formulas and explanations for the capture mode are given in the section Capture/Compare Blocks. 6.3.3.1 The ContInuous Mode This mode allows up to five completely independent, synchronous timings. The capture/compare register, CCRD, works exactly the same as the other registers (CCRx) when running in continuous mode. Note: The signal EQUD has the same influence on the Mode Control Logic as it does in the other timer modes. This means that only the Sst, Reset, and Toggle modes should be used if independent output signals are desired. Figure 6-12 shows two independent timings generated by capture/compare registers CCRD and CCR1. The content of the capture/compare registers On-Chip Peripherals 6-47 TheT/mer A (CCRx) is updated by software during each interrupt sequence by the addition of a calculated value, An. The value An represents a time interval, At, expressed in timer clock cycles. The software is described below. See the example for details. . The formulas for a given time interval, At, respective the corresponding cycle value An are: At = f:J.n x k ~ f:J.n = At >= MIN Yes, ok No, set error state 1 Reset overflow flag Back to main program The tasks started by the interrupt handlers are not shown; these include: o o o o o o 6-50 Incrementing software counters Checks after regular time intervals (keyboard, watchdog reset, etc.) Input tests Update of status bytes, etc. Measurementintervals Frequency generation with the output units The Timer A 6.3.3.2 The Up Mode The up mode is mainly used for the generation of asymmetric PWM signals. These PWM signals are absolutely synchronous due to the single timer register used for all signals. The period of the PWM repetition frequency is loaded into the period register (CCRO) and the pulse width for each ofthe outputs, TA 1 through TA4, is loaded into the capture/compare registers, CCR1 through CCR4. The formula for a given timer period, t, with respect to the corresponding cycle value neeRO is (neeRO < 65536): t = (nccRO + 1) xk t xfcLK_1 --+- nCCRO = fCLK k The formula for a given pulse width tpw and the corresponding cycle value n (the content of CCRx) is (n < 65536): n xk tpw = - - --+- n = fCLK tpw xfeLK k As long as no modifications to the period register or the capture/compare registers are made, the PWM signals are repeated without any CPU intervention necessary. The number of timer clock cycles between two equal timer register contents is neeRO +1. On-Ghip Peripherals 6-61 The Timer_~ •• OFFFFh CCROr---------~5a~--------. .~------~ CCR2~~----~--~~~--~--_H~~-----­ Oh~~----+---~~----~--~~~------ --+_...._ TA1 output 1--'-_ _+-__-/--'__........__ CCR1: output Mode 2: PWM Toggle/Reset or Output Mode 3: PWM Set/Reset CCR2: TA2 Output I-+--"I--+-I--.."...--P--""""'" Output Mode 8: PWM Toggle/Set or Output Mode 7: PWM Reset/Set TAO Output 1--........- ~+----4--~~~--~---*~-- E U2 EQUO TIMOV EQU1 EQU1 E U2 EQUO TIMOV CCRO: Output Mode 4: PWM Toggle Interrupts Generated Figure 6-13. Three Different Asymmetric PWM Timings Generated With the Up Mode If the timer register (TAR) reaches the content of capture/compare register CCRx (EQUx .. 1), with compare mode selected for capture/compare block x, then the content of the output unit x is modified. Depending on the output mode defined in the control register CCTLx, the output is toggled, set, reset, or not affected. If the interrupt for the capture/compare block is enabled, an interrupt is also generated. Ifthe timer register (TAR) counts up to the content ofthe period register CCRO (EQUO ... 1), then the timer register (TAR) is reset to 0 with the next timer clock and the content of the output units are toggled, set, reset, or not affected, depending on the selected output mode in control register CCTLx. The timer register continues with the counting starting at o. If the interrupt for the reaching of CCRO is enabled, then an interrupt is also requested. See Figure 6-13. 6-52 The Timer A Notes: The three interrupts caused by the TAIFG flag, the CCIFGO flag, and CCIFGx flags do not occur simultaneously if used with the up mode: o The CCIFGx flag is set when the capture/compare register x equals the timer register (TAR) (EQUx = 1) o The CCIFGO flag is prepared when the timer register equals the period register CCRO (EQUO =1). The CCI FGO flag is delayed one timer clock cycle and set, therefore, together with the TAIFG flag (timer register TAR contains 0) , o The TAIFG flag is set when the timer register is reset to 0 (TIMOV =1) This means for the up mode: only one interrupt handler is necessary together for the TAIFG flag and the CCIFGO flag. If the period register CCRO contains 0, then the timer register TAR continues counting until it also reaches O. Then the counting stops until a nonzero value is written to CCRO. Example 6-22. Three Different Asymmetric PWM Timings Generated With the Up Mode The software for the example illustrated in figure 6-13 is shown below. capture/compare block 1 generates a negative pulse with output unit 1, capture! compare block 2 generates a positive pulse with the output unit 2 and capture! compare block 0 (the period register block) outputs an evenly spaced output pulse with its output unit o. The initializing part of the example Is also shown. If no tasks must be executed (here tasks 0, 1, and 2), the interrupts may be switched off; the pulse generation continues. Initialization of the Timer-A: Up Mode, /1, interrupt enabled, MCLK INIT = 3.8MHz MOV #ISMCLK+D1+CLR+TAIE,&TACTL MOV #OMT+CCIE,&CCTLO ; Prepare Timer_A ; CCRO: toggle TAO MOV #OMTR+CCIE,&CCTL1 ; CCR1: toggle/reset TAl MOV #OMRS+CCIE,&CCTL2 ; CCR2: reset/set TA2 MOV MOV #190-1,&CCRO #114, &CCR1 MOV #48, &CCR2 fccrO = 20kHz tpw1 - 30us BIS.B tpw2 - 12.6us #TA2+TA1+TAO,&P3SEL; Enable TA2,TA1 TAO BIS #MUP,&TACTL ; Start init. timer. Up Mode On-Chip Peripherals 6-53 The Timer A ; Continue Interrupt handler for the Period Register CCRO C/C Block 0 outputs a signal with 1/2 of the frequency of the other C/C Blocks (50%/50%). It also increments the RAM extension of the Timer Register TIMAEXT. It is initialized to: toggle (EQUO) TIMMODO .EQU INC $ TIMAEXT start of handler Incr .. timer extension TaskO starts here RETI Interrupt handlers for Capture/Compare Blocks 1 to 4. TIM_HND .EQU ADD RETI JMP JMP JMP JMP $ &TAIV,PC TIMMODl TIMMOD2 TIMMOD3 TIMMOD4 TIMOVH Interrupt latency time Add Jump table offset TAIV - 0: No interrupt TAIV - 2: C/C Block 1 TAIV - 4 : C/C Blcck 2 TAIV = 6 : C/C Block 3 TAIV = s: C/C Block 4 TAIV - 10: Timer OVFL C/C Block 1 outputs a negative pulse automatically. It is ; initialized to: toggle/reset (EQU1/EQUO) TIMMODl .EQU Vector 2: C/C Block 1 Task1 starts here Back to main program $ RETI C/C Block 2 outputs a positive pulse automatically. It is initialized tc: reset/set (EQU2/EQUO) TIMMOD2 .EQU Vector 4: C/C Block 2 Task2 starts here Back to main program $ RETI The tasks started by the interrupt handlers are not shown; these may include: Pulse width modulation for control purposes with the output units DC generation (DAC) with the output units o Tasks like those shown for the continuous mode, but with special treatment due to the short period. The RAM extension (TIMAEXT) must therefore be taken into account for measurement. o o 6-54 The Time,-A 6.3.3.3 The Up/Down Mode The up/down mode is a symmetric PWM mode. Up to four absolutely synchronous PWM outputs may be generated. The advantage of this PWM mode is a minimum of generated harmonics due to the distributed switching of the output units. The half period of the PWM repetition frequency is loaded into the capture/compare register (CCRO) and a calculated number for the pulse width for each one of the used outputs (TAx) is loaded into the capture/compare registers (CCRx). The formulas for a given time period, t, of the Timer_A frequency with respect to the corresponding cycle value, nCCRO, are: t = 2 xnCCRO xk t xfcLK -+ nCCRO = - - fCLK 2 xk The formulas for a given pulse width time, tpw, with respect to the corresponding cycle value, n, are: tpw = 2 xn xk -+ n = fCLK xfcLK 2 xk tpw As long as no modifications to the period register or the capture/compare registers are made, the PWM signals are repeated indefinitely without any CPU intervention. OFFFFh CCRO~----~~~------------~--~-----.~ CCR1~----~~~----------~~~~-----+- TA3 Output COR3: t-~I--i--I--I--I-_""--I'---I--+--+-_ _ _ Output Mode 8: PWM Toggle/Set or Output Mode 4: Toggle i - - i - - COR1: TA 1 Output r---i;---+-i--F==t=~\Ill..:::;t==:.q....;..-t--i-TIMOV EQU3 I EQUOI EQU3 TIMOV EQU3 I EQUOI EQU3 EQU1 EQU1 EQU1 EQU1 Output Mode 2: PWM Toggle/Reset or Output Mode 4: PWM Toggle Interrupts Generated Figure 6-14. Two Different Symmetric PWM Timings Generated with the Up/Down Mode On-Chlp Peripherals 6-55 TheTImecA If the timer register (TAR) reaches the content of capture/compare register, CCRx (EQUx = 1), and the corresponding capture/compare block is switched to the compare mode, then the content of output unit x is modified (toggled, set, reset, or not affected) depending on the output mode of the control register (CCTLx). If the interrupt for the capture/compare block is enabled, then an interrupt is also generated. The timer register TAR reverses its count direction when it reaches the content of the period register (CCRO), and the content of output unit x is modified again (toggled, set, reset, or not affected) depending on the output mode of the control register (CCTLx). Ifthe interruptforthe reaching of CCRO is enabled, then an interrupt is also requested. If the timer register reaches the value 0 again, it starts counting upward with the next timer clock cycle. If the interrupt for the reaching of 0 is-enabled (TIMOV =1), then an interrupt is also requested with the TAIFG flag. See Figure 6-14. Note: If the period register (CCRO) contains 0, then the timer register (TAR) continues counting until it also reaches O. Then the counting stops until a nonzero value is written to CCRO. Example ~23. Two Different Symmetric PWM Timings Generated With the Up/Down Mode The software for the example illustrated in figure 6-,-14 is shown below. capture/compare block 3 generates a negative pulse with output unit 3 at the output TA3. capture/compare block 1 generates a positive pulse - symmetrically to the zero point - with the output unit 1 atthe output TA 1. The initializing part of the example is also shown. If no software tasks must be executed, the inter_ rupts for the capture/compare blocks 0, 1, and 3 may be switched off. TlMAEXT .EQU- 200h ; RAM extension (bits 17 - 23) Initialization of Timer_A: Up/Down Mode, /2, interrupt ; enabled, MCLK = 3.BMHz INIT 6-56 MOV #ISMCLK+D2+CLR+TAIE,&TACTL MOV MOV tOMOO+CCIE,&CCTLO ; CCRO: normal I/O pin #OMTR+CCIE,&CCTLl ; CCR1: toggle/reset TAl MOV #OMTS+CCIE,&CCTL3 ; CCR3: toggle/set TA3 MOV MOV U90,&CCRO U14,&CCRl fccrO = 5kHz tpwl = l20.0us MOV #48, &CCR3 tpw3 ; Prepare Timer_A = 50. Sus The Timer A BIS.B #TA3+TA1,&P3SEL Enable TA3 and TAL outputs BIS #MUPD,&TACTL start initialized timer i Continue Interrupt handler for the Period Register CCRO Block a sets the RAM extension TlMAEXT of the Timer Register (count down). The LSB of TlMAEXT indicates the count direction: LSB ~ LSB 0: count up 1: count down This indication is necessary if the Capture Mode is used. The count direction indication is self-synchronizing TIMMODO .EQU $ BIS n,TlMAEXT start of handler LSB 1: count down now ~ TaskO starts here RETI Interrupt handlers and decision (only 3 handlers shown) TIM_HND .EQU $ Interrupt latency time ADD &TAIV,PC Add Jump table offset JMP TIMMOD1 TAIV JMP TIMMOD2 TAIV 4: C/C Block 2 JMP TIMMOD3 TAIV 6: C/C Block 3 JMP TIMMOD4 TAIV RETI TAl V = 0: No interrupt 2: C/C Block 1 = Timer Register reached zero: LSB is set to TIMOVH 8: C/C Block 4 a (count up) .EQU $ TIMOV interrupt INC TlMAEXT TAIV - 10: Block 5 RETI C/C Block 1 outputs a positive pulse automatically. Initialized to: toggle/reset (EQU1/EQUO) TIMMOD1 . EQU $ Vector 2: C/C Block 1 On-Chlp Peripherals 6-57 The Timer A Taskl starts here Back to main program R~TI C/C Block 3 outputs a negati~e pulse automatically. Initialized to: toggle/set (EQU3/EQUO) TIMMOD3 .EQU Vector 6: C/C Block 3 $ Task3 starts here RET! Back to main program The tasks started by the interrupt handlers are not shown; these may be: 6.3.3.4 o Symmetric pulse width modulation for control purposes with the output units o o DC generation (DAC) with the output units Tasks like those shown for the continuous mode, but with special treatment due to the changing count direction and short period. The RAM extension TIMAEXT must therefore be taken into account for measurements. The Stop Mode The stop mode halts the timer register without the change of any control register. The timer actions can then continue on from exactly where they were stopped. Example 6-24. The Stop Mode The limer_A running in up/down mode is stopped. Afte{a certain time, it should continue from exactly where it was halted, incldding the count direction. BIC #MUPD,&TACTL Halt Timer_A BIS #MUPD,&TACTL Continue with Up/Down Mode Proceed without 6-58 Timer~ TheT/mecA Itt • • 6.3.3.5 Applications of the Timer Modes Table 6-11 gives an overview of the different applications of the Timer _A modes, together with the capture/compare registers. Table 6-11. Combinations of Timer_A Modes CAPTURE/COMPARE REGISTER 0 COMBINATIONS CAPTURE/COMPARE REGISTER X Continuous Mode Compare register Capture register Cl Cl Cl Cl Cl Cl Cl Cl Interrupt timing Slow PWM generation TRIAC timing SW/HW UART (transmitter) SW/HWSPI Same as for capture/compare register 0 Capturing of internal and external events SW/HW UART (receiver) Revolutions measurement Up Mode 0 0 Compare register Capture register Fixed to period register Not possible due to period register function Cl Cl Cl Cl Cl Cl Interrupt timing Asymmetric PWM generation Digital motor control TRIAC timing SWIHW UART (transmitter) Capturing of iilt. and ext. events SW/HW UART (receiver) Revolutions measurement UpJDown Mode Compare register Fixed to period register Capture register Not possible due to period register function Cl Symmetric PWM generation Cl Digital motor control Cl (Capturing of internal and external events is difficu~ due to up/down counting) On-Chip Periphers/s 6-59 The TlmecA 6.3.4 The TlmecA Interrupt Logic 6.3.4. 1 Interrupt Sources Several interrupt sources exist within the limecA hardware. An interrupt is requested only if the interrupt of the corresponding timer block is enabled (interrupt enable bit TAlE or CCIEx is set) and the general interrupt enable bit GIE (SR.3) is also set. If more than one interrupt is pending, then the interrupt with the highest priority is first in line for servicing. An interrupt is also requested immediately if any interrupt enable bit (CCIEx or TAlE) is set and the corresponding interrupt flag and GIE (SR.3) were already set. Timer Register Block - The timer interrupt flag TAIFG requests an interrupt if the timer register reaches 0 and the interrupt enable bit TAlE is set. The TAIFG flag is set, dependent on the actual mode: a Continuous Mode - after the overflow from OFFFFh to OOOOh a a Up Mode - one timer clock after the timer period in CCRO is reached Up/Down Mode - when the value OOOOh is reached during the countdown Capture/Compare Block x - The capture/compare interrupt Flags CCIFGx are set if one of the following conditions is met. An interrupt is requested only if the corresponding interrupt enable bit CCIEx arid GIE are also set. a .Capture Mode - an input value is captured in register CCRx (the capture condition at the selected input came true) a Compare Mode - the timer register counted to the value contained in register CCRx 6.3.4.2 Inte"upt Vectors Two interrupt vectors are associated with the limer_A module. 6-60 a The single-source vector for the capture/compare register CCRO has the highest priority of alilimer_A interrupts. The capture/compare register CCRO is used to define the timer period during the up mode and the up/ down mode. Therefore, it requires the fastest service. This interrupt vector is located at address OFFF2h. a The multi-source interrupt vector for all other interrupt sources of the limer_A (capture/compare registers x and limer Overflow). A 16-blt vector word - the timer vector register (TAIV) --- indicates the interrupt with the The Time,-A highest priority. The register TAl V is normally added to the Program Counter allowing a simple and fast decision without the need for a time consuming skip chain. See the section explaining the timer vector register (TAIV) for details. The mUlti-source interrupt vector is located at address OFFFOh. All interrupt flags (CCIFGx and TAIFG) can be accessed by the CPU. The internal priorities of the Timer_A are listed in Table 6-12 (for the MSP430x33x configuration). Table 6-12. Timer_A Interrupt Priorities INTERRUPT PRIORITY Highest Lowest FLAG NAME VECTOR ADDRESS Capture/Compare Register 0 INTERRUPT SOURCE CCIFGO OFFF2h Capture/Compare Register 1 CCIFGl OFFFOh Capture/Compare Register 2 CCIFG2 OFFFOh capture/Compare Register 3 Capture/Compare Register 4 CCIFG3 CCIFG4 OFFFOh TAIFG OFFFOh TImer Overflow OFFFOh Example 6-25. Timer_A Vectors The following software shows a possible definition for the nmer_A vectors. Timer_A Interrupt vectors . SECT "TIMVEC",OFFFOh Timer-A Vector Address . WORD TIM_HND Vector for all Blocks except 0 . WORD TIMMODO Vector for Timer Block 0 . SECT "INITVEC",OFFFEh RESET Vector . WORD INIT Start address On-Chip Peripherals 6-61 The TimecA 6.3.5 The Output Units Each capture/compare register (CCRx) is connected to an output unit x that controls the corresponding pulse output (TAx). Eight output modes exist and can be selected individually for each capture/compare block by the three output mode bits (OUTMODx) located in the capture/compare control register (CCTLx). For Table 6-13, it is assumed, that the corresponding control signal P3SEL.y is setto 1. See Figure 6-17 for details. The rightmost column of Table 6-13 indicates the behavior of the output TAx if the EQUx and EQUO signals are valid simultaneously. Table 6-13. Output Modes of the Output Units OUTPUT MODE 0 MODE NAME ACTION FOR EQUx ACTION FOR EQUO ACTION FOR EQUx .and. EQUO TAx is set according to bH OUTx (CCTLx.2) Output only 1 Set Sets output TAx No action 2 Toggle/Reset Resets output TAx Resets output TAx Sets output TAx No action Toggles output TAx 3 Set/Reset Toggles output TAx Sets output TAx· 4 Toggle Toggles output TAx Sets output TAx Sets output TAx 5 Reset Resets output TAx No action Resets output TAx 6 Toggle/Set Toggles output TAx Sets output TAx Resets output TAx 7 Reset/Set Resets output TAx Sets outpUt TAx Resets output TAx The dependence ofthe output units on the EQUO signal (shown in Table 6-13) limits the output unit 0 to the following output modes if the up mode or up/down mode is used (the other four output modes output the static signals shown in the rightmost column of Table 6-13). o Output Mode 0 Output Mode - TAO outputs content of the OUTx bit (CCTLx.2) o Output Mode 1 Set output - TAO is set from the EQUO signal o Output Mode 4 Toggle output - TAO is toggled from the EQUO signal o Output Mode 5 Reset output - TAO is reset from the EQUO signal If the output mode needs to be changed during the program run (from Setto Reset, for example), then the output Signal TAx will not change.its state falsely 6-62 The Timer A if at least one of the three OUTMOD bits retains the 1 state. If this is not the case, (with a change from output mode set to toggle, for example - mode 1 to mode 4), then for a transition time, the output mode 0 may be addressed and will transfer the content ofthe bit OUTx into the output flip-flop. This may cause glitches at the output terminal. Figure 6-15 shows the unsafe output mode changes. It indicates that all changes via the output mode 7 are safe. Mode Transitions 2 3 4 5 6 7 ToggleIResat SetIR8S8I Toggle Reeet Toggle/Set ReeetlSet Output Modes· 0 Output only Set Figure 6-15. Unsafe Output Mode Changes Example 6-26. Safe Output Mode Changes The following code may be used for safe changes. To avoid Output Mode 0, the change is made via Output Mode 7 Example: Output Mode x to 4 BIS #OMRS,&CCTL1 Set Output Mode 7 (OMRS) BIC #OMSR,&CCTL1 Reset LSBs with Output Mode 3 If one of the safe changes is possible, then only the different bits are changed: Change output Mode from Set to Reset (1 to 5) BIS #OMT,&CCTL1 ; Set MSB (OMT) for 1 to 5 Change output Mode from Reset to Set (5 to 1) BIC #OMT,&CCTL1 ; Reset MSB (OMT) for 5 to 1 If, for initialization purposes, a certain state of the output signal TAx is necessary, then the output mode 0 can be used. For the output mode toggle, the output signal OUTx is reset: Reset output signal TAl and switch output Unit 1 to toggle mode On-Chip Peripherals 6-63 The Timer A BIC #OMRS+OUT,&CCTLl OUTl = 0, output mode = 0 BIS #OMT,&CCTLl Start toggle mode wit OUTl = 0 If the input signals EaUO and EaUx occur simultaneously. then the output signal Outx behaves as shown in the rightmost column of Table 6-13. Figure 6-16 illustrates the simplified structure of the output units. All of the inputs that influence the behavior of the output Outx are shown. The reason that some mode changes are safe and some are not is the NOR gate that decodes the output mode o. Timer Clock EQUx OUTx(CCTLx.2j LogIc Output Slgnel Outx EQUO output~----~~~---; Timer Clock -+---i> Jl ~ Output Mode 0 Output Mode Bits (CCTLx.5-7) Figure 6-16. Simplified Logic of the Output Units 6-64. To Output LogIc TAx 6.3.5.1 Output Unit VOs The bits located in the selection register P3SEL (address 01 Bh) and the CAPx bits (CCTLx.8) define the function of the Port3 pins (the MSP430C/P33x configuration is shown - Other family members may use a different implementation, but the principle is the same). Table 6-14. Timer_A IIO-Port Selection P3SEL.y=O P3SEL.y= 1 CAPx.O P3SEL.y= 1 CAPx= 1 PortVO P3.0 Port 1/0 P3.0 Porti/O P3.0 PortVO P3.l Porti/O P3.1 Porti/O P3.l Port 1/0 P3.2 Timer Ciock input TACLK Timer clock Input TACLK PortVO P3.3 Output TAO capture input CCIOA Port 1/0 P3.4 Output TAl Capture Input CCI1A Port 1/0 P3.5 Output TA2 capture input CCI2A PortVO P3.6 Output TA3 Capture input CCI3A Port 1/0 P3.7 Output TA4 Capture input CCI4A Figure 6-17 illustrates the Timer_A interface to the external world. Six Port3 I/O terminals (MSP430C33x) may be selected individually as normal Port3 I/Os or as Timer_A I/Os. The control bit P3SEL.y selects the function: o P3SEL.y=0 The I/O pin Is connected to the Port3 module (input or output) o P3SEL.y = 1 The 1J0pin is connected to the Timer_A module (TAx output or CClxA input) On-Chip Peripherals 6-65 The TlmecA P3SEL.y P3DIR.y ---I--i""", 110 Direction CAP.x --+----C,""" Port31/0 PWMOutput P3OUT.y I CaPlrelnput --+---,""" ">----4t-<~> P3.y I TAx I CClxA Oua---I--i""", P3IN.y ---1---4"_---------. I y=X+ 3 1 Capture Input CClxA Figure 6-17. Connection of the Port3 Terminals to the Timer_A (MSP430C33x Configuration) Example 6-27. Port3 Output Control The initialization for the use of the TA2 and TA 1 outputs for PWM is shown. They are disconnected from the Port3 logic by the setting of the bits P3SEL.5 and P3SEL.4. Initialize the Timer_A: MCLK, Stop Mode, INTRPT enabled, /2 MOV #ISMCLK+D2+CLR+TAIE,&TACTL ; Define Timer_A MOV #200-1,&CCRO ; Define period 200 cycles Initialize Control Registers CCTL2 and CCTL1: Reset/set mode, INTRPT enabled, Compare Mode, Clear flags MOV #OMRS+CCIE,&CCTLl ; CCIFGl = 0, MOV #OMRS+CCIE,&CCTL2 ; CCIFG2 = 0 Initialize capture Compare Registers to PWM duty 6-66 The Timer-;A MOV nOO,&CCRl 50% PWM MOV #50,&CCR2 25% PWM Prepare Timer~ Output Units TA2 and TAl (P3.5 and P3.4) MOV.B #TA2+TAl,&P3SEL BIS #MUP,&TACTL Connect to Output Units ; Start Timer_A in Up Mode 6.3.5.2 Pulse Width Modulation in the Continuous Mode The continuous mode is not intended for PWM, but may be used for this purpose in two ways. The timing can be controlled from: o One capture/compare register only o One capture/compare register and additional capture/compare register 0 6.3.5.2.1 One Capture/Compare Register only The same capture/control register x sets and resets the outputTAx. The output modes toggle or altemating set and reset are used. For the second method (Set and Reset), the interrupt handler modifies the output mode in addition to the adding of the time interval to the register CCRx. PWM values near 0% and 100% must be realized with software. See also Section 6.3.6 The Limitations of TimecA. The output modes and their usability for the first method of PWM in the continuous mode are listed below: o Set Mode - used to get the output signal into the set state. It is necessary to alternate with the reset mode to get a PWM output signal o Toggle/Reset - not usable due to the influence of capture/compare register 0 o Set/Reset - not usable due to the influence of capture/compare register o o Toggle - usable, but a defined start position must be initialized. Otherwise, an inverted output signal is generated o Reset Mode - used to get the output signal into the reset state. It is necessary to altemate with the set mode to get a PWM output signal On-Chip Peripherals 6-67 The Tuner A o o OFFFFh Toggle/Set - not usable due to the influence of capture/compare register 0 Reset/Set - not usable due to the influence of capture/compare register o .......---------~r_-- I------------:~ Oh~~+_r_-_+_r--+-+-~~--~~-~~---~~-- Interrupt Event: EQU1 TA1 Output Signal Toggle or Alternating Set and R_t Output Mode To Set Output Mode To Reaet Change 01 Pulae Width Figure 6-18. PWM Generation in the Continuous Mode (CCR1 only controls TA 1) 6.3.5.2.2 One Capture/Compare Register and Additional capture/Compare Register 0 The capture/compare register CCRO has the same function as with the other two timer modes: it switches back the PWM output TAx into a defined state. Figure 6-19 shows PWM generation using the reset/set mode. This method allows PWM with higher repetition rates than the method described previously. With no pulse width modifications, the time interval between two interrupts are always identical. The capture/compare register 0 may be used for more than one PWM output used this method. The output frequency of capture/compare register 0 may be chosen in such a way that also supports other purposes - an auxiliary frequency output at TAO, for example. See also Figure 6-13. The output modes and their usability for the second method of the continuous mode are listed below: o o o Set - used to get the output signal TAx Into a defined set state initially. Toggle/Reset - usable, self-synchronizing PWM Set/Reset - usable, self-synchronizing PWM The Timer A o Toggle- not usable dueto the missing influence of capture/compare register 0 o Reset Mode - used to get the output signal TAx into a defined reset state initially o o Toggle/Set - usable, self-synchronizing PWM Reset/Set - usable, self-synchronizing PWM OFFF~ ~----------------~~~------------------~r---- Interrupt Events: EQUO Sets TA1 EQU1 ReHtsTA1: Toggle/Set or Reset/Set TA1 OUtput SIgnal Mode To Reaet or Toggle by EQU1 Handler Figure 6-19. PWM Generation in the Continuous Mode (CCRO and CCRl control TA 1) Example 6-28. PWM near 0% and 100% The PWM output values near 00/0 and 100% must be realized with special software code. A simple way to do this is to use the timer vector register (TAIV) once more after each completed interrupt handler to check to see if another timer interrupt is pending. The software example below shows this solution. It is applicable to all PWM modes. See figure 6-19. It saves 9 to 11 cycles if an additional Tlmer_A interrupt is pending. PWMper .EQU 333 ; PWM period (Timer Clock cycles) Interrupt handler for the Period Register CCRO. To handle PWM duties near 0% or 100% a check is made if other timer interrupts are pendent: return to TIMLHND On-Chip Peripherals 6-69 TIMMODO .EQU $ INC TIMAEXT start of handler Incr. timer extension ADD #PWMper,&CCRO Add period length to CCRO TaskO starts here Fall through to TIM_HND Interrupt handlers for Capture/Compare Blocks TIlLHND .EQU $ Interrupt latency time ADD &TAIV,PC Add Jump table offset RETI TAIV = 0: No interrupt JMP TIMMOD1 TAIV = 2: C/C Block 1 JMP TIMMOD2 TAIV = 4: C/C Block 2 JMP TIMMOD3 TAIV = 6: C/C Block 3 JMP TIMMOD4 TAIV = 8: C/C Block 4 TIMOVH TAIV = 10: Block 5 C/C Block 1 returns to the timer interrupt handler after completion to look for pendent timer interrupts TIMMOD1 .EQU $ Vector 2: C/C Block I ADD #PWMper,&CCR1 Add period length to CCR1 Task! starts here Pendent INTRPTs ? JMP 6.3.5.3 Pulse WIdth Modulation In the Up Mode The up mode permits all pulse widths from 0% to 100% without any special treatment necessary. The calculation software delivers results ranging from 0 to nCCRO+ 1. Like Figure 6-20 illustrates, the full range of PWM output signals is possible. The output modes and their usability for the up mode are listed below. D Set Mode - used to get the output signal initially into adefined set state. D Toggle/Reset CPU activity. 6-70 outputs self-synchronizing negative pulses without The Timer A o Set/Reset - outputs self-synchronizing negative pulses without CPU activity. o Toggle - this mode cannot be used with the up mode. It outputs a signal with 50% duty and doubled period for all contents of register CCRx, except for CCRx > CCRO. These contents retain the la~ state of output Outx due to the missing EQUx signal. o Reset Mode - used to get the output signal initially into a defined reset state. o Toggle/Set - outputs self-synchronizing positive pulses without CPU activity. o Reset/Set - outputs self~synchronizing positive pulses without CPU activity. Figure 6-20 illustrates the four usable output modes for PWM in the up mode. Note: No interrupts are generated from the capture/compare blocks x for CCRx '" oand for CCRx > CCRO. For these two cases, a special treatment is necessary. See the software examples in section Software Examples for the Up Mode. CCRx=O CCRx=1 CCRx=2 CCRx=CCRO CCRx>CCRO 4 Output Mode TAR Toggle/Set Reset/Set TAx Toggle/Reset SetlReset TAx 100% No EQUx Interrupt 80% EQUx No EQUx Interru Figure 6-20. PWM Signals at TAx in the Up Mode (CCRO contains 4) On-Chip Peripherals 6-71 The TimecA 6.3.5.4 Pulse Width Modulation in the UplDown Mode The output modes and their usability for the. up/down mode are listed below. D Set Mode - used to get the output signal initially into a defined set state. D Toggle/Reset - outputs self-synchronizing positive pulses without CPU activity. The limer_A hardware can produce all of the theoretically possible nCCRO+ 1 states. But special treatment is necessary if register CCRx contains O. Then the output signal Outx toggles only once per period, which means the output shows a 50% duty and not 0%. See figure 6-21. D Set/Reset - cannot be used with up/down mode. D Toggle - should not be used with the up/down mode. D Reset Mode - used to get the output signal initially into a defined reset state. D Toggle/Set - outputs self-synchronizing negative pulses without CPU. activity. See Toggle/Reset, above, for restrictions. D Reset/Set - cannot be used with up/down mode. As figure 6-21 also shows, the missing PWM values of 0% for toggle/reset and 100% for toggle/set can be output if CCRx contains a greater value than CCRO. Example 6-29. Pulse Width Modulation in the Up/Down Mode The checking software for output mode togglelreset is shown. All PWM values from 1 to nCCRO are valid. The value 0 is emulated by a number greater than nCCRO. R5 contains the calculated PWM value. PWM value in RS i.s checked to be in limits 1 to nCCRO CMP R5,&CCRO PWM value =< nCCRO? JHS L$l Yes, proceed MOV &CCRO,RS No, upper limit (100% PWM) If 0% PWM is needed: OFFFFh to R5 L$l 6-72 TST RS Zero value? JNZ L$2 No, proceed . The Timer A· Use largest, unsigned number #OFFFFh,R5 MOV Result in RS is in limits L$2 The above correction limits the maximum period length nCCRO to OFFFEh. Figure 6-21 illustrates the two possible PWM modes for the up/down mode. They correct themselves after one period. max. Output Mode Toggle/Set Toggle/Reset 50% 33% 100% 87% 0% ~~~~~~~-+-++---~~~----~-r-----+EQUO EQUO EQUx EQUO EQUO EQUx EQUx' Figure 6-21. PWM Signals at Pin TAx With the Up/Down Mode (CCRO contains 3) 6.3.6 Limitations of the nmer_A This section details how to check to see if the limitations imposed by the architecture ofthe limer_A are not exceeded. The abbreviations used in this chapter are: tintrpt Ptask Povhd fMCLK frep uCPU tlLmax Time for a complete interrupt sequence [sj Executed MCLK cycles for the task itself during the interrupt handler (e.g. incrementing of a counter). The necessary cycle count of an instruction depends on the addressing modes used. [sj Sum of MCLK cycles for the overhead of an interrupt sequence. See software overhead. [sj System clock frequency MCLK [Hz] Repetition rate of an event (e.g. an interrupt request) [Hzj CPU loading by a given task. Ranges from 0 to 1 (100%) Maximum (worst case) of the interrupt latency time due to other enabled interrupts [s1 On-Chip Peripherals 6-73 The Time,-A J L 'oa& L • The execution time tlntrpt for a complete interrupt sequence is the same for all three timer modes: = P,,,! + Povlul t. _pI foCLK The software overhead Povhd differs slightly for the three possible Timer_A interrupt sources: o o Capture/Compare Block CCRO 11 cycles (6 + 0 + 5) Capture/Compare Blocks CCR1 to CCR4 16 cycles (6 + 5 + 5) o Timer Overflow TAIFG 14 cycles (6 + 3 + 5) The software overhead Povhd consists of three parts: • Getting to the first instruction of the interrupt handler by the CPU (6 cycles) • Decision part: addition of timer vector register (TAIV) to the program counter and execution of the JMP instruction (0 to 5.cycles) • Return from interrupt instruction RETI (5 cycles). These software overhead cycles refer to the minimized software structure shown in all software examples. This structure is valid for all three timer modes. To get the complete interrupt loading, all execution times of the enabled interrupts are summed up during one period. To getthe loading ucpu (ranging from 0 to 1) olthe CPU by the interrupt activity, the following formula Is used: ucpu = :£(t 1nlrpt X frep) EXAMPLE Two Timerj. interrupts are active in continuous mode. The system clock frequency fMCLK Is 2.097MHz. 1) CCR1: repetition rate 1.2 kHz -16 cycles for the task, 16 cycles overhead 2) CCR3: repetition rate 2.0 kHz - 22 cycles for the task, 16 cycles overhead u cpu 16+16 =1: ( 2.097E6 22+16) x 1.2E3 + 2.097E6 x 2.0E3 =0.0545 .The above result means a CPU loading of approximate 5.5% due to the Timer_A. 6-74 The TImer A 6.3.6.1 Limitations of the Continuous Mode Interrupt Handling - the shortest repetitive time interval, teRmin, between two similar timer events using a compare register CCRx is: . p ..."""", t CRmin = t [/..max + + pOVHD fMCLK The shortest repetitive time interval, tCLmln, between two interrupt events using a capture register CCRx is: tCLmin = t [/..max p ..."""", + + pOVHD fMCLK Tlie time, ttaskmax, for the capture mode is the time to read the captured time value and to test and reset the COV flag. o Software Ovemead - the interrupt loading ranges from one interrupt request (request from CCIFGx) up to six Interrupt requests (requests from TAIFG, CCIFGO, and all CCIFGx flags). o Output Units - for relatively high PWM repetition rates special treatment may be necessary for PWM duties near the limits 0% and 100%. Maximum Resolution: r = k fCLK where: r is equivalent to the period of the timer clock 6.3.6.2 Limitations of the Up Mode o Interrupt Handling -the worst case sum of all the execution times needed by all interrupts during one timer period must be less than the timer period (defined by the period register, CCRO). Otherwise, the interrupt part will loose the synchronization due to overload. This means: (n CCRO + 1) xk fCLK o 1 >-fMCLK Software Ovemead - the overhead ranges from zero (PWM is output automatically after the loading ofthe timer registers), upto six interrupt requests per period (interrupt requests from TAIFG, CCIFGO, and from all CCIFGx flags). On-Gh/p Peripherals 6-75 o Outputunlts- aI/ values ranging from 0% to 100% for pulse width modulation (PWM) are possible without special treatment. o Maximum Resolution - for a given repetition rate, frep , of the timer output, a maximum resolution, r, is possible: = /MCLKmax = neCRO + 1 r Irq> This means that with a maximum system clock frequency of 4 MHz and a repetition rate of 20 kHz for a PWM output - due to audibility - a resolution of 200 steps is possible (0.50/0). 6.3.6.3 Limitations of the Up/Down Mode o Interrupt Handling - the worst case sum of all the execution times needed by all interrupts during one timer period must be less than the doubled period defined by the period register CCRO. Otherwise, the interrupt part will loose the synchronization due to overload. 2 xnCCRO xk fCLK 1 >-/MCLK ,=2 x"ccRD Xk jCLK :E PIDB_ + povhd .=0 o Software Overhead - the overhead ranges from zero (PWM is output automatically after the loading of the timer registers) up to ten interrupt requests per full period (interrupt requests from TAIFG, CCIFGO, and 2 interrupts per CCIFGx). o Output Units -the pulse width zero (0%) needs a special software treatment. Without this, the hardware outputs a 50% pulse width instead. This behavior will be changed in future versions. o Maximum Resolution - for a given repetition rate, frep,.of the timer output, a maximum resolution, r, is possible: r fMCLKmtIX = --2 xfrep = neCRO This means that with a maximum system clock frequency of 4 MHz and a repetition rate of 20 kHz for a PWM output - due to audibility - a resolution of 100 steps is possible (1.0%). The resolution of the up/down mode is less than it is in the up mode. With the same timer clock, the up mode delivers (nCCRO+2) different pulse widths and the up/down mode delivers (nCCRO+ 1) different pulse widths - but with a reduced output frequency due to the up and down counting. This means the resolution is approximately one half the resolution of the up mode. 6-76 The TimecA 6.3.7 Miscellaneous The frequencies generated by the Timer_A may also be used as the timebase lor other tasks il defined appropriately: o Serial Communication Interface (SCI) - If for an MSP430, a second UART (RS232) is needed, then with a timer frequency of 19.2 kHz (8 x 2.4 kHz) a software UART with 2400 baud can be implemented. This software UART uses the interrupt generated with the reaching of the content of the period register, CCRO (CCIFGO =1), for the synchronization of the UART software. o Timing Intervals for Control- These important control values can also be derived from the timer frequency by an appropriate software prescaling. This timing may be used for calculations, keyboard scan, measurement starts, etc. 6.3.8 Software Examples for the Continuous Mode This section shows several proven application examples for the Timer_A. Whenever possible, the abbreviations used in the Architecture Guide and Module Library are used. All examples use the value FLLMPY - it defines the master clock frequency fMCLK. / MeLK = FLLMPY x/crystal If this frequency, fMeLl(, is too high for the application (for example: it causes values forthe timer registers exceeding the 16-bit range), then the Input divider of the Timer_A may be used. It allows a prescaling by 1, 2, 4, and 8. For prescaling by 2, the definitions at the start of each example are simply changed to: FLLMPY .equ TCLK .equ 100 FLLMPY*32768/2 FLL multiplier for 3.2768MHz ; Timer Clock = 1.6384MHz The Input Divider D2 is used to get MCLK/2 for the TCLK MOV #ISMCLK+D2+TAIE+CLR,&TACTL ; Use D2 divider Note: The software and hardware examples shown here are specific to the MSP430C/P33x family. Other MSP430 family members may use other I/O ports and addresses for the Timer_A registers and signals. The programming principles are unchanged - only address definitions may need to be modified. On-Chip Peripherals 6-77 The TlmecA The software examples were tested with the software simulator and an EVK330 evaluation kit. For all examples, the loading of the CPU is given. The terms used are defined below: o Overhead - the sum of necessary CPU cycles to get to the first instruction of the interrupt handler and to get back to the interrupted program sequence (wakeup cycles, storing of PC and SR, determination of the interrupt source, and RETI cycles) o Task - the CPU cycles used for the interrupt task: incrementing of a counter, calculations, etc. Advantages of the Continuous Mode: • Five complete, independent timings and captures are possible. Any mix is possible • No dominance by a period register Disadvantages of the Continuous Mode: 6.3.8.1 • Software update necessary for the capture/compare registers to allow continuous run • Speed limit due to the necessary software update Common InltlallzaUon SubrouUne The initialization subroutine INITSR is used by all examples. It executes the following tasks: 6-78 o A check is made if the initialization subroutine is called after applying the supply voltage (the RAM word INITKEY does not contain OF05Ah) or after an external reset or watchdog reset (INITKEY contains OF05Ah). If the applying of the supply voltage caused the reset, then the RAM is cleared and the INITKEY is initialized to OF05Ah. o The system clock oscillator is programmed with the FLL multiplier N. This defines the MCLK frequency fMCLK. See above. o The correct DCa switch FN_x for the chosen MCLK frequency (fMCLK) is set. These switches allow the system clock oscillator to operate with one of the center taps of the digitally controlled oscillator (000). This way ihe DCa operates always in a nonsaturated condition. The Timer A o Adelay of 30000 clock cycles is included to give the oscillator time to settle at the correct frequency. Common Initialization Subroutine Check the INITKEY value first: If value is OFOSAh: a reset occurred, RAM is not cleared otherwise Vcc'was switched on: complete initialization INITSR INO CMP #OFOSAh,INITKEY PUC or POR? JEQ INO Key is ok, continue program CALL #RAMCLR Restart completely: clear RAM MOV #OFOSAh,INITKEY Define 'initialized stateR MOV.B #FLLMPY-l,&SCFQCTL .if FLLMPY < 48 Use the right DCO current: MOV.B #O,&SCFIO MCLK < 1.SMHz: .if FLLMPY < 80 1.SMHz < MCLK < 2.SMHz? MOV.B #FN_2,&SCFIO Define MCLK frequency FN~ off .else .else .if FLLMPY < 112 2.SMHz < MCLK < 3.SMHz? MOV.B #FN_3,&SCFIO Yes, FN_3 on #FN_4,&SCFIO MCLK > 3.SMHz: FN_4 on Allow the FLL to settle .else MOV.B .endif .endif .endif INl MOV nOOOO,R5 DEC RS at the correct DCO tap JNZ INI during 30000 cycles RET Return from initialization Subroutine for the clearing of the RAM block .bss INITKEY,2,0200h OFOSAh: initialized state On-Ghip Peripherals 6-79 RAMSTRT .equ 0200h RAMEND .equ OSFEh RAMCLR RCL CLR CLR RS RAMSTRT(RS) .INCD CMP RS #RAMEND-RAMSTRT+2,RS ; RAM cleared? No, once more RCL JLO RET Start of RAM Highest RAM address (33x) Prepare index register 1st RAM address Next word address ; Yes, return 6.3.8.2 Generation of Five Independent Timings The software example explains the use of the timer vector register (TAIV) and the overhead of the interrupt handling. It refers to figure 6-22. The interrupt handler of timer block x adds the appropriate time interval, At, to the corresponding compare register, CCRx. The MCLK frequency (3.2768 MHz) is used also for the timer clock. The five timings generated are defined as follows (see also Table 6-15): o Capture/Compare Block 0 - a positive pulse with a 10kHz repetition rate is generated and output at terminal TAO; The pulse is reset by the interrupt handler of timer block O. The pulse is used for the precise triggering of an external analog-to-digital converter. The error of the repetition rate due to the MCLK frequency used is -{)'097% o Capture/Compare Block 1 - an internal interrupt with variable timing is generated. The cycle count is stored in the RAM word TIM1 REP. The maximum value of this cycle count is OFFFFh, the minimum value is 1000. The output terminal TA 1 is not used. o Capture/Compare Block 2 - a square wave with a fixed 1 kHz repetition rate is generated and output at terminal TA2. The pulse is used as a reference for external devices. The error of the repetition rate due to the MCLK frequency used is -244 ppm. o Capture/Compare Block 3 - an internal interrupt with a fixed 200 Hz repetition rate is generated. The outputterminal TA3 is not used. The error of the repetition rate due to the MCLK frequency used is -244 ppm. o Capture/Compare Block 4 - a square wave with a variable output frequency is generated and output at terminal TA4. The output frequency starts at 409.6 Hz (4000 cycles) and increases up to 1638.4 Hz (1000 cycles). The square wave is used for the control of an external DC/DC converter. The Timer A The formula for calculating the value, An, that is added to the timer register (TAR) depends on the application. Forthe internal interrupts (CCR1 and CCR3 in the example) and the external pulse (CCRD in the example), An is: t:.n = /)J x /CLK k For the external-generated square wave signals with the frequency fext (CCR2 and CCR4 in the example) An is: /),.n Where: fClK fext k At = /CLK k x2 x/ext [Hz] [Hz] Frequency at the input of the input divider Frequency to be output with toggle mode Input divider constant (1, 2, 4, 8) Time interval to be generated [s1 Table 6-15. Short Description of the five independent Timings CAPTURE! COMPARE BLOCK TIME INTERVAL (TIMER CLOCK CYCLES) SIGNAL TYPE COMMENT a 328 External Pulse: 10kHz ADC repetMian rate 1 Variable Internal Cycle count stored In TIM1 REP (min 1000) 2 1638 External 1 kHz @ 3.2768 MHz (error: -244 ppm) 3 16384 Internal Fixed frequency 200 Hz 4 400010 1000 External Increasing frequency for ext. DC/DC converter The software example is written for an fMClK of 3.276 MHz. If other frequencies are used, the time intervals need to be adapted. Subsequent examples show methods of writing frequency-independent software. Figure 6-22 illustrates the five timings described above: On-Chip Peripherals 6-81 The Timer A OFFFFh Timer Reglater Ohi-t==========~~~~~========~~/"'~ILI 66536mmer Clock External Pulses 10 kHz at TAO variable Internal Interrupt CCR1 External Frequency 1kHzatTA2~UUUU~~~~~UUUU~~~~~UUUU~~~~UUUU~ Fixed Internal Interrupt 200 Hz Increasing Frequency atTA4 +..L.____..L_ _ _ _-A_ _ _ _---'L-_ _ _ _""'-_ JtLC1..L1.CLCLl:J..r:U~O'OJDl]lJlIlllDllIIDIDlDll~ Time ---+ Figure 6-22. Five Independent Timings Generated in the Continuous Mode The timing of the signals output at the TAx pins (the dedicated 1/0 pins of the Timer_A) is independent of interrupt latency: the TAx outputs are set, reset or toggled exactly at the programmed time (contained in the capture/compare register x) by the output unit x. The requested interrupt when this occurs is .. used to update the capture/compare register x and to execute necessary tasks. Example 6-30. Five independent Timings Generated in the Continuous Mode The software example also shows how to output the MCLK frequency at the output terminal XBUF for reference purposes. For example, an external ASIC may be driven by this frequency. . Software example: five independent timings using the Continuous Mode of the 16-bit Timer~ Hardware definitions FLLMPY TCLK .equ .equ FLLMPY*32768 FLL multiplier for 3.2768MHz TCLK: FLLMPY x fcrystal STACK .equ 600h Stack initialization address RAM definitions 100 The Timer A Repetition rate Block I TIMIREP .equ 202h TIM4REP .equ 204h Repetition rate Block 4 TIMAEXT .equ 206h Extension for Timer Register .text OFOOOh lNlT Software start address MOV tSTACK,SP Initialize Stack Pointer CALL UNITSR lnit. FLL and RAM ;- Initialize the Timer_A: MCLK, Cont. Mode, INTRPT on MOV tISMCLK+TAIE+CLR,&TACTL MOV #OMSET+CCIE,&CCTLO MOV #OMOO+CCIE,&CCTLI No output, lNTRPT on MOV #OMT+CCIE,&CCTL2 Toggle, INTRPT on MOV #OMOO+CCIE,&CCTL3 No output, INTRPT on MOV #OMT+CCIE,&CCTL4 Toggle, INTRPT on Set, lNTRPT on MOV tOFFFFh,TIMIREP start value Block 1 MOV UOOO,TIM4REP Start value Block 4 MOV.B #TA4+TA2+TAO,&P3SEL ; Define TAx outputs MOV #1,&CCRO Immediate start MOV #l,&CCRl with defined contents MOV #1,&CCR2 for the Capture/Compare MOV #l,&CCR3 Registers MOV #1,&CCR4 CLR TIMAEXT MOV.B #CBMCLK+CBE,&CBCTL ; Output MCLK at XBUF pin BIS #MCONT,&TACTL EINT MAINLOOP ; Clear TAR extension start Timer Enable interrupt Continue in background Interrupt handler for Capture/Compare Block O. An -ext. ADC is started every IOOus (326 cycles @ 3.2766MHz MCLK) with a positive pulse at TAO (set exactly from Output Unit). On-Ghip Peripherals 6-83 The Timer A The interrupt flag CCIFGO is, reset automatically. TIMMODO .EQU $ ADD #328,&CCRO Prepare next INTRPT (10kHz) BIC #OMRS+OUT,&CCTLO Reset TAO BIS #OMSET,&CCTLO RETI start of handler Back to Set Mode .' Return from Interrupt Timer Block 3 generates an internal used Sms interrupt 16384/3.2768MHz = O.OOSs TIMMOD3 .EQU $ ADD U6384,&CCR3 vector 6: Block 3 'Add time interval (Sms) Task3 starts here, Fall through to TIM_HND Interrupt handlers for Capture/Compare Blocks 1 to' 4. ,The interrupt flags CCIFGx are reset by the reading of the Timer vector Register TAIV TIM,..HND .EQU $ ADD &TAIV,PC Add Jump table offset JMP TIMMOD1 Vector 2: Block 1 JMP TIMMOD2 vector 4: Block 2 JMP TIMMOD3 Vector 6: Block 3 JMP TIMMOD4 Vector 8: Block 4 RETI Interrupt latency ; Vector 0: No interrupt Block 5. Timer Overflow Handler: the Timer Register is expanded into the RAM location TIMEXT (MSBs) TIMOVH .EQU $ Vector 10: TIMOV Flag INC TIMAEXT Incr. Timer extension RETI Block 1 uses a variable repetition rate defined in TIM1REP 6-84 The Timer A Repetition Rate TIMMOD1 = 3.2768MHz/(TIM1REP) .EQU $ Vector 2: Block 1 ADD TIM1REP,&CCR1 Add time interval Task1 starts here RETI Back to main program The used time interval delta t2 is 1638 cycles. This delivers an external 1kHz signal (1638/3.2768MHz TIMMOD2 = 500us) .EQU $ Vector 4: Block 2 ADD U638,&CCR2 Add time interval (1/2 period) Task2 starts here Back to main program RETI Block 4 uses a variable repetition rate starting at 4000 cycles and going down to 1000 cycles. It is used for an external DCjDC converter. Toggle Mode is used TIMMOD4 T41 .EQU $ Vector 8: Block 4 ADD TIM4REP,&CCR4 Add time interval (1/2 period) CMP nOOO,TIM4REP Final value reached? JLO T41 Yes, no modification SUB #l,TIM4REP No, modify interval RETI Back to main program . sect HTIMVECH,OFFFOh Timer_A Interrupt Vectors . word TIM_HND Timer Blocks 1 to 4 . word TIMMODO Vector for Timer Block . sect HINITVECH,OFFFEh Reset Vector . word INIT ° The example above results in a maximum (worst case) CPU loading UCPU (ranging from 0 to 1) by the TimecA activities: u cpu = 1 -/1 I:{ n inJrpt x f rep ) MCLK On-Chip Peripherals 6-85 TheTlmecA Where: [Hz] Frequency of the DCO n'ntrpt Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler frap fMCLK CCRO CCR1 CCR2 CCR3 CCR4 TIMOV - u repetition rate 10kHz repetition rate 3.27 kHz repetition rate 2.0 kHz repetition rate 0.2 kHz repetition rate 3.27 kHz repetition rate 50 Hz [Hz] 15 cycles for the task, 11 cycles overhead 6 cycles for the task, 16 cycles overhead 5 cycles for the task, 16 cycles overhead 5 cycles for the task, 20 cycles overhead 17 cycles for the task, 16 cycles overhead 4 cycles for the task, 14 cycles overhead 26 cycles 22 cycles 21 cycles 25 cycles 33 cycles 18 cycles - 26 x10 4 + 22 x3276.8 + 21 x 2000 + 25 x200 + 33 x 3276. 8 + 18 x50 _ 0 15 3.2768 x106 • CPU - The result above means a CPU loading of approximative 15% due to the Timer_A (the tasks of the timer blocks 1, 2, and 3 are not included). 6.3.8.3 DTMF Generation Modern telephones use dual-tone multi-frequency (DTMF) signaling for the dialing process. A pair of frequencies defines each of the 16 possible numbers and characters, and are selected from the matrix shown in Table 6-16. Two Timer_A outputs (TA2 and TA 1) are used to generate the frequency pair. External filters clean up the waveform and mix the two frequencies. The length of the output signals is normally 65 ms to 100 ms. Table 6-16. DTMF Frequency Pairs FREQUENCY 1209 Hz 1336 Hz 1477 Hz 1633 Hz 697Hz 1 2 A 770Hz 4 5 852Hz . 8 3 6 9 C 0 # 0 941 Hz 6-86 7 B The Time,-A Table 6-17 shows the errors of the generated DTMF frequencies caused by the timer clock frequency used. Rounding is used for the timer values to get the smallest possible errors. Table 6-17. Errors of the DTMF Frequencies Caused by the MCLK FLL MULTIPUER N 32 64 96 116 FREQUENCY 1.048 MHz 2.096 MHz 3.144 MHz 3.801 MHz 697 Hz +0.027% +0.027% +0.027% +0.027% 770 Hz -0.015% -0.016% +0.033% -0.016% +0.031% 852 Hz +0.059% -0.023% +0.005% 941 Hz +0.029% +0.029% +0.029% +0.035% 1209 Hz -0.079% +0.036% +0.036% -0.003% 1336Hz +0.109% -0.018% +0.025% +0.025% 1477Hz -0.009% -0.009% -0.009% -0.009% 1633Hz +0.018% +0.018% +0.018% +0.018% Figure 6-23 shows a proven hardware solution to mix the two output frequencies. A low-pass filter is used for the high output frequency and another one for the low output frequency. The outputs of these low-pass filters are summed by a third operational amplifier. The filter hardware was developed by Robert Siwy/Bavaria. . JlIl r-----, Fillers Mixer 2.2 Ill" >--_*--l L DTMF HlghDTMF MSP430 I J1fL Output T'00nF OV VCC Vss 5V OV LowDTMF All Components ara 10% Tolerance Figure 6-23. DTMF Filters and Mixer On-Ghip Peripherals 6-87 The Tlme,-A The two low-pass filters and the mixer are shown in figure s-.23. The symmetri. cal output pulses at TA2 and TA1 bias the filter amplifiers with Vccl2. The component values are valid for the specification of the German public telephone system. The positive supply voltage .for the operational amplifiers is switched by a TP output or an 0 output. With the two resistors R1 and R2, the filters can be adapted to the specifications of the telephone systems in other countries. These resistors define the high and low DTMF frequency parts of the DTMF output signal. Example 6-31. DTMF Software The following DTMF software routine is independent of the timer clock frequency used. During the assembly, the new timer values are calculated. The length of the DTMF output signal is defined with the value DL - its value is in milliseconds. Hardware definitions FLLMPY .equ 3.2 FLL,multiplier for l.048MHz TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal DL .equ 82 DTMF signal length (65 .. 100ms) STACK .equ 600h Stack initialization address RAM definitions STDTMF .equ 202h status Hi and Lo frequency TIMAEXT .equ 204 Timer Register Extension LENGTH .equ 206h DTMF length counter .text OFOOOh Software start address Initialize the Timer_A: MCLK, Cont. Mode, INTRPT enabled Prepare Timer_A output Units, MCLK = 1.048MHz (autom.) INIT 6-88 MOV #STACK,SP ; Initialize Stack Pointer SP CALL UNITSR ; Init. FLL and RAM MOV #ISMCLK+TAIE+CLR,&TACTL ; Define Timer MOV.B #TA2+TAl,&P3SEL ; TA2 and TAl at P3.5/4 The Tlmer_A CLR TIMAEXT Clear TAR extension BIS #MCONT,&TACTL Start Timer_A Enable interrupt EINT MAINLOOP Continue in main loop A key was pressed: SDTMF contains the table offset of the two frequencies (0 .. 6,0 .. 6) in the high and low bytes MOV &TAR,R5 For immediate start: ADD FDTMFLO,R5 Short time offset 1st change after O.71ms MOV R5,&CCRI MOV R5,&CCR2 1/(2x697) =O.71ms MOV #OMT+CCIE,&CCTLl Toggle, INTRPT on MOV #OMT+CCIE,&CCTL2 Toggle, INTRPT on MOV.B STDTMF,R5 Counter for 82ms RRA R5 # of low frequ. changes MOV.B DTMFL(R5) ,LENGTH for the signal length. Continue background CCRO interrupt handler (not implemented here) TIMMODO RETI Interrupt handler for Capture/Compare Registers 1 to 4 TI)LHND ADD &TAIV, PC Serve highest priority request HCCRl CCRl request (low DTMF frequ.) JMP HCCR2 CCR2 request (high DTMF fr.) JMP HCCR3 CCR3 request JMP HCCR4 CCR4 request INC TIMAEXT Extension of RETI JMP TIMOVH No interrupt pending: RETI Timer~ 32 bit RET! On-Chip Peripherals 6-89 The TlmecA Low DTMF frequencies: TAl is toggled by Output unit 1 Output changes of TAl are counted to control signal length HCCRl PUSH. R5 Save used register MOV.B STDTMF,R5 Status low DTMF frequency ADD FDTMFLO(R5),&CCRl Add length of half period DEC.B LENGTH Signal length DL elapsed? JNZ TARET No Yes, terminate DTMF signal: disable interrupts, Output only TARET BIC #OMRS+OUT+CCIE,&CCTLl Reset TAl BIC #OMRS+OUT+CCIE,&CCTL2 Reset TA2 POP R5 RETI Restore R5 Return from interrupt High DTMF frequencies: TA2 is toggled by Output Unit 2 HCCR2 PUSH R5 Save used register MOV.B STDTMF+l,R5 Status high DTMF frequency ADD FDTMFHI(RS),&CCR2 Add length of half period POP R5 Restore R5 RETI Return from interrupt HCCR3 Task controlled by·CCR3 RETI HCCR4 Task controlled by CCR4 RETI Table with the DTMF frequencies: the table contains the number of MCLK cycles for a half period. The values are adapted to the actual MCLK frequency during the assembly Rounding assures the smallest possible frequency error FDTMFLO 6-90 . word «TCLK/697)+1)/2 . word «TCLK/770)+1)/2 Lo DTMF frequ. 770Hz 697Hz The Timer A FDTMFHI . word {{TCLK/852)+1)/2 . word {{TCLK/941)+1)/2 . word {{TCLK/1209)+1)/2 852Hz 941Hz Hi DTMF frequ. 1209Hz . word {{TCLK/1336)+1)/2 1336Hz . word {{TCLK/1477)+1)/2 1477Hz . word {{TCLK/1633)+1)/2 1633Hz Table contains the number of half periods for the signal length DL (ms). The low DTMF frequency is used for the timing DTMFL . byte 2*697*DL/1000 Number of half periods . byte 2*770*DL/1000 per DL ms . byte 2*852*DL/1000 . byte 2*941*DL/1000 .sect "TIMVEC",OFFFOh . word Timer-A Interrupt Vectors Timer Block 1 .. 4 Vector . word Vector for Timer Block .sect "INITVEC",OFFFEh . word INIT ° Reset Vector Example 6-32. DTMF Software - Faster Another software ,solution that is faster - but needs more RAM - is shown below. The table containing the length of the half waves is read only once for the two DTMF frequencies and the read values are stored in RAM words DTMFLO and DTMFHI. The Tlmer_A interrupt routines use these two values. The tables are the same as with the example above. FLLMPY .equ 32 FLL multiplier for l.048MHz TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal DTMF time ms (65 .. 10Oms) DL .equ 82 STDTMF .equ 202h status Hi and Lo frequency TIMAEXT .equ 204 Timer Register Extension LENGTH .equ 206h DTMF length counter DTMFLO .equ J08h Half wave of low frequency DTMFHI .equ 20Ah Half wave of high frequency On-Chip Peripherals 6-91 ThsTimscA .equ STACK Stack initialization address 600h .text OFOOOh Initialize the Prepare INIT Timer~: Timer~ Software start address MCLK, Cont. Mode, INTRPT enabled Output Units, MCLK = 1.048MHz (autom.) MOV lISTACK,SP. Initialize Stack Pointer SP CALL #INITSR Init. FLL and RAM MOV lIISMCLK+TAIE+CLR,&TACTL • Start Timer MOV.B lITA2+TAl,&P3SEL TA2 and TAl at P3.S/4 CLR TlMAEXT Clear TAR extension BIS #MCONT,&TACTL Start Timer_A EINT Enable interrupt MAINLOOP Continue in main loop A key was pressed: STDTMF contains the table offset of the two frequencies (0 .. 6,0 .. 6) in the high and low bytes MOV &TAR,RS For immed:iate start': ADD FDTMFLO,R5 Short time offset MOV R5,&CCRl 1st change after 0.71ms MOV R5,&CCR2 1/(2x697) = 0.7lms Fetch the two cycle counts for the DTMF frequencies MOV.B STD~MF+1,RS MOV FDTMFHI(RS),DTMFHI ; Length of half period ; High DTMF frequency MOV.B STDTMF,RS MOV FDTMFLO(R5),DTMFLO ; Length of half period RRA RS MOV.B DTMFL(RS),LENGTH # MOV #OMT+CCIE,&CCTLl Toggle, INTRPT on MOV #OMT+CCIE,&CCTL2 Toggle, INTRPT on ; Low DTMF frequency Counter for length Mainloop 6-92 prepare byte index of low frequ. changes to The Timer A CCRO interrupt handler (not implemented here) TIMMODO RETI Interrupt handler for Capture/Compare Registers 1 to 4 TIM_HND ADD &TAIV,PC TIMOVH Serve highest priority request No interrupt pending: RET I RETI JMP HCCRl CCRl request (low DTMF frequ.) JMP HCCR2 CCR2 request (high DTMF fr.) JMP HCCR3 CCR3 request JMP HCCR4 CCR4" request INC TIMAEXT Extension of Timer_A 32 bit RETI Low DTMF frequencies: TAl is toggled by Output Unit 1 HCCRl ADD DTMFLO,&CCRl Add length of half period DEC.B LENGTH DL ms elapsed? JNZ TARET No Terminate DTMF output: disable interrupts, Output only TARET BIC #OMRS+OUT+CCIE,&CCTLl Reset TAl BIC #OMRS+OUT+CCIE,&CCTL2 Reset TA2 ; Return from interrupt RETI High DTMF frequencies: TA2 is toggled by Output Unit 2 HCCR2 ADD RETI HCCR3 DTMFHI,&CCR2 Add length of half period Return from interrupt Task controlled by CCR3 On-Chip Peripherals 6-93 The Timer A RET! Task controlled by CCR4 HCCR4 RET! Tables and interrupt vectors are identical to the previous example The second example, with maximum frequencies on both channels, results in a maximum CPU loading, uCPU (ranging from 0 to 1), by the Timer_A activities due to OTMF generation: ucpu 1 =-;::- I (ninlrpt x f rep) J",CLK Where: Frequency of the system clock oscilator (OCO) nintrpt Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler frep fMeL!( CCR1 - repetition rate 2x941 Hz CCR2 - repetition rate 2x1633 Hz 12 cycles for the task, 16 cycles overhead 6 cycles for the task, 16 cycles overhead =28 x2 x941 +22 x2 x1633 U CPU [Hz] [Hz] 28 cycles 22 cycles 0.12 1.048 x10 6 This result shows a worst case CPU loading of approximate 12% due to the OTMF generation. This loading occurs only during the 82 ms activity. 6.3.8.4 TRIAC Control TRIAC control for electric motors (OMC) or other loads is a simple task when using the Timer_A. The software loads one of the capture/compare registers (CCR4 with this example), prepares the output unit to change the TAx output after the desired time, and continues with the background task.. When the loaded time interval elapses, the output unit fires the TRIAC gate at exactly the programmed time and requests an interrupt. The interrupt handler can use dynamic control (several short pulses to save current) or static control (one long gate pulse), which is used with this example. See figure 6-25 for details. The TRIAC control software contains some security features. They ensure that no gate triggering of the previous half wave can last into the next half wave and cause gate triggering there also: 6-94 The TimecA • The zero crossing part (PO.O handler) immediately switches off the gate signal by setting of the TA4 terminal to high • The PO.O handler calculates a value, OFFTIME, that defines a time for the actual half wave where the gate signal must be switched off at the latest • The timer block 4 handler checks before each switch-on of the TRIAC gate to see if the on-time of the gate exceeds the calculated value, OFFTIME, or not. If the value in OFFTIME is exceeded, then it is used for the maximum on time The TRIAC control software is independent of the ac line frequency. For each full wave of the line voltage, the period is measured and used for the security features. The calculation software also uses the timer clocks value of the halfperiod stored in RAM location MAINHW. Figure 6-24 shows the hardware for the TRIAC control in this example. The temperature measurement, the overcurrent detection, and the revolution control are not included in the software example. After power up, the TA4 terminal is switched to input mode. The base resistor of the PNP transistor switches the gate of the TRIAC off and prevents the motor from running. ov -L 3'iS61B _ _ Ci3 MCLK ClN COM SEL XBUF TP.2 RSENS2 TP.1 RSENS1 TP.O 230 V ACLlna MSP430 230VACLlna TA4 ,.-.::..t.....------f PO.o P0.4 3.BV Overcurrenl __~__~______-+__~____-+~DI~NC~d~~~__~~~__~~~____~~~ OV . Figure 6-24. TRIAC Control With Timer_A On-Chip Peripherals 6-95 The Timer:...A Figure 6-25 shows a TRIAC control with three different conduction angles. Dynamic control and static control is included. The software example is written for the static control only. but it is relatively easy to add additional states to the TRIAC handler (timer block 4). which means more than one gate pulse per half wave. typically 5to8Puises Dynamic Control -t---- TA40utput Static Control ~----~~--------~~------~~~--- Voltage ACLIne Figure 6-25. Static and Dynamic TRIAC Gate Control The software shown below works up to a timer clock frequency (fClK) of MCLK (in this case due to k = 1): feLl( < Where: felK k fUNE 216 X k X 2 xfUNE Input frequency at the input divider input of TimecA Pre-divider constant of the input divider (1. 2. 4 or 8) AC line frequency used [Hz] [Hz] If fClK is higher than defined above. then the input divider of limer_A must be used. This restriction is caused by the 16-bit structure of limer_A and the RAM. 6-96 The Timer A Example 6-33. Triac Control The check to see if the gate pulse starts after the security time, SEC, is not included below. It must pccur during the calculation. Definitions for the TRIAC control software FLLMPY .equ 32 FLL multiplier for 1.048MHz TCLK .equ FLLMPY*32768 TCLK (Timer Clock) [Hz] SEC .equ (500*TCLK/1000)/lOOO ; Security time (500us) Gate_on .equ (1200*TCLK/IOOO)/1000 ; TRIAC Gate on (1200us) RAM definitions TlMAEXT .equ 202h Timer Register Extension OFFTlME .equ 204h Time when gate MuST be off MAINHW .equ 206h Length of half wave (TCLK) PRVTAR .equ 208h Value of TAR at last pos. edge FlRANGL .equ 20Ah Half wave - conduction angle STTRIAC .equ 20Ch Control byte (0 STACK .equ 600h Stack initialization address . text = off) Start of ROM code Initialize the Timer_A: MCLK, Cont. Mode, INTRPT enabled Prepare Timer_A Output Units INIT MOV #STACK,SP Initialize Stack Pointer SP CALL UNITSR Init. FLL and RAM MOV #ISMCLK+TAIE+CLR,&TACTL MOV #OMOO+CCIE+OUT,&CCTL4 ; Set TA4 high BIS.B #TA4,&P3SEL BIS.B #POIEO, &lEl Enable PO.O interrupt CLR TlMAEXT Clear TAR extension CLR.B STTRIAC TRIAC off status (0) BIS #MCONT,&TACTL Start Timer-A in Cont. Mode MOV.B #CBMCLK+CBE,&CBCTL ; MCLK at XBUF pin EINT Init. Timer TA4 controls gate transistor ; Enable interrupt On-Chip Peripherals 6-97 The Time,-A MAINLOOP Continue in mainloop Some control examples: Start electric motor: checked result (TCLK cycles} in R5. The result is the time difference from the zero crossing to the first gate pulse measured in Timer Clock cycles MOV R5,FIRANGL MOV.B #l,STTRIAC Gate delay to FIRANGL Activate TRIAC control Continue in background The motor is running. A new calculation result is available in R5. It will be used with·the next mains half wave MOV RS,FlRANGL Gate delay to FlRANGL Continue in background Stop motor: switch off TRIAC control CLR.B STTRIAC MOV #OMOO+CCIE+OUT,&CCTL4 ; TRIAC gate off ; Disable TRIAC control ; Continue with background Interrupt handlers for Capture/Compare Blqcks 1 to 4. The interrupt flags CCIFGx are reset when reading the Timer Vector Register TAIV TIM_HND EINT ADD Real time environment &TAIV,PC RETI Add "Jump table" offset Vector 0: No interrupt JMP TIMMODl Vector 2: Block 1 JMP TIMMOD2 Vector 4 : Block 2 JMP TIMMOD3 Vector 6 : Block 3 JMP TIMMOD4 Vector 8 : Block 4 Block- 5. Timer Overflow Handler: the Timer Register is 6-98 The Tlme,-A expanded into the RAM location TIMAEXT (16"MSBs) TIMOVH .EQU $ Vector 10: TIMOV Flag INC TIMAEXT Incr. Timer extension JMP TIM_HND Another Timer-A interrupt? The interrupt handlers for the Timer Blocks a to 3 follow They are not implemented here TIMMODO .equ $ Handler for Timer Block a TIMMOD1 .equ $ Handler for Timer Block 1 TIMMOD2 . equ $ Handler for Timer Block 2 TIMMOD3 .equ $ Handler for Timer Block 3 RETI Timer Block 4: interrupt handler for the TRIAC control TIMMOD4 CC4TAB PUSH RS Save help register RS MOV.B STTRIAC,RS Status of TRIAC control MOV.B CC4TAB(RS) ,RS Fetch offset to status handler ADD R5,PC Branch to status handler . byte STATEO-CC4TAB Status 0: No TRIAC activity . byte STATEO-CC4TAB Status 1: activition made . byte STATE2-CC4TAB Status 2: 1st gate pulse . byte STATE3-CC4TAB Status 3: TRIAC gate off . even TRIAC status 2: gate is switched on for "Gate_ON" time The On time is shortened to the OFFTIME value if the OFFTIME is before the Gate_On time STATE2 MOV &CCR4,RS ADD #Gate_On,&CCR4 INV RS INC RS ADD OFFTIME,R5 ; Copy time of interrupt Set end of ON state ; Negate last INTRPT time OFFTIME - last INTRPT time On-Chip Peripherals 6-99 The Timer A CMP OFFTIME later than next INTRPT? JHS Yes, ok The calculated ON time ends after OFFTIME: OFFTIME is used MOV ST20 OFFTIME,&CCR4 MOV #OMSET+CCIE,&CCTL4 ; Prepare for gate off INC.B STTRIAC TRIAC status + 1 TRIAC status 0: No activity. TRIAC is off always STATEO POP R5 Restore help register RETI Return from interrupt TRIAC status 3: gate pulse is output. No activity until next half wave. STATE3 MOV #OMOO+CCIE+OUT,&CCTL4 ; Gate off (TA4 high) MOV.B #1, STTRIAC JMP STATEO ; TRIAC status: wait for O-cross. PO.O Handler: the mains voltage causes interrupt with each zero crossing. The TRIAC gate is switched off first, to avoid the ignition of the corning half wave. Hardware debounce is necessary for the mains signal! See schematic POO_HNDLR MOV #OMOO+CCIE+OUT,&CCTL4 ; Switch off TRIAC PUSH R5 Save used register XOR.B #l,&POIES Change interrupt edge of PO.O MOV &TAR,R5 O-crossing time to R5 The shorter positive halfwave is measured (TCLK cycles) 6-100 BIT.B #1, &POIN Positive edge of mains? JZ POl No, MOV R5,PRVTAR Yes, for next HW calculation JMP P03 Save time of O-crossing The Timer A POl MOV SUB If STTRIAC is not 0 ( 0 firing is prepared P03 Measure pos. mains half wave Difference is length of pos. HW R5,MAINHW PRVTAR,MAINHW TST.B STTRIAC JZ MOV.B P02 inactivity) then the next gate 0: no activity STTRIAC STTRIAC > 0: prep. next firing #2,STTRIAC The TRIAC firing time is calculated: Timer Reg. + FIRANGL MOV ADD MOV R5,&CCR4 TAR to CCR4 FIRANGL,&CCR4 TAR + delay -> CCR4 #OMR+CCIE+OUT,&CCTL4 ; TA4 is reset by INTRPT The worst case switch-off time for the TRIAC is calculated: Zero crossing time + half period - security time This calculation ensures a safe distance to the next zero crossing of the mains P02 ADD SUB MOV POP RETI . sect . word . word . sect . word . sect . word MAINHW,R5 #SEC,R5 R5,OFFTIME R5 TAR + MAINHW Subtract security time worst; case switch-off time Restore R5 "TIMVEC",OFFFOh Interrupt Vectors Timer Blocks 1 .. 4 Vector Vector for Timer Block 0 Po.o Vector Timer~ TI~HND TIMMODO 'POOVEC",OFFFAh POO_HNDLR HINITVEC',OFFFEh INIT Reset Vector The TRIAC control example results in a nominal CPU loading uCpu (ranging from 0 to 1): 1 = - - 1: (n/ntrPI x j rep) jMCLK On-Chip Peripherals 6-101 The Timer A Where: Frequency of the system clock generator (DCO) nintrpt Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler frep fMCLK CCR4 - repetition rate 100Hz PO.O - repetition rate 100Hz UCPU 79 cycles for the task, 16 cycles overhead 60 cycles for the task, 11 cycles overhead =100 x 95+100x 71 1.048 x 10 6 [Hz] [Hz] 95 cycles 71 cycles 0.016 . This shows a CPU loading of approximately 1.6% due to the static TRIAC control. 6.3.8.5 Mixture of Capture and Compare Modes Any mix of capture and compare mode is possible with the Timer_A. The following software example shows two timer blocks using the capture mode and three timer blocks using the compare mode. For formulas, see Section 6.3.8.2. 6-102 o Capture/Compare Block 0 - a short negative pulse with a 1 kHz repetition rate is generated and output at the terminal TAO. The pulse is reset to high by the interrupt handler of timer block O. The pulse is used for the precise triggering of an external peripheral. The error of the repetition rate due to the MCLK frequency used is -0.055%. o Capture/Compare Block 1 - the period of the input signal at the CCI1 A input terminal is measured in timer clock cycles. The period is measured from leading edge to leading edge of the input signal. The last measured value is stored in the RAM word PERIOD. The maximum period length that can be measured this way is k x 216/fCLK' o Capture/Compare Block 2 - a square wave with a variable repetition rate is generated and output at the terminal TA2. The actual cycle count for one half-wave is stored in the RAM word TIM2REP. o Capture/Compare Block 3 - the event time of the trailing edge of the input signal at the CCI3A input terminal is captured. The last captured value is stored in the RAM word STOR3. o Capture/Compare Block 4 - a square wave with a variable output frequency is generated and output at the TA4 terminal. The output frequency starts at 4 kHz and decreases to 1 kHz. The square wave Is used for the control of an external peripheral. The Time,-A The software routine is independent of the MCLK frequency used. Only the FLL multiplier constant, FLLMPY, needs to be redefined if another MCLK frequency is selected. Table 6-18. Short Description of the Capture and Compare Mix TIMER BLOCK TIME INTERVAL OUTPUT UNIT COMMENT 0 1 ms outputs frequency Negative pulses: 1 kHz 1 External Not used Measures period of signal at input CCll A. leading edge to leading edge. Minimum signal length: 2 ms 2 Variable Outputs frequency Length of a half-period stored in TIM2REP. (2 kHz max) 3 External. Not used captures event time of the trailing edge of the Signal input at CCI3A. Maximum signal - 500 Hz 4 250 f1S to 1 ms Outputs frequency Decreasing frequency from 4 kHz to 1 kHz The maximum frequencies and minimum signal length shown do not indicate the limits of the Timer_A. They are given for the calculation of the loading of the CPU only. Figure 6-26 illustrates the above described five tasks: OFFFFh Timer Register 6SS36/T1mer Clock Oht~========~~~~~========~~/ Externel Pulses 1 kHzatTAO Signal"at CCI1A Capture Intarrupt CCRl Variable Frequency atTA2 Signal at CCI3A Capture Interrupt ceR3 Decreaalng Frequency· atTA4 Captured Trailing Edge IIIDIIIIHJOllOO Tlma ---+ Figure 6-26. Mixture of Capture Mode and Compare Mode With the Continuous Mode On-Chfp Peripherals 6-103 The Timer A The software example also shows how to output the ACLK frequency at output terminal XBUF for reference purposes. An external device may be driven by this stabfe and precise crystal-controlled frequency. A special method is used for the return from interrupt. The interrupt handlers of the five timer blocks do not return normally with a RETI instruction but jump back to the start of the timer handler for a test to see if another llmer_A interrupt is pending. This makes it necessary to enable the interrupt at the start of the timer handler. Otherwise, the interrupt latency time will get too long for other interrupts. Example 6-34. Mixed Capture and Compare Modes Software example: three independent timings and two inputs with capturing. The Continuous Mode of Timer_A is used FLLMPY .equ 64 FLL multiplier for 2.096MHz TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal OLDRE .equ 202h .Time of last edge at CCllA PERIOD .equ 204h Calc. period of CCllA event TIM2REP .equ 206h Repetition rate Block 2 STOR3 .equ 208h Last neg. edge. at CCI3A TIM4REP .equ 20Ah Repetition rate Block 4 TIMAEXT .equ 20Ch Extension for Timer Register STACK .equ 600h Stack initialization address INIT . text OFOOOh Software start address MOV #STACK,SP Initialize Stack Pointer CALL UNITSR Init. FLL and RAM Initialize the Timer~: MCLK, Cant. Mode, INTRPT on Inputs (CCIxA) and outputs (Tax) of 6-104 Timer~ are defined MOV #ISMCLK+TAIE+CLR,&TACTL MOV #OMR+CCIE,&CCTLO; Reset Mode, INTRPT on MOV #CMPE+ISCCIA+SCS+CAP+CCIE,&CCTLl ; MOV #OMT+CCIE,&CCTL2; Toggle, INTRPT on MOV iCMNE+ISCCIA+SCS+CAP+CCIE,&CCTL3 ; MOV #OMT+CCIE,&CCTL4 Toggle, INTRPT on MOV #OFFFFh,TIM2REP Start value Block 2 The Timer A MOV #«TCLK/4000)+1)/2,TIM4REP ; 4kHz start frequ. MOV.B #TA4+TA3+TA2+TA1+TAO,&P3SEL ; Define I/Os MOV #l,&CCRO Immediate start MOV #1,&CCR2 for the Capture/compare MOV #1,&CCR4 Registers CLR TlMAEXT Clear TAR extension MOV.B #CBACLK+CBE,&CBCTL BIS #MCONT,&TACTL EINT ; Output ACLK at XBUF pin Start Timer Enable interrupt continue in background MAINLOOP Interrupt handler for Capture/Compare Block O. An ext. peripheral is started every lms with a negative pulse at TAO (set exactly in time by Output Unit 0). The handler resets the negative signal. TIMMODO .EQU $ ADD #«2*TCLK/l000)+1)/2,&CCRO MOV #OMOO+CCIE+OUT,&CCTLO; Set TAO: pulse off BIS #OMR,&CCTLO ; Start of handler For next INTRPT Back to Reset Mode Fall through to TI~HND Interrupt handlers for Capture/Compare Blocks 1 to 4. The interrupt flags CCIFGx are reset by the reading of the Timer vector Register TAIV TIM_HND .EQU $ EINT THO ADD Start of Timer_A handler Allow interrupt nesting &TAIV,PC RETI Add Jump table offset Vector 0: No interrupt JMP TIMMODl Vector 2: Block 1 JMP TIMMOD2 Vector 4 : Block 2 JMP TIMMOD3 Vector 6: Block 3 JMP TIMMOD4 Vector B: Block 4 Block 5. Timer Overflow Handler: the Timer Register is On-Chip Peripherals 6-105 The Timer A expanded into the RAM location TlMEXT (MSBs) TIMOVH .EQU $ INC TlMAEXT Vector 10: TIMOV Flag Incr. Timer extension JMP THO Test for other interrupts Timer Block 1 measures the period of an input signal at pin CCI1A. The interval between two rising edges is measured TIMMOD1" .EQU $ Vector 2: Block 1 MOV &CCR1,PERIOD Time of captured rising edge SUB OLDRE,PERIOD Calculate period (difference) MOV &CCRl,OLDRE Store actual edge time JMP THO Test for another interrupts The used time interval delta t2 is stored in TIM2REP. TIMMOD2 .EQU $ Vector 4: Block 2 ADD TIM2REP,&CCR2 Add time interval JMP THO Test for another interrupts Task2 starts here Timer Block 3stores the time for a trailing edge at CCI3A STOR3 contains the time of the latest trailing edge TIMMOD3 .EQU $ MOV &CCR3,STOR3 Store event time JMP THO Test for another interrupts Vector 6: Block 3 Block 4 uses a variable repetition rate starting at 4kHz cycles and going down to 1kHz. TIMMOD4 6-106 .EQU $ vector 8: Block 4 ADD TIM4REP,&CCR4 Add time interval CMP #((TCLK/lOOO)+l)/2,TIM4REP ; Final value? JHS THO ; Yes, no modification The Time,-A INC TIM4REP No, modify interval JMP THO Test for other interrupts . sect "TIMVEC",OFFFOh Timer_A Interrupt Vectors . word TI!CHND Timer Blocks 1 .. 4 vector . word TTMMODO Vector for Timer Block 0 .sect "INITVEC",OFFFEh Reset vector . word INIT The software example above results in a maximum (worst case) CPU loading uCPU (ranging from 0 to 1) by the TImer_A activities: u cpu Where: fMCLK nintrpt frep =30 x10 3 1: (n inlrP1 x f rep) Frequency of the system clock generator (DCO) Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler CCRO - repetition rate 1 kHz CCR1- rep. rate max. 0.5 kHz CCR2 - repetition rate 2 kHz CCR3 - repetition rate 0.5 kHz CCR4 - repetition rate 8 kHz TIMOV - rep. rate 32 Hz@2 MHz uCPu 1 =-/1 MCLK 15 cycles for the task, 15 cycles overhead 18 cycles for the task, 22 cycles overhead 6 cycles for the task, 22 cycles overhead 6 cycles for the task, 22 cycles overhead 17 cycles for the task, 22 cycles overhead 4 cycles for the task, 20 cycles overhead +40 x 500 + 28 x2000+28 x 500 + 39 x 8000 + 24 x32 2.096 x10 6 [Hz] [Hz] 30 cycles 40 cycles 28 cycles 28 cycles 39 cycles 24 cycles 0.21 This shows a worst case CPU loading of approximate 21 % due to the TimecA (the task of the timer block 2 is not included). If fMCLK is chosen to be 3.B MHz, then the CPU loading is only 11.5%, max. Any pending TImer_A interrupt during the return phase saves 6 cycles because of the code In this example. On-Chip Peripherals 6-107 TheT/mer A 6.3.6.6 Applications Exceeding the 16-81t Range of the Tlmer_A If the periods of the internal interrupt timings or the time Intervals to be captured are longer than one period ofthe timer register, then a special method is necessary to take care of the larger time periods. The same is true if a half period of a generated output frequency is larger than the period of the Timer_A. This special method, using extension registers for the capture/compare registers is necessary if: tSiGNAL > 216 X k fCLK Where: tSIGNAl felK k [Hz) [Hz) Time interval to be measured or generated Input frequency at the input divider input of Tlmer_A Predivider constant of the input divider (1, 2, 4 or 8) Figure 6-27 illustrates the hardware and RAM registers used with the compare mode if the compared values exceed the range of 16 bits (values are greater than 65535): 15 o Timer Clock Timer Comparison Value At ~------------------~ Figure 6-27. Compare Mode with Timer Values Greater than 16 Bit (shown for CCRt) Figure 6-28 illustrates the hardware and RAM registers used with the capture mode if the captured values exceed the range of 16 bits (values are greater than 85535): 6-108 The Timer A o 15 TIMOV Carry Figure 6-28. Capture Mode With Timer Values Greater than 16 Bit (shown for CCR3) Figure 6-29 illustrates five examples. The tasks are defined as follows: o Capture/Compare Block 0 - a symmetric 1 kHz signal is generated and output at terminal TAO. It is used for the control of external peripherals (e.g. ADCs). o Capture/Compare Block 1 - an internal interrupt with a period At1 = 1s (considerably longer than the timer register period) is generated. o Capture/Compare Block 2 - the length, At2, ofthe high part ofthe input signal at the CCI2A input terminal is measured and stored in the RAM words PP2MSB and PP2LSB. The captured time of the leading edge is stored in the RAM words TIM2MSB and TIM2LSB. o Capture/Compare Block 3 - the event time of the leading edge of the signal at the CCI3A input pin is captured. The captured value is stored in the RAM words TIM3MSB and TIM3LSB. o Capture/Compare Block 4 - Asymmetrical, external signal is output at terminal TA4. The time interval, At4, between two output signal edges is defined in TIM4MSB and TIM4LSB. The RAM extension of the timer register TIMAEXT is used for all applications exceeding the 16-bit range ofthe Timer_A. Due to the low priority of the TIMOV interrupt, however, checks are necessary in the application software to see if the RAM extension is updated yet or not. The software routine is independent of the MCLK frequency used. Only the FLL multiplier constant, FLLMPY, needs to be redefined if another MCLK frequency is selected. For the example, 3.801 MHz is used. The task of capture/compare block 0 shows that tasks extending the 16-bit range of the limer_A may be mixed with normal tasks that fit into the 16-bit range. On-Chip Peripherals 6-109 The TlmecA Table 6-19. Short Description of the Capture and Compare Mix TIMER BLOCK OUTPUT UNIT TIME INTERVAL COMMENT 0 1 ms Outputs frequency Pulses: 1 kHz @ 3.801 MHz 1 1 s. Not used Generation of an Internal reference frequency: 18 for time and date 2 External event Input pin CCI2A is used Measures high signal part.Stored in PP2MSB and PP2LSB 3 External event Input pin CCI3A Is used Captures event time of the leading edge of the Input signal- stored In TIM3 MSB and TIM3 LSB 4 Variable ~uts Symmetric output signal - half period is defined by TIM4 MSB and TIM4 LSB frequency Figure 6-29 illustrates the four tasks described above (not to scale): Content of TIMAEXT 4h 5h 8h 7h OFFFFh Timer Reglater Oh-r-M~----------~--------~--~----------~'---Frequency Generation 1 kHzatTAO Internal Interrupt OCRI ' - - - - A l l (la) ----~ Time Measurement aICCI2A capturing of Leading Edges al OCI3A OutpUI Signal Generallon al TA4 captured Edge If-- AI4 1-------1 TIme--+ Figure 6-29. Five Different Timings Extending the Normal Time,-A Range 6-110 The Time(.A Example 6-35. Extending the Normal Timer_A Range The assembler definitions for T1 (V1 sMSB and V1 sLSB) show a way to define times exceeding the range of one word. FLLMPY .equ 116 3. B01MHz TCLK .equ FLLMPY*3276B TCLK: FLLMPY x fcrystal T1 .equ 1 T1 is I second V1sMSB .equ T1*FLLMPY*3276B/65536 ; MSBs of 1s value V1sLSB .equ (T1*FLLMPY*3276B)-«Tl*FLLMPY*3276B/65536)*65536) TIM2MSB .equ 202h TIM2LSB .equ 204h PP2MSB .equ 206h PP2LSB .equ 20Bh TIM3MSB .equ 20Ah TIM3LSB .equ 20Ch TIM4MSB .equ 20Eh TIM4LSB .equ 210h TlMAEXT Time of leading edge at CCI2A Length of high signal at CCI2A Time of leading edge at CCI3A Time interval between TA4 edges .equ 212h TlMAEXTl .equ 214h Extension for Timer Block 1 TlMAEXT4 .equ 216h Extension for Timer Block 4 STACK 600h Stack initialization address INIT .equ Extension for Timer Register .text OFOOOh Software start address MOV #STACK,SP Initialize Stack Pointer CALL UNITSR Init. FLL and RAM Initialize the Timer_A: MCLK, Cant. Mode, INTRPT on MOV #ISMCLK+TAIE+CLR,&TACTL MOV #OMT+CCIE,&CCTLO Toggle Mode, INTRPT on MOV #OMOO+CCIE,&CCTLl No output, INTRPT on MOV #CMBE+ISCCIA+SCS+CAP+CCIE,&CCTL2 Both edges MOV #CMPE+ISCCIA+SCS+CAP+CCIE,&CCTL3 + edge MOV #OMT+CCIE,&CCTL4; Toggle Mode, INTRPT on MOV.B #TA4+TA3+TA2+TAO,&P3SEL ; Define timer I/Os On-Chip Peripherals 6-111 The TimecA MOV n,&CCRO Immediate start for TAO CLR TIMAEXT Clear Timer Register extension MOV tVlsLSB,&CCRl Next INTRPT time block 1 MOV #VlsMSB,TIMAEXTl MOV TIM4LSB,&CCR4 MOV TIM4MSB,TIMAEXT4 Next INTRPT time block 4 MOV.B #CBMCLK+CBE,&CBCTL ; Output MCLK at XBUF pin BIS ltMCONT,&TACTL EINT Start Timer Enable interrupt MAINLOOP Continue in background Interrupt handler for Capture/Compare Block O. An external peripheral is started every lms with the negative edge of TAO (set exactly from Output unit 0). TIMMODO .EQU $ ADD #«TCLK/lOOO)+l)/2,&CCRO'; For next INTRPT ; Start of handler RETI Interrupt handlers for Capture/compare Blocks 1 to 4'. The interrupt flags CCIFGx are reset by the reading of the Timer Vector Register'TAIV TI!CHND .EQU $ Start of Timer_A handler ADD &.TAIV,PC Add Jump table offset RETI Vector 0: No interrupt JMP TIMMODl JMP TIMMOD2 Vector 4: Block 2 JMP TIMMOD3 Vector 6: Block 3 JMP TIMMOD4 Vector 8: Block 4 Vector 2: Block 1 Block 5. Timer Qverflow Handler: the Timer Register is expanded into the RAM location TIMAEXT (MSBs 16 to 31) TIMOVH 6-112 .EQU $ Vector 10: TIMOV Flag INC TIMAEXT Incr. Timer extension Thenmer A RETI Timer Block 1 gen. the Is reference used for date and time TIMMODI TM12 .EQU $ Vector 2: Block 1 BIT liTAIFG,&TACTL TIMOV pending? JNZ TMll Yes, checks necessary CMP TIMAEXT,TIMAEXTI MSBs also equal? JEQ T13 Yes RETI TMll T13 TMIR TST &CCRI TAIFG = 1: check CCRI IN TM12 CCRI > 7FFFh: correct values PUSH TlMAEXT TlMAEXT not yet updated INC O(SP) Updated value of TIMAEXT CMP @SP+,TIMAEXTI MSBs equal? JNE TMIR No, return ADD #VlsLSB,&CCRI Yes, prepare next INTRPT (Is) ADDC #VlsMSB,TIMAEXTI MSBs of 1 second CALL #RTCLK Increment time by Is JNC TMIR if C CALL #DATE 00.00 o'clock: next day = 1: incr. date RETI Capture Mode: the high part of the CCI2A input signal is measured. The result is stored in PP2MSB and PP2LSB. TIMMOD2 .EQU $ BIT #CCI,&CCTL2 Input signal high? JZ TM21 No,calculation necessary Vector 4: Block 2 MOV &CCR2,TIM2LSB Store LSBs of capt. time MOV TIMAEXT,TIM2MSB MSBs of capt. time BIT #TAIFG,&TACTL TIMOV pending? JZ TM2RET No, values are correct TST &CCR2 Yes, check CCR2 IN TM2RET CCR2 > 7FFFh: correct values On-Chip Peripherals 6-113 The Timer A INC TIM2MSB MSBs not yet updated TM2RET RETI TM21 MOV &CCR2,PP2LSB Store LSBs of capt. time MOV TIMAEXT,PP2MSB MSBs of capt. time TIMOV pending? High part is calculated TM22 BIT #TAIFG,&TACTL JZ TM22 No, values are correct TST &CCR2 Yes, check CCR2 IN TM22 CCR2 > 7FFFh: correct values INC TIM2MSB MSBs not yet updated SUB TIM2LSB,PP2LSB Build difference SUBC TIM2MSB,PP2MSB Task 2 to do RETI Timer Block 3 captures the time of a leading edge at CCI3A TIM3MSB and TIM3LSB contain the time of the actual edge TIMMOD3 .EQU $ MOV &CCR3,TIM3LSB vector 6: Block 3 Store LSBs of event time MOV TIMAEXT,TIM3MSB MSBs of event time TIMOV pending? BIT #TAIFG,&TACTL JZ TM31 No, values are correct TST &CCR3 Yes, check CCR3 IN TM31 CCR3 > 7FFFh: correct values INC TIM3MSB MSBs not yet updated Task 3 to do TM3l RETI Timer Block 4 gen. a symmetric pulse at pin TA4 f = 0.5 X TCLK/TIM4xSB TIMMOD4 TM42 6-114 .EQU $ Vector 8: Block 4 BIT #TAIFG,&TACTL TIMOV pending? JNZ TM41 Yes, checks necessary CMP TIMAEXT,TIMAEXT4 MSBs also equal? The Timer A JEQ Interval is reached T43 RETI TM41 T43 TST &CCR4 TAIFG IN TM42 CCR4 > 7FFFh: correct values PUSH TIMAEXT TIMAEXT not yet updated INC O{SP) Updated value of TlMAEXT CMP @SP+,TIMAEXT4 MSBs equal? No, return ~ 1: check CCR4 JNE TM4R ADD TIM4LSB,&CCR4 LSBs of interval ADDC TIM4MSB,TlMAEXT4 MSBs of interval XOR #OUT,&CCTL4 Toggle TA4 without Output Unit Task 4 TM4R RET! . sect "TIMVEC",OFFFOh Timer_A Interrupt Vectors . word TIM_HND Timer Blocks 1 .. 4 Vector . word TIMMODO Vector for Timer Block 0 .sect "INITVEC",OFFFEh Reset Vector . word INIT The example above results in a nominal CPU loading uCpu (ranging from 0 to 1) by the Timer_A activities: ucpu 1 =-/1 MCLK I: (nlnlrP' x frep) Where: fMCLK nintrpt frep CCRO CCR1 CCR2 CCR3 CCR4 - repetition rate 1 kHz repetition rate 58 Hz rep. rate max. 58 Hz rep. rate max. 58 Hz rep. rate max. 58 Hz TIMOV - 58 Hz with 3.8 MHz Frequency of the system clock (DCO) Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler 5 cycles for the task, 11 cycles overhead 16 cycles for the task, 16 cycles overhead 30 cycles for the task, 16 cycles overhead 25 cycles for the task, 16 cycles overhead 32 cycles for the task, 16 cycles overhead 4 cycles for the task, 14 cycles overhead On-Chip Peripherals [Hz) [Hz) 16 cycles 32 cycles 46 cycles 41 cycles 48 cycles 18 cycles 6-115 The Timer A _16x103 +32x58+46x 58+41x58+48x58+18x58 0007 u cpu - 3.801 X 10 6 • This results in a nominal CPU loading of approximate 0.7% due to the TimecA activities (the tasks of the timer blocks 2, 3, and 4 are not included). If fMCLK is chosen to be 1 MHz, then the CPU loading is 2.6%, max. B.3.B.7 MSP430 Operation Without a Crystal The MSP430 may be used without a 32 kHz crystal. The FLL loop is opened and a DCO tap with a frequency near the desired frequency is used (the dependence of the MCLK frequency on the DCO tap used is shown in the MSP43D Architecture Guide and Module Library). If an application requires a relatively stable MCLK frequency, DCO control by software is possible. The MCLK frequency is compared to the AC line frequency or another external stable reference frequency. No capture/compare register is necessary, but if one is used, LCD operation is also possible. Software Regulated MCLK 5V vcc VCC Xln XBUF Xout CIN I-----e TP.2 J--,J~....-4I TP.1 ........~....-4I Temperature Measurement TP.O j...-.JVV\,-J Rret MSP430 Reference Frequency 230 V AC Line ' \ ; 10M ._IEI 3liS61B COM ..--4_-l PO.7 SEL 3.5 V Figure 6-30. MSP430 Operation Without Crystal Any external reference frequency, fREF, may be used if it is in the range: k X2 16 -., , - < fREF < Jcuc 6-116 f ..2!f!:!£. 100 The TimecA The lower limit prevents overflow of the result, the upper (arbitrary) limit prevents overloading ofthe CPU (the control task needs approximately SO cycles per reference period). I! the reference frequency is far above the main frequency (kilo Hertz range), then it is recommended to use the PO.O input due to its dedicated interrupt vector. I! the reference frequency disappears, then the MCLI< frequency continues to work with the actual 000 value until the reference frequency appears again. The frequency of the system clock generator does not step down to the lowest DCO frequency due to the open Qontrolloop. Example 6-36. Operation Without Crystal An ac line-powered system works without a crystal. The line frequency, fMAINS is connected to PO.7, causing interrupt for each positive edge. The PO.7 interrupt handler calculates the cycle difference between two interrupts - which is the number of MCLK cycles during one mains period - and compares this difference to a maximum value, HID, and a minimum value, LOWD. If the difference is out of these limits, the DCO is corrected in small steps· (22 of nDeOmod). See Section 6.S The System Clock Generatorfor an explanation of nDeOmod. The nominal value ofthe frequency fMClK is chosen to 2 MHz. The hardware is shown in Figure 6-30. The software example below works up to a maximum frequency fClK: ICLK < Where: fClK k fMAINS 216XkxlMAlNS Input frequency at the input divider input of TImer_A Predivider constant of the input divider (1, 2, 4 or 8) AC Line frequency used [Hz] [Hz] If no LCD is used, then the value LCD is set to 0: LCD .equ o ; No LCD used The value fleD used with the example is calculated: lieD Where: fFRAME MUX = IFRAME X 2 x MUX Recommended frame frequency for the used LCD Driving method for the used LCD (1, 2, 3, or 4 MUX) On-Chlp Peripherals [Hz] 6-117 The Timer A Hardware definitions FLLMPY .equ 64 TCLK .equ 40*50000 Timer input clock 2.0MHz = MCLK FMAIN .equ 50 Mains frequency 50Hz FLCD .equ 256 4MUX: fFRAME LOWD .equ TCLK/FMAIN*99/100 Lower MCLK limit 99% TCLK HID .equ TCLK/FMAIN*101/100 ; Upper MCLK limit 101% TCLK LCD .equ only for FN_x selection po 256/8 = 32Hz ; 1: LCD drive implemented too 1 RAM definitions . equ 202h Last TAR content for delta CNTMAINS .equ TARSTOR 204h Mains frequency counter STACK 300h Stack address .equ . text' OFOOOh INIT Software start address MOV #STACK,SP CALL UNITSR Initialize RAM, set FN_2 Prepare System Clock Generator for operation without crystal BIS.B #SCGO,SR FLL: loop Control off CLR.B &SCFQCTL Modulation on MOV.B #050h,&SCFIl Tap 10: 2MHz (nom. with FN_2) Initialize the Timer~: MCLK, Cont. Mode, INTRPT on MOV #ISMCLK+MCONT+TAIE,&TACTL MOV #OMOO+CCIE,&CCTL4 TA4 not used, Intrpt on BIS.B #OeOh,&POIE Enable INTRPT for PO.7 (mains) BIC.B #080h,&POIES INTRUPT for leading edge .if LCD=l If LCD is needed too MOV.B #O,&BTCTL Prepare Basic Timer. Use fLCD .endif MOV.B EINT 6-118 #CBMCLK+CBE,&CBCTL MCLK at XBUF pin The Time,-A MAINLOOP Interrupt handler PortO: PO.2 to PO.7. The mains input is at pin PO.7 P072_HNDL PUSH P07Tl R5 Save R5 BIT.B #080h,&POFG PO.7 (mains) INTRPT? .No, check PO. 6 to PO. 2 JZ P062 MOV &TAR,R5 Act. Timer Register SUB TARSTOR,R5 Build delta MCLK cycles For next MCLK measurement MOV &TAR,TARSTOR CMP #LOWD,R5 fMCLK < lower MCLK limit? JHS P07TI No, check upper limit Yes, increase DCO frequency INC.B &SCFII CMP #HID,R5 fMCLK > upper MCLK limit? JLO P07T2 No, return DEC &SCFIl Yes, decrease DCO frequency P07T2 INC CNTMAINS Mains counter + 1 (time base) P062 MOV.B &POIFG,R5 Read PO flags BIC.B R5,&POIFG Reset read flags (PO.7 to PO.2) POP R5 All done, return LCD=l If LCD is needed too Process inputs PO.6 to PO.2 P072RET RETI .if Interrupt handlers for Capture/Compare Blocks 1 to 4. TIM_HND ADD &TAIV,PC RETI Add Jump table offset vector 0: No interrupt JMP TIMMODl JMP TIMMOD:2 vector 4: Block :2 JMP TIMMOD3 vector 6 : Block 3 JMP TIMMOD4 vector 8: Block 4 RETI Vector 2: Block 1 ; TIMOV not used here On-Chip Peripherals 6-119 The Timer A The interrupt handlers for the Timer Blocks 0 to 3 follow They are not implemented here TIMMODO TIMMODl TIMMOD2 TIMMOD3 .equ .equ Handler for Timer Block 0 Handler for Timer Block 1 $ $ .equ $ .equ RETI $ Handler for Timer Block 2 Handler for Timer Block 3 Timer Block 4: interrupt handler for the LCD drive. The BTCNTl register - which generates fLCD - is incremented twice with the fLeD period to generate both edges TIMMOD4 ADD.B i010h,&BTCNTl ADD #TCLK/(2*FLCD),&CCR4 ; Add 1/(2*fLCD) RET I .endif . sect End of LCD drive part "TIMVEC",OFFFOh TIM_HND . word . word .sect . word .sect . word ; Toggle BTCNT1.4 Timer~ Interrupt Vectors Timer Blocks 1 .. 4 Vector Vector for Timer Block 0 TIMMODO "P072VEC",OFFEOh ; PO.x Vector P072_HNDLR Handler for PO.7 to PO.2 "INITVEC',OFFFEh Reset Vector INIT :rhe example results in a maximum (worst case) CPU loading uCpu (ranging from 0 to 1) by the limecA activities: ucpu Where: fMCLK nintrpt frep LCD timing - 2><256 Hz MCLK frequency control 50 Hz ~i-120 =- 1f l MCLK :E (n inrrp, x f rep ) Frequency of the system clock (DCO) Number of cycles executed by the Interrupt handler Repetition rate of the interrupt handler 10 cycles for the task, 16 cycles overhead 49 cycles for the task, 11 cycles overhead [Hz] [Hz] 26 cycles 60 cycles The Timer A =26 x512 + 60 x50 =0.008 u CPU 2.0 x10 6 This results in a CPU loading of approximate 0.8% due to the Timer_A tasks, the LCD timing, and the MCLK control. 6.3.8.8 RF Timing Generation Different modulation methods for RF timing generation are shown in Figure 6-32. All are used with metering devices (electric meter, water meter, gas mater, heat allocation meters, etc.) for the long-distance readout ofthe consumption. For the generation of the modulated RF, normally a regulated 6-V supply voltage is used. If this voltage is not available, the stejrUp power supply shown in figure 6-31 may be used. An existing supply voltage (here 3 V) is transformed by the step-up circuit to 8 V and regulated down to the desired 6 V. The step-up frequency is delivered by the MSP430. The XBUF output, with its four possible output frequencies, is used. The sequence starts with the ACLK frequency (32.768 kHz) and then lowers to ACLKl2 and ACLKl4. In this way, the CPU is not loaded with the frequency generation at all. Figure 6-31 illustrates the connection of an RF interface module to an MSP430. rlOh32kHz Xln Xout Vee MSP430 V 8V 3V 1 L ,."..,...,.. Step-Up Frequency XBUF lIULf J ....L ~~I Voltage -:: ~" F:e Vss TAO 6V J Vee -=-- Regulator 1 - RF-Antenna RF·Module GND Modulation Modulation Figure 6--31. RF Interface Module Connection to the MSP430 Modulation modes used are: o Amplitude Modulation - the RF oscillator is switched on for a logical 1 and switched off for a logical 0 (100% modulation). o Blphase Code - the information is represented by a bit time consisting of one half bit without modulation and one half bit with full modulation. A logical 1 starts with 100% modulation, a logical 0 starts with no modulation. On-Chip Peripherals 6-121 The Timer A o Blphase Space - a logical 1 (space) is represented by a constant signal during the complete bit time. A logical o (mark) changes the signal in the middle of the bit time. The signal changes after each transmitted bit. The last two modulation modes do not have a dc part. Figure 6-32 shows all three modulations modes. If the LSBs are transmitted first, the information sent is 096h. o o o o InformaUon 096h Amplitude Modulation Blphaae Space I I Bit Length -III14-~~ Tlme~ Figure 6-32. RF Modulation Modes The timer block 0 is used with the software examples for all three modes due to the following two reasons: o The fastest possible response. The decision making with the timer vector register is not necessary for the timer block 0 - it uses its own, dedicated interrupt vector. o The capture/compare register 0 interrupts not only if the timer register and CCRO are equal (like with the other CCRs), but also if the timer register contains a higher value. This prevents the loss of synchronity due to other interrupts during the transmission. The software of the other four timer blocks is not shown with the following software routines. Many examples of their use are given in the previous examples. The software examples also show how to output the ACLKl2 frequency at output terminal XBUF. This accurate frequency may be used for the clocking of external peripherals. 6-122 The Timer_A 6.3.8.8.1 RF Amplitude Modulation This is the simplest method - a set data bit (1) switches on the RF, a zero data bit switches off the RF. o o o o Informatlon 096h Amplitude Modulation Time --+ Figure 6-33. Amplitude Modulation o If the speed of the software is not sufficient, dedicated registers (R4 to R15) may be used for RFDATA and RFCOUNT. This register method is used with the biphase code and biphase space software. See sections 8.8.2 and 8.8.3. o "the MSB needs to be output first, then the instruction RRA RFDATA (after label TMOl) is simply replaced by RLA RFDATA Example 6-37. Amplitude Modulation Methods Software example: Amplitude Modulation methods. Hardware definitions FLLMPY .equ 48 FLL multiplier for 1.S72MHz TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal fRF .equ 19200 Bit rep. frequency (Baud Rate) Bit-1ength .equ «2*TCLK/fRF)+1)/2; Bit length (TCLK cycles) STACK 600h .equ ; Stack initialization address RAM definitions. Use dedicated CPU registers (R4 to R1S) if the speed is not sufficient RFDATA .equ 202h 16 bit data to be sent TlMAEXT .equ 204h 32 bit extension Timer_A RFCOUNT .equ 206h Counter for 16 bits (byte) On-Chlp Peripherals 6-123 ThsT/mscA .text OFOOOh INIT Software start address MOV #STACK,SP CALL UNITSR Initialize the Timer~: Initialize Stack Pointer • Init. FLL and RAM MCLK, C~nt. Mode, no INTRPT MOV tISMCLK+CLR,&TACTL MOV #OMOO,&CCTLO Reset TAO, INTRPT off MOV.B #TAO,&P3SEL Define TAO output CLR TIMAEX~ Clear TAR extension MOV.B #3,&CBCTL Output ACLK/2 at XBUF pin BIS iMCONT,&TACTL EINT Start ·Timer Enable interrupt MAINLOOP Continue in background A 16 bit value is to be output. R5 contains data MOV R5,RFDATA Value into data word MOV.B U6+2,RFCOUNT Bit count+2 to RFCOUNT MOV &TAR,&CCRO For fast response: ADD UOO,&CCRO Time of 1st bit test MOV tOMOO+CCIE,&CCTLO Enable interrupt for CCRO Continue in background Test in background if 16 bits are output: RFCOUNT - 0 TST.B RFCOUNT output completed? JZ BPCJW)E Yes, interrupt bit is reset No· continue Interrupt handler for Capture/Compare Block O. Data in RFDATA is output: LSB first 6-124 The Timer A TIMMODO .EQU $ ADD #Bit_Length,&CCRO Start of CCRO handler Time of next bit change DEC.B RFCOUNT Bit count - 1 JNZ TMOl Not zero: continue MOV #OMR, &CCTLO Finish output: reset TAD RE'l'I TMOl INTRPT off RRA RFDATA Next bit of RFDATA JC TM02 Bit is one MOV #OMR+CCIE,&CCTLO Bit is 0: prepare reset RETI TM02 MOV #OMSET+CCIE,&CCTLO ; Bit is 1: prepare set RETI .Beet "TIMVEC",OFFF2h Timer_A Interrupt Vector . word TIMMODO Vector for Timer Block 0 .sect "INITVEC",OFFFEh Reset Vector . word INIT The example results in a maximum (worst case) CPU loading ucpu (ranging from 0 to 1) by the limer_A activities: ucpu 1 =jMCLK 33 x19200 (n imrp• x j rep) = . 1.572E6 0.44 Where: fMClK nlntrpt frep Frequency of the system clock (OCO) Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler [Hz] [Hz] The RF amplitude modulation loads the CPU to 44% of its capacity when running with 1.572 MHz. On-Ghip Peripherals 6-125 · The Timer A 6.3.8.8.2 RF Blphase Code Modulation The biphase code modulation represents each data bit by a change of the information in the middle of the sent data bit: o Data bit is 0: the information starts with 0 (RF off) and in the middle of the info bit the RF is switched on for the remaining half of the bit time. o Data bit is 1: the information starts with 1 (RF on) and in the middle of the info bit the RF is switched off for the remaining half of the bit time. o o o o Information 096h BipllaseCode Time --+ Figure 6-34. Biphase Code Modulation Due to the information change in the middle of the data bit, biphase code modulation needs twice the repetition rate of amplitude modulation - 38400 bits! second for a baud rate of 19200. Therefore, a system clock frequency of 1.048 MHz is not sufficient for this modulation. Instead, 1.606 MHz is selected for the MCLK frequency for biphase modulation. All members of the MSP430 family can use this frequency. The information is not converted in real time due to the high transmission rate of 38400 bits/second. The conversion is made before the transmission - bytes from eight arbitrary addresses (ADDRESSO to ADDRESS7) are converted and the bit pattern stored in a RAM block of 128 bits in length. This 128-bit buffer is output in real time. Example 6-38. Biphase Code Modulation Software example: Bi-Phase Code Modulation Input in R6 Some examples: 6-126 Output in RS 096h -> 06996h OOOh -> OAAAAh OFFh -> OS555h 069h -> 09669h Ollh -> OA9A9h Input -> output The Timer A Hardware definitions FLLMPY .equ 49 TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal ; FLL multiplier for 1.606MHz fRF .equ 38400 Bit rep. frequency Bit_Length .equ «2*TCLK/fRF)+1)/2 ; Bit length (TCLK cycles) STACK 600h .equ ; Stack initialization address RAM Definitions TlMAEXT .equ 202h .equ 212h .text OFOOOh INIT Converted data 16 bytes 32 bit extension Timer_A Software start address MOV JlSTACK,SP Initialize Stack Pointer CALL UNlTSR lnit. FLL and RAM Initialize the Timer_A: MCLK, Cont. Mode, INTRPT on MOV lIISMCLK+TAIE+CLR,&TACTL MOV #OMOO,&CCTLO Reset TAO, INTRPT off MOV.B lITAO,&P3SEL Define TAO output CLR TlMAEXT Clear TAR extension MOV.B #3,&CBCTL Output ACLK/2 at XBUF pin BIS #MCONT,&TACTL EINT Start Timer Enable interrupt MAINLOOP Continue in background 64 bits of data is to be output with Bi-Phase Code Modul. The data is converted into a 128-bit RAM block with the Bi-Phase Code sequence CLR RS For Bi-Phase Space necessary MOV #RF_BLK,R8 Address 8 word send block MOV.B ADDRESSO,R6 1st data byte to R6 On-Chip Peripherals 6-127 The Timer A CALL #BI_PHASE_CODE Convert it to 16 bits MOV R5,O(R8) Converted data to RF-Block MOV.B ADDRESS7,R6 8th data byte to convert to R6 CALL #BI_PHASE_CODE Convert to 16 bits MOV R5,14(R8) Converted data to RF-Block Convert next 6 bytes same way MOV #RF_BLK+16,R9 1st word after RF_BLK MOV #16+1,R6 Bit count for 1st 16 bits MOV @R8+,R5 1st 16 bits for output Switch off all interrupts to allow exact RF timing. This is not necessary if ALL OTHER interrupt handlers start with an EINT instruction MOV &TAR,&CCRO For fast response: ADD nOO,&CCRO Time of 1st bit test MOV #OMOO+CCIE,&CCTLO Enable interrupt for CCRO ; Continue in background Test in background if 128 bits are output: INTRPT of Timer Block ° is switched off by the INTRPT handler BIT #CCIE,&CCTLO output completed? JZ BPC...,MADE Yes No continue Interrupt handler for Capture/Compare Block ° Data in RF_BLK is output: LSB first TIMMODO 6-128 .EQU $ Start of CCRO handler ADD #Bit_Length,&CCRO For next INTRPT DEC R6 Bit count - 1 JNZ TM01 Not zero: continue The Timer A TM01 MOV @R8+,R5 Next 16 bits for output MOV #l6,R6 Bit count CMP R9,R8 End of buffer reached? JHS TM03 Yes, finish output RRC R5 Next data· bit to carry JC TM02 Bit is one MOV #OMR+CCIE,&CCTLO Bit is 0: prepare reset RETI TM02 MOV #OMSET+CCIE,&CCTLO Bit is 1: prepare set RETI TM03 MOV #OMR,&CCTLO RETI Output complete: Reset TAO, INTRPT off Subroutine transforms the data byte in R6 (8 bits) to Bi-Phase Code in R5 (16 bits). CALL + 86 cycles/byte BI_PHASE_CODE .equ $ BIPL Conversion routine MOV #8,R7 Convert 8 bits RRA R6 LSB to Carry RRC R5 Bit to R5 MSB BIT #8000h,R5 Copy bit once more RRC R5 to R5 XOR #8000h,R5 and invert it DEC R7 Bit count - 1 JNZ BIPL 8 bits not yet converted RET 16 info bits in R5 .sect "TIMVEC",OFFF2h Timer~ . word TIMMODO Vector for Timer Block 0 . sect "INITVEC",OFFFEh Reset Vector . word INIT Interrupt Vector The example results in a CPU loading ucpu (ranging from 0 to 1) by the Timer_A activities: On-Chip Peripherals 6-129 The Timer A ) _ (27 x15116 + 34 xlI 16) x2 x19200 1 ucpu = jMCLK 1: (n;nt'Pt X frep - 1.606E6 0.66 Where: fMCLK nlntrpt frep Frequency of the system clock (DCO) Number of cycles executed by the Interrupt handler Repetition rate of the interrupt handler [Hz) [Hz) This results in a MSP430 CPU load of 66% when outputting Biphase Code Modulation at 19200 baud with an MCLK frequency of 1.606 MHz. RF Biphase Space Modulation The realtime software - that outputs the 128-bit block - is exactly the same as the biphase code modulation shown in Section 8.8.2. Only the subroutine that converts the binary data to the biphase space code is different -the actual bit depends also on the previous bit. Therefore, only the different conversion subroutine is shown below. The CPU loading is, due to the equal real time part, is also 66%, like it is for the biphase code modulation. . o o o o Information 096h BI·Phase Space Time - - . Figure 6-35. Biphase Space Modulation Example 6-39. Biphase Space Modulation The information cannot be converted in real time due to the high transmission speed of 38400 bits/second. The conversion is made before the transmission: bytes from eight arbitrary addresses (ADDRESSO to ADDRESS7) are converted and the bit pattern is stored in a RAM block with 128 bits in length. This 128-bit buffer is output in real time by the timer block O. See Section 8.8.2. Subroutine converts the data byte in R6 (8 bits) to Bi-Phase Space Code in R5 (16 bits). CALL + 162 cycles/byte R5 contains the MSB (2nd half bit) of the last conversion. 6-130 The Timer A Input in R6 Some examples: Output in RS 096h -> 02B4Dh Prevo 2nd half bit OOOh -> OS5S5h o OFFh -> 03333h 069h -> 04D2Bh Ollh -> 054abh Oi6h -> OAB4Dh OOOh -> OAAAAh Prevo 2nd half bit = 1 OFFh -> OCCCCh Conversion routine BPSL MOV #B,R7 Number of bits CLR R9 Table Pointer BIT #BOOOh,RS Test last half bit (MSB RS) RLC R9 Bit to LSB RRC R6 Next info bit RLC R9 2 bit table address in R9 MOV.B BPSTAB(R9),R9 Data for 2 bits to be sent SWPB R9 OOxO -> xOOO CLRC Free two bits for new data RRC RS RRA RS in RS ADD R9,RS Insert new data to MSBs DEC R7 Bit count - 1 JN2; BPSL RET 8 bits not yet converted 16 info bits in R5 Table with 2-b1t info for all possible four bit combinations Prev Half-Bit BPSTAB Curro Bit Info Bits . byte 040h 0 0 . byte OCOh 0 1 11 . byte OBOh 1 0 01 . byte OOOh 1 1 00 10 The example results in a constant CPU loading ucpu (ranging from 0 to 1) by the TimecA activities of 66%, as with the biphase code modulation due to the equal RF part. On-Chip Peripherals 6-131 Th~ TlmecA 8.3.8.9 Real Time Clock T/le Timer_A can also be used as a real time clock (RTC) , especially in the low power mode 3 (LPM3). The ACLK is summed up and when one of the capturel compare registers is equal to the timer register (TAR), then an interrupt wakes up the CPU. The interrupt handler adds the time interval to the capturel compare register and returns to LPM3. Due to the available five capturel compare registers, up to five independent wake up frequencies may be programmed. Their handlers have the same structure as shown here for timer block 1. The timer overflow delivers an additional 0.5 Hz wake up frequency (2 16132768 Hz = 2 s). If this timing is sufficient, no interrupt by a capture! compare register is necessary. OFFFFh Timer Register Oh ~~~~----------------------------------~~-=~ __-----------------2s------------------~ ACLKPul_ 32.788 kHz Wake Up 0.25 s Timer Block 1 WskeUp2s Timer Overflow ~.......- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.......- . Time ---+ Figure 6-36. Real Time Clock Application of the Time,-A The software example shows a real time application with a wake up every 0.25 s initiated by timer block 1 (the software for the other timer blocks is not shown). The 0.25 s interrupt increments a RAM counter (RTC_CNT) and updates the time and date if a full second has elapsed. Example 6-40. Real Time Clock Application of the Timer_A Software example: Real Time Clock application of the Timer_A running in the Continuous Mode Hardware definitions 6-132 The Timer:...A FLLMPY .equ 32 TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal RTC_DELTA .equ 32768/4 ACLK delta for 4Hz wake-up STACK 600h Stack initialization address .equ FLL multiplier for l.048MHz RAM definitions RTC_CNT . equ 202h RTC counter for the 4Hz TlMAEXT .equ 204h TAR extension .text OFOOOh INIT Software start address MOV #STACK,SP Initialize Stack Pointer CALL UNITSR Init. FLL and RAM Initialize the Timer~: ACLK, Cont. Mode, INTRPT on MOV #ISACLK+TAIE+CLR,&TACTL CLR &CCRO Defined start value CLR TlMAEXT Clear TAR extension CCRl used for RTC MOV #OMOO+CCIE,&CCTLl MOV.B #CBACLK+CBE,&CBCTL ; output ACLK at XBUF pin BIS #MCONT,&TACTL EINT Start Timer Enable interrupt MAINLOOP Continue in background Enter LPM3. The watchdog must be held (ACLK continues) MOV #05AOOh+HOLD+CNTCL,&WDTCTL ; Hold watchdog BIS #CPUOFF+GIE+SCGl+SCGO,SR ; Enter LPM3 Interrupt handlers for Capture/Compare Blocks 1 to 4. The interrupt flags CCIFGx are reset by the reading of the Timer Vector Register TAIV On-Chip Peripherals 6-133 The Timer A TIMJiND ADD &TAIV,PC RETI Add Jump table offset vector 0: No interrupt JMP TIMMOD1 Vector 2 : Block 1 JMP TIMMOD2 Vector 4: Block 2 JMP TIMMOD3 TIMMOD4 Vector 6 : Block 3 Vector 8: Block 4 JMP Block 5. Timer Overflow Handler: the Timer Register is expanded into the RAM location TIMAEXT (MSBs). TIMAEXT is incremented every 28 TIMOVH .EQU $ INC TIMAEXT Vector 10: TIMOV Flag Incr. Timer extension 0.5Hz task starts here RETI Timer Block 1 is used for the Real Time Clook Repetition Rate - 4Hz (0.25s) TIMMOD1 .EQU $ Vector 2: Block 1 ADD #RTC_DELTA,&CCR1 INC RTC_CNT Add time interval (0.25s) RTC Task 4Hz starts here Increment 4Hz counter BIT JZ #3,RTC_CNT one second elapsed? TASK Yes No, back to LPM3 CALL #RTCLK Time + Is JNC CALL TMI #DATE ·Next day RETI TASK TM1 6-134 RETI If carry: 00.00· o'clock Return to LPM3 .sect "TIMVEC",OFFFOh Timer_A Interrupt Vectors . word . word TI)LHND TIMMODO Vector for blocks 1 to 4 Vector for Timer Block 0 . sect . word INIT "INITVEC",OFFFEh Reset Vector The Timer A The example results in a maximum (worst case) CPU loading uCPU (ranging from 0 to 1) by the Timer_A activities: CCR1 - repetition rate 4 Hz TIMOV - repetition rate 0.5 Hz ucpu 16 cycles for the task, 16 cycles overhead 4 cycles for the task, 14 cycles overhead 1 = jMCLK 1: (nintrpt X 32 cycles 18 cycles J. ) = 32 x4 +18x 0.5 =0.00013 rep 1.048E6 Where: fMCLK nintrpt frep Frequency of the system clock (OCD) Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler [Hz] [Hz] This result means that the MSP430 CPU uses the low power mode 3 during 99.987% of the time when running the RTC software shown (time and date tasks are not included). On-Chip Peripherals 6-135 The TimecA '" 6.3.8. 10 ConclusIon This section demonstrated the many and versatile possibilities ofthe Timer_A running in the continuous mode. Any mixture of capture and compare modes is possible with the five capture/compare registers (CCAx). It is also possible to change the mode of a capture/compare register during the run: a capture/ compare register used in capture mode during the calibration process may be used as a compare register during the normal run and vice versa. Also worth mentioning is the absolute synchronization of the generated timings. This is a resuH of the single timer register used for all capture/compare registers. This feature is very important for digital motor control applications. The readlwrlte feature of all the Timer_A registers additionally offers possibilities beyond the scope of this discussion. 6.3.9 Software Examples for the Up Mode This section shows several proven application examples for the Timer_A running in the up mode. The software definitions appear near the beginning of this section. Whenever pOSSible, the abbreviations defined in the MSP430 Architecture Guide and Module Library are used with the software examples. The software examples are written to be independent of the MCLK frequency in use. Only the FLL multiplier constant, FLLMPY, and the period for the period register need to be redefined If another combination is needed. The source lines for the definition of these important values are: FLLMPY fper TCLK PERIOD 6-136 .equ . equ .equ .equ 122 19200 FLLMPY*32768/4 «2*TCLK/fper)+1)/2 1. FLL multiplier 2 . PWM Repetition rate 3. FLLMPY x fcrystal/4 4. Period of the PWM o Definition of the CPU frequency fMCLK. The multiplier FLLMPY for the digitally Controlled oscillator (DCO) is defined. The value for the actual frequencyfMCLKis (FLLMPYx2 15). The value 122 stands for fMCLK = 122 x 215 = 3.9977 MHz. o Definition ofthe desired repetition rate. The value 19200 stands for fper = 19.2 kHz. o Definition ofthe Inputfrequencyfor the Timer Register (TAR). The expression /4 indicates that the input divider is set to the Divide-by-Four mode. The shown value stands for TCLK = 3.9977 MHzl4 = 999.424 kHz. Only the selected predlvlder for the Input divider (here /4) needs to be defined. o Calculation of the TCLK cycles for the defined period. This expression is used for the rounding of the result. No change is necessary for this line. The Timer A * 6.3.9.1 Common Remarks The up mode is designed primarily for pulse width modulation (PWM) or DC generation applications. If none of these applications is needed, then the continuous mode, with its five independent timings, should be used. Advantages of the Up Mode: o o o Free run without CPU load for stable PWM values (e.g. DAC, PWM) High PWM frequency is possible due to the pure hardware control Clever selected timings are usable for more than one real time job Disadvantages of the Up Mode: o Dominance of the period register - it defines the time frame for all other capture/compare blocks (C/C Blocks) o Current switching occurs at the saine time for all PWM outputs - this is the case when the timer register (TAR) equals the period register CCRD 6.3.9.1.1 Initialization The initialization subroutine, INITSR, is used in all examples. This subroutine was described in Section 6.3.8.1. It includes the following tasks: o Checks the reason for the initialization (switch on of the supply voltage, watchdog interrupt, or activation of the RESET input) o o Clears the RAM - or not - depending on the result of the above check. o Programs the system clock oscillator (multiplication factor N and optimum current switch FN_2, FN_3, or FN_4) Allows the digitally controlled oscillator to settle at the appropriate tap, providing the correct MCLK frequency 6.3.9.1.2 Timer Clock The information in this section is also valid for the continuous mode and the up/down mode. All software examples use the value FLLMPY - it defines the master clock frequency, fMCLK. On-Chip P~ripherals 6-137 The Timer A I MeL!( = FLLMPY xl crystal If this frequency, fMCLK Is too high for the application (it causes values for the timer registers exceeding the range from 0 to 65535, for example), then the input divider of the Timer_A may be used. This allows a prescaling of 1, 2, 4, or 8 for the timer input frequencies (fMCLK. fACLK or fTACLK) Example 6-41. Prescaling Factor of 2 For a required prescaling of 2, the definitions at the start of each example are simply changed to: FLLMPY .equ 100 FLL multiplier for 3.2768MHz TCLK .equ FLLMPY*3276B/2 Timer Clock = 1.6384MHz Input Divider D2 is used to get MCLK/2 for the TCLK MOV iISMCLK+D2+MUP+TAIE+CLR,&TACTL ; Use /2 divider The examples normally use an internally generated timer clock - the MCLK or the ACLK. It is also possible to use an external clock. This clock signal is connected to the TACLK terminal and selected with the following code sequence during the initialization: Ext. clock, Up Mode, Interrupt enabled, Timer Reg. cleared MOV #ISTACLK+MUP+TAIE+CLR,&TACTL BIS.B #TACLK,&P3SEL ; External clock to Timer_A 6.3.9.1,3 Timing Considerations The five independent timings provided by the continuous mode are not possible anymore in the noncontinuous modes because the period register (CCRO) dictates the timing frame for all other capture/compare blocks. Therefore, the period of the timer must be chosen very carefully to allow all the necessary timings. For example, a period chosen for PWM with 19.2 kHz also allows the timing for a software UART running at 2400 baud (19200/8) or 4800 baud (19200/4). 6-138 The Timer A To allow comparison and capturing also with the noncontinuous modes, it is a good practice to have not only a register that counts the overflows (period counter) -like TIMAEXT used with the continuous mode - but also a 16-bit or 32-bit register that counts the TCLK cycles. This allows the use of simple additions for the calculation of a time point. Otherwise, a multiplication is necessary (period counter x period length) to get the elapsed time. The examples given use both registers: TIMACNT TIMACYCx Period counter Cycle counter counts the number of full periods counts the cycles of the timing (one or more words) See also figure 6-43; the contents of these two registers are shown there for an example. Frequencies used by the CPU and the Timer_A. The following software examples are (nearty) independent of the MCLK and timer clock frequency in use. During the assembly, the new values for the period register and the timer clock frequency are calculated. A worst case calculation is necessary if a fMCLK that is too low is used. Update of Extension Registers. Unlike the case with the continuous mode, the update of these extension registers is made with the interrupt handler of the period register (CCRO). This has three reasons: o The interrupt of the period register occurs one cycle before the TIMOV interrupt o The period register (CCRO) has the highest interrupt priority of alilimer_A interrupts o A dedicated interrupt vector (address FFF2h) allows the fastest response to interrupt requests Real Time Environment. For all applications of the Timer_A running in one of the noncontinuous modes and using interrupt frequencies in the kilohertz range, it is recommended that strict real time environment programming be used. Otherwise, interrupt handlers are delayed and information may be lost. To achieve a real time environment, the following simple rules should be applied to all interrupt handlers: o The first instruction after the processing of time critical data - Timer~ related data for the Timer_A handlers, for example - should be the EINT (Enable Interrupt) instruction. This allows nested interrupts, a feature possible due to the stack architecture of the MSP430 family. o Interrupt handlers should be as short as possible. Only the absolutely necessary tasks should ~e executed (incrementing of counters, update of the On-Ghip Peripherals 6-139 The Timer A status bytes, etc.). The time consuming main tasks should be shifted to the background, where the software executes them according to the status byte information. Output Units. The PWM examples shown all use the set/reset mode or the reset/set mode of the output units. This has the advantage..,.. compared to the use of toggling - that no incorrect pulse widths can be generated during the change of the pulse width. 6.3.9.1.4 Interrupt Overhead The calculations for the CPU loading that are appended to the software examples split the necessary cycles for each capture/compare block into two parts: o Overhead - This part sums the cycles that are necessary for the CPU to execute the interrupt (saving of the program counter and the status register, decision on which interrupt needs to be served, restoring of the CPU . registers). o Update or Task - This part actually does the work that needs to be done (incrementing of counters, changing of status bytes, etc.). The number of overhead cycles shown with the examples are derived from the following sequences: • Interrupt ofthe period register CCRD (or other interrupt sources with a dedicated vector): Cycles from interrupt request to 1st instruction of the interrupt handler: Return from Interrupt instruction: RETI Sum of overhead • Interrupt of capture/compare registers CCR1 to CCR4: Cycles from interrupt request to 1st instruction of the interrupt handler: Decision which source caused the interrupt: ADD &TAIV, PC Addressed jump instruction: JMP TIMMODx Return from Interrupt instruction RETI Sum of overhead • 6 cycles 5 cycles 11 cycles 6 cycles 3 cycles 2 cycles 5 cycles 16 cycles Interrupt of the timer register TIMOV: This interrupt needs the same number of cycles as the interrupt of the capture/compare registers, but without the JMP TIMMODx instruction. This results in 14 cycles overhead. 6-140 The Timer A 6.3.9.2 Update of the Capture/Compare Registers If the capture/compare registers are updated asynchronously with the periodic timing of the Timer_A, the output pulses may become too long or may be missing. Therefore, a synchronous update should be used, which means the PWM value is written into a buffer, read out from this buffer at the correct time, and then written into the capture/compare register. Three possibilities exist for the synchronous update: 1) - Frequent update by the appropriate Interrupt Handler 2) Infrequent update by the appropriate Interrupt Handler 3) Update by the interrupt handler of capture/compare block 0 The three possibilities are described in the following paragraphs. To find the appropriate solution for a given timing problem, the following decision path maybe used: D Is an individual interrupt task necessary for one are more than one of the capture/compare blocks? If yes, use solution 1, otherwise continue. D Is a very fast update of the capture/compare registers necessary? If yes, use solution 1, otherwise solution 2. Frequent Update by the Appropriate Interrupt Handler The interrupt handler of capture/compare block x updates the capturel compare register CCRx with the repetition rate defined by the period register (CCRO). This method is necessary if an additional task is to be executed by the interrupt handler - medium preparation effort in the background, fast C/C register change. This method is used with Generation of Asymmetric Pulse Width Modulation and RF Timing Generation. The following software examples refer to the first application. If the range for the PWM output values is limited from 1 cycle to (period-1) cycles, then the following simple update sequence may be used: R6 contains new PWM info for CCR2. Range: I to (period-I). MOV.B R6,TA2PWM ; Actualize PWM buffer If the PWM output values 0% or 100% are actually used (CCRx =0 resp. CCRx ~ period), then a special treatment is necessary due to the not-generated inter- rupt request of the capture/compare block x under these circumstances. The On-Chip Peripherals 6-141 . The Timer A new CCRx value is then written immediately. To determine these special cases, the following update sequence may be used: . R6 contains new PWM info for CCR2. Range: 0 to full period. Check if an immediate update is necessary: This is the case for CCR2 = 0 .or. CCR2 >= period Software is written for a constant Period Register CCRO CMP IIPERIOD,&CCR2 CCR2 actually >= period? JHS L$21 Yes, update CCR2 immediately TST &CCR2 No, CCR2 JNZ L$22 CCR2 > 0: normal procedure = O? L$21 MOV R6,&CCR2 No interrupt: immed. update L$22 MOV.B R6;TA2PWM Actualize TA2PWM buffer Continue Infrequent Update by the Appropriate Interrupt Handler The interrupt handler of capture/compare block x UPdates the capture/ compare register (CCRx) with a repetition rate given by the calculation speed of the background program. If a new PWM value is calculated for a capture! compare block, then an individual flag is set and the interrupt for this capture! compare block is enabled. The first asynchronous interrupt is rejected and the second one (synchronous) is used for the update of the capture/compare register x. An interrupt task is possible only with the update repetition rate. This method is used if the PWM values for the update are not available at the same time - minimum interrupt overhead, Individual C/C register change. This method is used with Digital-to-Analog Conversion and TRIAC Control. The following software examples refer to the first application. If the range for the PWM output values is limited from 1 cycle to (periocl-1) cycles, then the following simple update sequence may be used: R6 contains: new PWM info for CCR2. Range: 1 to (period-1). MOV R6,DACOOV BIS.B #i,FLAG Set update flag for DACO BIS #CCIE,&CCTL2 Enable interrupt for DACO ; 6-142 ... Actualize DACO pulse length Continue in background The Timer A If the output values 0% or 100% are actually used (CCRx = 0 resp. CCRx ~. period), then a special treatment is necessary. The interrupt of the capture! compare block x is not generated in these cases. To determine these special cases, the following update sequence may be used: R6 contains the new PWM info for CCR2. Range: a to period. The interrupt is enabled individually for the update. A check is made if a special treatment is necessary: CCR2 = a .or. CCR2 >= period Software is written for a variable Period Register CCRa L$21 L$22 MOV R6,DACaOV Actualize DAca pulse length CMP &CCR2,&CCRa CCR2 >- period actually? Yes, update CCR2 immediat. JLO L$21 TST &CCR2 No, is CCR2 = a actually? JNZ L$22 No, proceed normally MOV R6,&CCR2 Update CCR2 immediately JMP L$23 Update made, no interrupt BIS.B #I,FLAG set update flag for DACa BIS #CCIE, &CC.TL2 Enable interrupt L$23 f~r DACO Continue in background For a constant period register (CCRO). the sequence is: Software is written for a constant period register CCRa MOV R6,DACOOV Actualize DAca pulse length CMP #PERIOD,&CCR2 CCR2 >- period actually? JHS L$21 Yes, update CCR2 immediat. TST &CCR2 No, is CCR2 = a actually? Same as above; On-Ghip Peripherals 6-143 The Timer·A Update by the Interrupt Handler of Capture/Compare Block 0 The interrupt handler of capture/compare block 0 updates the capture/ compare registers (CCRx) with the repetition rate given by the period register JCCRO). No additional tasks are possible for the other capture/compare blocks - their interrupts are disabled. The output units control the TAx outputs without software overhead - minimum interrupt overhead. fastest C/C register change. If an update is made from relatively large CCRx values to small ones (approximately interrupt latency time). then 100% pulses may occur. Therefore. this method is only recommended for small changes of the PWM value. This method can be used only if: o o o A very fast update is necessary Only a minimum overhead can be tolerated (no additional handler is needed. the CCRO handler is only slightly longer due to this operation) Erroneous output pulses with 100% length can be tolerated An example for this update method is given in section Capturing with the Up Mode for capture/compare block 4. These three possibilities may be mixed if it is advantageous. The examples of this section apply the same solution for all capture/compare blocks. Table 6-20 shows the overhead calculation and the percentage of the update overhead for the three different update methods. The calculation results are based on: Where: 4.0 MHz Frequency of the DCO (MCLK) fMCLK 100kHz fupdate Update frequency for the capture/compare registers Tlmer_A repetition rate (defined by the period register CCRO) 19.2 kHz fper Number of C/C blocks used for the PWM generation 3 n Table 6-20. Interrupt Overhead for the three different Update Methods UPDATE METHOD Frequent Update wtth appropriate Handler Infrequent Update with appropriate Handler Update by Capture/Compere Block 0 OVERHEAD FORMULA (CPU CYCLES) OVERHEAD PERCENTAGE nXfperx22 31.7% n X fupdate x 44 3.3% nXfperX6 8.6% i i Note: No interrupts are generated - and therefore no interrupt overhead - for capture/compare registers containing 0 or a value greater than or equal to the period register (CCRO). i 6-144 The Timer A 6.3.9.3 Generation of Asymmetric Pulse Width Modulation (PWM) The medium output voltage VPWM at the pin TAx resp. the necessary register content nccrx for a given voltage VPWM is: == Vccx nCCRx tpw == VccxnCCRO + 1 tper -7 ncCRx VPWM ( ) -v: x \nCCRO + 1 cc Where: VPWM Vee nCCRO neeRx tpw tper Medium output voltage at the TAx pin Supply voltage of the system Content of the period register CCRO Content of the capture/compare register CCRx Time generated by the capture/compare register Period generated by the period register CCRO M [V] [s1 [s1 Table 6-21 shows the necessary content of a capture/compare register CCRx to get some defined unsigned output values for VPWM: Table 6-21. Output Voltages for unsigned PWM OUTPUT VOLTAGE (VPWM) CONTENT OF COAx "CCRx OV 0 x Vee 0.5 x Vee 0.75 x Vce x 0.25 (neCRO + 1) x 0.5 (neeRO + 1) x 0.75 Vee (nCCRO + 1) 0.25 (nCCRO + 1) If the output voltage is seen as a signed voltage -like for 3-phase digital motor control- then the voltage 0.5 x Vee is seen as the 0 point. The signed output voltage VPWM gets: VPWM == vccx~:::l-O.5) '-+ nccRx = (:::+O.5)x(nccRo+l) Table 6-22 shows the contents of a capture/compare register (CCRx) required to get some defined values for a signed output voltage VPWM: On-Chip Peripherals 6-145 The Timer A Table 6-22. Output Voltages for Signed PWM OUTPUT VOLTAGE (VPWM) COMMENT CONTENT OF CCRx "CCRx -0.5 x Vee 0 -0.25 x Vee (neeRO + 1) x 0.25 OV (neeRO + 1) x 0.5 0.25 x Vee (nCCRO + 1) X 0.75 0.5 x V"" Most negative output voltage Hall negative output voltage ovoltage Hall pos~lve output voltage n""Qn+ 1 Most posftive output voltage Example 6-42. Generation of Two PWM Output Signals The software example shows the generation of two PWM output signals at the output terminals TA1 and TA2: o Output Pin TA 1 - a positive PWM signal. The length of the active high part is defined in the RAM location TA 1PWM (TCLK cycles). o Output Pin TA2 - a negative PWM signal. The length of the active low part is defined in the RAM location TA2PWM (TCLK cycles). Additional tasks need to be executed by the interrupt handlers of the capturel compare blocks 1 and 2, therefore an individual handler is used for both of them. The system clock frequency in use is 4 MHz (exactly fMCLK = 122 x 32768 = 3.9977 MHz), and the pulse repetition frequency is 19.2 kHz to allow the use of this frequency for other timings as well (a software UART with 4800 baud = 19.2 kHzl4, for example). For this application, bytes are sufficient for TA 1PWM and TA2PWM because the maximum possible value of its content is 209. (4.0 MHzl19200 =208.33). The output unit 0 outputs 9600 Hz without any overhead. This signal may be used for peripherals or for synchronization - the Signal is always present, even if the signals at TA1 and TA2 disappear due to an output Signal with 0% or 100% pulse width. The example uses the Frequent Update by the Appropriate Interrupt Handler. See Section 6.3.9.2 for details. 6-146 Timer Register Content i OFFFFh CCROr-----------~----------~~---------- CCR1 r-----~~--_i------~~--~----~~-CCR2~~~--4_--_i~~--~----~~~-----­ Oh~~----_r----~~----_r----~~-------- i-- ! - - COR1: TA1 Output t--I-----i---t--l-----I---t---'-- Output Mode 7: PWM Reset/Set r--IPW1 ~ CCR2: TA2 Output t--+----~-----,Io-+-----+---~......+ - Output Mode 3: PWM Set/Reset H-t TAO Output PW2 t--;---4--+--i------+-----I--;-- E U2 EQUO EQU1 (TIMOV) I E U2 EQUO (TIMOV) EQU1 E U2 EQUO CORO: Output Mode 4: PWM Toggle Interrupts Generated (TIMOY) Figure 6-37. Three Different Asymmetric PWM-Timings Generated With the Up Mode Software example: TAO: symmetric output signal 9.6kHz TAl: positive PWM signal 19.2kHz. Length in TA1PWM TA2: negative PWM signal 19.2kHz. Length in TA2PWM Hardware definitions FLLMPY .equ 122 FLL multiplier for 3.9977MHz fper .equ 19200 19.2kHz repetition rate TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal PERIOD .equ ((2*TCLK/fper)+I)/2 ; Period of output signals STACK .equ 600h ; Stack initialization address RAM definitions TAIPWM .equ 202h Pulse length Block 1 (0 .. 209) TA2PWM .equ 203h Pulse length Block 2 (0 .. 209) On-Chip Peripherals 6-147 The Timer_A Low cycle counter (bits 15 .. 0) TlMACYCO .equ 204h TlMACYC1 .equ 206h High cycle counter (31 .. 16) TlMACNT 208h Counts # of periods .equ Software start address . text INIT MOV #STACK,SP Initialize Stack Pointer CALL #INITSR Init. FLL and RAM Initialize the Timer_A: MCLK, Up Mode, INTRPTs on MOV #ISMCLK+CLR,&TACTL ; Define Timer_A MOV #PERIOD-1,&CCRO Period to Period Register MOV #0,&CCR1 TAl: pulse width MOV #0,&CCR2 TA2: pulse width MOV #OMT+CCIE,&CCTLO TAO: Toggle Mode MOV #OMRS+CCIE, &CCTL1 TAl: Reset/Set Mode TA2: Set/Reset Mode o o MOV #OMSR+CCIE,&CCTL2 MOV.B #TA2+TAl+TAO,&P3SEL ; Define Timer_A I/Os MOV.B #CBMCLK+CBE,&CBCTL ; Output MCLK at XBUF pin CLR.B TA1PWM CLR.B TA2PWM Start value Block 2: OV CLR TIMACYCO Clear low cycle counter CLR TlMACYC1 Clear high cycle counter CLR TIMACNT Clear period counter BIS #MUP,&TACTL start Timer in Up Mode EINT Start value Block 1: OV Enable interrupts MAINLOOP Continue in background Calculations resulted in new PWM values. The new results are stored in R6 (C/C Block 1) and R7. (C/C Block 2) Check if immediate update is necessary: CCRx = a .or. >= period. CMP 6-148 #PERIOD,&CCR1 CCR1 actually >= period? The Timer A Yes, update CCRI immediately JHS L$l1 TST &CCRI No, is CCRI = O? JNZ L$12 CCRI > 0: normal procedure L$l1 MOV R6,&CCRl No interrupt: immed. update L$12 MOV.B R6,TAIPWM Actualize TAlPWM buffer CMP #PERIOD,&CCR2 CCR2 actually >= period? JHS L$21 Yes, update CCR2 immediately TST &CCR2 No, CCR2 = O? JNZ L$22 CCR2 > 0: normal procedure L$2l MOV R7,&CCR2 No interrupt: immed. update L$22 MOV.B R7,TA2PWM Actualize TA2PWM buffer Continue in background Interrupt handler for CCRO: the Period Register. The cycle counters and the period counter are updated. A symmetric 9.6kHz signal is output by the Output Unit 0 Return from interrupt via 'the handler of C/C Blocks 1 to 4. TIMMODO ADD #PERIOD,TIMACYCO ; Add (fixed) period to ADC TIMACYCI INC TIMACNT cycle counters Period counter +1 TaskO (if any) Fall through to TIM_HND Interrupt handlers for Capture/Compare Blocks 1 to 4. The actual interrupt flag CCIFGx is reset by the reading of the Timer Vector Register TAIV TIM_HND ADD &TAIV,PC RETI Add Jump table offset Vector 0: No interrupt pending JMP TIMMODI Vector 2: Block 1 JMP TIMMOD2 Vector 4: Block 2 JMP TIMMOD3 Vector 6 : Block 3 (not shown) JMP TIMMOD4 RETI Vector 8: Block 4 (not shown) Vector 10: TIMOV not used On-Chip Peripherals 6-149 The Time,-A Capture/Compare Block 1 outputs a positive PWM signal at TAl The pulse width is defined in TAlPWM (0 .. PERIOD) TIMMODI MOV.B EINT TAlPWM,&CCRl Pulse width to CCRI Allow nested interrupts Task1 starts here Back to main program RETI Capture/Compare Block 2 outputs a negative PWM signal at TA2 The pulse width is defined in TA2PWM (0 .. PERIOD) TIMMOD2 MOV.B EINT TA2PWM,&CCR2 Pulse width to CCR2 Allow nested interrupts Task2 starts here Back to main program RETI The tasks for the C/C Blocks 3 and 4 are not shown TIMMOD3 Handler for C/C Block 3 RETI TIMMOD4 Handler for C/C Block 4 RETI . sect . word . word . sect . word "TIMVEC",OFFFOh TIM_HND Timer_A Interrupt Vectors C/C Blocks 1 to 4 Capture/Compare Block 0 Reset Vector TIMMODO "INITVEC" , OFFFEh INIT The example results in a nominal CPU loading uCpu (ranging from 0 to 1) by the Timer_A activities: 1 = -- ~ /MeLK Where: fMCLK nintrpt frep 6-150 (n1nJ'P' X f rep) Frequency of the system clock (DCO) Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler [Hz] [Hz] The TimecA Note: The formula and the definitions given above are also valid for all subsequent software examples. They are therefore not repeated. ! CCRO - repetition rate 19.2kHz CCR1 - repetition rate 19.2kHz CCR2 - repetition rate 19.2kHz ucpu 13 cycles for the task, 14 cycles overhead 6 cycles for the update, 17 cycles overhead 6 cycles for the update, 17 cycles overhead = 27 cycles 23 cycles 23 cycles 19200 x (27 +23+23) 3.9977 X = 0.35 ]06 This result shows a CPU loading of 35% due to the Timer_A (the tasks of the capture/compare blocks 1 and 2 are not included). 6.3.9.4 Dlgltal-to-Analog Conversion (DC Generation) With the Timer_A running in the up mode, a maximum of four digital-to-analog converters (DACs) can be created. With appropriate external filters, dc output voltages are available. The Figure 6-38 shows Simple hardware solutions for cleaning up the output dc voltage. The ripple shown on the dc output voltages is exaggerated for explanation purposes. ~ TA2 TA2 PWM Output TA3 PWM output TA3 DAC1 Output Voltage OV OV I I I TDAC1 x fCCRO x vee r ~~------~f-~1/Jf~CCCRROO I I ov O.5VCC TA3 PWM Output DAC10utputVoitage I4-TDAC2 lJ TA4 5V I ~ MSP430 Vss ~ ~iIII---__~~ 1lfCCRO ~ l' vee 14- TDAC1 .H TA4PWM Output I I TDAC2 x fCCRO x VCC ~~ 'T -+ - - -T-t- - - f DAC2 Output Voltage Figure 6-38. Digital-to-Analog Conversion On-Chip Peripherals 6-151 The Timer A Example 6-43. Digital-to-Analog Conversion This software example creates three DACs that are updated at individual times and relatively infrequently compared to the repetition rate defined by the period register (CCRO): o DACO - output TA2, positive output signal, output value stored in DACOOV. o DAC1 - output TA3, positive output signal, output value stored in DAC10V. o DAC2 - output TA4, negative output signal, output value stored in DAC20V. The higher the selected output frequency at the TAx outputs, the better the suppression of the ac part of the output signal is. The interrupt is used only after a new PWM value is calculated and needs to be transferred to the capture/compare register. The update rate is approximately 500 Hz. The repetition frequency for all three DAC outputs is 3.072 kHz, the system clock frequency selected is 3.1457 MHz. This results in 1024 different steps (10 bits resolution) for the DAC output voltages. This example uses the Infrequent Update by the Appropriate Interrupt HandIer. See Section 6.3.9.2 for details. The software is written for a variable period register. Software example: three independent DACs at TA2, TA3 and TA4 Hardware definitions FLLMPY .equ 96 fper .equ 3072 3.072kHz repetition rate TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal FLL multiplier for 3.14S7MHz PERIOD .equ ((2*TCLK/fper)+I)/2 ; Period of output signal STACK .equ 600h ; Stack initialization address ; RAM definitions DACOOV .equ 202h Output value DACO (10 bits) DAClOV .equ 204h Output value DACI (10 bits) 6-152 The Time,-A DAC20V .equ 206h Output value DAC2 (10 bits) TIMACYCO .equ 208h Cycle counter low (bits 15 .. 0) TIMACYCl .equ 20Ah Cycle counter high (bits 31 .. 16) TIMACNT .equ 20Ch Period counter FLAG .equ 20Eh Flag register for DACs .text Software start address Initialize the Timer_A: MCLK, Up Mode, CCRO INTRPT enabled Prepare Timer_A Output Units, MCLK = 3.l457MHz INIT MOV #STACK,SP CALL HNITSR MOV #ISMCLK+CLR,&TACTL MOV #OMOO+CCIE,&CCTLO Enable INTRPT Per. Reg. MOV #OMRS,&CCTL2 DACO: Reset/Set MOV #OMRS,&CCTL3 DACl: Reset/Set MOV #OMSR,&CCTL4 DAC2: Set/Reset MOV #PERIOD-l,&CCRO Load Period Register CLR &CCR2 DACO: 0% output CLR &CCR3 DACl" CLR &CCR4 DAC2 MOV.B #TA4+TA3+TA2,&P3SEL ; Output Unit I/Os CLR TIMACNT Clear period counter CLR TIMACYCO Clear cycle counters CLR TIMACYCI CLR.B FLAG Disable update of DACs BIS #MUP,&TACTL Start Timer_A with Up Mode EINT MAINLOOP Initialize Stack Pointer SP Init. FLL and RAM ; Define Timer_A Enable interrupts Continue in background Calculations for the new DAC values start. The new results in R6 are written to DACxOV after completion The interrupt is enabled individually for the update. A check is made if special treatment is necessary: CCRx = 0 .or. >= period On-Chip Peripherals 6-153 The Timer A Software is written for a variable period register CCRO Calculate DACO value to R6 MOV L$2l L$22 L$23 R6,DACOOV Actualize DACO pulse length CMP &CCR2,&CCRO CCR2 >- period actually? JLO L$2l Yes, update CCR2 immediat. TST &CCR2 No, is CCR2 JNZ L$22 No, proceed normally MOV R6,&CCR2 Update CCR2 immediately JMP L$23 update made, calc. CCR3 PWM BIS.B #l,FLAG Set update flag for DACO BIS #CCIE,&CCTL2 Enable interrupt for DACO .equ $ MOV R6,DAC10V Actualize DACl pulse length CMP &CCR3,&CCRO See comment for DACO JLO L$3l = 0 actually? Calculate DACl value to R6 L$3l L$32 L$33 TST &CCR3 JNZ L$32 MOV R6,&CCR3 JMP L$33 BIS.B #2 ,FLAG BIS #CCIE,&CCTL3 .equ $ MOV R6,DAC20V Actualize DAC2 pulse length CMP &CCR4,&CCRO See comment for DACO JLO L$4l Calculate DAC2 value to R6 L$41 L$42 6-154 TST &CCR4 JNZ L$42 MOV R6,&CCR4 JMP L$43 llIS.B #4,FLAG BIS #CCIE,&CCTL4 The Timer A Continue in background L$43 Interrupt handler of the Period Register CCRO. A way is shown how to update the cycle counters if the timer period is variable during the program flow TIMMODO SETC Period - (CCRO)+l ADDC &CCRO,TlMACYCO Add actual period to ADC TlMACYCl cycle counters TlMACYCx INC TlMACNT Period counter +1 EINT Allow nested interrupts TaskO (if any) RETI Interrupt handler for Capture/Compare Registers 1 to 4 TIM_HND ADD &TAIV,PC Serve highest priority requ. JMP TIMMODl CCR1 request JMP TIMMOD2 DACO request JMP TIMMOD3 DAC1 JMP TIMMOD4 RETI No interrupt pending RETI DAC2 Timer overflow disabled Capture/Compare Block 1 interrupt handler. May be used for comparison or capturing. Not implemented here. TIMMODl Handler start RETI DACx updates. Interrupt is used only if a new result is calculated. Update frequency is 0.5kHz. The 1st interrupt is rejected, due to the always set interrupt flag CCIFGx. The 2nd synchronous interrupt updates the C/C Block. TIMMOD2 BIT.B #l,FLAG Update possible? (flag - 0) On-Chip Peripherals 6-155 The Timer A T20 JNZ MOV BIC RETI BIC.B RETI T20 DACOOV, &CCR2 #CCIE,&CCTL2 No, asynchronous interrupt Yes, update DACO Disable interrupt n,FLAG Indicate update readiness Return from interrupt DACl update. Same as above for DACO TIMMOD3 T30 BIT.B JNZ MOV BIC RET I BIC.B RETI #2,FLAG T30 DAC1OV,&CCR3 #CCIE,&CCTL3 update possible? (flag = 0) No, asynchronous interrupt Yes, update DACl Disable interrupt 1t2,FLAG Indicate readiness Return from interrupt DAC2 update. Same as above for DACO TIMMOD4 T40 BIT.B JNZ MOV BIC RETI BIC.B RETI #4 ,FLAG T40 DAC20V,&CCR4 #CCIE,&CCTL4 update possible? (flag = 0) No, asynchronous interrupt Yes, ·update DAC2 Disable interrupt #4,FLAG Indicate readiness Return from interrupt .sect . word . word .sect . word "TIMVEC",OFFFOh TIM_HND TIMMODO "INITVEC",OFFFEh INIT Timer~ Interrupt Vectors Vector for C/C Block 1. .4 Vector for C/C Block Reset Vector ° This example results in a maximum CPU loading ucpu (ranging from 0 to 1) by the Timer_A activities (maximum update frequencies on all three DAC channels): CCRO CCR2 CCR3 CCR4 - 6-156 repetition rate 3.072 kHz repetition rate 0.5 kHz repetition rate 0.5 kHz repetition rate 0.5 kHz 16 cycles for the task, 11 cycles overhead 27 cycles for the update, 32 cycles overhead 27 cycles for the update, 32 cycles overhead 27 cycles for the update, 32 cycles overhead 27 cycles 59 cycles 59 cycles 59 cycles The Timer A _ 3072 x27 +500 x(59+59 +59) -00 3.1457 x10 6 • 55 u cpu - Note that an update for the capture/compare blocks 2 to 4 needs two interrupt services. The above result means a worst case CPU loading of approximate 5.5% due to the three DACs. If all three tasks are updated with a 100 Hz update rate, then the CPU is loaded with only 3.2%. 6.3.9.5 TRIAC Control TRIAC control for electric motors (DMC) or other loads is also possible with the up mode of the TimecA. But the time frame, defined by the period register, does not allow the same resolution as with the continuous mode. The control software now counts the number of periods and fires the TRIAC after the reaching of the programmed number. The medium resolution pmed is: 1 pmed = - - - - - 2 X /MAINS X tper Where: fMAINS tper AC Line frequency Period of the Timer_A, defined by CCRO [Hz] [s] The integrated energy E 6f a sine half wave dependent on the time t is described by the equation: E~l-cosro 1 t =0 ... 2f t=1-cos21tft Due to this nonlinear energy increase, the worst case resolution Pmin - near theangle1tl4 (90°) -is reduced by a factorof1tl2 (1.57) compared to the medium resolution Pmed: pmin = 1 2 x/MAlNS X tperx 1t /2 The TRIAC control software contains fewer security features than the version shown for the continuous mode: o The zero crOSSing part (PO.O handler) immediately switches the gate signal off by setting terminal TAO to high. This prevents the firing for the next half wave. On-Chip Peripherals 6-157 The Timer A This means, the background software has to check to see ifthe calculated time forthe firing ofthe TRIAC - the number oftimer periods after the zero crosSing of the ac line voltage (FIRANGL) - is not too near to the next zero crossing. No capture/compare register is needed for the TRIAC control- only the period register with its interrupt and output unit 0 is used. This frees the remaining capture/compare blocks for other taskS. Figure 6-39 shows the hardware for the TRIAC control of this example. After power up, the TAO terminal is switched to input mode - the base resistor of the PNP transistor switches the gate of the TRIAC off and prevents a run of the motor. The necessary hardware debounce for the zero crossing signal at PO.O is made with the internal capacity, Cz, of the zener diode. 5V >1 M J1.J"L PWM Output 2 J1.J"L PWM Output 1 Figure 6-39. TRIAC Control with Time,-A Figure 6-40 illustrates the software example given below. The period of CCRO is not shown in to scale - 160 steps make one half wave of the 50 Hz line. 6-158 The Timer A PO.Olnput Zero Craning .-+----"'------l-----.J-------'----- TAO Output to TRIAC Gate -+----'-.........I--------"L....a,,:--:=-=-~--+_'-+-.......- - - Voltage AC Figure 6-40. Signals for the TRIAC Gate Control With Up Mode Example 6-44. Static TRIAC Control A static TRIAC control software example is shown. The calculated number of periods until the TRIAC gate is fired after the zero crossing of the ac line voltage, is contained in the RAM word FIRANGL. The medium resolution Pmed is 160 steps per 50 Hz line half wave (16 kHzl100 Hz =160). The minimum resolution, Pmln, is 102 steps (160 x 217t = 102), which means approx. 1% resolution. See the equations above. At the TA1 and TA2 terminals, positive PWM signals are output. The period is defined by the Period register CCRO, the pulse length (TCLK cycles) is contained in the RAM bytes TA1PWM and TA2PWM. The update is made with 1 kHz. The example uses the Infrequent Update by the Appropriate Interrupt Handler. See Section 6.3.9.2 for details. ; Definitions for the TRIAC control software FLLMPY .equ 64 fper .equ 16000 16.000kHz repetition rate TCLK .equ FLLMPY*32768 TCLK (Timer Clock) [Hz] PERIOD .equ {{2*TCLK/fper)+1)/2 ; Period in Timer clocks OP .equ 2 FLL multiplier for 2.096MHz TRIAC gate pulse length (per.) On-Chip Peripherals 6-159 The Timer A RAM definitions TlMACYCO .equ 202h Timer Register Extensions: TlMACYC1 .equ 204h Cycle counters TlMACNT .equ 206h Counter of periods FlRANGL .equ 208h Half wave - conduction angle FIRTIM .equ 20Ah TA1PWM .equ 20Ch Fire time rel. to TlMACNT PWM cycle count for· Block 1 TA2PWM .equ 20Dh PWM cycle count for Block 2 STTRIAC .equ 20Eh Control byte (0 FLAG .equ 20Fh 1: update for PWM necessary STACK .equ 600h Stack initialization address . text off) Status start of ROM code Initialize the Timer_A: MCLK, Up Mode, INTRPT enabled Prepare Timer_A Output Units INIT 6-160 MOV #STACK,SP Initialize Stack Pointer SP CALL HNITSR Init. FLL and RAM MOV #ISMCLK+CLR,&TACTL ; Init. Timer MOV #PERIOD-1,&CCRO MOV #OMOO+CCIE+OUT,&CCTLO MOV #OMRS,&CCTL1 TAl: pos. PWM pulses MOV #OMRS,&CCTL2 TA2: pos; PWM pulses BIS.B #TA2+TA1+TAO,&P3SEL ; Define timer outputs BIS.B #POIEO,&IE1 ; Period to CCRO ; Set TAO high Enable PO.O interrupt (mains) CLR TlMACYCO Clear low cycle counter CLR TlMACYC1 Clear high cycle counter CLR TlMACNT Clear period counter CLR.B STTRIAC TRIAC off status (0) CLR.B FLAG No update CLR.B TAIPWM TAl: no output (0% duty cycle) CLR.B TA2PWM TA2: no output (0% duty cycle) BIS #MUP,&TACTL Start Timer_A in Up Mode MOV.B #CBMCLK+CBE,&CBCTL ; MCLK at XBUF pin The Timer A Enable interrupts EINT Continue in mainloop MAINLOOP Some TRIAC control examples: Start electric motor: checked result (Timer_A periods) in R5 The result is the time difference from the zero crossing of the mains voltage (PO.O) to the first gate pulse (measured in Timer_A periods) MOY R5,FIRANGL Delay (periods) to FIRANGL MOY.B #2,STTRIAC Activate TRIAC control Continue in background The motor is running. A new calculation result is available in RS. It will be used with the next mains half wave MOY RS,FIRANGL Delay (periods) to FIRANGL Continue in background stop motor: switch off TRIAC control CLR.B STTRIAC Disable TRIAC control BIC #OMRS,&CCTLO TRIAC gate off BIS #CCIE+OUT,CCTLO TAO high, Output only Mode Continue with background Calculations for the new PWM values start. The new results in R6 are written to TAxPWM after completion The interrupt is enabled individually for the update. A check is made if special treatment is necessary: Actual CCRx = 0 .or. >= period Software is written for a constant period register CCRO Calculate TAlPWM value to R6 MOY.B R6,TAlPWM Actualize pulse length CMP #PERIOD,&CCRl CCRl >- period actually? On-Chip Peripherals 6-161 The Timer_A L$l1 L$l2 L$l3 JHS L$l1 Yes, update CCRl immediat. TST &CCRl No, is CCRl JNZ L$l2 No, proceed normally MOV R6,&CCRl update CCRl immediately JMP L$l3 Update made, calc. next PWM = 0 actually? BIS.B U,FLAG set update flag for TAlPWM BIS *CCIE,&CCTLl Enable interrupt .equ $ MOV.B R6,TA2PWM Actualize pulse length CMP *PERIOD,&CCR2 CCR2 >= period actually? JHS L$2l Yes, update CCR2 immediat. TST &CCR2 No, is CCR2 = 0 actually? Calculate TA2PWM value to R6 L$2l L$22 JNZ L$22 No, proceed normally MOV R6,&CCR2 update CCR2 immediately JMP L$23 Update made, continue BIS.B #2 ,FLAG Set update flag for TA2PWM BIS *CCIE,&CCTL2 Enable interrupt for DACO L$23 Continue in background Interrupt handler for CCRO: the Period Register: - The cycle counters and the period counter are updated: - The TRIAC control task is executed TIMMODO ADD #PERIOD,TlMACYCO Add (fixed) period to ADC TlMACYCl Cycle counters INC TlMACNT Increment period counter Interrupt handler for the TRIAC control EINT 6-162 -Allow nested interrupts PUSH RS Save help register RS MOV.B STTRIAC,RS Status of TRIAC control MOV STTAB(RS) ,PC Branch to status handler The Timer A STTAB . word STATED Status D: No TRIAC activity . word STATED Status 2: activation pcssibLe . word STATE4 Status 4: wait for gate pulse . word STATE6 Status 6: wait for gate off TRIAC status 4: gate is switched on for OP periods after the value in FIRTIM is reached STATE4 CMP FIRTIM,TIMACNT TRIAC gate time reached? JNE STATED No BIS #OMR+CCIE,&CCTLD ; Prepare for gate on pulse ADD.B #2,STTRIAC ; Next TRIAC status (6) TRIAC status D: No activity. TRIAC is off always STATED POP RS RETI Restore help register Return from interrupt TRIAC status 6: gate pulse is active. Check if it's time to switch the gate off. STATE6 MOV FIRTIM,RS ADD #OP,RS Gate-on time (periods) CMP RS,TIMACNT On-time terminated? JLO STATED No BIC #OMRS,&CCTLD Yes, BIS #OMSET+CCIE,&CCTLD; prepare TRIAC Gate off MOV.B #2,STTRIAC TRIAC status: JMP STATED Wait for next zero crossing Interrupt handler for capture/Compare Blocks 1 to 4 TIM_HND ADD &TAIV,PC Serve highest priority requ. JMP TIMMODl PWM 1 request JMP TIMMOD2 PWM 2 request RETI RETI No interrupt pending Not used On-Chip Peripherals 6-163 The Timer A RETI Not used RETI Timer oyerflow disabled C/C Block updates. Interrupt is used only if a new result is calculated. Update frequency is 1.0kHz. The 1st interrupt is rejected, due to the always set interrupt flag CCIFGx. The 2nd synchronous interrupt updates the C/C Register. TIMMOD1 Update possible? (flag = 0) BIT.B #1,FLAG JNZ TIO No, asynchronous interrupt MOV.B TAlPWM,&CCR1 Yes, update C/C Block I BIC IICCIE,&CCTLI Disable interrupt RETI TIO BIC.B III,FLAG RET I TIMMOD2 Indicate: ready for update Return from interrupt BIT.B J;2,FLAG Update possible? (flag JNZ T20 No, asynchronous interrupt MOV.B TA2PWM, &CCR2 Yes, update C/C Block 2 BIC #CCIE,&CCTL2 Disable interrupt = 0) RETI T20 BIC.B #2,FLAG RETI Indicate: ready for update Return from interrupt Po.o Handler: the mains voltage causes interrupt with each zero crossing. The TRIAC gate is switched off first, to avoid the ignition for the actual half wave. Hardware debounce is necessary for the mains signal! POO_HNDLR BIC BIS JOMRS,&CCTLO EINT XOR.B Switch off TRIAC gate #CCIE+OUT,&CCTLO Allow nested interrupts #1,&POIES Change interrupt edge of PO.O If STTRIAC is not 0 ( 0 = inactivity) then the next gate firing is prepared: STTRIAC is set to 4 6-.164 The Timer A TST.B STTRIAC JZ POO STTRIAC = 0: no activity MOV.B #4, STTRIAC STTRIAC > 0: prep. next firing The TRIAC firing time is calculated: TlMACNT + FlRANGL POO MOV TIMACNT,FIRTIM Period counter ADD FlRANGL,FIRTIM TIMACNT + delay -> FIRTIM RETI . sect "TIMVEC",OFFFOh Timer_A Interrupt Vectors . word TIILHND C/C Blocks 1 .. 4 Vector . word TIMMODO Vector for C/C Block 0 .sect "POOVEC",OFFFAh PO.O Vector . word POO_HNDLR . sect "INITVEC",OFFFEh . word INIT Reset Vector The TRIAC control example results in a nominal CPU loading ucpu (ranging from 0 to 1) for the active TRIAC control (STIR lAC = 4): CCRO - repetition rate 16 kHz CCR1 - repetition rate 1 kHz CCR2 - repetition rate 1 kHz PO.O - repetition rate 100 Hz 32cycles for the task, 11 cycles overhead 27 cycles for the update, 32 cycles overhead 27 cycles for the update, 32 cycles overhead 32 cycles for the task, 11 cycles overhead 16.0 x10 3 x43+1.0 x10 3 x (59 +59)+100 x47 2.096 x106 43 cycles 59 cycles 59 cycles 43 cycles = 0.39 The above result means a CPU loading of approximate 39% due to the static TRIAC control. The necessary tasks for the update of the period counter and the cycle counters are included. The PWM activities alone load the CPU with less than 6% using this method (fupdate = 1 kHz). On-Chip Peripherals 6-165 The TlmecA 6.3.9.6 RF Timing Generation The repetition rate used in the up mode must be a multiple of the data change frequency. The three different modulation methods and its conversion subroutines were explained in depth in the section RF generation. The RF modulation modes described earlier were: o Amplitude Modulation - the RF oscillator is switched on for a logical 1 and switched off for a logical 0 (100% modulation). o Biphase Code - the information is represented by a bit time consisting of one half bit without modulation and one half bit with full modulation. A logical 1starts with 100% modulation, a logical Ostarts with no modulation. o Blphase Space - a logical 1 (space) is represented by a constant signal (100% or 0% modulation) during the complete bit time. A logical 0 (mark) changes the signal in the middle of the bit time. The signal changes after each transmitted bit. This means, the previous bit influences the current bit. Figure 6-41 shows the three different modulation modes for an input byte containing the value 96h. o o o o Informallon 096h Amplitude Modulation Blphasa Space Bit Length Figure 6-41. RF Modulation Modes 6-166 "*--.J Tlma-. The capture/compare block 0 is used with the software example due to two facts: o The fastest possible response. Decision making with the timer vector register is not necessary for the capture/compare block 0 - it uses its own, dedicated interrupt vector. The vector address is OFFF2h. o The capture/compare block 0 delivers the necessary timing anyway. The use of the period register therefore frees the remaining capture/compare registers for other tasks. Example 6-45. RF Modulation Modes The real time task common to all three modulation modes is given below. The background software prepares a 128-bit block starting at address RF_BlK, containing the information to be output in the desired coding format. This 12S-bit buffer is output in real time with the same handler for all three modulation modes. The selected half-bit repetiti~n frequency is 19200 Hz, because 38400 Hz is too high a PWM frequency (increased switching losses, too few resolution steps). The capture/compare blocks 1 to 3 are used for the PWM generation. The table processing used allows (nearly) simultaneous update of all three capture/compare blocks. The method used is the fastest one for updating. The number range for the PWM is from 1 to (period-1), therefore, the fast update - without range checks - is possible. The CPU registers RS and RS are reserved for the RF timing. RS contains the data to be output currently, RS pOints to the next data word. They must not be overwritten by other tasks. The conversion subroutines forthe biphase code and biphase space modulation are described in the section RF Generation. The example uses the Frequent Update by the Appropriate Interrupt Handler. See Section 6.3.9.2 for details. Hardware definitions FLLMPY .equ 122 FLL multiplier for 3.998MHz fRF .equ 19200 Half-bit rep. frequency TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrysta1 PERIOD .equ «2*TCLK/fRF)+1)/2 ; Bit length (TCLK cycles) On-Chip Peripherals 6-167 stack initialization address Converted data 128 bits Cycle counter Timer-A Period counter Timer-A Status of RF transmission Value for C/C Block 1 Value for C/C Block 2 Value for C/C Block 3 ; Software start address Initialize Stack Pointer Init. FL~ and RAM Initialize the Timer_A: MCLK, Up Mode, INTRPT on for CCRx MOV 6-168 #ISMCLK+CLR,&TACTL ; MCLK, TIMOV off MOV ~OMOO+CCIE,&CCTLO Reset TAO, INTRPT on MOV #OMSR+CCIE,&CCTLl TAl: Set/Reset MOV #OMSR+CCIE,&CCTL2 TA2: Set/Reset MOV #OMSR+CCIE,&CCTL3 TA3: Set/Reset MOV #PERIOD-l,&CCRO 19.2kHz period MOV.B lIl,&CCRl Minimum PWM length MOV.B U,&CCR2 MOV.B U,&CCR3 MOV.B #TA3+TA2+TAl+TAO,&P3SEL CLR TlMACYC Clear cycle counter CLR TlMACNT Clear period counter MOV.B U,TAlPWM Minimum PWM output MOV.B #1,TA2PWM Define timer outputs MOV.B #l,TA3PWM MOV.B #CBMCLK,&CBCTL Output MCLK at XBUF pin CLR.B RFSTAT RF status = 0 The Timef A BIS #MUP,&TACTL EINT Start Timer in Up Mode Enable interrupts Continue in background MAINLOOP The data to be transmitted by RF is converted into a 12B-bit RAM block starting at address RF_BLK with the appropriate conversion routine. The subroutines described in Part III are used. See there for explanation. R5 and R8 are reserved for the RF transmissioni MOV.B ADDRESSO,R6 1st data byte to R6 CALL #BI_PHASE-.xxx Convert it to 16 bits MOV RS,O(RB) Converted data to RF-B1ock Continue with converting Initialize transmission of the converted data (12B-bit) MOV #RF_BLK,RB MOV @RB+,R5 1st 16 bits for output to R5 MOV.B #16+1,RFSTAT Bit count for 1st 16 bits Start of 128-bit block Continue in background ° Test in background if 12B bits are output: RFSTAT TST.B RFSTAT Output completed? JZ BPC_MADE Yes, RFSTAT = ° No, continue New values for the three PWM channels are read from a table MOV ANGLE,R15 MOV.B TABLE+OO(R15),TA1PWM ; Actual angle for DMC Update PWM channels MOV.B TABLE+12(R1S),TA2PWM out of a sine table MOV.B TABLE+24(R1S),TA3PWM ; Continue in background On-Ghip Peripherals 6-169 The rlme,-A A second example is given for a 64 bit block: Initialize transmission of only 64 bits: the start address differs, the end address is again RF_BLK+16 MOV #RF_BLK+B,RB Start of 64-bit block MOV @RS+,R5 1st 16 bits for output to R5 MOV.B U6+1,RFSTAT Bit count for 1st 16 bits Continue in background TABLE . byte 1,15,29,43 ... PERIOD-1 PWM table Interrupt handler for Capture/Compare Block 0 (CCRO) Data in RF_BLK is output: LSB first. The Output Unit outputs the data bit prepared during the last period. The data bit for the next period is prepared now. Output is completed, when (last word +4) is addressed by RS. TIMMODO ADD lIPERIOD,TlMACYC Add period to cycle counter INC TIMACNT i EINT TM01 TM04 Increment period counter Allow nested interrupts TST.B RFSTAT JZ TM03 RF transmission underway? No, return from interrupt DEC.B RFSTAT Yes, bit count - 1 JNZ TM01 Not zero: continue MOV @RS+,R5 Next 16 bits for output CMP #RF_BLK+1S,RS End of buffer+2 reached? JHS TM04 Yes, MOV.B #l6,RFSTAT Bit count for next word finish output (RFSTAT=O) RRC RS Next data bit to carry JC TM02 Bit is one MOV #OMR+CCIE,&CCTLO Bit is 0: prepare reset RETI TM02 6-170 MOV #OMSET+CCIE,&CCTLO Bit is 1: prepare set The Timer A TM03 RETI Interrupt handlers for Capture/Compare Blocks 1 to 4. The actual interrupt flag CCIFGx is reset by the reading of the Timer Vector Register TAIV TIILHND ADD &TAIV,PC RET I Add Jump table offset Vector 0: No interrupt pending JMP TIMMOD1 Vector 2: Block 1 JMP TIMMOD2 Vector 4: Block 2 JMP TIMMOD3 Vector 6: Block 3 Vector 8 : Block 4 (not used) RETI .RETI Vector 10: TIMOV not used Capture/compare Block 1 outputs a positive PWM signal at TAl The pulse width is defined in TA1PWM (1 .. PERIOD-1) TIMMOD1 MOV. B TA1PWM,&CCR1 RETI Pulse width to CCR1 Back to main program Capture/Compare Block 2 outputs a positive PWM signal at TA2 The pulse width is defined in TA2PWM (1 .. PERIOD-1) TIMMOD2 MOV.B TA2PWM,&CCR2 Pulse width to CCR2 Back to main program RETI Capture/Compare Block 3 outputs a positive PWM signal at TA3 The pulse width is defined in TA3PWM (1 .. PERIOD-1) TIMMOD3 MOV.B TA3PWM,&CCR3 RETI Pulse width to CCR3 Back to main program .sect "TIMVEC",OFFFOh Timer_A Interrupt Vector . word TIILHND Vector C/C Blocks 1 to 3 . word TIMMODO Vector for C/C Block 0 . sect "INITVEC",OFFFEh Reset Vector .word INIT On-Chip Peripherals 6-171 The Timer A The RF timing generation example results in a nominal CPU loading ucPU (ranging from 0 to 1) for the active transmit (RFSTAT > 0): CCRO CCR1 CCR2 CCR3 - repetition rate 19.2 kHz repetition rate 19.2 kHz repetition rate 19.2 kHz repetition rate 19.2 kHz 30 cycles for the task, 11 cycles overhead 6 cycles for the update, 16 cycles overhead 6 cycles for the update, 16 cycles overhead 6 cycles for the update, 16 cycles overhead 41 cycles 22 cycles 22 cycles 22 cycles The above example results· in a medium CPU loading uCPU (ranging from 0 to 1) by the TlmecA activities: =_1_1: u CPU fMcLK n. (,ntrpt x frep )=19.2X10 3 X(41+22+22+22)=0.51 3.998 x 10 6 The result means that the MSP430 CPU is loaded 20% when outputting the RF buffer with 19200 baud and an MCLK frequency of 4 MHz. The updates of the cycle counters and the period counter are included. The update of the PWM registers adds 31%, if used. 6.3.9.7 Softwsre UART With a carefully chosen timer period, a software UART can be implemented relatively simply. The complete software, a status-controlled handler, will be the topic of an external application report. This report will describe a full-duplex UART controlled by the timing of Timer_A. 6.3.9.8 Compsrlson With the Up Mode Comparison with the up mode is made the same way as described in the section Applications exceeding the 16-8it Range of the TimecA for thecontinuous mode. As in that case, the timings to be created exceed the period of the timer register and external RAM extensions are therefore necessary. 6.3.9.9 Cspturlng WIth the Up Mode If the periods of the Internal interrupt timings or the time intervals to be captured are longer than one period ofthe timer register, then a special method is necessary to take care of the longer time periods. The same is true if a half period of a generated output frequency is longer than the period of the Timer_A. This special method, with the use of extension registers for the capture! compare registers, is necessary if: tS/GNAL > (nccrll + 1) xk fCLK 6-172 The Timer A Where: tSIGNAl fClK k nCCRO lime interval to be captured Input frequency at the input divider input of limer_A Pre-divider constant of the input divider (1, 2, 4 or 8) Content of period register CCRO [s] [Hz] Figure 6-42 Illustrates the hardware and RAM registers used with the capture mode if the captured values are greater than one period of the limer_A. o 15 15 Cycle Counter o Timer Clock carry to TIMACYC1 16-Blt CaptUred Value Figure 6-42. Capture Mode with the Up Mode (shown for CCR 1) Figure 6-43 illustrates five examples. The tasks are defined as follows: o Capture/Compare Block 0 - outputs a symmetrical 9.6 kHz signal. The edges contain the information forthe period generated by the period register (CCRO). This signal is always available (the PWM signals of the capture/compare blocks disappear for pulse widths of 0% and 100%). o Capture/Compare Block 1 - generates a positive PWM signal with the period defined by the period register. The pulse length is stored in the RAM word TA1 PWM. A dedicated interrupt handler is used. o Capture/Compare Block 2 -the length, At2, of the high part of the input signal althe CCI2A input terminal is measured and stored in the RAM word PP2. The captured time of the leading edge is stored in the RAM word TIM2. The max. repetition rate used is 2 kHz. o Capture/Compare Block 3 - the event time of the leading edge of the signal at the CCI3A input terminal is captured. The last captured value is stored in the RAM word TIM3. The max. repetition rate used is 3 kHz. o Capture/Compare Block 4 - generates a negative PWM signal with the period defined by the period register. The pulse length is stored in the RAM On-Chip Peripherals 6-173 ThaT/mer A word TA4PWM. Update is made with the interrupt handler of capture! compare block o. For the example, 3.801 MHz is used. The resolution is 224 steps due to the repetition frequency of 16.969 kHz (3.801 MHzl16.969 kHz =224). Table 6-23. Short Description of the Capture and PWM Mix ClCBLOCK TIME INTERVAL TIMERI/Os COMMENT O· Doubled period Outputs 0.5 X PWM Frequency Period register CCRO. Output of a symmetrical 8.484 kHz signal 1 Period Outputs PWM 1 .. PERIOD-1 Generation of PWM. Pulse length stored in TAl PWM. Dedicated interrupt handler for update. 2 External event Input pin CCI2A is used Measures high signal part capt. value BIT ltCCIFG,&CCTLO Yes, TIMACYCO yet updated? JNZ TM20 No, value matches with CCR2 SUB #PERIOD,&CCR2 Yes, use CCR2 for correction BIT #CCI,&CCTL2 Input signal high? JZ TM21 No, time for calculation MOV TIMACYCO,TIM2 Yes, store cycle counter ADD &CCR2,TIM2 Time for leading edge in TIM2 TIMACYCO,PP2 Event time of trailing edge ADD &CCR2,PP2 Add captured time SUB TIM2,PP2 Subtr. time of leading edge RETI High part is calculated: TM2l MOV RETI Length of high part in PP2 Capture/Compare Block 3 captures the time of trailing edges at CCI3A. TIM3 stores the time of the actual edge TIMMOD3 TM30 CMP &CCR3,&TAR JHS TM30 No, Timer Reg. > capt. value BIT #CCIFG,CCTLO Yes, TIMACYCO yet updated? Occurred overflow of TAR? JNZ TM30 No, value matches with CCR3 SUB #PERIOD,&CCR3 Yes, use CCR3 for correction MOV TIMACYCO,TIM3 Store sum of cycle counter ADD &CCR3,TIM3 and captured event time . sect "TIMVEC",OFFFOh Timer_A Interrupt Vectors . word TIM_HND RETI 6-178 ; C/C Blocks 1 .. 4 Vector The TimecA . word TIMMODO Vector for C/C Block 0 . sect "INITVEC",OFFFEh Reset Vector . word INIT The above example results in a maximum (worst case) CPU loading ucpu (ranging from 0 to 1) by the Timer_A activities: CCRO CCR1 CCR2 CCR3 CCR4 - repetition rate 16.969 kHz repetition rate 16.969 kHz repetition rate max. 2 kHz repetition rate max. 3 kHz repetition rate 16.969 kHz 19 cycles for the task, 11 cycles overhead 6 cycles for the update, 17 cycles overhead 60 cycles for the update, 32 cycles overhead 20 cycles for the update, 16 cycles overhead 6 cycles for the update, 0 cycles overhead 30 cycles 23 cycles 92 cycles 36 cycles 6 cycles The above result means a worst case CPU loading of approximate 34% due to the Timer_A activities (the tasks of the capture/compare blocks 2, 3 and 4 are not included). 6.3.9.10 Conclusion This section demonstrated the possibilities of the Timer-.A running in the up mode. Despite the dominance of the period register (CeRO) it is possible to capture signals, compare time intervals, and create timings in a real-time environment - all this in parallel with the pulse width modulation generated with the up mode. On-Chip Peripherals 6-179 The Timer.:..t- • , 6.3.10 Software Examples for the Up/Down Mode This section shows several proven application examples for the limecA running in the up/down mode. Software definitions appear in the appendix. Whenever possible, the abbreviations defined in the MSP430 Architecture Guide and Module Library are used. The software examples are independent of the MCLK frequency in use. Only the FLL multiplier constant, FLLMPY, and the repetition rate, fpe... need to be redefined if another combination is needed. The source lines for the definition of these important values ,are: FLLMPY ,equ 122 l. fper ,equ 19200 2. PWM Repetition rate TCLK ,equ FLLMPY*32768/4 3. FLLMPY x fcrystal/4 HLFPER ,equ (TCLK/fper)/2 4. Half Period of the PWM FLL multiplier Note: The definitions assume an external crystal or an external frequency at the 15 , XIN input with a frequency of 32.768 kHz (2 Hz). 1) Definition of the CPU frequency fMCLK. The multiplier FLLMPV for the digitally controlled oscillator (OCO) is defined. The value for the actual frequency fMCLK is (FLLMPV x 215). The value 122 stands for fMCLK = 122 x2 15 =3.9977 MHz. 2) Definition of the desired repetition rate. The value 19200 stands for a repetition rate of 19.2 kHz, which means 19200 complete up and down counts of the timer register TAR. 3) Definition ofthe Inputfrequency for the Timer Register (TAR). The expression /4 indicates that the input divider is switched to the Divide-byFourmode. The value shown stands for TCLK =3.9977 MHz /4 =999.424 kHz. Only the predivider used for the input divider (here /4) needs to be defined. 4) Calculation ofthe TCLK cycles for the defined half period. The full period consists of the half period counting up to the content of the period register CCRO and the one counting down to 0 again. No change is necessary for this line. 6-180 6.3.10.1 Common Remarks The up/down mode should be considered only for pulse width modulation (PWM) or DC generation. The advantage of this special PWM mode is the contributed switching of the output signals - unlike the up mode that switches on all output pulses at exactly the same time (when the timer register TAR is reset to 0), the up/down mode switches on and off the output pulses symmetrical to the 0 content of the timer register. See figure 6-44. Ifthis feature is not needed, then the up mode with its simpler handling or the continuous mode with its five independent timings should be used. Advantages of the Up/Down Mode: o Distributed current switching (e.g. for digital motor control (DMC) applications) o o o Free run without CPU loading for fixed PWM values (DAC, DMC) o High PWM frequency possible due to pure hardware control Clever timings of the period register are usable for more than one real-time job For a given PWM repetition rate, an equally spaced second interrupt is available from the timer overflow interrupt, TIMOV. This doubles the available resolution for some applications Disadvantages of the Up/Down Mode: o o Dominance of the period register - defines the time frame Direction change of the period register during the run needs special software handling. Interrupt-driven count direction indication is necessary for the software. o Capturing has an inherent uncertainty for capturing values near the zero point (TAR = 0) and the middle of the period (TAR = CCRO). o RAM extension for the timer register is necessary due to the normally short period. o Change of the pulse width may cause an erroneous signal during one period. On-Chip Peripherals 6-181 The Timer A 6.3.10.1.1 Initialization The. initialization subroutine INITSR is used by all examples. This subroutine was explained and included in section Software Examples of the Continuous Mode. It includes the following tasks: o Checks the reason for the initialization (switch on of the supply voltage, watchdog interrupt, or activation of the RESET input) o o Clears the RAM - or not - depending on the result of the check above o Programs the system clock oscillator (multiplication factor N and optimum current switch FN_2, FN_3, or FN_4) Allows the digitally controlled oscillator to settle at the appropriate tap, providing the correct MCLK frequency 6.3.10.1.2 TImer Clock For the timer clock, there is no difference between the up mode and the up/ down mode. See section Software Examples for the Up Mode for detaiis. 6.3.10.1.3 Timing Considerations As with the up mode, the independence of the five timings provided by the continuous mode is not possible with the up/down mode. The period register (CCRD) dictates the timing frame for all other capture/compare blocks. With the up/down mode, things are a littie bit more complex due to the count direction change of the timer register (TAR) when it reaches the content of the period register (CCRD). Two additional RAM registers - as with the up mode - are used for the management of the compared or captured data: o o TI MACNT - Period counter. This register counts the number of half periods. Its bit D(LSB) functions as the count direction bit for the timer register TAR: • TIMACNT.D = D- Timer register counts upward to nCCRD • TIMACNT.D =1 - Timer register counts downward to D TIMACYCx - Cycle counter. Counts the TCLK cycles of the timing (one or more words) See also figure 6-48. The contents of these two registers, including the count direction bit, are shown there for an example. Figure 6-52 gives an explanation of the update of these two registers. 6-182 Update of Extension Registers - Unlike with the continuous mode and the up mode, the update of these extension registers is made with the interrupt handlers of both the period register (CCRO) and the timer overflow interrupt (TIMOV). The reason is the count direction bit that needs to be updated each half period (up and down count direction). The main part is executed by the interrupt handler of the period register due to its higher interrupt priority and faster interrupt response. The method used for the update of the extension registers allows an automatic self synchronization: BIS #l,TlMACNT CCRO: TlMACNT always odd INC TlMACNT Timer Overflow: increment Real Time Environment - See section Software Examples for the Up Mode for details. There is no difference between the up mode and the up/down mode. Output Units - The shown PWM examples all use the toggle/reset mode (positive output pulses) or the toggle/set mode (negative output pulses) of the output units. The other output modes are not applicable for PWM generation in the up/down mode. 6.3.10.1.4 Interrupt Overhead The calculations for the CPU loading that are appended to the software examples split the necessary cycles for an interrupt into two parts: o Overhead - This part sums the cycles that are necessary for the CPU to execute the interrupt (saving of the program counter and the status register, decision as to which interrupt needs to be serviced, and restoring of the CPU registers). o Update or Task - This actually does the work that needs to be done (incrementing of counters, changing of status bytes, reading of input information, etc.). Like it is for the up mode, the number of overhead cycles is: Interrupt of the period register CCRO Interrupt of capture/compare registers x: Interrupt of the timer register overflow: 11 MCLK cycles 16 MCLK cycles 14 MCLK cycles On-Chip Peripherals 6-183 The TlmecA 6.3.10.2 Differences Between the TlmerJ. Versions Two versions of the T1mer_A hardware exist. They differ only in the performance of the up/down mode: o The version in the current MSP430C33x outputs a 50% PWM signal with a doubled period if the capture/compare register contains O. See Figure 6-44. o CCRx=O The improved version running in the MSP430C11 x, MSP430C33xA, and all future family members outputs a fixed voltage (0% or 100% PWM) for the capture/compare register content =O. See Figure 6-45. CCRx=1 CCRx = CCRCl-1 CCRx = CCRO CCRx>CCRO output Mode TogglelSet TogglelReMt CCRO TIMOV Contelns3 Figure 6-44. PWM Signals at Pin TAx for the CUffent MSP430C33x Version 6-184 The Timer A CCRx=O CCRx=1 CCRx = CCRO-l CCRx =CCRO CCRx>CCRO Output Mode Toggle/Set CCRO Con18ln83 TIMOV Figure 6-45. PWM Signals at Terminal TAx for the Improved MSP430C11x Version The software examples are applicable to both versions - the distinction is made by a software flag named TAVO: TAVO =0 - the limer_A version of the current MSP430C33x is used TAVO = 1 - the improved TimecA version for the MSP430C11 x is used Both versions output the correct 0 value for CCRx > CCRO. The longest half period that can be used is OFFFEh, due to the value OFFFFh neceS$ary for O. 6.3.10.2.1 .MACRO Definition for the PWM Range Check Due to the behavior of the limer_A running in the up/down mode, checks must be made to determine if the calculated PWM values are in the acceptable range or not. Note: These checks are not necessary if tables that contain valid data only are used, - OFFFFh for the output value 0 and the content of the period register CCRO as the maximum value (1 00%), for example. ! To get a legible source, these checks are written as an assembler macro. This macro replaces the following two checks: o If the calculated PWM value is greater than the half period contained in the period register CCRO o If the calculated PWM value is 0 On-Chip Peripherals 6-185 The Timer A If one of these two possibilities is true, then a corrected value is used. The macro is designed for two modes. They are distinguished by the software flag PERIOD_VAR: o Fixed period - period register CCRO always contains the same value. PERIOD_VAR - 0 o Variable period - CCRO contains variable values. PERIOD_VAR = 1 The macro also distinguishes between the two Timer_A hardware versions (see Section 6.3.10.2 for detailS): o o The current MSP430C33x hardware: TAVO=O The improved MSP430Cllx hardware: TAVO= 1 Example 6-47. Macro Code The MACRO corrects input values addressed by argl (0 to OFFFEh) to valid input values. The four destination addressing modes are valid for argl. CHCK_PWM_RNG . macro argl argl: address of PWM value .if PERIOD_VAR-O Fixed or variable period? CMP #HLFPER+l,argl Fixed: result> HLFPER? JLO L$l? No, proceed MOV #HLFPER,argl Yes, use HLFPER (100%) .else Variable period CMF argl,&CCRO JHS L$l? Result> Period Register? No, proceed MOV &CCRO,argl Yes, use HLFPER (100%) .endif L$l? L$2? .equ $ .if TAVO=O MSP430x33x or xlxx? TST argl MSP430x33x: JNZ L$2? is argl MOV #OFFFFh,argl Yes, use max. value .equ $ .endif 6-186 = O? The Timer A .endm The call of the above macro is ; Definitions for the .MACRO PERIOD_VAR .equ 0 Fixed period TAVO .equ 0 MSP430x33x version MOV R6,TAIPWM Corrected value to buffer MOV HELP,TAIPWM Update buffer Check calc. PWM value in R6 or Check PWM value in HELP Note: Software written for the MSP430C33x version ofthe Timer_A is upward compatible with the MSP430C11 x version - it will also run well with the improved , TimecA hardware (only an unnecessary check for zero is made). 6.3.10.3 Update of the Capture/Compare Registers As with the up mode, only a synchronous update will give undisturbed output pulses. The update with the accompanying interrupt handler is not possible for the up/down mode - the required toggling results in unpredictable output pulses for this kind of update. Four possibilities are shown here for the synchronous update by the Interrupt Handlers of capture/compare block 0 and the timer overflow: 1) Frequent common update of the capture/compare registers by the CCRO handler 2) Frequent common update of the capture/compare registers by the TI MOV handler 3) Infrequent common update 4) Infrequent individual update Unlike with the continuous mode and the up mode, only the interrupts of the period register (CCRO) and the timer overflow (TIMOV) are enabled for all of the four update modes. The four possibilities are described in the following paragraphs. To find the appropriate solution for a given timing problem, the following decision path may be used: On-Chip Peripherals 6-187 ·The TimecA D Is a very fast update of the capture/compare registers necessary? If yes, use solution 1 or 2, If no, continue. D Are all of the new update values available at the same time? If yes, use solution 3, otherwise use solution 4. 6.3.10.3.1 Frequent Common Update by CCRO The interrupt handler of capture/compare block 0 updates the capture! compare registers CCRx with the repetition rate defined by the period register CCRO. This update mode is used for the Digital Motor Control with Symmetric Pulse Width Modulation. If the range for the PWM output values is limited from 1 cycle to (CCRO) cycles, then the following simple update sequence may be used: R6 contains new PWM info for CCR2. Range: 1 to (CCRO). MOV R6,TA2PWM ; Actualize PWM buffer If the calculation results for the PWM output values can be 0% or >100%: CCRx> CCRO .or. CCRx =0 for the current MSP430C330x CCRx>CCRO .for the MSP430Cll Ox, then a special treatment is necessary due to the special behavior of the capture/compare logic under these circumstances. The capture/compare register x value then needs to be modified. To determine these special cases, the following update sequence may be used (the macro CHCK_PWM_RNG is explained in Section. 6.3.1 0.2.1 .MACRO Definition for the PWM Range Checl<): R6 contains the calculated PWM info for CCR2. Range: 0 to HLFPER+x. Check if a modification is necessary Software is written for a constant Period Register CCRO PERIOD_VAR .equ 0 Constant period TAVO .equ o MSP430x3.3x version MOV R6,TA2PWM Actualize TA2PWM buffer Correct R6 if out of range Continue 6-188 The Timer A If a variable period is used - the content of the period register CCRO changes during the program flow - then the lines above change to: R6 contains the calculated PWM info for CCR2. Range: a to HLFPER+x. Check if a modification is necessary Software is written for a variable Period Register CCRa PERIOD_VAR .equ TAva 1 Variable period .equ o MSP43ax33x version MOV R6,TA:2PWM Actualize TA2PWM buffer Correct R6 if out of range Continue The part of the code that modifies the PWM values of the Timer_A looks like this: Handler of the Period Register CCRa TIMMODO MOV TAIPWM, &CCRl MOV TA2PWM, &CCR2 Modify C/C Block 1 synchr. Modify C/C Block :2 synchr. MOV TA3PWM,&CCR3 Modify C/C Block 3 synchr. ADD #2*HLFPER,TIMACYCa Other tasks of .the handler RETI 6.3.10.3.2 Frequent Common Update by the Timer Overflow TIMOV If the interrupt handler of the period register CCRO has to perform many tasks, then it is advised to shift one half of these tasks to the interrupt handler of the timer overflow (TIMOV). This handler has the lowest interrupt priority, but with the up/down mode, this does not playa role because the interrupts of the capture/compare blocks 1 to 4 are normally disabled. The same background software is used as is shown with the update by the period register (CCRO) (the macro CHCK_PWM_RNG is explained in Section 6.3.10.2.1 .MACRO Definition for the PWM Range Checl<). PERIOD_VAR .equ TAVO .equ a Fixed period 1 MSP430xllx version Calc. PWM value in R7 On-Chip Peripherals 6-189 The TImer A Correct R7 if out of range MOV R7,TA2PWM Actualize TA2PWM buffer Continue The part of the code that modifies the PWM values of the Timer_A looks like this: TIILHND ADD &TAIV,PC Serve highest Timer_A request RETI No request RETI C/C Block 1: INTRPT disabled RETI C/C Block 2: INTRPT disabled C/C Block 3: INTRPT disabled RETI JMP TIMMOD4 C/C Block 4: capturing Handler of the Timer Overflow TIMOV TIMOV MOV TAIPWM,&CCRl Timer~ MOV TA2PWM,&CCR2 Modify C/C Blocks x MOV TA3PWM,&CCR3 INC TlMACNT reached zero: 'Actualize half period counter RETI 6.3.10.3.3 Infrequent Common Update The interrupt handlers ofthe capture/compare block 0 orthe timer overflow update the capture/compare registers CCRx with a repetition rate given by the calculation speed of the background program. If new PWM values are calculated or read for all capture/compare blocks, then a common flag is set and the update is enabled in this way. This solution is used if the PWM values for the update are available at (nearly) the same time - by table prdcessing, for example. This update mode is used with the example TRIAC Control. If the range for the calculated PWM output values is limited from 1 cycle to (CCRO) cycles, then the following simple update sequence may be used: R6 to RB contain new PWM info for Output Units 1 to 3 Range: 1 to (CCRO). 6-190 MOV R6,TA1PWM Actualize CCRl pulse length MOV R7,TA2PWM CCR2 MOV R8,TA3PWM CCR3 BIS.B #i,FLAG Set update flag Intrpt handler resets FLAG If the output values 0% or >1 00% are actually used, then a special treatment is necessary. To correct these special cases, the following update sequence may be used (the macro CHCK_PWM_RNG is explained in Section 6.3.1 0.2.1 .MACRO Definition for the PWM Range Check): R6 to R8 contain new PWM info for Output Units 1 to 3. Range: 0 to (CCRO)+x. Check if a correction is necessary. CHK_PWM_RNG MOV R6 R6,TA1PWM CHK_PWM..,RNG MOV R7 R7,TA2PWM CHK_PWM_RNG R8 Check the PWM range Write corrected R6 to buffer Check the PWM range Write corrected R7 to buffer Check the PWM range MOV R8,TA3PWM Write corrected R8 to buffer BIS.B U,FLAG Start common update Continue in background The update part of the code in the interrupt"handlers of the period register CCRO or the timer overflow TIMOV looks like this: BIT.B #l,FLAG Is update flag set? JZ L$1 No, continue MOV TA1PWM,&CCRl Actualize CCR1 pulse length MOV TA2PWM,&CCR2 dito CCR2 MOV TA3PWM,&CCR3 dito CCR3 BIC.B #l,FLAG L$l Reset update flag Continue INTRPT handler Ifthe other seven bits ofthe RAM byte FLAG are not used, then a faster version of the above update sequence may be usSd. The resetting of the bit is not necessary and saves 4 cycles. RRA.B FLAG ; Is update flag FLAG. 0 set? On-Chip Peripherals 6-191 ThaT/mer A JNC L$l No, continue MOV TA1PWM, &CCRl Actualize CCRl pulse length MOV TA2PWM, &CCR2 dito CCR2 MOV TA3PWM,&CCR3 , dito CCR3 Continue INTRPT handler L$l 6.3.10.3.4 Infrequent Individual Update The interrupt handler of the period register or the limer Overflow update the capturefcompare register CCRx with a repetition rate given by the calculation speed of the background program. If a new PWM value is calculated for a capture/compare block, then an individual flag is set and the update for this capturefcompare block is made. This method is used if the PWM values for the update are not available at the same time. This update mode is used with the example capturing with the Up/Down Mode. It is the update mode with the lowest overhead. The macro CHCK_PWM_RNG is detailed in Section 6.3.10.2.1 .MACRO Definition for the PWM Range Check. R6 contains new PWM info for CCR1. Range: 0 to (CCRO)+x. Check if a modification is necessary: Software is written for a variable Period Register CCRO TAVO .equ o MSP430X33x version Variable period Check/correct result in R6 MOV R6/TA1PWM Actualize TA1PWM buffer BIS #2,FLAG Start update of CCRl Start calculation for CCR2 R6 contains new PWM info for CCR2. Range: 0 to (CCRO)+x MOV R6,TA2PWM BIS #4,FLAG Actualize TA2PWM buffer Start update of CCR2 Continue The interrupt handler of the period register CCRO or the timer overflow (TIMOV) decodes the necessary task as follows (4 to 20 MCLK cycles are needed): 6-192 The Timer A ADD RETI JMP JMP MOV P2 Pl MOV CLR RETI MOV CLR RETI TIMOV or CCRO handler Flag contains 0 to 6 0: No update necessary 2: Update CCRl FLAG,PC Pl 4: Update CCR2 P2 TAlPWM,&CCRl TA2PWM, &CCR2 6: Update CCR2 and CCRl 4: Update only CCR2 FLAG TAlPWM,&CCRl 2: Update only CCRI FLAG The above sequence may be changed easily for the update of three capture/ compare registers (like is used for three phase DMC). 6.3.10.3.5 Overhead for the Update These four update modes may be mixed if this is an advantage. Table 6-24 shows the overhead calculation and the percentage of the update overhead for the four different update methods. The calculation results are based on: fMCLK fupdate fper n Frequency of the system clock generator (MCLI<) Update frequency for the capture/compare registers limer_A repetition rate defined by the period register CCRO Number of C/C blocks used for the PWM generation 4 MHz 1 kHz 12kHz 3 Table 6-24. Interrupt Overhead for the Four Different Update Methods UPDATE METHOD . OVERHEAD FORMULA (CPU CYCLES) OVERHEAD PERCENTAGE Frequent Update with CCRO nxfoerx6 5.4% Frequent Update with TIMOV nxfoerx6 5.4% Infrequent Common Update (foer x 6) + (fuodate x (n x 6 + 4)) 2.3% Infrequent Individual Update (foer-fuodatel x 3 + (fuodate x 15) 1.2% Note: No interrupt is generated - and therefore no interrupt overhead - for capture/ compare registers containing a value greater than the content of the period register CCRO (output TAx = 0 for Toggle/Reset resp. TAx = 1 for Toggle/Set). On-Chlp Peripherals 6-193 The Timer A 6.3.10.4 Dlgltai Motor Control With Symmetric Pulse Width Modulation The medium output voltage V PWM atthe TAx terminal with respect to the necessary register content (nCCRx) for a given voltage VPWM is: VPWM = Vee X nccRx tpw ~ Vee X - ~er nCCRO VPWM nCCRx = -- Vee x neCRO Where: VPWM VCC nCCRO nCCRx tpw tper Medium output voltage at the TAx terminal Supply voltage of the system Content of the period register CCRO Content of the capture/compare register CCRx Time generated by the capture/compare register Period generated by the period register CCRO [V] [V] [s] [s] Table 6-25 shows the necessary content of a capture/compare register CCRx to get some defined values for an unsigned output voltage VPWM: Table 6-25. Output Voltages for Unsigned PWM OUTPUT VOLTAGE (VPWM) 0.25 0.5 0.75 CONTENT OF CCRx "CCRx OV 0 x VCC x VCC x VCC x 0.25 nCCRO x 0.5 "CCRO x 0.75 Vcc nccRO nCCRO If the output voltage is seen as a signed voltage -like for 3-phase digital motor control- then the voltage 0.5 x VcC is seen as the 0 point. The signed output voltage VpWM gets: VPWM nccRx ) Veex ( ---0.5 ~ nccRx VPWM = (- + 0.5) x nCCRO Vee nCCRO To calculate the value for nCCRx for the sine of a given angle, a., the formula is (full Vce range): neCRx 1 + sina = - - - X neCRO 2 Table 6-26 shows the necessary contents of a capture/compare register CCRx to get some defined values for a signed output voltage VPWM. 6-194 The Timer A Table 6-26. Output Voltages for Signed PWM OUTPUT VOLTAQE (VPWM) -0.5 COMMENT CONTENT OF CCRx nCOAx x Vce Most negative output voltage 0 -0.25 X Vee neCRO OV x 0.25 Half negative output voltage ovoltage neeRO X 0.5 0.25 X Vee "eeRO 0.5 X Vee x 0.75 Half positive output voltage nr.r.Rn Most positive output voltage Figure 6-46 shows some of the output voltages listed above for a three-phase system. (CCRx) i (CCRO) Phsse Voltage i Ul JU Vmmax I I I I (CCRO)/2 120" 0 -Vmmax • I I I vmo:]Il --+ Tlma U . Figure 6-46. PWM Outputs for Different Phase Voltages Note that a volt for a motor phase is generated by a pulse width of one half of the length of the period. Example 6-48. PWM Outputs for Different Phase Voltages The software example shows the generation of PWM output signals for a three-phase electric motor. The MSP430 delivers the PWM output signals and controls the speed of the motor by the input signal CCI4A coming from the tach/generator. The capture/compare blocks 1 to 3 are used for the generation of the PWM signals for the three phases. The capture/compare block 4 is used for the capturing of the speed signal coming from the shaft of the motor. Up to 6000 rpm (100 rev/sec) are used with this example, with four output pulses per revolution. The positive edge of the input Signal is captured and requests interrupt. On-Chip Peripherals 6-195 The Timer A All security functions are included in the external control chip 1R2130 (over current, delays for the transistors, etc.). ~~ 2.3.~. 123t.fS61.B _ _ !Error! TA4~------------------------------------~~-J 15v--_e------e--r~ Vcc 5V TAO 5kHz MSP430C33x 74HCOO TA1 LIN1 ' - - - - - - ; HIN1 UN2 TA2 '--==:---; HIN2 TA3 UN3 L -____; v~I-+_~-------+--~----~_e~ VS11-..---------. .4 ..... L031------------t--f------t--t---, HIN3 L01 ~------__+_l PO.x I---t>----I FAULT L021---------....::=r--f---' VS~---.------~~~~--.--e------~~-e-- VSS OV Itrlp 5V Overcurrent Adjustment r-~----------~------------~-----OV Figure 6-47. PWM Motors Control for High Motor Voltages The system clock frequency is 4 MHz (exactly fMCLK" 122 x 32768 = 3.9977 MHz). The pulse repetition frequency is 12 kHz. The output unit 0 outputs 6 kHz without any overhead. This signal may be used for peripherals or for synchronization. The signal is always present, even if the signals at the TAx outputs disappear due to an output signal with 0% or 100% pulse width. The example uses the frequent common update of the compare/compare register. See Section 6.3.10.3.1 Frequent Common Update by CCRO for details. 6-196 The Time,-A Figure 6-48 shows the output signals at the times that they have phase shifts of 0·. +120· and -120·. (2n + 2) x thlfper 1 0 2nxlhlfper TIMACYCO Direction Bit o 2n+1 2n TIMACNT (2n + 4) x lhlfper 1 0 2n+2 2n+3 2n+4 OFFFFh CCRO ~--------~--------~--------~k-------~r---------~ CCM r-------~~~----~r_------~~~------r_------~ CCR1 CCR3 ~~-+--~~T---r-~rlr.~--+---;-~---r--~~~-+--~­ Oh ~~--~--~~--~--~~--~---+~r-~---+~~--~--+TA10u1put TA2 Output TA30utpul 0" I-i---_+---t-!-"t----r--;+;---+---t-I-f"--+---~:_;_--_+-__t- (0.5 x Vmotor) I-+---+---I-+-"I----r---f++---+----t-!-f----+--+ir+---+----f~ 120· (0.93 x Vmotor) -120· i+--I----+-+-+--I--f-+-+--+--+-ii-+-+--f-iH---I---t- (0.07 x Vmotor) TlMOV EQUO TIMOV EQUO TIMOV Interrupts Figure 6-48. Symmetric PWM Timings Generated With the Up/Down Mode Example 6-49. Symmetric PWM Timings Generated With the Up/Down Mode Software example: TAO: symmetric output signal 6.0kHz TAl: positive PWM signal 12.0kHz. Length in TA1PWM TA2: positive PWM signal 12.0kHz. Length in TA2PWM TA3: positive PWM signal 12.0kHz. Length in TA3PWM Hardware definitions FLLMPY .equ 122 fper .equ 12000 12.0kHz repetition rate TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal HLFPER .equ (TCLK/fper)/2 Period of output signals FLL multiplier for 3.9977MHz On-Chip Peripherals 6-197 The Timer A TAVO .equ 0 MSP430C33x Timer_A PERIOD_VAR .equ 0 Invariable period in CCRa STACK 600h Stack initialization address .equ RAM definitions TAlPWM .equ 202h Pulse length Block 1 (0 .. 167) TA2PWM .equ 204h Pulse length Block 2 (0 .. 167) TA3PWM .equ 206h Pulse length Block 3 (0 .. 167) CPT4 .equ 208h Captured motor shaft events Low cycle counter (15 .. 0) TlMACYCO .equ 20Ah TlMACYCl .equ 20Ch High cycle counter (31 .. 16) TlMACNT 20Eh Period Counter, Bit 0 = Dir .equ . text INIT Software start address MOV #STACK,SP Initialize Stack Pointer CALL HNITSR Init. FLL and RAM Initialize the Timer_A: MCLK, Up/Down Mode, INTRPTs on for TIMOV, Period Register and C/C Block 4 (Capture Mode) MOV 6-198 #ISMCLK+CLR+TAIE,&TACTL ; Define Timer_A MOV #HLFPER,&CCRO Period Register MOV #HLFPER/2,R5 Value for OV to R5 MOV R5,&CCRI TAl: pulse width = OV MOV R5,&CCR2 TA2: as before MOV R5,&CCR3 TA3: as before MOV #OMT+CCIE,&CCTLO TAO: Toggle Mode MOV #OMTR,&CCTL1 TAl: Toggle/Reset Mode MOV #OMTR,&CCTL2 TA2: Toggle/Reset Mode MOV #OMTR,&CCTL3 TA3: Toggle/Reset Mode MOV #CMPE+ISCCIA+SCS+CAP+CCIE,&CCTL4 ; +edge shaft MOV.B #TA4+TA3+TA2+TAl+TAO,&P3SEL ; Define I/Os MOV R5,TAlPWM Start value Block 1: av The Timer_A MOV RS,TA2PWM MOV RS,TA3PWM Start value Block 2: OV Start value Block 3: OV CLR TIMACYCO Clear low cycle counter CLR TIMACYC1 Clear high cycle counter CLR TlMACNT Clear period counter MOV.B #CBMCLK+CBE,&CBCTL ; output MCLK at XBUF pin BIS #MUPD,&TACTL EINT Start in Up/Down Mode Enable interrupts Continue in background MAINLOOP Calculations resulted in new PWM values. The new results are stored in R6 (C/C Block 1), R7 (C/C Block 2) and RB (C/C Block 3). Check if ranges are valid: CHCK_PWM_RNG MOV CHCK_PWM_RNG MOV Correct R6 range R7 Correct R7 range R7,TA2PWM CHCK_PWM_RNG MOV R6 R6,TA1PWM R8 Correct R8 range R8,TA3PWM Continue in background Read the last captured value of the tacho generator MOV CPT4,R6 For calculations control algorithm for speed Interrupt handler for CCRO: the ·period Register. The cycle counters and the half period counter are updated. A symmetric 6.0kHz signal is output by the Output Unit 0 TIMACYCO points to next the O-crossing of the TAR TIMMODO MOV TA1PWM,&CCR1 MOV TA2PWM,&CCR2 Update PWM registers On-Chip Peripherals 6-199 The TimecA MOV TA3PWM,&CCR3 ADD #2*HLFPER,TIMACYCO ; Add fixed period to ADC TIMACYC1 cycle counters BIS #l,TIMACNT Half period counter +1 (Down) RETI Interrupt handlers for capture/Compare Blocks 1 to 4 and Timer Overflow. Only the timer overflow interrupt and the C/C Block 4 are used. The other interrupts are disabled. The PWM generation is made by the timer hardware and updated by the CCRO intrpt TIM_HND ADD &TAIV,PC Add Jump table offset RETI No interrupt pending RETI C/C Block 1: Intrpt disabled RETI C/C Block 2: Intrpt disabled RETI JMP C/C Block 3 : Intrpt disabled TIMMOD4 C/C Block 4: Capturing used Timer overflow: the half period counter is incremented 'l'IMOV INC TIMACNT RETI Make TIMACNT even (DIR UP) Back to main program C/C Block 4 captures the revolutions of the motor. Dependent on the count direction of TAR, CCR4 is added or subtracted. The positive edge of the input signal at TA4 is captured and requests interrupt. Time out cannot occur due to low input frequency. TIMMOD4 MOV TIMACYCO,CPT4 Cycle counter fOr calculation BIT #l,TIMACNT Direction UP? JNZ T40 No, DOWN (1) Direction is UP ADD RET I 6-200 &CCR4,CPT4 Build time of captured event Back to main program The Timer A Direction is DOWN T40 SUB Build time of captured event &CCR4,CPT4 RET I .sect "TIMVEC",OFFFOh Timer_A Interrupt vectors . word TIM_HND C/C Blocks 1 to 4 . word TIMMODO Capture/Compare Block 0 .sect "INITVEC",OFFFEh Reset vector . word INIT The example results in a nominal CPU loading uCPU (ranging from 0 to 1) by the Timer_A activities: Where: fMCLK nintrpt frep Frequency of the system clock (DCO) Number of cycles executed by the interrupt handler Repetition rate of the interrupt handler [Hz] [Hz] Note: The formula and the definitions given above are also valid for all subsequent software examples. Therefore they are not repeated. ! CCRO - repetition rate 12 kHz CCR4 - repetition rate 0.4 kHz TIMOV - repetition rate 12 kHz 32 cycles for the task, 11 cycles overhead 18 cycles for the task, 16 cycles overhead 4 cycles for the update, 14 cycles overhead 12000 X (43+ 18)+400 x 34 ------'~-...:.---- 3.9977xl0 6 43 cycles 34 cycles 18 cycles = 0.186 The result means a CPU loading of 19% due to the Timer_A for the digital motor control task. 6.3.10.5 TRIAC Control TRIAC control for electric motors (DMC) or other loads is possible using the up/down mode as shown with the up mode of the Timer_A. But due to the seoOn-Chip Peripherals 6-201 TheTlmer;..A ond interrupt coming from the timer overflow (TIMOV), the doubled resolution is possible as with the up mode. The control software now counts the number of half periods and fires the TRIAC after the reaching of the calculated value. The medium resolution Pmed is: pmed 1 =----2 X jMAINS X thlfiJer Where: fMAINS thlfper AC line frequency Half period of the Timer_A, defined by CCRa [Hz] [s] All considerations and formulas shown for the up mode are also valid for the up/down mode, except the doubled resolution for the same PWM period. Again, no capture/compare register is needed for the TRIAC control because only the period register with its interrupt and output unit 0 is used. This frees the remaining capture/compare blocks for other tasks. Figure 6-49 shows the hardware for the TRIAC control of this example. The TRIAC hardware is exactly the same hardware as used with the up mode. In addition, a second three-phase motor is controlled by the same MSP430. 230VAC Revolutions Zero CrQ8S1ng 5V Vee >1 M PO.O Cz OV MSP430 3.5 V OVercurrent Detection Vss PO.7 Vrnotor TA1 TA2 Driver TA3 OV Figure 6-49. TRIAC Control and 3-Phase Control With the Time,-A 6-202 OV The Timer A Figure 6-50 illustrates the software example given below. The timer register (TAR) is not shown to scale - 320 steps make one half wave of the 50-Hz line. PO.O Input Zero Crossing 4 - - - - - f - - - - - - I - - - - - O + - - - - -.......- - - - TAO Output to TRIAC Gate -+___--'-""-"-'-_____-=-'"-':::-:::::-=--:--_ _'-'-+.1-_ __ Voltages AC Figure 6-50. Signals for the TRIAC Gate Control With Up/Down Mode Example 6-50. Static TRIAC Control Software A static TRIAC control software example is shown. The calculated number of half periods until the TRIAC gate is fired after the zero crossing of the AC line voltage, is contained in the RAM word FIRANGL. The medium resolution Pmed is 320 steps per line half wave (2 x 16 kHz/1 00 Hz =320). The minimum resolution, Pmin, is 204 steps (320 x 2ht =204) which means approximately. 0.5% resolution. See the equations above. At the TA1, TA2, and TA3 terminals negative PWM signals for digital motor control are output. The half period is deti ned by the period register (CCRO), the actual pulse length (TCLK cycles) is contained in the RAM words TA 1PWM, TA2PWM, and TA3PWM. The common update is made with ",1 kHz. The speed of the TRIAC-controlled motor is measured with the input signal at input TA4 (CCI4A). The negative edges are captured and an interrupt is requested afterward. On-Chip Peripherals 6-203 ThaT/mer A The example uses the infrequent common update executed by the timer overflow handler. See Section 6.3.1 0.3 Update of the Capture/Compare Registersfor details. Definitions for the TRIAC control software FLLMPY .'equ 122 fper .equ 16000 16.000kHz repetition rate TCLK .equ FLLMPY*32768 TCLK (Timer Clock) [Hz) FLL multiplier for 4.0MHz HLFPER .equ (TCLK/fper)/2 Half period in Timer clocks OP .equ 4 TRIAC gate pulse length TAVO .equ 0 MSP430C33x Timer_A 0 Fixed half period in CCRO PERIOD_VAR .equ RAM definitions TIMACYCO .equ 202h Timer Register Extensions: TIMACYC1 .equ 204h Cycle counters TlMACNT .equ 206h Counter for half periods FIRANGL .equ 208h Half wave - conduction angle FIRTIM .equ 20Ah Fire time rel. to TIMACNT TA1PWM .equ 20Ch PWM cycle count C/C Block 1 TA2PWM .equ 20Eh C/C Block 2 TA3PWM .equ 210h STTRIAC .equ 212h Control byte (0 FLAG .equ 213h 1: update for PWM request CPT4 .equ 214h Captured shaft value STACK .equ 600h Stack initialization address . text C/C Block 3 off) Status Start of ROM code Initialize the Tirner-A: MCLK, UP/Down Mode. Enable INTRPT for C/C Blocks 0 and 4 and Timer Overflow TIMOV. prepare Timer_A Output Units INIT 6-204 MOV IISTACK,SP Initialize Stack Pointer SP CALL UNITSR Init. FLL and RAM The Timer A MOV #ISMCLK+CLR+TAIE,&TACTL ; Init. Timer MOV #HLFPER, &CCRO MOV #OMOO+CCIE+OUT,&CCTLO ; Set TAO high, Output MOV #OMTS,&CCTLl MOV #OMTS,&CCTL2 TA2: neg. PWM pulses MOV #OMTS,&CCTL3 TA3: neg. PWM pulses ; Half period to CCRO TAl: neg. PWM pulses MOV #CMNE+ISCCIA+SCS+CAP+CCIE,&CCTL4 ; -edge shaft BIS.B #TA4+TA3+TA2+TAl+TAO,&P3SEL ; Define I/Os BIS.B #POIEO, &IEl MOV.B #CBMCLK+CBE,&CBCTL ; MCLK at XBUF pin Enable PO.O interrupt mains CLR TlMACYCO Clear low cycle counter CLR TlMACYCl Clear high cycle counter CLR TlMACNT Clear half period counter CLR.B STTRIAC TRIAC off status (0) MOV #HLFPER/2,TAlPWM TAl: OV MOV #HLFPER/2,TA2PWM TA2: OV MOV #HLFPER/2,TA3PWM TA3: OV MOV.B #I,FLAG Update PWM registers CCRx BIS #MUPD,&TACTL Start Timer-A (UpjDown) EINT Enable interrupts MAINLOOP Continue in mainloop Some TRIAC control examples: Start electric motor: checked result (half periods) in R5 The result is the time difference from the zero crossing of the mains voltage (PO.O) to the first gate pulse (measured in Timer_A half periods) MOV R5,FlRANGL MOV.B #2,STTRIAC Delay (half per.) to FlRANGL Activate TRIAC control Continue in background The motor is running. A new calculation result is available in R5. It" will be used with the next mains half wave On-Chip Peripherals 6-205 ThsTlmscA MOV RS,FlRANGL Delay (half per.) to FlRANGL Continue in background stop motor: switch off TRIAC control, TRIAC gate off CLR.B STTRIAC Disable TRIAC control BIS #OUT,CCTLO TAO high, Output only Mode Continue with background Read the captured value of the tacho generator MOV CPT4,R6 Control algorithm for speed Preparation for the new PWM values start. A table with valid values only is used: no check is necessary MOV ANGLE,R6 CUrrent phase angle MOV TABLE(R6),TAlPWM Phl: add MOV TABLE+l20(R6),TA2PWM Ph2: add 120 degrees MOV TABLE+240(R6),TA3PWM Ph3: add 240 degrees BIS.B n,FLAG . word HLFPER/2,lOO, ... o degrees Initiate cornrnpn update Continue in background TABLE sin 0 to sin 600 Interrupt handler for CCRO: the Period Register. - The cycle counters and the half period counter are updated - The TRIAC control task is executed TIMMODO ADD #2*HLFPER,TIMACYCO ; Add (fixed) period to ADC TIMACYCO cycle counters BIS n,TIMACNT Half period counter +1 (Down) Interrupt handler for the TRIAC control. Entry point also from the Timer Overflow handler 6-206 The TimecA TRIACC STTAB EINT Allow nested interrupts PUSH RS Save help register RS MOV.B STTRIAC,RS Status of TRIAC control MOV STTAB(RS) ,PC Branch to status handler . word STATEO Status 0: NO TRIAC activity . word STATEO Status 2: activation possible . word STATE4 Status 4: wait for gate pulse . word STATE6 Status 6: wait for gate off TRIAC status 4: TRIAC gate is switched on for ·Op· half periods after the value in FIRTIM is reached STATE4 CMP FIRTIM,TIMACNT JNE STATEO TRIAC gate time reached? No BIC #OUT,&CCTLO Yes, TRIAC gate on ADD.B #2,STTRIAC Next TRIAC status (6) TRIAC status 0: No activity. TRIAC is off always STATEO POP RS RETI Restore help register Return from interrupt TRIAC status 6: gate pulse is active. Check if it's time to switch off the TRIAC gate. STATE6 MOV FIRTIM,RS Time TRIAC firing ADD #OP,RS Gate-on time (half periods) CMP RS,TIMACNT On-time terminated? JLO STATEO No BIS lIOUT,&CCTLO Yes, TRIAC gate off MOV.B #2,STTRIAC TRIAC status 2: JMP STATEO Wait for next zero crossing Interrupt handler for C/C Blocks 1 to 4 and Timer Overflow &TAIV,PC Serve highest priority requ. On-Chip Peripherals 6-207 The Timer A RETI No interrupt pending RETI C/C Block 1: INTRPT off RETI C/C Block 2: INTRPT off RETI JMP C/C Block 3: INTRPT off TIMMOD4 C/C Block 4 : Speed measurement The Timer Overflow interrupt handler: - Updates the PWM registers if necessary: FLAG.Q 1 - The TRIAC control task is executed TIMOV INC TIMACNT Incr. period counter (UP) BIT.B n,FLAG Update necessary? JZ TRIACC No, to TRIAC ·control task MOV TAIPWM,&CCRI Yes update C/C Blocks MOV TA2PWM,&CCR2 MOV TA3PWM,&CCR3 BIC.B n,FLAG· Clear update flag JMP TRIACC To TRIAC control task C/C Block 4 captures the revolutions of the motor. Dependent on the count direction of TAR, the captured TAR value in CCR4 is added or subtracted. CPT4 contains the 16-bit value of the captured negative edge of the signal at TA4. TIMMOD4 MOV TIMACYCQ,CPT4 Save cycle counter BIT #l,TlMACNT Direction UP? JNZ T40 No, DOWN {ll ADD &CCR4,CPT4 Build time of captured event Directioll is UP: RETI Back to main program Direction is DOWN: T40 SUB &CCR4,CPT4 Build time of captured event RETI PO.O Handler: the mains voltage causes interrupt with each zero crossing. The TRIAC gate is switched off first, to 6-208 The Timer A avoid the ignition for the actual half wave. Hardware debounce is necessary for the mains signal! POO_HNDLR BIS #OUT,&CCTLO Switch off TRIAC gate EINT XOR.B Allow nested interrupts #l,&POIES Change intrpt edge of PO.O If STTRIAC is not 0 ( 0 = inactivity) then the next TRIAC gate firing is prepared: STTRIAC is set to 4 TST.B STTRIAC TRIAC control active? JZ POO STTRIAC MOV.B #4,STTRIAC Yes, STTRIAC > 0 = 0: no activity The TRIAC firing time is calculated: TIMACNT + FIRANGL (current time + angle) in half periods POO MOV TIMACNT,FIRTIM Half period counter ADD FIRANGL,FIRTIM TIMACNT + delay -> FIRTIM RETI .sect "TIMVEC", OFFFOh Timer_A Interrupt Vectors . word TIM_HND Vector for C/C Blocks 1 .. 4 . word TIMMODO Vector for C/C Block 0 . sect "POOVEC",OFFFAh PO.O Vector . word POO_HNDLR . sect "INITVEC',OFFFEh . word INIT Reset Vector The TRIAC control example results in a nominal CPU loading uCPU (ranging from 0 to 1) for the active TRIAC control (STIR lAC =4): CCRO - repetition rate 16 kHz TIMOV - repetition rate 16 kHz CCR4 - repetition rate 0.4 kHz PO.O - repetition rate 100 Hz Update - 1 kHz (TIMOV) 35cycles for the task, 11 cycles overhead 34 cycles for the update, 14 cycles overhead 18 cycles for the update, 16 cycles overhead 17 cycles for the task, 11 cycles overhead 22 cycles for the task, 0 cycles overhead On-Chip Peripherals 46 cycles 48 cycles 34 cycles 28 cycles 22 cycles 6-209 TheTimBf A 16.0 X 103 x (46 +48)+0.4X10 3 x34+100x28+1.0x10 3 x22 = ----------~--~~--------~--------------------4.0 x 106 0.386 This results in a CPU loading of approximate 39% due to the static TRIAC control. The necessary tasks for the update ofthe half period counter and the cycle counters are included. The PWM activities alone load the CPU with less than 1% this way (fupdate =1 kHz). 6.3.10.6 RF Timing Generation The repetition rate of the up/down mode In use must be a multiple of the data change frequency. The timing is now made by the Interrupts ofthe period regis'ter and of the timer overflow. This allows the output of biphase code modulation and biphase space modulation with a 19.2 kHz repetition rate. The three different modulation methods and their conversion subroutines were discussed in detail in the section Software Examples for the Continuous Mode. The software shown in this section may be used with the following, simple modifications: 1) The repetition frequency is also chosen to 19.2 kHz, but the equally spaced TIMOV interrupt allows a 38.4 kHz time frame. 2) The output handler for the 128-bit buffer is executed by the interrupt handlers of the period register and the timer overflow (TIMOV) to get the doubled bit rate (as shown for the TRIAC control example in Section 6.3.10.5). 3) The output unit 0 uses the output only mode (exactly as shown for the TRIAC control example in Section 6.3.10.5). The interrupt handler of the period register CCRO sets and resets the output TAO by software. Figure 6-51 shows the biphase code modulation for an input byte containing the value 96h. The other two modulation modes work the same way. The timing of the interrupts is shown below: 6-210 The Timer A , ° ° ° ° Information 096h BI.phase Code OCRO~~'-~~~~r-+-~~~r-~~~-'~--w-~­ Timer Register TAR Direction Bit (TIMACNT.O) Interrupts o~~~~--~----~---.----.---~--~~--~1°111°11° 1 0 1 1 °11 1 ° .1.. i 1 • EQUO 1 BltLength H TIMOV Bit Langth 1 i 1 Time • =1/19200 s --+ EQUO Figure 6-51. Biphase Code Modulation With the Up/Down Mode 6.3.10.7 Comparison With the Up/Down Mode Comparison with the up/down mode is nearly impossible due to the uncertainty of the direction of the actual count. If comparison - which means precise interrupts or switching of the corresponding output unit - is important, then the up mode or the continuous mode should be used. With the up/down mode - and its normally high repetition rates - only interrupt-driven software switching is .possible. The TRIAC Control example shows a method to use the interrupts of the period register (CCRO) and the timer overflow (TIMOV) for the control of outputs. 6.3.10.8 Capturing with the Up/Down Mode Capturing of events is not as easy as with the continuous mode or the up mode. The reason is the changing count direction of the timer register (TAR) In the middle of the timer period. Due to the interrupt latency time. tiL, an uncertainty zone exists at the two points where the timer register changes its direction. This uncertainty zone has the length 2 x tiL. The interrupt latency time. tiL. depends on the actual software - it ranges from 6 MCLK cycles to the longest program sequence with disabled interrupt. See also figure 6-52. To get the time of an event with least calculation effort, the method shown in figure 6-62 is used: On-Chip Peripherals 6-211 ThaTimer A o The interrupt handler of the period register CCRO adds the length of a period to the cycle counters TIMACYCx. This is done in such a way, that these counters pOint forward to the next time point in which the timer register (TAR) reaches 0 again (TIMOV interrupt). o The interrupt handler of the period register also sets the bit 0 (LSB) of the half period counter TIMACNT. This bit is used as the direction bit and indicates with this 1 the downward count direction. o The interrupt handler of the timer overflow (TIMOV) increments the bit 0 (LSB) of the half period counter TIMACNT and sets it to 0 (upward count direction). The setting (CCRO) and incrementing (TIMOV) of the direction bit (TIMACNT.O) results in an incrementing that is self synchronizing. To calculate the time of an event at terminal TAx, it is only necessary to read the actual direction bit: o If the direction bit TIMACNT.O is 0 (upward count), then the captured time (0 to nCCRO) in the capture/compare register x is added to the cycle count in TIMACYCO. The captured event occurred after the time stored in TIMACYCO. o If the direction bit TIMACNT.O is 1 (downward count), then the captured time (0 to nCCRO) in the capture/compare register x is subtracted from the cycle count in TIMACYCO. The captured event occurred before the time stored in TIMACYCO. The sections Dlgita/ Motor Control and TRIAC Control also contain examples for the use of capturing with the up/down mode. 6-212 The Time,-A i TIMACYCD TIMACNT Direction Bit Time Register TAR 2(n + 1) x nCCRD 2nxnCCRD I 2n + 1 2n+2 2n I Up Down Up I I I ~ Uncertainty Zone 2(n + 2) x nCCRD 2n+3 2n+4 Down Up nCCRD nCCRx1 Dh~--------~I~I----~~--'I----+-------~--------~ Interrupts I Capt 1 I Capt2 I EQUD TIMOV EQUD CCRD Handler Wrltee I CCRD Handler Writes 2(n + 1) x nCCRD to TIMACYCO: I 2(n + 2) x nCCRD to TIMACYCD: Incr. TIMACNT (Dlr Down) Incr. TIMACNT (Dlr Down) = III Capt 1 = 2(n + 1) x nCCRD - nCCRx1 Capt 2 = 2(n + 1) x nCCRD + nCCRx2 Subtract CCRx + I - --+ Time = • Add CCRx TIMACYCO Points to This Time: Incr. TIMACNT (Dlr =Up) Figure 6-52. Capturing With the Up/Down Mode Figure 6-£3 illustrates the hardware and RAM registers used with the up/down mode for capturing. The RAM words TIM31 and TIM30 store the time of the last captured event. Figure 6-£3 refers to the capture/compare block 3 of the following example. On-Chip Peripherals 6-213 The Timer A Timer Clock 32-Blt Ceptured Value Figure 6-53. Capture Mode With the Up/Down Mode (Capture/Compare Block 3) Figure 6-54 illustrates five tasks. They are exactly the same tasks that are used for the up mode in the section Software Examples for the Up Mode (only the capture/compare block 3 part - that captures the leading edge of an input signal- is extended to 32 bits). This way a comparison is possible between the up mode and the up/down mode. The tasks are defined as follows: 6-214 o Capture/Compare Block 0 - outputs a symmetrical 8.484 kHz signal. The edges contain the information for the period generated by the period register CCRO. This signal is always available for external peripherals (the PWM signals of the capture/compare blocks disappear for pulse widths of 0% and 100%). o Capture/Compare Block 1 - generates a positive PWM signal with the half period defined by the period register CCRO. The pulse length is stored in the RAM word TA1PWM; it ranges from 1 to HLFPER. o Capture/Compare Block 2 - the length, At2, olthe high part olthe input signal at the CCI2A input terminal is measured and stored in the RAM word PP2. The captured time of the leading edge is stored in the RAM word TIM2. The maximum repetition rate used is 2 kHz. o Capture/Compare Block 3 - the event time of the leading edge of the signal at the CCI3A input terminal is captured. The last captured value (TCLK cycles, 32 bits length) is stored in the RAM words TIM30 and TIM31. The maximum repetition rate used is 3 kHz. See also figure 6-53. o CapturelCompare Block 4 - generates a negative PWM signal with the period defined by the period register. The pulse length is stored in the RAM word TA4PWM; it ranges from 0 to HLFPER. For the example, 3.801 MHz is used. The resolution for the PWM is 224 steps due to the repetition frequency of 16.969 kHz (3.801 MHzl16.969 kHz = 224). The Infrequent Individual Update Mode is used. See Section 6.3.10.3 for details. The maximum input frequencies for capturing purposes mentioned above are used for the overhead calculation only. The limits of the Timer_A hardware allow the capture much of higher input frequencies. Figure 6-54 illustrates the four tasks described above - they are not shown to scale: On-Chip Peripherals 6-215 The Timer A TIMACYCO 2nxnCCRO (2n + 2) x nCCRO I I 1 Direction Bit (2n + 4) x nCCRO 0 I I 1 0 Timer Register CCRO CCR4 CCR1 Oh TA10utput TA40utput Time Measurement atCCI2A Capturing of Leading Edges at CCI3A Doubled Period at TAO I Capt 20 Interrupts TIMOV EOUO I I Capt 3 TIMOV Capt21 EOUO I TIMOV Figure 6-54. PWM Generation and Capturing With the Up/Down Mode Example 6-51. TimecA Used for PWM Generation and Capturing ; Timer_A used for PWM-generation and Capturing. fMCLK = 3.801MHz FLLMPY .equ fper . equ 116 16969 . 16.969kHz repetition rate TCLK .equ FLLMPY*32768 TCLK: FLLMPY x fcrystal HLFPER .equ (TCLK/fper)/2 fper = 16.969kHz TAVO .equ 0 MSP430C33x version 0 Fixed period PERIOD_VAR .equ 6-216 ---+ Time The Timer A RAM Definitions TAlPWM .equ 202h PWM pulse length TAl TIM2 .equ 204h Time of leading edge at CCI2A PP2 .equ 206h Length of high part at CCI2A TIM30 .equ 20Sh Time of leading edge LSBs TIM3l .equ 20Ah at CCI3A MSBs TA4PWM .equ 20Ch PWM pulse length for TA4 TlMACYCO .equ 20Eh Cycle counter low TlMACYCl .equ 2l0h Cycle counter high TlMACNT .equ 2l2h Half period counter. BitO FLAG .equ 214h Update information STACK .equ 600h Stack initialization address . text INIT Dir Software start address MOV #STACK,SP Initialize Stack Pointer CALL UNITSR Init. FLL and RAM Initialize the Timer_A: MCLK, Up/Down Mode, INTRPTs on for TIMOV, C/C blocks 0, 2, and 3 MOV #ISMCLK+CLR+TAIE,&TACTL'; Define Timer_A MOV #HLFPER,&CCRO Define half period MOV #OMT+CCIE,&CCTLO Toggle TAO, INTRPT on MOV #OMTR,&CCTLI Toggle/Reset Mode MOV #CMBE+ISCCIA+SCS+CAP+CCIE,&CCTL2 Both edges MOV #CMPE+ISCCIA+SCS+CAP+CCIE,&CCTL3 Pos. edge MOV #OMTS,&CCTL4 MOV.B #TA4+TA3+TA2+TAl+TAO,&P3SEL ; Define I/Os MOV.B #CBACLK+CBE,&CBCTL ; Output ACLK at XBUF pin ; Toggle/Set Mode CLR TlMACYCO Clear low cycle counter CLR TlMACYCl Clear high cycle counter CLR TlMACNT Clear half period counter MOV #l,TAlPWM TAl pulse length 1 MOV #0,TA4PWM TA4 pulse length 0 On-Chip Peripherals 6-217 The Timer A MOV #6 ,FLAG Actualize PWMs immed. BIS #MUPD,&TACTL start Timer in Up/Down Mode EINT Enable interrupts MAINLOOP Continue in background Calculations for ·the new PWM values start. The new result in R6 is written to TAIPWM after completion. The PWM range is from 1 to HLFPER-l: no checks necessary Calculate TAL value to R6 MOV R6,TAIPWM BIS #2 ,FLAG Actualize pulse length Initiate update Continue in background The new result in R6 is written to TA4PWM after completion. The PWM range is from 0% to 100%: check necessary Calculate TA4 value to R6 Check and correct result MOV R6,TA4PWM BIS U,FLAG Actualize pulse length Initiate update Continue in background Use the measured high part MOV PP2,R7 i~ PP2 for calculations Read measured pulse length Control algorithm Use the captured 32 bit value in TIM3l/TIM30 for calculations MOV TIM3l,R7 Captured MSBs MOV TIM30,R6 Captured LSBs Control algorithm Interrupt handler for the Period Register CCRO. B.4B4kHz are output at TAO for synchronization. 6-218. The Timer A TIMMODO ADD #2*HLFPER,TIMACYCO ADC TIMACYCl BIS j/I,TIMACNT Actualize cycle counters Incr. half period counter RETI Dir = Down Interrupt handlers for Capture/Compare Blocks 1 to 4. The interrupt flags CCIFGx are reset by the reading of the Timer Vector Register TAIV TIM_HND ADD &TAIV, PC. RETI Add Jump table offset Vector 0: No interrupt pending RETI C/C Block 1: INTRPT disabled JMP TIMMOD2 JMP TIMMOD3 RETI C/C Block 2: Capt. both edges C/C Block 3: Capt. pos. edge C/C Block 4: INTRPT disabled TIMOV Interrupt: dependent on FLAG the CCRl and CCR4 PWM registers are updated. TIMOV INC TIMACNT ADD FLAG,PC RET I P4 Incr. half period cnt (Down) .' FLAG with update info 0: Nothing to do JMP PI JMP P4 4: Update CCR4 MOV TA1PWM,&CCRI 6 : Update CCR1 and CCR4 MOV TA4PWM,&CCR4 4: CLR FLAG 2: Update CCRl RETI P1 MOV TAIPWM, &CCRI CLR FLAG 2: Update CCR1 RETI The high part of the CCI2A input signal is measured. The result is stored in PP2. The complete handler is time critical: nested interrupts cannot be used. On-Chip Peripherals 6-219 The Timer A TIMMOD2 BIT #CCI,&CCTL2 JZ TM21 Input signal high? No, time for calculation MOV TIMACYCO,TIM2 Build time of event BIT #l,TIMACNT Pos. edge: count direction Up? JNZ T20 No; Down (1) Direction is Up ADD &CCR2,TIM2 Build time of pos. edge in TIM2 RETI Direction is Down T20 SUB &CCR2,TIM2 Build time of pos. edge in TIM2 TIMACYCO,PP2 Event time of trailing edge BIT #l,TIMACNT Direction Up? JNZ T22 RETI Neg. edge: High part is calc. TM21. MOV No, Down (1) Direction is Up ADD &CCR2,PP2 JMP T23 Time of trailing edge in PP2 To calculation of high part Direction is Down T22 SUB &CCR2,PP2 T23 SUB TIM2,PP2 RETI Time of trailing edge in PP2 Subtr. time of leading edge Length of high part in PP2 Capture/Compare Block 3 captures the time of leading edges at CCI3A. TIM3x stores the 32 bit time of the actual edge TIMMOD3 MOV TIMACYCO,TIM30 MOV TIMACYC1,TIM31 BIT #l,TIMACNT JNZ T30 Store cycle counters (32 bit) Count direction Up? No, Down (1) Direction is Up ADD &CCR3,TIM30 ADC TIM31 Time of pos. edge in TIM3x RETI Direction is Down T30 6-220 . SUB &CCR3,TIM30 Time of pos. edge in TIM3x The Time,-A SBC TIM31 RETI . sect "TIMVEC",OFFFOh Timer_A Interrupt vectors . word. TIM_HND CjC Blocks 1 .. 4 Vector . word TIMMODO Vector for CjC Block 0 . sect "INITVEC",OFFFEh Reset Vector . word INIT The above example results in a maximum (worst case) CPU loading ucpu (ranging from 0 to 1) by the Timer_A activities: CCRO CCR1 CCR2 CCR3 CCR4 TIMOV - repetition rate 16.969 kHz update rate 1 kHz rep. rate max. 2 kHz rep. rate max. 3.0kHz update rate 1.0kHz rep. rate 16.969kHz 13 cycles for the task, 11 cycles overhead 12 cycles for the update, 16 cycles overhead 64 cycles for the update, 32·cycles overhead 30 cycles for the update, 16 cycles overhead 12 cycles for the update, 0 cycles overhead 7 cycles for the task, 14 cycles overhead 24 cycles 28 cycles 96 cycles 46 cycles 12 cycles 21 cycles ",J 6. 969 X 10 3 x45+1.0x10 3 x40+2~Ox103 x96+3.0x10 3 x46 =0.298 U CPU 3.801 x 10 6 This results In a worst case CPU loading of approximate 29% due to the Timer_A activities. 6.3.10.9 Conclusion This section demonstrated the possibilities of the Timer_A running in the up/ down mode. Despite the dominance ofthe period register CCRO and its changing direction during a period, it is possible to capture signals, compare time intervals, and create timings in a real-time environment - all this in parallel with the pulse width modulation generated with the up/down mode. On-Chlp Peripherals 6-221 The Hardware MuHiplier 6.4 The Hardware Multiplier The 16 x 16-bit hardware multiplier of the MSP430 family is detailed in the following sections. Function and modes are discussed, and proven application examples are given for this fast and versatile peripheral. Also shown is a comparison of the speed of solutions using this peripheral compared to pure soft~ ware solutions. The hardware multiplier can also execute the Signed Multiply and Accumulate function. The register to be used for the Operand 1 has the address 136h. The function is the same as for the Signed Multiplyfunction, exceptthatthe new product is added to the accumulated sum in the SumHi/SumLo registers. The SurhExt register indicates the sign of the accumulated sum. It is the user's responsibilty to ensure that no overflow can occur (by worstcase calculation of the factors used). 6.4.1 Function of the Hardware Multiplier The hardware multiplier allows three different multiply operations (modes): o o o The multiplication for unsigned 16-bit and a-bit operands The multiplication for signed 16-bit and 8-bit operands The multiply-and-accumulate function (MAC) for unsigned 16-bit and a-bit operands Any mixture of operand lengths (16 bits and a bits) is possible. If assisting software is used, other operations are also possible - the signed Multiply-andAccumulate function, for example. 6-222 The Hardware Multiplier 15 rw o Operand 1 (Address Defines Operation) • Accessible Register Mods 8=0 8=1 MAC C=O C=1 Figure 6-55. Block Diagram of the MSP430 16 x 16-Bit Hardware Multiplier Figure 6-55 shows the hardware modules of the MSP430 multiplier. The accessible registers are explained in the following sections. The hardware of Figure 6-55 does not precisely depict the actual circuitry - it illustrates how the programmer sees the hardware multiplier. 6.4.1.1 Hardware and Register The Hardware Multiplier is not part of the MSP430 CPU - it is a peripheral like the limer_A or the Basic limer. This means its activities do not interfere with the CPU activities. The multiplier registers are normal peripheral registers that are loaded and read with the CPU instructions. The registers that the programmer can access are explained in this section. The hardware multiplier registers are not affected by POR or PUC. With the exception of the SumExt register, all other registers can be read from and written to. On-Ch/p Peripherals 6-223 The Hardware Multiplier Definitions for the Hardware Multiplier appear in Section 6.4.3. r--------------------------~ ROM RAM Address Bust6-BIls Tesl MSP430 CPU Including t6 Reglstsrs JTAG 1/'-_ _ _ _-' Data Bus 1I1..BII8 Hardware MPYer ~--------------------------~ Figure 6-56. The Internal Connection of the MSP430 16 x 16-Bit Hardware Multiplier 6.4.1.2 The~Opsrand1 Registers The MSP430 hardware multiplier mode to be used is selected by the hardware address where the Operand 1 is written: o o o Address 130h - the unsigned multiplication is executed Address 132h - the signed multiplication is executed Add,...s 134h -the unsigned Multiply-and-Accumulatefunction is executed Only the address used for the operand1 determines which operation the multiplier will execute (after the modification of the operand2). No operation is started with the modification of the operand register 1 alone. 6-224 The Hardware Multiplier Example 6-52. Multiply Unsigned A MPY (multiply unsigned) operation is defined and started. The two operands reside in R14 and R15. MOV R15,&l30h MOV R14, &l38h Define MPY operation Start MPY with operand 2 Product in SumHilSurnLo 6.4.1.3 The Opersnd2 Register The operand register 2 (at address 138h) is common for all three multiplier modes. The modification of this register (normally with a MOV instruction) starts the selected multiplication of the two operands contained in the operand 1 and 2 registers. The result is written immediately into the three hardware registers: Sum Ext, SumHi, and SumLo. The result can be accessed with the next instruction unless the indirect addressing modes are used for the source addressing. 6.4.1.4 The SumLo Register This 16-bit register contains the lower 16 bits of the calculated product or summed result. All instructions may be used to access or modify the SumLo register. The high byte cannot be accessed with byte instructions. 6.4.1.5 The SumHI RegIster This 16-blt register contains - dependent on the previously executed operation - the following information: o MPY Unsigned Multiply - the most significant word of the calculated product. o MPYS Signed Multiply - the most significant word including the sign of the calculated product. Two's complement notation is used for the product. o MAC Unsigned Multlply-and-Accumulate - the most significant word of the calculated sum. All instructions may be used with the SumHi register. The high byte cannot be accessed with byte Instructions. On-Chip Peripherals 6-225 The Hardware Multiplier 6.4.1.6 The SumExt Register The Sum Ext register (sum extension) eases the use of calculations with results exceeding the range of 32 bits. This read only register contains the information that is needed for the most significant parts of the result - the information for the bits 32 and higher. The content of the Sum Extension Register is different for the three multiplication modes: o MPY Unsigned Multiply - Sum Ext always contains O. No carry is possible and the maximum result possible is: OFFFFh x OFFFFh = OFFFE0001 h. o MPYS Signed Multiply - Sum Ext contains the extended sign of the 32-bit result (bit 31). This means that if the result of the multiplication is negative (MSB =1), then SumExt contains OFFFFh. Ifthe result is positive (MSB =0), then SumExt contains OOOOh. o MAC Unsigned Multiply-and-Accumulate-SumExt contains the carry of the accumulate operation. SumExt contains 0001 if a carry occurred during the accumulation of the new product. Sum Ext contains 0 if no carry occurred. The sum extension register improves multiple word operations. No time wasting and ROM-space wasting conditional jumps are necessary - ordinary adds are used instead. The new product of a MPYS operation (multiplicands in R14 and R15) is added to a signed 64-bit result located in the RAM words RESULT to RESULT +6: Example6-53. 64-8it Result MOV R15,&MPYS First operand MOV R14,&OP2 Start MPYS with operand 2 ADD SumLo,RESULT Lower 16 bits of result ADDC SumHi,RESULT+2 Upper 16 bits ADDC SumExt", RESULT+4 Result bits 32 to 47 ADDC SumExt,RESULT+6 Result bits 48 to 63 Note: It is strongly recommended the MACROs defined in section Assembler .MACROS be used instead of the method shown above. The code above is much less descriptive than the MACROs, using known abbreviations like MPYU, MPYS and MACU. With the software shown above, no checks and conditional jumps are necessary. The result always contains the Signed, accumulated slim automatically. 6-226 The Hardware Multiplier 6.4.1.7 Rules for the Hardware Multiplier o The hardware multiplier is a word module. The hardware registers can be addressed in word mode or in byte mode, but the byte mode can address the lower bytes only (the upper byte cannot be addressed). o The operand registers of the hardware multiplier (addresses 0130h, 0132h, 0134h and 0136h) behave like the CPU working registers AO to A15 if modified in byte mode - the upper byte is cleared in this case. This allows 6-bit and 16-bit multiplications in any mixture. See the examples in Section 6.4.2.4. o The foating point package (FPP) version 4 uses the hardware multiplier if the variable HW_MPY is defined as 1: .equ 1 See chapter 5.6 for details. o 6.4.2 If the result of a hardware multiplier operation is addressed with indirect mode or indirect-autoincrement mode, a NOP Instruction is necessary after the multiplication to allow the completion of the multiplication. See the examples in Section 6.4.3.1. Multiplication Modes Three different multiplication modes are available. They are explained in the following sections. 6.4.2.1 Unsigned Multiply The two operands written to the operand registers 1 and 2 are treated as unsigned numbers with: • OOOOOh as the smallest number • OFFFFh as the largest number. The maximum possible result is reached for the operands: OFFFFh x OFFFFh = OFFFE0001 h No carry is possible, the Sum Ext register always contains O. Table 6-27 shows the products for some special multiplicands. On-Chip Peripherals 6-227 Table 6-27. Results With the Unsigned Multiply Mode OPERANDS SumExt SumHI SumLo 0000 x 0000 0000 0000 0000 0001 x 0001 0000 0000 0001 7FFFx7FFF 0000 3FFF 0001 FFFFxFFFF 0000 FFFE 0001 7FFFx FFFF 0000 7FFE 8001 8000 x 7FFF 0000 3FFF 8000 8000xFFFF 0000 7FFF 8000 8000 x 8000 0000 4000 0000 6.4.2.2 Signed Multiply The two operands written to the operand registers 1 and 2 are treated as signed twO's complement numbers with: • 08000h as the most negative number (-32768) • 07FFFh as the most positive number (+32767) The SumExt register contains the extended sign of the calculated result: • SumExt = OOOOOh: the result is positive • Sum Ext = OFFFFh: the result is negative Table 6-28. Results With the Signed Multiply Mode 6-228 OPERANDS SumExt SumHI SumLo 0000 x 0000 0000 0000 0000 0001 x 0001 0000 0000 0001 7FFFx7FFF 0000 3FFF 0001 FFFFxFFFF 0000 0000 0001 7FFFxFFFF FFFF FFFF 8001 8000 x 7FFF FFFF COOO 8000 8000 x FFFF 0000 0000 8000 8000 x 8000 0000 4000 0000 The Hardware Multipiier 8.4.2.3 Multlply-and-Accumulats (MAC) The two operands written to the operand registers 1 and 2 are treated as unsigned numbers (Oh to OFFFFh). The maximum possible result is reached for the input operands: OFFFFh x OFFFFh = OFFFE0001 h This result is added to the previous content of the two sum registers (SumLo and SumHi). If a carry occurs during this operation, the SumExt register contains 1, otherwise it is cleared. • SumExt =OOOOOh: no carry occurred during the accumulation • SumExt =00001 h: a carry occurred during the accumulation For the results of Table 6-29, it is assumed that SumHi and Sum Lo contain the accumulated content COOO,OOOO before the execution of each of the shown examples. See Table 6-27 for the results of an unsigned multiplication without accumulation. Table 6-29. Results With the Unsigned Multiply-and-Accumulate Mode 8.4.2.4 OPERANDS SumExt SumHI SumLo 0000 x 0000 0000 0000 0001 x 0001 0000 COOO COOO 7FFFx7FFF 0000 FFFF 0001 FFFFxFFFF 0001 BFFE 0001 7FFFxFFFF 0001 3FFE 8001 0001 80oox7FFF 0000 FFFF 8000 8000xFFFF 0001 3FFF 8000 8000 x 8000 0001 0000 0000 Word Lengths for the Multiplication The MSP430 hardware multiplier allows all combinations that are possible with 8-bit and 16-bit operands. The examples given in Section 6.4.3 for 8-bit and 16-bit operands may be adapted to mixed length operands. It must be taken into account that the input operand registers operand1 and operand2 behave like CPU registers - the high register byte is cleared if the register is modified by a byte instruction. This eases the use with 8-bit operands. Examples for the 8-bit operand are given for all three modes of the hardware multiplier. On-Chip Peripherals 6-229 The Hardware Muftlplier Use the 8-bit operand in R5 for an unsigned multiply. MOV.B ; The high byte is cleared R5,&MPY ,. Use an 8-bit operand for a signed multiply. MOV.B R5,&MPYS The high byte is cleared SXT &MPYS Extend sign to high byte, Use an 8-bit operand for a multiply-and-accurnulate. MOV.B R5,&MAC ; The high byte is cleared Operand2 is loaded as shown above for operand1 . This allows all four possible combinations for the input operands: 16x16 8x16 16x8 8x8 The MACROS that can be modified are shown in the next section. 6.4.3 Programming the Hardware Multiplier At the beginning. the registers of the hardware multiplier are defined In accordance with the MSP430 Family Architecture Guide and Module Library. This avoids confusion. MSP430 Hardware Multiplier Definitions MPY .equ l30h MPYS .equ l32h Multiply signed MAC .equ 134 Multiply-and-Accumulate OP2 .equ 138h Operand 2 Register Result Register LSBs 15 .. 0 Multiply unsigned SurnLo .equ 013Ah SumHi .equ 013Ch Result Register MSBs 32 .. 16 SumExt .equ 013Eh Sum Extension Register 47 .. 33 6-230 The Hardware Multiplier 6.4.3.1 Assembler .MACROS Due to the MACRO construction of the multiply instructions for source and destination (normally two MOV instructions form the multiplication sequence). all seven addressing modes are possible. If the register indirect or register indirectwith autoincrementaddressing modes are used to address the result. then a NOP is necessary after the .MACRO call to allow the completion ofthe multiplication.The named addressing modes access the source operand so fast. that they do not allow the completion of the multiplication. Examples are given with each .MACRO definition. The execution cycles depend on the addressing modes used for the multiplier and the multiplicand. The given MACROs can easily be changed to subroutines. An example is given for the unsigned multiplication: Subroutine Definition for the unsigned multiplication 16 x 16 bits. The two operands are contained in R4 and RS MPYU_16 MPYU16 R4,RS RET 6.4.3.2 Unsigned MPY 16 x 16 Result in SumHilSumLo Unsigned Multiplication 16 x 16-blts ; Macro Definition for the unsigned multiplication 16 x 16 bits MPYU16 . MACRO arg1,arg2 MOV arg1,&0130h MOV arg2,&0138h .ENDM ; Unsigned MPY 16x16 ; Result in SumHilSumLo Multiply the contents of the two registers R4 and R5 MPYU16 R4,R5 MOV SumLo,R6 LSBs of result to R6 MOV SumHi,R7 MSBs of result to R7 MPY R4 and R5 unsigned Continue Multiply the contents located in a table, R6 points to The result is addressed in indirect mode: a NOP is necessary On-Chip Peripherals 6-231 The Hardware Multiplier to allow the completion of the multiplication MOV #SumLo,R5 Pointer to LSBs of result MPYU16 @R6+,@R6 MPYU the table contents Allow completion of MPYU16 NOP MOV @R5+,R7 MOV @R5,R8 Fetch LSBs of result Fetch MSBs of result Continue Macro Definition for the unsigned multiplication and accumulation 16 x 16 bits MACU16 . MACRO arg1,arg2 Unsigned MAC 16x16 MOV argl,&0134h Carry in SumExt MOV arg2,&0138h Result in SumExtlSumHilSumLo .ENDM Multiply-and-accumulate the contents of registers R5 and R6 to the previous content (IROP1 x IROP2L) of the Sum registers MPYU16 IROP1,IROP2L Initialize Sum registers MACU16 R5,R6 Add (R5 x R6) to result ADD &SumExt,RAM Add carry to RAM extension Continue 6.4.3.3 Signed Multiplication 16x 1f$-blt The following software examples perform Signed 16 x 16-bit multiplications (MPYS16) or signed Multfplication and Accumulation (MACS16). The Sum Ext register contains the extended sign of the result in SumHi and SumLo: OOOOh (positive result) or OFFFFh (negative result). Macro Definition for the signed multiplication 16 x 16 bits MPYS16 6-232 . MACRO arg1,arg2 MOV arg1,&0132h MOV arg2,&0138h Signed MPY 16x16 bits The Hardware Multiplier Result in SumExtlSumHilSumLo .ENDM Multiply the contents of two registers R4 and R5 MPY signed R4 and RS MPYSl6 R4,R5 MOV &SumLo,R6 LSBs of result to R6 MOV &SumHi,R7 MSBs of result to R7 MOV &SumExt,R8 Sign of result to R8 Continue Multiply the contents located in a table, R6 points to The result is addressed in indirect mode: a NOP is necessary to allow the completion of the multiplication MOV #SumLo,RS Pointer to LSBs of result MPYS16 @R6+,@R6 MPY signed table contents Allow completion of MPYS16 NOP MOV @RS+,R7 LSBs of result to R7 MOV @RS+,R8 MSBs of result to R8 MOV @RS,R9 Sign of result to R9 Continue Macro Definition for the signed multiplication-andaccumulation 16 x 16 bits. The accumulation is made in the RAM: MACHi, MACmid and MAClo. If more than 48 bits are used for the accumulation, the SumExt register is added to all further extensions (RAM or registers) here shown for only one extension (48 bits) . MACS16 . MACRO arg1,arg2 Signed MAC 16x16 bits MOV argl,&0132h Signed MPY is used MOV arg2,&0138h ADD &SumLo,MAClo Add LSBs to result ADDC &SumHi,MAcmid Add MSBs to result ADDC &SumExt,MA~hi Add SumExt to MSBs .ENDM On-Chip Peripherals 6-233 The Hardware Multiplier Multiply and accumulate signed the contents of two tables MACS16 2(R6),@R5+ MACS for the table contents Accumulation is yet made 6.4.3.4 Unsigned Multiplication Bx B-blts If byte instructions are used for the loading of the hardware multiplier registers, then the high byte of these registers is cleared like a CPU register. This behavior is used with the unsigned 8 x 8-bits multiplications. Macro Definition for the unsigned multiplication 8 x 8 bits MPYU8 . MACRO arg1,arg2 Unsigned MPY 8x8 MOV.B argl,&0130h OOxx to 0130h MOV.B arg2,&0138h .ENDM OOyy to 0138h Result in SumLo. SumHi - 0 Multiply the contents of the low bytes of two registers MPYU8 R12,R15 MOV &SumLo,R6 MPY low bytes of R12 and R15 16 bit result to R6 SumExt - SumHi = 0 Macro Definition for the unsigned multiplication-andaccumulation 8 x 8 bits MACU8 . MACRO argl,arg2 Unsigned MAC 8x8 MOV.B argl,&0134h OOxx MOV.B arg2,&0138h .ENDM OOyy Result in SumExtlSumHilSumLo Multiply-and-accumulate the low bytes of R14 and a table MACU8 6-234 R14,@R5+ CALL the MACU8 macro (R5+l) The Hardware Multiplier 6.4.3.5 Signed Multiplication 8 x B-blts If byte instructions are used for the loading of the hardware multiplier registers, then the high bytes of their registers are cleared like a CPU register. It therefore needs only to be sign-extended. Macro Definition for the signed multiplication 8 x 8 bits MPYS8 . MACRO arg1,arg2 Signed MPY 8x8 MOV.B arg1,&0132h OOxx SXT &0132h Extend sign: OOxx or FFxx MOV.B arg2,&0138h OOyy SXT &0138h Extend sign: OOyy or FFyy .ENDM Result in SumExtlSumHilSurnLo Multiply signed the low bytes of RS and location EDE MPYS8 RS,EDE CALL the MPYS8 macro MOV &SurnLo,R6 Fetch result (16 bits) MOV &SumHi, R7 Sign: 0000 or FFFF Macro Definition for the signed multiplication and accumulation 8 x 8 bits. The accumulation is made in the locations MACHi, MACrnid and MAClo (registers or RAM) If more than 48 bits are used for the accumulation, the SumExt register is added to all further RAM extensions MACS8 . MACRO arg1,arg2 Signed MAC 8x8 bits MOV.B arg1,&0132h MPYS is used Extend sign; OOxx or FFxx SXT &0132h MOV.B arg2,&0138h OOyy SXT &0138h Extend sign ADD &SumLo,MAClo Accumulate LSBs 16 bits ADDC &SumHi,MACmid Accumulate MIDs ADDC &SumExt, MAChi Add SurnExt to MSBs .ENDM Multiply-and-accumulate signed the contents of two byte On-Chip Peripherals 6-235 The Hardware Multiplier tables MAese 2(R6),@R5+ CAL~ the MACSe macro (R5+1) Accumulation is yet made 6.4.3.6 Interrupt Usage Operating in the foreground only (interrupt handlers). the hardware multiplier can be used freely. If the hardware multiplier is used in the foreground andthe background, or in nested interrupt handlers, however, there are additional considerations. The hardware multiplier may be used in interrupt handlers and in the background (which is not typical real-time programming practice) .if three rules are observed: o The loading of the two registers operand 1 (MPY, MPYS and MAC) and operand2 may not be separated by an interrupt using the multiplier. The input information for operand1 cannot be restored due to the three input registers that are possible. See the example below. o The registers operand1 and operand2 cannot be reread by the background software - they may be overwritten by the interrupt handler. o The operand1 information cannot be used for more than one multiplication - only the operand2 register is changed for the next multiplication. The floating point package, FPP4, uses this method to speed up the calculation. so It must be changed. The place is indicated. Background: multiplication is used together with interrupt The interrupt latency time is increased by 9 cycles. The NOP is necessary: one additional instruction may be executed after the DINT instruction DINT Ensure non-interrupted - NOP MPYUl6 load of the MPYer registers R4, R6 EINT (R4) x (R6) -> Sum Allow interrupts again Continue with result The interrupt handler must save and restore the Sum registers &SumLo 6-236 Save the SumLo register The Hardware Multiplier Save the SumHi register PUSH &SumHi PUSH &SumExt Save the SumExt register MPYUl6 #X,Cl Call unsigned MPY: X x Cl Continue with MPYer result POP &SumExt Restore SumExt register POP &SumHi SumHi register POP &SumLo SumLo register Return to background RETI 6.4.3.7 Speed Comparison with Software Multiplication Table 6-30 shows the speed increase for the different 16 x 16-bit multiplication modes. o The cycles given for the software loop include the subroutine call (CALL #MULxx). the subroutine itself. and the RET instruction. Only CPU registers are used for the multiplication. o The cycles given for the hardware multiplier include the loading of the multiplier operand registers operand1 and operand2 from CPU registers. and - in the case of the signed MAC operation - the accumulation of the 48-bit result to three CPU registers (see Section 6.4.3.1.2). Table 6-30. CPU Cycles Needed for the Different Multiplication Modes OPERATION SOFTWARE LOOP HARDWARE MPYer SPEED INCREASE Unsigned MuHiply MPY 139...171 8 17.4...21.4 UnSigned MAC 137... 169 8 17.1 ...21.1 Signed MuHiply MPY 145•.. 179 143... 177 8 18.1 ...22.4 17 8.4 ... 10.4 Signed MAC 6.4.3.8 Software Hints If the operand1 is used for more than one multiplication in sequence. then it is not necessary to move it again into the operand1 register. The first example shows two unsigned multiplications with the content of address TONI. Four bytes and six CPU cycles are saved compared to the normal procedure. Multiply TONI x R6 and TONI x RS. Results to diff. locations MPYUl6 TONI,R6 TONI x R6 -> SumHilSumLo On-Chip Peripherals 6-237 Resul t to R8 IR7 • MOV &SumLo,R7 MOV &SumHi,R8 MOV RS,&0138h ; TONI still in &0130h MOV &SumLo,RESULT ; TONI x RS -> SumHilSumLo MOV &SumHi,RESULT+2; Result to RESULT+2IRESULT The second example shows three multiply-and-accumulate operations with the same operand1. The three operands2 cannot be added simply and multiplied once -.,.. their sum may exceed the range of 16 bits. Eight ROM bytes and twelve CPU cycles are saved by using this method compared to the normal procedure. Multiply-and accumulate TONI x R6, TONI x RS and TONI x EDE The accumulated result is moved to RESULT .. RESULT+4 ; Initialize Sumxxx registers MACU16 TONI,R6 ADD &SUmExt,RESULT+4 MOV RS,&0138h ADD &SumExt,RESULT+4 MOV MOV EDE,&0138h . &SumLo, RESULT MOV &SumHi,RESULT+2 ADD &SumExt,RESULT+4 ; TONI x R6 + SumHilSumLo Add carry to extension ; Add TONI x RS to Sumxxx Add carry to extension Add TONI x EDE to sumxxx TONI x (RS+R6+EDE) in Sumxxx Result to RESULT .. RESULT+4 6.4.3.9 Speed Increase for the Floating Point Package The hardware multiplier only increases the speed of floating point multiplication. For the speed evaluation shown, the variables X and Yare used. they are defined as follows: .if DOUBLE=O 32-bit format X . float 3.1416 3.1416 y . float 3.1416*100 .else 314.16 48-bit format X . double 3.1416 3.1416 y . double 3.1416*100 314 .16 .endif The execution cycles shown Include the addressing of one operand and the subroutine CALL, itself: 6-238 The Hardware Muniplier MOV #X,RPRES MOV #Y,RPARG Address 1st operand Address 2nd operand CALL #FLT_MUL Call the MPY subroutine Product X x Y on TOS Table 6-31 shows the number of necessary cycles needed for the multiplication: Table 6-31. CPU Cycles Needed for the FPP Multiplication (FLT_MUL) OPERATION Multiplication X x y Multiplication X x y Speed increase .FLOAT .DOUBLE COMMENT 395 153 2.58 692 Software loop 213 3.25 Hardware MPYer used SW cycleslHW cycles Due to the speed advantage of the hardware multiplier only for multiplication, it is recommended that divisions be replaced by multiplications wherever possible. This is most simple for divisions by constants, like is shown in the next example. Example 6-54. Division by Multiplication The division of the last result - on top of the stack - by the constant 2.7182818 is replaced by a multiplication with the constant 1/2.7182818. This reduces the calculation time by a factor of 4051153 =2.65. First, the original sequence: DOUBLE .equ 0 Use the .FLOAT format HW..,MPY .equ 1 Use the HW-MPYer MOV #FLTe, RPARG Address ,constant e CALL #FLT_DIV TOS/e: Division 405 cycl. . float 2.7182818 Quotient on TOS FLTe Constant e The above division is replaced by a multiplication using the hardware multiplier: HW..,MPY .equ 1 MOV #FLTei,RPARG ; Use the HW-MPYer Address constant lie On-Ghip Peripherels 6-239 CALL #FLTJ4UL TOS xl/e. MPY 153 cycles . float 0.3678794 Constant l/e Result on TOS FLTei If the .DOUBLE version (48 bits) of FPP4 is used, then the division execution time is decreased by a factor of 7561213 =3.55. 6.4.4 Software Applications Typical proven software examples are given for the application of the hardware multiplier. The comments indicate for some examples the location of the (think hexa-) decimal point: ±2.13 ~'-..... s Integer Bits Fraction Bits II ~ 1 I 0 6.4.4.1 Multiplication Exceeding 16 Bits The first software example shows the unsigned multiplication of two 4O-bit numbers (the MSBytes contain 0) - 48 bits of the result are used subsequently. The lower 32 bits of the product are not used. The first operand is contained in the registers ARG1_xxx and the second operand in ARG2_xxx. The result is placed into RESULT_xxx (CPU registers or RAM). The multiply routine is abstracted from the FPP4 package. The execution time for CPU registers is 94 cycles. 6-240 The Hardware Mump!~r MulUpller MulUpllcand x o 39 o 39 o 31 00 ARGCLSB )( ARG2_MSB Intermediate Products MSB MID LSB Final Product 79 32 Figure 6-57. 40 x 4D-Bit Unsigned Multiplication MPYU40 ; Register Definitions for the 40 x 40 unsigned MPY and MAC ARGIJ1SB .equ R5 ARGIJ1ID .equ R6 ARG1_LSB .equ R7 ARG2_MSB .equ R8 ARG2J1ID .equ R9 ARG2_LSB .equ RIO RESULT_MSB .equ Rll Argument 1 (Multiplicand) Argument 2 (Multiplier) Result (Product) On-Chip Peripherals 6-241 The Hardware Multiplier RESOLTJ{ID .egu R12 RESULT_LSB .egu R13 MPY040 CLR RESOLTJ{SB CLR RESOLT_MID CLR RESOLT_LSB MPY016 ARG2_LSB,ARG1J{ID ; Bits 16 to 47 MAC016 ARG1_LSB,ARG2J{ID ADD &SumHi,RESOLT_LSB MAC040 Clear Result ADDC &SumExt,RESOLT_MID MPY016 ARG1_MSB,ARG2_LSB ; Bits 32 to 63 MAC016 ARG1_LSB,ARG2J{SB MAC016 ARG1J{ID,ARG2_MID ADD &SumLo,RESOLT_LSB ADDC &SurnHi,RESOLTJ{ID ADDC &SumExt, RESOLTJ{SB' MPY016 ARG1_MSB,ARG2J{ID ; Bits 48 to 79 MAC016 ARG2_MSB,ARGl_MID ADD &SumLo,RESOLTJ{ID ADDC &SumHi,RESOLT_MSB MPY016 ARGl_MSB,ARG2_MSB ; Bits 64 to 79 ADD &SumLo,RESULT_MSB RET 48 MSBs in result The second software example shows all four possible multiplication routines for two 32-bit numbers; the full 64-bit result may be used afterward. The signed 16 x 16-blt hardware multiplication MPYS cannot be used; it is designed forthe special case of 16 x 16 bits. So the unsigned multiplication MPY is used with a correction of the final sum at the start of the subroutine. Execution times (without CALL): MACU32 MPYU32 MACS32 MPYS32 6-242 58 cycles 64 cycles 64 to 68 cycles 68 to 72 cycles unsigned MAC unsigned MPY signed MAC signed MPY The Hs'tfwsre Multiplier Multiplicand Muhlpller Is I OP2HI OP2LO o 15 X II 0 15 S OP1HI OP1LO o 15 0 0 15 31 OP2LOxOP1LO OP2LO x OP1HI OP2Hlx OP1LO I Is I OP2Hlx OP1HI Product SUM3 SUM1 SUM2 SUMO 63 Figure 0 ~58. 32 x 32-Bit Signed Multiplication MPYS32 Example ~55. 32 x 32-bit Multiplication and MAC Functions All four possible 32 x 32-bit multiplication and MAC functions are shown below. The defined operands and result registers maybe working registers (as defined) or RAM locations. SUM3 .equ R15 Result: sign and MSBs SUM2 .equ R14 (registers or RAM locations) SUM1 .equ R13 SUMO .equ R12 LSBs OP1HI .equ Rll 1st operand: sign and MSBs OP1LO .equ RlO LSBs OP2HI .equ R9 2nd operand: sign and MSBs OP2LO .equ R8 LSBs The unsigned 32 x 32 bit multiplication MPYU32 CLR SUM3 Clear the result registers CLR SUM2 64 cycles CLR SUM1 On-Chip Periphers/s 6-243 The,Hardware ,Multiplier CLR .SUMO JMP MS321 Proceed at common part The signed 32 x 32 bit multiplication MPYS32 CLR SUM3 Clear the result registers CLR SUM2 68 to 72 cycles CLR SUMl CLR SUMO The signed 32-bit 'Multiply-and-Accumulate" subroutine The final result is corrected. 64 to 68 cycles MACS32 MS320 TST OPIHI JGE MS320 No SUB OP2LO,SUM2 Yes, correct final sum SUBC OP2HI,SUM3 Operandl negative? TST OP2HI JGE MS32l No SUB OPlLO,SUM2 Yes, correct final sum SUBC OPlHI,SUM3 Operand2 negative? The unsigned 32-bit 'Multiply-and-Accumulate" subroutine MACU32 .equ $ 58 cycles Main part for all multiplication subroutines MS321 6-244 MPYU16 OPILO,OP2LO LSBs x LSBs ADD &SumLo, SumO Add product to result ADDC &SumHi,Suml ADC Sum2 ADC Sum3 MPYU16 OPlLO,OP2HI Necessary only for MACx32 LSBs x MSBs The HB"!"YB"! Multiplier MACU16 OP2LO,OP1HI LSBs x MSBs ADD &SurnLo,Suml Add accumulated products ADDC &SumHi,Sum2 to result ADDC &SumExt,Sum3 Necessary only for MACx32 MPYU16 OP1HI,OP2HI MSBs x MSBs ADD &SumLo,Sum2 Add product to final result ADDC &SurnHi,Sum3 RET 6.4.4.2 Sensor Characteristics For many applications, the digital values delivered by analog-to-digital converters. 1/0 ports, or calculation results must be corrected or adapted. A common method is to use polynomials for this purpose. For example a cubic polynomial to calculate the corrected output value y from the input value x is: y = a3 X x3 + a2 X x 2 + al x x + ao With the hardware multiplier, a common solution may look like the following code. This subroutine is written for the highest possible speed - the coefficients 83 to ao have decreasing numbers of bits after the (think hexa-) decimal point. If this cannot be tolerated, then shifts and stores between the multiplications are necessary. The input value x stays in operand1 (MPYS 0132h) and is used for all three multiplications. Example 6-56. Value Correction The output value of the ADC is corrected with a cubic polynomial. All values are scaled to values less than 1 to get the maximum resolution. The coefficients an used for correction are: a3: +0.01 82:-0.25 a1: -0.5 aO: +0.999 The HORNER scheme is used for the computation: y = «((a3 xx) + a2 )x x + al )X x + ao The numbers +--a.b in the code comments indicate the bits before and after the decimal point of the numbers used. Execution time (without CALL): 45 cycles On-Ghlp Peripherals 6-245 The Hardware Multiplier Polynomial Calculation for y = a3x h 3 +a2Xh2 +alx h l +aOxhO Result in SumHi reg.ister POLYNOM MPYS16 X,A3 +-0.15 x +-0.15 (+-1.14) ADD A2,&SumHi +-1.14 + +-1.14 -> +-1.14 MOV &SumHi,&OP2 +-1.14 x +-0.15 (+-2.13) ADD Al,&SumHi +-2.13 + +-2.13 -> +-2.13 MOV &SumHi,&OP2 +-2.13 x +-0.15 (+-3.12) ADD AO,&SumHi RET +-3.12 + +-3.12 -> +-3.12 SumHi: +-3.12 Table of coefficients A3 . word +100*08000h/10000 ; +O.Oi A2 .word -2500*04000h/10000 -0.25 (+-1.14) (+-0.15) Al . word -5000*02000h/10000 -0.5 AD . word +9999*01000h/10000 +0.9999 (+-3.12) (+-2.13) 6.4.4.3 Table calculation The .MACRO instructions used for the different multiplication possibilities (8 bits versus 16 bits, signed and unsigned, multiply and multiply-and-accumulate) have the advantage to allow all seven addressing modes of the MSP430 architecture for source and destination. Therefore, the MPY instructions are ideal for table processing - both operands of a multiply instruction can also be addressed Indirectly. An example for the table calculation is given in Section 6.4.4.5 6.4.4.4 Wave Digital Filters The main advantage of wave digital filters is that for fixed coefficients, no mUltiplication is needed. Instead, an optimized shift-and-add sequence is used for the filter algorithm. But this optimization is not possible if Adaptive Filter Algorithms are used, which means changing coefficients. In this case, a hardware multiplier has significant advantages - the calculation time is independent of the coefficients used. 6-246 The Hardware MuHipller 6.4.4.5 Finite Impulse Response (FIR) Digital Filter The formula for a simple FIR filter is: Yn = ao x xn + al x xn-l + a2 X xn-2 +... ak x Xn-k - + - - - - -........ Yn Yn =ao xn + 81 xn·1 •••• +ak xn-k Figure 6-59. Finite Impulse Response Filter The example below shows an algorithm that uses the last ADC result for the input of a seventh-order FIR filter. The coefficients an are stored in ROM (fixed coeffiCients) or in RAM (adaptable coefficients). The filter maybe changed easily to a higher order: o o The value k must be changed to the desired order o The table with the coefficients an must be enlarged to (k+ 1) coeffiCients (k+ 1) words in RAM must be allocated for the input samples xn starting at label X Execution time: 28 CPU cycles are necessary per filter tap. The example does not show a real filter - for example, for a linear phase response the coefficients an must be: which means: aO = ak, a1 = ak-1 etc. On-Chip Peripherals 6-247 The Har;Jware Multiplier . Coefficients Input Values Xn-1 Sk-1 xn·k+1 R5-+ II s X Xn-k R7 R8 o 15 R6-+ 15 sk An I R9 o 15 0 Figure 6-60. Storage for the Finite Impulse Response Filter The special "Multiply-and-Accumulate" .MACRO accumulates the products X x An in the registers R71R81R9. Execution time: 19 cycles for the example below with the indirect addressing mode used for both operands. MACS16 . MACRO arg1,arg2 Signed MAC 16x16 MOV arg1,&0132h Signed MPY is used MOV arg2,&0138h Start MPYS ADD &SumLo,R9 Add LSBs to result ADDC &SumHi,R8 Add MSBs to result ADDC &SumExt,R7 .ENDM Add SumExt to result Result in R71R81R9 Definitions: - Value k defines the order of the FIR-filter - OFFSET is used to get signed values (EOOOh .. 1FFFh) out of the unsigned 14-bit ADC results (0 ... 3FFFh) - X defines the address for the oldest input sample x(n-x) in a sample buffer with (x+1) words length X .equ 7 (x + 1)samples are used - OFFSET .equ 02000h to get signed ADC values 6-248 Rssult Registers The Hardware Multiplier x .equ 0200h x(n-k) sample address With the Timer_A interrupt the calculation is made TIMA_INT PUSH RS PUSH R6 MOV #X,RS Address xn buffer (oldest x) MOV #An,R6 Address an constants (ak) MOV &ADAT,2*k(R5) SUB #OFFSET, 2*k(RS) TAOO CLR R7 CLR R8 CLR R9 Save R5 and R6 New ADC sample to xn Create signed value for xn ; ; Clear result reg. (MSBs) MACS16 @RS+,@R6+ ak * xn-k added to R71R81R9 MOV @RS,-2(R5) xn-k+1 -> xn-k CMP #X+2+(2*k),R5 Through? (RS points outside) JNE TAOO No, once more POP R6 Restore RS and R6 POP R5 BIS #CS,&ACTL RETI Start next ADC conversion Result: +-17.30 (3 words) The constants An are fixed in ROM. Format: +-0.15 (1 bit sign, IS bits fraction) Range: -0.99996 to +0.99996 An . word +9999*8000h/l0000 ak +0.9999 . word -9999*8000h/l0000 ak-l -0.9999 . word +SOOO*8000h/l0000 al +O.S . word -SOOO*8000h/l0000 aO -0.5 ak-2 to a2 On-Chip Peripherals 6-249 '!!'.~.!:,ardware Multiplier 8.4.4.8 Fast Fourier Transform Algorithm The buffer - located in the RAM - the pointer that pQR points to, is transformed and overwritten with the result of the fast Fourier transformation (FFT). The formula used for each block consists of real and imaginary numbers: PRi' PIi' QRi' QIi' (PRi + (QRI X WRi + QIi X WIi)/2 (PII + (QII x WRi - QRi x WIi)/2 (PRi - (QRi X WRI + QII x WIi)/2 (Pli - (QIi x WRi - QRi x WIi)12 Where: WRI Wli real part of Pi imaginary part of Pi real part of Qi imaginary part of QI cos (i x 2 1t IN) =cos (00 x i) sin (i x 2 1t IN) = sin (00 x i) OJ 2m i PRI PRi' Index number Real part of PRi before FFT Real part of PRI after FFT Figure 6~1 shows the allocation of the three tables in the RAM and ROM of the MSP430. Execution time: the buffer shown, with eight complex numbers each for the P .and Q part, needs 717 cycles (without CALL) for the transformation (185 J.1S @4MHz). 6-250 The Hardware Multiplier Slne/CoIIIna Table PO Real pWI-+ sinO PIValuea sin (1/SIt) PO Imaginary Addressss 1 Pn-1 Real Pn-1 Imaginary QOReal pQR-+ QlValues QO Imaginary Qn-1 Real sin (4181t1 cosO sin (51S1t) cos (1/SIt) SIn (8/SIt) cos (21S1t) sin (7/SIt) cos (31S1t) sin (10/SIt) cos (8/SIt) sin (11/SIt) cos (7/8,,) Qn-1lmaglnary Figure 6-61. RAM and ROM Allocation for the Fast Fourier Transformation Algorithm Algorithm: 'FFT' optimized butterfly radix 2 for MSP430x33x Originally developed by M.Christ/TID for TMS320CBO Input data: PRO,PIO,PR1,?I1, ...... ,QRn-1,QIn-1 (16 bit words) Algorithm: PR' (PR+(QR*WR+QI*WI»/2 WR=cos(wt) PI' (PI+(QI*WR-QR*WI»/2 WI=sin(wt) QR' = (PR-(QR*WR+QI*WI»/2 QI' (PI-(QI*WR-QR*WI»/2 Procedure: real imag = (QR*WR+QI*WI)/2 (QI*WR-QR*WI)/2 On-Chip Peripherals 6-251 The Hardware Mult"'!,ler PR' PR/2 + real OR' PR/2 PI' PI/2 + imag 01' PI/2 - imag real N .equ 16 16 point complex FFT N2 .equ .equ N*2 RS Byte count (OR - PRJ Pointer to QRi pOR pWI .equ R6 Pointer to sine table tabs in real .equ R7 storage imag .equ R8 TEMP .equ R9 01 x WR + OR x WI Temporary storage TEMPl .equ RIO OR x WR + OI.x WI Storage The subroutine FFT is called after the loading of the pointer to ORO. Call: MOV tOR,pQR Pointer to ORO of block (RAM) CALL iFFT Call the FFT subroutine Input table contains results Definition of the input table located in the RAM .bss PR,2,0200h PRO Preal .bss PI,2 PIO Pimaginary .bss PRi,N2-4 PR1, PIl. .. PRn-l, Pln-l .bas OR,2 ORO Oreal .bss 01,2 010 Oimaginary .bss ORi,N2-4 OR1, OIl ... ORn-l , OIn-l start of the FFT subroutine. pOR contains address of ORO FFT 6-252 MOV itabsin,pWI Pointer to sin 0 The "!.!'ifwaTe Multiplier Execution of the 4 multiplications. The halfed result is calculated without additional shifts due to the format 2.14 Calculation of the real part: real = (OR x WR + 01 x WI)/2 FFTLOP MPYS16 @pOR+,tabcos-tabsin(pWI); MOV &SumHi,real store (OR x WR)/2 MPYS16 @pOR,@pWI (01 x WI)/2 ADD &SumHi,real store real part (2.14) (2.14) Calculation of the imaginary part: imag - (01 x WR - OR x WI)/2 MPYS16 @pOR+,tabcos-tabsin(pWI); MOV &SumHi,imag Store (or x WR)/2 (2.14) MPYS16 -4 (pQR) , @pWI+ (OR x WI)/2 (2.14) SUB &SUmHi,imag Btore imaginary part Calculation of PR', PI', OR', 01'. pOR points to ORi+1 Calculation of PR': PR' = (PR + (OR x WR + 01 x Wr»/2 MOV -N2-4(pOR) ,TEMP RRA TEMP PRi/2 MOV TEMP,TEMP1 Copy PRi/2 ADD real,TEMP1 MOV TEMP1,-N2-4(pOR) PRi to TEMP PRi/2 + (ORxWR + OIxWI)/2 ; to PR' (1.15) Calculation of OR': OR' = (PR - (OR x WR + 01 x WI»/2 SUB real,TEMP PR/2 - (ORxWR + OIxWI)/2 MOV TEMP,-4(POR) to OR' (1.15) Calculation of PI': PI' (PI + (01 x WR - OR x WI»/2 MOV -N2-2(pOR) ,TEMP RRA TEMP PI/2 MOV TEMP,TEMP1 Copy PI/2 PI On-Chip Peripherals 6-253 The.Ha..~are Multiplie; ADD imag, TEMPI PI/2 + (QIxWR - QRxWI)/2 MOV TEMP1,-N2-2(pQR) to PI' (1.15) Calculation of QI': QI' (PI - (QI x WR - QR x WI»/2 SUB imag,TEMP PI/2 - (QI*WR+QR*WI)/2 MOV TEMP,-2(pQR) to Q1' (1.15) To next input data. Check if FFT is finished CMP #tabsinO, pWL JLO FFTLOP Through? (pWI tabsinO) No Yes, return RET Sine and cosine table. Format: s.fraction (1.15) tabs in tabcos tabsinO . word +0000*8000h/10000 sin 0.0 0.00000 . word +3827*8000h/10000 sin 1t/8 0.38268 . word +7071*8000h/10000 sin 21t/8 0.70711 . word +9239*8000h/10000 sin 31t/8 0.92388 . word 10000*8000h/lOOOO-1 ; . word +9239*8000h/lOOOO sin 51t/8 cos 1t/8 . word +7071*8000h/lOOOO sin 61t/8 cos 21t/8 . word +3827*8000h/lOOOO sin 71t/8 cos 31t/8 . word +0000*8000h/lOOOO cos 41t/8 sin 41t/8 . word -3827*8000h/lOOOO cos 51t/8 . word -7071*8000h/10000 cos 61t/8 . word -9239*8000h/lOOOO cos 71t/8 cos 0.0 An example is given for the FFT: The following table contains 32 values that are the data for the FFT 16 point complex FFT radix 2 DIT DataSt 6-254 . word 014abh,02e90h,Of6d4h,005d3h PRO, PIO .. PIl . word 004b2h,Ofecdh,Of78ch,Ofcb2h PR2, PI2 .. PI3 The Hardware Multiplier . word 0093ch,004fOh,Offb5h,OO17ch . word Ofbebh,002a5h,Of3a3h,Ofb38h PR4, PH .. PI5 PRG, PIG .. PI? . word O1854h,02a29h,Offb9h,Of9beh ORO, 010 .. OIl . word Ofa49h,00907h,OOalOh,Of99bh OR2, 012 .. 013 . word 0030ch,Ofdadh,Ofa2ah,OO2e3h OR4, 014 .. 015 . word Ofddbh,0029bh,Ofdf9h,00225h ORG,OI6. OI? The following 32 values are output by the FFT Result . word 0167fh,02c5ch,Ofa16h,OOO13h . word 00384h,0049ch,Ofabeh,Of879h PR' 0 .. PI' 1 PR'2 .. PI'3 .word 00374h,OOOf2h,OO24dh,OO2e2h PR' 4 .. PI' 5 . word Offa4h,00128h,Ofb2ah,OfdOlh PR'6 .. PI'7 . word Ofe2bh,00233h,Ofcbdh,OO5bfh OR'O .. 01' 1 . word OO12dh,Ofa30h,Ofccdh,OO438h OR'2 .. 01'3 . word 005c7h,003fdh,Ofd67h,Ofe99h OR' 4 .. 01' 5 . word Ofc47h,0017ch,Of879h,Ofe36h OR'6 .. 01' 7 6.4.4.7 Conclusion As shown by the examples, the hardware multiplier has its biggest advantages when used for signed and unsigned 16-bit operands. But also for other applications -like for a-bit operands, 32-bit operands or floating point numbers - the speed increase is valuable compared to the pure software solution. On-Chip Peripherals 6-255 The System C~ Generator 6.5 The System Clock Generator The system clock generator of the MSP430 family provides many features not available with other microcomputers. To allow the full use of all the possibilities, some basics concerning the function of the oscillator are needed. A detailed description of the hardware Is given in the MSP430 Family Architecture User's Guide and Module Ubrary, chapter Osci/lator and System Clock Generator. The output frequency, MCLK, of the system clock generator is generated in a digitally controlled oscillator (DCO), having 32 taps. Each one of these taps represents a typical output frequency ranging from 500 kHz to 4 MHz. These tap frequencies depend on temperature and supply voltage, and referencing to a crystal is therefore necessary. Software definitions for the programming examples SCGl .equ OBOh System Clock Generator Control Bit 1 SCGO .equ 040h System Clock Generator Control Bit 0 OSCoff .equ 020h If 1: Oscillator off CPUoff .equ OlOh If 1: CPU off GIE .equ OOBh General Interrupt Enable Bit SCFIO FN_2 . equ 050h System Clock Frequency Integrator Reg . .equ 004h DCO current switch for 2 x fnom SCFIl .equ 051h DCO tap register TAP .equ OOBh 2~5 SCFQCTL .equ 052h System Clock Frequency Control Register M .equ OBOh Modulation Bit in SCFQCTL. M = 1: off 6.5.1 2~9 to 2~2 bit in SCFI1 Initialization After the application of the supply voltage, Vcc; the system clock frequency fsystem is initialized to 1.024 MHz, if a 32.768 kHz crystal is used. This is automatically made by setting of the multiplication factor, N, to 32 and clearing of the FN_x bits in the control bytes SCFIO and SCFI1. If the CPU is always on afterward and 1.024 MHz is the desired frequency, then there is nothing else to do. 8.5.1.1 First <tlng of the DCO Taps during Initialization The digitally controlled oscillator of the MSP430 starts at tap 0, which means at the lowest possible frequency ('" 500 kHz). To get from one tap to the next 6-256 The System C1oc: Generator one, 210 (1024) cycles are needed. Thirty-two taps are implemented, so 32 x 1024 cycles are needed, worst case, to get to the correct DCD tap. The initialization routine should therefore have a length of 32000 cycles. If this is not the case, a delay routine should be added to guarantee this length. An example is given below: Loop Control is on (SCGl INIT L$l 6.5.2 = SCGO #11000,R5 Init delay to allow DCO·setting DEC R5 11000 x 3 cycles = 33000 cycles JNZ L$1 BR #MAINLOOP MOV = 0) Start program Entering of Low Power Mode 3 The low power mode 3 (LPM3 -crystal on, DCD and loop control off) is the normal mode for battery-powered systems. Enabled interrupts (e.g. the basic timer) wake up the CPU. LPM3 is entered with the following source code: BIS #CPUoff+GIE+SCG1+SCGO,SR; Enter LPM3 6.5.3 Wake-Up From Interrupts In Low Power Mode 3 Wake-up from LPM3 clears only bit SCG1 (LPM1). Due to the set bit SCGO, the loop control of the DCD is off. Normal interrupt routines are too short to allow the loop control to adjust the DCD tap -1 024 cycles are necessary to get from one tap to the other one. It is not necessary, therefore, to switch on the loop control. The CPU uses the DCD tap set during the last adaptation. Anormal, short interrupt routine looks like this: BT_HAND INC RETI COUNTER LPM1: Loop Control stays off: ; DCO is on for 17 cycles only If woken-up from LPM3, the interrupt latency time (6 cycles) is increased by typo 2 j.LS@ 1 MHz versus 1 j.LS@ 2 MHz (if FN_2 =1). This means 8 cycles are typically needed from the interrupt event to the start of the Interrupt handier. The time the DCD needs to settle to the nominal frequency is typically 4 cycles. This means interrupt handlers are processed with the correct frequency. 6.5.4 Adaptation of the DCO Tap During Calculations The DCD tap of the system clock generator should be updated during longer on times of the CPU (e.g. during calculations). This is necessary especially if On-Chip Peripherals 6-257 The System Clock Generator accurate timing of the instructions is needed. During all calculations that exceed 100 cycles in length, the loop control of the DCO should be switched on. The way to do this is to reset the SCGO bit in the status register after the wakeup: Calculations are necessary. Allow adaptation of the DCO tap BIC #SCGO,SR Switch on DCO loop control Calculate energy (>100 cycles) RETI Return to LPM3 with adapted DCO tap The RETI instruction restores the CPU mode from the stack as it was when the interrupt occurred. 6.5.5 Wake-Up From Interrupts In Low Power Mode 4 The low power mode 4 normally lasts much longer than the low power mode 3 - it may last for months until a stored module is woken-up for calibration. This means that the environment temperature may have changed seriously. lfthe LPM4 was entered at a high temperature, the used DCOtap will be a relatively high one due to the negative temperature coefficient of the DCO. If then the device is woken-up at a low temperature and the crystal turns on fast, this high DCO tap may lead to a very high DCO frequency, a frequency the system cannot operate with. Therefore, It is a good programming practice, to program a low DCO tap before entering LPM4: Enter Low Power Mode 4: Set DCO tap to 2 MOV.B #TAP*2,&SCFll BIS #CPUoff+OSCoff+GIE+SCG1+SCGO,SR ; Enter LPM4 ; Set DCO tap to 2 If woken-up from LPM4, it may last up to seconds until the crystal has reached its nominal frequency. The frequency Integrator counts down continuously as long as the crystal oscillator has not started its operation. This lasts until the lowest DCO tap (with the lowest system frequency) is reached. After the start of the crystal oscillator, .the loop control will set the system frequency to its correct value by stepping up the taps. 6-258 The System Clock Generator 6.5.6 Change of the System Frequency The system clock frequency fsystem depends on two values: jsrSlem Where: N fcrystal = N X jcrySlal Multiplication factor of the DCO loop (SCFQCTL contains N-1) Frequency of the crystal (normally 32.768 kHz) The normal way to change the system clock frequency is to change the multiplication factor N. The system clock frequency control register SCFQCTL is loaded with (N-1) to get the new frequency. To allow the DCO to work always in one of the center taps (13 to 18), three switches FN_2 to FN_4 are implemented in the register SCFIO. It gives a safety not to be at the frequency limits ofthe DCO. These switches increase the internal current ofthe DCO and allow higher output frequencies if set. The switch nearest to the programmed DCO output frequency should be used. The switches FN_x typically settle within ±1 tap if the change is from the nominal frequency of one switch to the nominal frequency of the other one. For example, if in the example below, the initial system frequency is 1 MHz, then the new tap is one of the neighboring taps. This means, to settle at 2 MHz, needs a maximum of 1024 cycles (0.5 ms) only. If FN_2 is not used, it would take up to 16 x 1024 cycles (8 ms) because the misalignment could be up to 16 taps. Note: The switches FN_2, FN_3, and FN_4 need to be set correctly in dependence of the system clock frequency, fsystem' Otherwise, erroneous behavior of the system will result. Only one switch may be in use at the same time - the one that is nearest to the actual frequency should be used. FN_2 controls frequencies near 2 MHz, FN_3 controls frequencies around 3 MHz, and FN_4 controls frequencies around 4 MHz. , Change system frequency to 2.048MHz (fcrystal N = 64 FN_2 M - = 0 = 32.768kHz) Multiply 32kHz by 64 to get 2.048MHz 1: Adjust DCO current to 2MHz output frequency Switch on modulation MOV.B #64-1,&SCFQCTL 64 x 32kHz MOV.B #FN_2,&SCFIO Adjust DCO current to 2MHz = 2.048MHz, M - 0 On-Chip Peripherals 6-259 Th~ System Clock Generator 6.5.7 The Modulation Bit M The modulation bit M (SCFQCTL.7) switches off. and on the influence of the 5 LSBs (NOCOmod) of the system clock frequency integrator: o M =0 - the modulation is on. This means 8111 0 bits of the integrator influence the DCO. The used tap of the DCO may be changed with every clock cycle to get the correct system clock frequency. This is the case if the programmed frequency lies exactly between two tap frequencies. o M =1-the modulation is off. This means only the 5 MSBs (Noco) ofthe integrator influence the DCO. The used tap of the DCO is changed only after 1024 clock cycles (forfsystem =1 MHz) to get the correct system clock frequency. If the programmed frequency lies exactly between two tap frequencies, then 1024 cycles are output with the lower tap frequency and 1024 cycles are output with the upper tap frequency. In any case, independent of the modulation status, the integral error of the DCO will be zero. The modulation may be switched off If a series of MCLK cycles is needed with exactly the same length (for measurements with the universal timer/port module, for example). To get this, the loop control also should be switched off. Ensure stable, non regulated output pulses with equal length: BIS.B #SCGO,SR BIS.B #M,&SCFQCTL Switch off loop control Switch off modulation Use non-regulated MCLK Return to a regulated MCLK with closed loop and modulation 6-260 BIC.B #SCGO,SR Switch on loop control BIC.B #M,&SCFQCTL Switch on modulation . The System Glock Generator 6.5.8 Use Without Crystal If for an application, no precise timing is necessary, then the crystal may be omitted. If no ACLK is present (due to the missing crystal), then the DCO will run with its lowest frequency, which is approximately 500 kHz. No special instructions are necessary to get this behavior. If this lowest DCC frequency is too low, then a higher DCO tap (eg. 10) may be used. This tap normally results in an MCLK frequency near 1MHz. It is Im- portant to switch off the FLL loop, otherwise the FLL control will step down to tap 0 slowly. The software for this use of the DCO follows: Initialization of the DCO for non-crystal mode: Loop control off, tap number = 10: MCLK ~ 1MHz BIS.B #SCGO,SR Switch off loop control CLR.B &SCFIO Reset FN_x bits MOV.B #050h,&SCFIl Set bits for tap number 10 If an external reference like the ac line is available, then the a.ctual MCLK frequency can be controlled simply by the counting of the MCLK output with one of the timers (e.g. for one ac line period). An example is given in section The Timer_A where the control of an LCD is also shown without a crystal and missing LCD control frequency due to the missing ACLK 6.5.9 High System Frequencies Together With the 14-blt ADC The maximum MCLK without input division is 1.5 MHz (132 cycles are needed for a conversion). To allow the full range of the system clock MCLK, together with the active ADC, a clock divider is included in the ADC module. It allows the division of the system frequency MCLK by factors of 1, 2, 3, and 4. See section Analog-ta-Digital Converters for examples. 6.5.10 Dependencies of the System Clock Generator If the DCO runs with an open loop, its frequency depends on the temperature and the supply voltage, Vee. Nominal values for these dependencies are: o o Temperature dependence: -:5.6 kHzWC x MHz) Voltage dependence: +60 kHZ/(V x MHz) These two dependencies are brought to zero if the DCO loop is closed (SRbits: SCGO .. SCG1 = OscOff =0). See the next section for short term deviations of the system clock generator (MCLK). On-Chip Peripherals 6-261 The System Clock ~erator 6.5.11 Short Time Accuracy of the System Clock Generator The error of the system clock generator is zero for long time periods (compared to the system frequency fsystem)' Normally, no tap of the DCC can deliver the correct system frequency, fsystem, which is defined for the settled state to Therefore, the system clock generator switches continuously between two adjacent DCC taps - the one with a lower frequency fN and the tap with a higher frequency fN+ 1. This switching between the two DCCtaps Noco and Noco+ 1 is interlaced in such a way that it results in a small error at any time within the ACLK period. The resulting error for a complete ACLK period is nearly zero and the integral error for a longer period is zero. Figure 6-62 shows the use of the 1D bits of the registers SCFID and SCFI1. The five MSBs Nococontrolthe DCC-taps, the five LSBs NOCOmod control the modulation scheme of the DCC. Bits located in the System Clock Frequency Integrator Registers SCFIO and SeFI1 0 4 x x x x ~ NOCO ceo Tap Control (0 ••31) x 0 4 J x x x x x ~ NocOmod oeo Modulation Control (0 .. 31) Figure 6-62. Control of the DCa by the System Clock Frequency Integrator Figure 6-63 illustrates the DCC switching between the lower and the higher DCC tap for selected values of NOCOmod. 6-262 The System Clock Generator NOCOmod Value 0/ the 5 LSBs 01 the System CIocI< Frequency Integrator 131 JJj;::.=================-;;;;Am~ax=================:;J.L 24~ 16 15 5-1___.-JIr=-::Amax ~~____--'n. . ___ 4-1__~n n n nL-__ 3-1_________---'fl~________~rl~________~rl~_________ 2~------~fl....------_=~---. . . fl . ....~----­ -t---------------.. . .rl$ UpperCOOTapFrequencyl.!.,_ . fA""er COO Tap Frequency'" active o o I, 10 5 15 25 20 --'I 30 31 0 MCLK Cycles 1MHz I-_--1 Spike Vee VoHage Drop-out + + Powerfail + V1h+ vth- RSTINMI Cch MSP430 OV v.s Supply from: Accumulator Mains Rectifier Capacnor Supply Figure ~9. RESET Circuit With a Schmitt Trigger and a Reference Diode All of the resistors (R2, R3, and R4) are relative to a calculated resistor Ri, which is the resulting resistance of the paralleled resistors R2 and R3. The value of Ri depends on the input offset current (Ioff) of the operational amplifier and the maximum tolerable error voltage (Ue) caused by loff. The maximum value of Ri is calculated first: Ri < Ue Ioff With the calculated value of Ri, the three resistors (R2, R3, and R4) are calculated next: R4 = R·X( VTH+XVml Vref X (vTH+-VTH-) 1) On-Chip Peripherals 6-275 The RESET Function R2 = RiX( Vref V77i+ X(1 Ri +1\ ) R4 ) Example 6-57. RESET Circuit" A RESET circuit similar to that shown in Figure 6-69 is built with the following behavior: RST/NMI is Vss for Vee <2.5 V RSTINMI is Vee for Vee> 3 V Vref= 1.25 V loffmax = ± 200 nA (maximum offset current of the inverting input) Maximum voltage error due to loff: ± 150 mV Ri < 150mV ~ Ri < 0.75Mo. 200nA 0.75Mo. R4 X( 3V x 2.5V ;\ 1.25V x (3V -2.5V) J x f-) \1 _ +J\ 1 R3 = O.75Mo. 9Mo. . = 137Mo. 1.25V X (0.75Mo. 3V 9Mo.) R2 = 0.75Mo. x ( 1 1.25V x (0.75Mo. + 1\ 3V 9Mn ') ) = 1.67Mo. Figure 6-70 illustrates the connection of an operational amplifier with an output voltage higher than Vee (here the unregulated voltage Vcl to the MSP430 RSTINMI terminal. The diode protects the RST/NMI terminal and resistor Rrst provides the positive voltage. 6-276 The RESET Function Non-regulated Voltage +3V >+----.......-'''-'-1 VoHage Regulator Vee MSP...-*..-..... =-1 RSTINMI \/lei AD Figure 6-70. RESET Generation With a Comparator 6.6.3.4 Supply Voltage Supervisors The use of a supply voltage supervisor is one of the best methods of getting a reliable RESET signal. All necessary parts such as reference, programmable delay, output stage, and so on are integrated in a single IC. Only a few external components are necessary. Two different solutions are explained: o o The TL770x supply voltage supervisor. The TP3750 supply voltage supervisor and regulator. This IC integrates two functions: supply voltage regulation, and supply voltage supervision. 6.6.3.4.1 TL7701 Supply Voltage Supervisor The schematic for a supervised MSP430 is shown In Figure 6-71. The TLC7701 is programmed with the resistors R1 and R2 to reset the MSP430 when the output voltage of the 5-V regulator falls below VCCmin (2.5 V). +5V Vout Vee RSTINMI MSP= RS? Yes, no overflow Transition from OFFh to 0 occured, read actual MSB; it now has the correct (value + 1). L$1 MOV.B &TPCNT2,R6 Read actual MSBs DEC.B R6 MSB - 1 is correct SWPB R6 MSBs to high byte ADD RS,RS Build 1S-bit value in RS yyxx OOyy yyOO On-Chip Peripherals 6-283 The Universal Timer/Port Module , 6.7.2.2 Pulse Width Modulation Mode Figure 6-76 shows the generation of low frequency PWM with the Universal Timer/Port module. If the ACLK is used for the timing, then two PWM outputs with up to 256 Hz are possible. The software is-described in the paragraph PWM Digital-to-Analog Converter with the Universal Timer/Port Module of section Digital-ta-Analog Converters. OFFh ) - - - - : ; ; r - - - . : " j - - - - : * - - 7 i - - - - 4~---r--~---_r-~~---- Oh+------4----+-------+---r--------Output RC2FG RC2FG RC2FG RC2FG Intenupts Figure 6-76. Low Frequency PWM Timing Generated With the Universal Timer/Port Module . 6-284 The Crystal Bu~~r Output 6.8 The Crystal Buffer Output This is a relatively simple module, but it can be very helpful. It allows the use of frequencies generated by the MSP430 for external modules without any influence to the accuracy of the crystal. Figure 6-77 shows an application with two MSP430s. The right side MSP430 uses the buffered crystal output - @ 32 kHz - of the left side MSP430. This allows both to be run with the accuracy of a crystal controlled oscillator, but only one crystal is necessary. The right side MSP430 uses the XBUF terminal for the output of the MCLK frequency to drive an external ASIC. 32kHz Xin 32kHz 10 Peripherals Xout XBUF 32kHz Xin XBUF 3.2MHz ClK ASIC Xoul AI On Data 16 Port2..3 MSP43OC32x AO Vss PortO Ports Peripherals MSP430 ontral Vee 8 PortO COM SEl _ _ [§E] 3"'561.83"'56 Vss Figure 6-77. Two MSP430sRunning From the Same Crystal Only a single instruction is needed to implement the output of an internal frequency at the XBUF terminal: Hardware definitions for the Crystal Buffer CBCTL .equ 053h CBE .equ OOlh Enable XBUF output CBACLK .equ OOOh ACLK is output at XBUF ACLK/2 is output at XBUF Crystal Buffer Control Byte CBACLK2 .equ 002h CBACLK4 .equ 004h ACLK/4 is output at XBUF CBMCLK .equ 006h MCLK is output at XBUF ; Output the crystal frequency ACLK at pin XBUF On-Chip Peripherals 6-285 The Cry~!aI ~u"er Output MOY.B ; ACLK to XBUF pin #CBACLK+CBE,&CBCTL Output the half crystal frequency ACLK/2 at pin XBUF MOY.B #CBACLK2+CBE,&CBCTL ; ACLK/2 to XBUF pin Output the crystal frequency ACLK divided by four at pin.XBUF MOY.B #CBACLK4+CBE,&CBCTL ACLK/4 to XBUF pin output the MCLK frequency at pin XBUF MOV.B #CBMCLK+CBE,&CBCTL ; MCLK to XBUF pin As shown with the previous definitions, four different frequencies can be output at terminal XBUF. With the CBE bit, these four frequencies can be enabled or disabled. The four possible frequencies are: 0 MCLK The frequency of the system clock generator (DCO): 500 kHz t04MHz 0 ACLK The frequency of the crystal (normally 32768 Hz) 0 ACLKl2 The halved crystal frequency (normally 16384 Hz) 0 ACLKl4 The crystal frequency divided by 4 (normally 8192 Hz) , The crystal-buffer control byte CBCTL is a write-only byte. This means the rull information must always be written to it. The following code sequence provides an output of ACLK and not -as it is intended - to outputthe MCLK frequency: Switch off and on the MCLK at pin XBUF 6-286 MOV.B #CBMCLK+CBE,&CBCTL ; MCLK to XBUF pin BIC.B #CBE,&CBCTL MCLK off BIS.B #CBE,&CBCTL WRONG: ACLK is output NOT MCLK MOY.B #CBMCLK+CBE,&CBCTL ; CORRECT: MCLK on again Figure 6-78 shows an application with a DC/DC converter that is controlled by the output frequency of the XBUF terminal. The converter is driven with the frequency that fits best the actual status (8.192 kHz, 16.384 kHz or 32.768 kHz). The sequence starts with the high output frequency and steps down after the buildup of the voltage to the 8 kHz frequency. No software overhead is necessary for the generation of this frequency. 32kHz XIN XOUT Vet; OVo-! +6V -- 3V/1.6uA L Voltage Regul. CIN tJ RF-Antenna Vee HFModul TP.O TP.1 TP.2 Vss GND PO.O XBUF Mod. Modulation (Data) 32kHz/16kHz/8kHz MSP430C31x PO.4 PO.3 COM0-3 SEL 123'-1561.8 _ _ ITempl PO.112 LCD Figure 6-78. The Crystal Buffer Output Used for a DC/DC Converter On-Chip Peripherals 6-287 The USART Module 6.9 The USART Module The universal synchronous asynchronous receiveltransmit communication Interface (USART) - whose block diagram is shown in figure 6-79 - can work in two different modes: the asynchronous mode and the synchronous mode. This section describes the software routines usable for the asynchronous mode (SCI, RS232). Note: It is recommended to also consult the data book MSP430 Family Architecture Guide and Module Library. The hardware-relatef.! information given there is very valuable and complements the information given in this section. The examples and the hardware definitions shown use the addresses of the MSP430x33x. Future MSP430 family members may have different hardware addresses - especially for the I/O ports used. I The hardware features of the USART module substantially exceed the examples shown in this section. To get the USART running quickly, the UART mode is recommended, with or without the interrupt capability. The most often used features are included in the examples given. Figure 6-79 shows the block diagram of the MSP430 USART module. 6-288 The USART Module S NC URXD I 0 I I I STE ------ USART) On-Chip Peripherals 6-291 The USART Module URXD .equ OSOh Receive Input P4.7 UTXD .equ 040h Transmit Output P4.6 Low Power Mode bit 1 SCGl .equ OSOh SCGO .equ 040h Low Power Mode bit 0 CPUoff .equ OlOh Switches CPU off GIE .equ OOSh General Interrupt Enable Bit SCFQCTL .equ 052h FLL multiplier and M bit SCFIO .equ 050h FLL current switches FN_2 .equ 004h Switch for 2 MHz FN_3 .equ OOSh Switch for 3 MHz FN_4 .equ OlOh Switch for 4 MHz 6.9.1.2 MSP430 UART Attributes A short overview to the USART running in the UART mode is given below: o o 6-292 7-bit and 8-bit data length is selectable Error detection for the receive path: • Frame error. The stop bits have space potential. • Parity error. Parity is enabled and the parity bit has the wrong value. • Overrun error. The next character is read in before the last one is read out by the software. • Break detect. The URXD terminal has low potential for more than 10 bits o Baud rate generation possible also from 32 kHz crystal due to the modulation register o o o o Interrupt-driven transmit and receive functions Two independent interrupt vectors. one for transmit and one for receive Full functionality also during LPM3 End-of-frame flag usable with interrupt or polling The USART Module 6.9.1.3 Data Format The RS232 data format is used. Figure 6-81 shows how this format is seen at the MSP430 ports (URXD and UTXD) and Figure 6-82 how it is defined on the transmission line. The format shown in Figures 6-81 and 6-82 is: o Seven data bits. The least significant bit follows the start bit o o o Parity enabled. The parity bit follows the most significant bit of the data No address bit. This is the normal case Two stop bits Name Signal Level Data Vee Mark SlOP BIIs Space OV Figure 6-81. The RS232 Format (Levels at the MSP430) The signal on the transmission line has the inverted state as seen at the MSP430 ports and different voltage potentials. Figure 6-82 shows this. Name Signal Level Data >+3V Slop BIIs I c-3V Figure 6-82. The RS232 Format (Levels on the Transmission Line) 6.9.1.4 UART Hardware Registers The USART is controlled by seven control registers and one read-only register. All are 8-bit registers and therefore should be accessed only with byte instrucOn-Chip Peripherals 6-293 The USART Module tions. Figure 6-83 gives an overview to these eight registers including the names, assembler mnemonics, hardware addresses and the initial states. The register and bit (:Iefinitions are contained in Section 6.9.1. Register Name Mnemonic Register Access USAIITConInII Regleler Tranllllll eon..... Reg_ _01.. COntrol Regleler Modulalton COntrol Reg. Baud _ Regl_ 0 UCTL UTCTL URCTL UMCTL UBRO UBRI URXBUF UTXBUF Baud RateReg"'r I ReceIve Butrer Tranarnft B _ UCTl 070h 1 1 1 1 1..-1 PENA rw-O UTCTL 071 SP CHAR rw-O rw-O rw-o SYNC tw-o _no - _rite _001, 1 MM rw-o ISWRSTI rw-l rw-O rw-0 rw-D rw-o rw-o rw-o rw-1 UBRO 074h UBRI 07511 UMCTL 07311 ,216 I. 2' 1 2· 12' 12' 12' 1 221 2' 12· r r t r UTXBUF 077h unchanged unchanged uncIIanged ~ ~ 2'4 ( 2'3 M tw M ~ M M I I I I I 2'2 M 28 2'0 2; tw 28 M tw Im'I~I~Im4I~I~lm'l~ M 076h M I I M 072h 8eobelow S8ebeloW 8eobeloW unchanged unchanged 12' 1 2' 12' 12' 12' 1 221 2' 1 2· ~ URCTL URXBUF Initial State 07Qh 071h 072h 073h 074h 076h 07eh 077b -- I"""".IO..L1SSEL1 ISSELO IURXSEITXWakeI""-ITXEPT1 rw-O h PEV rw-O Address _no _no Reod/Wrno M tw tw I' I I I . 2 2° 25 24 IWlWrwrvt tw M 1 2' 1 M rw tw 1 tw 22 1 2' 1 2· rtf rw Figure 6-83. USART Control Registers Used for the UART Mode 6.9.2 Baud Rate Generation To generate the desired baud rate from a relatively high frequency (1 MHz to 5 MHz) is a simple task. The resulting baud rate error is small due to the large integer part of the quotient compared to the truncated fractional part. This changes completely if the timebase is a crystal of only 32 kHz. Then the error due to the truncated fractional part of the quotient gets large and leads to the loss of synchrony at the trailing bits of the frame. The MSP430 USART therefore uses a correction to keep the baud rate error small. The modulation register, UMCTL, contains 8-bit data to correct the baud rate of the received or transmitted UART signal. The bits define how the predivider information contained in the two baud rate registers UBRO and UBR1 is used: 6-294 o A 0 bit in the UMCTL register means that the information contained in UBR1/UBRO is used as is. o A 1bit means thatthe 16-bit content of UBR 1/UBRO is incremented by one and used with this value. The content of UBR1/UBRO is not changed. The USART Module o UCLK 7 0 7 ...------, Start ,>--OI...IC~ Compare 0 or 1 BITCLK Start ~ BRCLK~ Counter BITCLK~ Divide by I nI2 In/2-1In12-21 1 0 1 nl2 n/2-1 1 1 1 n/2 In/2-1In/2-21 1 1 nI2 In/2-11n12-21 ~ .y'~'---I..--IN-T-(n-/2-),-m-=-oINT(n/2)+m(-1) 121110lnl21 I I 1 1 0 1 nl2 InI2-11 1 1 n/2 In/2-1In/2-21 I n(even), m=o-1 n (odd) or n(even)+m(c1) n(odd)+m(-l) l1li_II1II1 - - - - 1 1 Figure 6-84. The Baud Rate Generator The LSB (mO) of register UMCTL is used for the start bit, the next bit (m 1) is used for the LSB of the data, and so on. After the use of bit m7, the bit sequence mO to m7 is used again. See figure 6-85 for an explanation. Example 6-58. 4800 Baud from 32 kHz Crystal The baud rate of 4800 is needed from a crystal frequency of 32,768Hz. This is necessary because the UART also needs to run during the low power mode 3. With only the ACLK avail!!ble, the theoretical division factor - the truncated value is the content of the baud rate register UBR (UBR1/UBRO) - is: On-Chlp Peripherals 6-295 The USART Module UBR = 32768 4800 = 6.82667 This means the baud rate register, UBR1, (MSBs) is loaded with 0 and the UBRO register contains 6. To get a rough value for the 8-bit modulation register, UMCTL, the fractional part (0.826667) is multiplied by 8 (the number of bits in the register UMCTL): UMCTL = 0.82667 x 8 = 6.613 The rounded result, 7, is the number of 1s to be placed into the modUlation register, UMCTL. The resulting, corrected baud rate with the UMCTL register containing seven 1s is: BaudRate This results in an average baud rate error of: · E 4766.2545-4800 100 B a udR aterror= x 4800 = -0.703% To get the bit sequence for the modulation register, UMCTL, that fits best, the following algorithm can be used. The fractional part of the theoretical division factor is summed eighttimes and if a carry to the integer part occurs, the actual m-bit is set. Otherwise it is cleared. An example with the above fraction 0.82667 follows: FractIon AddItIon Carry to next Integer UMCTL Bits 0.82667 + 0.82667 = 1.65333 Yes mO 1 1 1.65333 + 0.82667 =2.48000 m1 Yes 1 2.48000 + 0.82667 =3.30667 m2 Yes 3.30667 + 0.82667 =4.13333 1 Yes m3 4.13333 + 0.82667 = 4.96000 o No m4 4.96000 + 0.82667 =5.78667 Yes m5 1 5.78667 + 0.82667 =6.61333 Yes m6 1 6.61333 + 0.82667 = 7.44000 Yes m7 1 The result ofthe calculated bits m7.•.mO (11101111b) is EFh with seven 1s.ln Section 6.9.3.3.2, a software macro (CALC_UMCTL) is contained that uses the algorithm shown above. It calculates for every combination of the USART clock and the desired baud rate, the optimum value for the modulation register, UMCTL. For the above example, the algorithm also finds EFh with its seven 1s. 6-296 The USART Module A second software macro (CALC_ USR) calculates the values for the two USR registers. Example 6-59. 2400 Baud From 32 kHz ACLK Figure 6-85 gives an example for a baud rate of 2400 generated with the ACLK frequency (32,768 Hz). The data format for figure 6-85 is: Eight data bits, parity enabled, no address. bit, two stop bits. Figure 6-85 shows three different frames: o The upper frame is the correct one with a bit length of 13.65333 ACLK cycles (32,76812400 = 13.65333) o The middle frame uses a rough estimation with 14 ACLK cycles for the bit length o The lower frame shows a corrected frame using the best fit (60h) for the modulation register. It can be seen that the approximation with 14 ACLK cycles accumulates an error of more than 0.3 bit length after the second stop bit. The error of the corrected frame is only 0.011 bit length. The error of the crystal clock is not yet included, but it adds to the above errors. Precise Timing Start Bit LSB 1UG 13.15 13.85 13.85 13.85 13.85 13.85 13.85 MSB Parity Bit 13.85 13.85 Stop BIt(s) 13.85 13.85 Rough Approxlmatton I Start Bit LSB 14 14 14 14 14 14 14 MSB Parity Bit 14 14 14 -..oJ ~or 14 Corrected Timing UMCTL Bits (8Dh) Vco I OV I Stop BIt(s) 14 I Start Bit LSB 14 13 14 14 13 14 14 13 rna rnl a rn2 rn3 rn4 rn5 rn6 rn7 rna 1 1 0 1 1 0 1 1 MSB Parity Bit 14 Stop Blt(S) 13 14 14 rnl rn2 rn3 0 1 1 - ~ Error Figure 6-85. Baud Rate Correction Function On-Chip Peripherals 6-297 The USART Module Tables 6-33 and 6-34 contain the average errors (full frame) for the normally used baud rates when produced with the described baud rate generation. The software examples contain software MACROs that automatically insert the correct values for the UBR registers and the modulation register, UMCTL. The software MACROs - that do not need ROM or RAM - may be hidden in the listing by a .mnolist assembler directive. See Section 6.9.3.3.2. 6.9.2.1 Baud Rate Generation With the MCLK Table 6-33 shows the optimum values for the UBR and UMCTL registers. The UART clock is the MCLK (1,048 MHz). The values for the UMCTL and UBR1/UBRO registers are calculated by the software MACROs In Section 6.9.3.3.2. The crystal error is not included. Table 6-33 contains the following columns: Baud Rate - The baud rate for the data exchange (transmit and receive use the same baud rate) Division Factor - The quotient UARTCLKlbaud rate UBR11UBRO Content - The truncated 16-bit hexadecimal result of the division factor (UARTCLKlbaud rate). The value is calculated by the software macro CALC_UBR. The high byte is the UBR1 value, the low byte is the UBRO value Calculated UMCTL Content - The 8-blt result that fits best for the modulation register. It is calculated by the software macro CALC_UMCTL. Used Fraction - The number of 1s in the Modulation Register divided by eight. It is an approximation to the truncated fractional part of the division factor. Mean Error - The resulting error of a complete character caused by the approximation to the division factor 6-298 The USART Module Table 6-33. Baud Rate Register UBR Content (MCLK = 1,048 MHz) BAUD RATE DIVISION FACTOR UBR1IUBRO CONTENT CALCULATED UMCTL CONTENT FRACTION USED MEAN ERROR(%) +0.000 110 9532.51 253Ch 55h 0.5 300 3495.25 OOA7h 44h 0.25 0.000 600 1747.63 06D3h 60h 0.625 +0.000 '-0.007 1200 873.81 0369h EFh 0.875 2400 436.91 01B4h FFh 1.000 -0.002 4800 218.45 OOOAh AAh 0.50 -0.023 9600 109.23 006Dh 88h 0.25 -o.Q18 19200 54.61 0036h AOh 0.625 -0.027 38400 27.31 00lBh 24h 0.25 +0.220 On-Chip Peripherals 6-299 The USART Module 6.9.2.2 Baud Rate Generation With the ACLK With the relatively low ACLK frequency (32,768 Hz), the modulation register UMCTL becomes much more important compared to the normally high MCLK frequency used for the UART timing. Table 6-34 shows the optimum values for the UBR and UMCTL registers for commonly used baud rates generated with the ACLK (32,768 Hz). The table values are calculated by the MACROs described in Section 6.9.3.3.2. The crystal is considered to be without frequency error. The table columns are described in Section 6.9.2.1. Table 6-34. Baud Rate Registers UBR Content (ACLK = 32,768 Hz) BAUD RATE 6-300 DIVISION FACTOR UBR1IUBRO CONTENT CALCULATED UMCTL CONTENT FRACTION USED MEAN ERROR(%) -0.04 110 297.8909 0129h FFh 1.00 300 109.2267 0060h 88h 0.25 -0.02 600 1200 54.6133 0036h AOh 27.3067 001Bh 24h 0.625 025 -0.02 +0.21 2400 13.6533 ooOOh 60h 0.625 +0.21 4800 6.8267 0006h EFh 0.875 -0.71 4Ah 0.375 +1.12 9600 3.4133 0003h 19200 1.7067 - 38400 0.8533 - The USART Module 6.9.3 Software Routines The following sections show proven software routines, subroutines, and software MACROs for the UART mode of the USART. Note: The program sequence for the initialization ofthe UART is important. As long as the SWRST bit (UCTL.O) is set, the receive and transmit control registers URCTL and UTCTL cannot be initialized. The program sequences given in the software examples comply with this fact and are therefore recommended. As long as the SWRST bit is set, the following control bits are held in the 0 state: TXWAKE, RXERROR, RXWAKE, BRK, OE, FE, PE, URXIFG, URXIE, UTXIE. , The following control bits are held in the 1 state: UTXIFG, TXEPT 8.9.3.1 Nonlnterrupt Processing The simplest way to use the USART is in the UART mode. The interrupt is not enabled, the software checks if it is possible to output the next byte (UTXIFG = 1) and it checks if a new character is received (URXIFG = 1). Example 6-60. Full Duplex Modem A full duplex UART software running without the use of the UART interrupt is shown. It is designed for: 0 Baud rate: 1200 baud 0 The MCLK (1.048 MHz) is used for the UART clock 0 Eight data bits 0 Two stop bits 0 Parity enabled with odd parity 0 Receive of errorfree characters only STACK .equ 0600h ; Stack start address Definitions for the UART part: user defined On-Chip Peripherals 6-301 The USART Module Baudr .equ 1200 Baudrate is 1200 Baud FLLMPY .equ 32 FLL multiplier for ·1,048MHz UARTCLK .equ FLLMPY*3276B MCLK is used for UARTCLK The content for the UMCTL and UBR registers are calculated. The two software macros do not use RAM or ROM, they only define the variables CUMCTL, CUBRI and CUBRO for the UART registers UMCTL, UBRI and UBRO INIT CALC_UMCTL Calc, Modulation Reg. content CALC_UBR Calculate UBRI/UBRO contents . text Software start address MOV #STACK,SP CALL #INITSR Initialize Stack Pointer Init. FLL and RAM Proceed with initialization Initialize the UART: Odd parity, B data bits, 2 stop bits MCLK for UART clock MOV,B #CUMCTL,&UMCTL Modulation Register MOV.B #CUBRO,&UBRO Baud Rate Register low MOV.B #CUBRl,&UBRl Baud Rate Register high BIS,B #URXD+UTXD,&P4SEL Select RXD + TXD at Port4 BIS.B lIUTXE+URXE,&ME2 Enable USART Moduls MOV,B lIPENA+SP_+CHAR,&UCTL ; USART Control Register MOV.B tSSELl+SSELO,&UTCTL ; Transmit Control Reg. MCLK MOV.B 1I0,&URCTL Receive Control Register Continue with initialization MAINLOOP Start Mainloop UART parts within the mainloop. The software checks these two parts regularly. UART Receive part: 6-302 The USART Module check if a new character is received R7 contains the received information. BIT.B #RXERR,&URCTL JZ L$3 Error during receive? No Error handling L$3 BIC.B #FE+PE+OE+BRK+RXERR,&URCTL ; Clear error flags JMP L$2 ; Cpntinue in mainloop BIT.B #URXIFG,&IFG2 JZ L$2 No, proceed in mainloop MOV.B &URXBUF, R7 , Yes, move character to R7 L$2 Character received? Continue in mainloop UART Transmit part: check if the next character can be transmitted. R6 contains information to be transmitted. BIT.B #UTXIFG,&IFG2 JZ L$l No, wait MOV.B R6,&UTXBUF Empty: move info to TX buffer MOV.B src,R6 L$l Transmit buffer empty? Next character to R6 Continue with mainloop BR #MAINLOOP End of mainloop Interrupt vectors .sect "INITVEC",OFFFEh Reset Vector .word INIT Program Start Address If the above software is to be used with the ACLK for the UART clock, then only the following two source lines need to be modified: UARTCLK .equ 32768 ; ACLK is used for UARTCLK MOV.B #SSELO,&UTCTL ; Transmit Control Register ACLK All other necessary modifications are made automatically by the macros CALC_UMCTL and CALC_UBA. On-Chip Peripherals 6-303 The USART Module 6.9.3.2 Interrupt Processing This is the normal mode for the use of the UART. Interrupt is requested if the general interrupt enable bit GIE (SR.3) is set and . o A character is transmitted and the transmit interrupt is enabled (IE2.1 = 1) or o A character is received and the receive interrupt is enabled (IE2.0 = 1) Note: If an error occurred during the reception of a character, then the error flags of the Receive control register (PE, FE, BRK, and RXERR) must be reset within the UART interrupt handler. Otherwise, the set error flags will block the next interrupt. This is not the case for the overrun error flag OE. I 6.9.3.2.1 MCLK Used tor the UART Clock The following example is for when the MCLK is used for the generation of the UART clock or for external frequencies in the MCLK range (500 kHz to 3.8 MHz). For high baud rates - higher than 38400 baud - dedicated CPU registers may be necessary to lower the interrupt overhead. The time for the saving and restoring of the register is not necessary. The software example shown in Section 6.9.3.2.2 uses dedicated registers. Example 6-61. Full Duplex UART Full duplex UART software using the two UART interrupts is shown. It is designed for: o o o o o o Baud rate: 19200 baud The MCLK (3.144 MHz) is used for the UART clock Seven data bits One stop bit Parity enabled with even parity Receive of errorfree characters only Transmit Part - the start address xxxx is loaded into the pointer TXPOI and the number of characters to be output is loaded into the character count 6-304 The USART Module TXCNT. The interrupt routine outputs the programmed character sequence starting at address xxxx. Receive Part-the start address yyyy of a RAM buffer is loaded into the pointer RCPOI and the number of characters to be received is loaded into the character count RCCNT. The interrupt routine receives the characters and stores them into the buffer. Only error-free characters are accepted. STACK .equ 0600h ; Stack start address Definitions for the UART part Baudr .equ 19200 FLLMPY .equ 96 FLL multiplier for 3,144MHz UARTCLK .equ FLLMPY*32768 MCLK is used for UARTCLK . even Baudrate is 19200 Baud Word boundary .bss TXPOI,2 Pointer to transmit buffer .bss RCPOI,2 Pointer to receive buffer .bss TXCNT,l Counter/status for transmit .bss RCCNT,l Counter/status for receive The content for the UMCTL and UBR registers are calculated The two software macros do not use RAM or ROM INIT CALC_UMCTL Calculate Mod. Reg. content CALC_UBR Calculate UBRI/UBRO contents . text Software start address MOV #STACK,SP CALL UNITSR Initialize Stack Pointer Init. FLL and RAM Proceed with initialization Initialize the UART: Even parity, 7 data bits, 1 stop bit MCLK for UART clock, only errorfree characters to URXBUF MOV.B #CUMCTL,&UMCTL Modulation Register On-Chip Peripherals 6-305 The USART Module MOV.B #CUBRO,&UBRO Baud Rate Register low MOV.B #CUBRl,&UBRl Baud Rate Register high BIS.B #URXD+UTXD,&P4SEL Select RXD +·TXD at Port4 BIS.B #UTXE+URXE,&ME2 Enable USART Moduls MOV.B #PENA+PEV,&UCTL USART control Register MOV.B #SSELl+SSELO,&UTCTL ; Transmit Control Reg. MCLK MOV.B #O,&URCTL BIS.B #UTXIE+URXIE,&IE2 Enable USART interrupts CLR.B TXCNT Disable transmit CLR.B RCCNT Receive Control Register Disable receive Continue with initialization EINT Enable interrupt MAINLOOP Start of Mainloop Preparation for the reception of m bytes. The input buffer starts at address yyyy TST.B RCCNT JNZ L$l No, wait MOV #yyyy, RCPOI Buffer start address to RCPOI MOV.B #m,RCCNT L$l Data input completed? Number of bytes to RCCNT Continue in mainloop Stop the reception of data. The currently received character is input completely CLR.B RCCNT status to zero Continue Preparation for the transmission of n bytes starting at address xxxx. A check is made if the last transmit operation is really completed. 6-306 BIT.B #TXEPT,&UTCTL Transmit part ready? JZ L$2 No, buffers are not yet empty The USART Module MOV.B #n-l,TXCNT MOV #xxxx+l,TXPOI Ready, init. byte count Init. transmit buffer pointer MOV.B xxxx,&UTXBUF First info byte to TX buffer continue in background L$2 stop the transmission of data. The currently sent character is transmitted completely CLR.B TXCNT Status to zero Interrupt Handlers Interrupt handler for the UART Receive part. RCINT RCRET TST.B RCCNT JZ RCRET Reception allowed? No, status is 0 BIT.B #RXERR,&URCTL Error during receive? JNZ RCERR Yes DEC.B RCCNT No, Byte count -1 PUSH R5 Save R5 MOV RCPOI,R5 Pointer to buffer MOV.B &URXBUF,O(R5) Next byte to buffer INC RS To next buffer byte MOV R5,RCPOI Update pointer POP R5 Restore R5 RET I RCERR ; Error handling BIC.B #FE+PE+OE+BRK+RXERR,&URCTL ; Clear error flags RETI Interrupt handler for the UART Transmit part. TXINT TST.B TXCNT Something to transmit? JZ TXRET No, buffer is empty On-Chip Peripherals 6-307 The USART Module TXRET DEC.B TXCNT PUSH R5 Byte count -1 MOV TXPOI,R5 Pointer to buffer· MOV.B @R5+,&UTXBUF Next byte for output. MOV R5,TXPOI Update pointer POP R5 RETI Interrupt vectors . sect "SCIVEC",OFFECh USART Interrupt Vectors . word TXINT Transmit Vector .word RCINT Receive Vector .sect "INITVEC",OFFFEh Reset Vector . word INIT Program Start Address 6.9.3.2.2 ACLK Used for the UART Clock The following example is for when the ACLK is used for the generation of the UART clock or for extemal frequencies lower than 100 kHz. It is very similar to that of Section 6.9.3.2.1. The ACLK can also be used as the UART clock. See that section for details. This section shows another approach, however. The CPU is normally off and leaves the LPM3 only when the programmed number of received or transmitted characters is reached. Example 6-62. Full Duplex UART With Interrupt Full duplex UART software using the UART interrupt is shown. II is designed for: o o o o o o o 6-308 Baud rate: 2400 baud The ACLK (32,768 Hz) is used for the UART clock Eight data bits Two stop bit Parity enabled with odd parity Receive of errorfree characters only The CPU normally uses the low power mode 3 (LPM3) The USART Module ¥¥ Transmit Part - the start address xxxx of the output sequence is loaded into the pOinter TXPOI and the number of characters m is loaded into the character count TXCNT. The interrupt routine outputs the character sequence and when TXCNT reaches 0 (output completed), it resets the CPUoff bit of the stored status register on the stack. This manipulation omits the return to LPM3 and initializes the next transmit sequence. R6 is exclusively used for the transmit part. Receive Part - the start address yyyy of a RAM buffer is loaded into the pointer RCPOI and the number of characters n is loaded into the character count RCCNT. The interrupt routine receives the characters and stores them in the buffer until RCCNT reaches 0 (input completed). Then it resets the CPUoff bit of the stored status register on the stack. This manipulation omits the return to LPM3 and allows the processing of the received data. Only errorfree characters are accepted. R7 is exclusively used for the receive part. STACK .equ 0600h ; Stack start address Definitions for the UART part Baudr .equ 2400 Baudrate is 2400 Baud FLLMPY .equ 64 FLL multiplier for 2,096MHz UARTCLK .equ 32768 ACLK is used for UARTCLK .bss TXCNT,l· counter/status for transmit .bss RCCNT,l Counter/status for receive INIT CALC_UMCTL Calculate Mod. Reg. content CALC_UBR Calculate UBRI/UBRO contents . text Software start address MOV #STACK,SP Initialize Stack Pointer CALL #INITSR lnit. FLL and RAM Proceed with initialization Initialize the UART: Odd parity, 8 data bits, 2 stop bits ACLK used for the UART clock MOV.B lICUMCTL,&UMCTL Modulation Register On-Chip Peripherals 6-309 The USART Module MOV.B iCUBRO,&UBRO Baud Rate Register low MOV.B *CUBRl,&UBRl Baud Rate Register high BIS.B iURXD+UTXD,&P4SEL Select RXD + TXD at Port4 BIS.B #UTXE+URXE,&ME2 Enable USART Moduls MOV.B #PENA+SP_+CHAR,&UCTL ; USART Control Register MOV.B #SSELO,&UTCTL Transmit Contr. Reg. ACLK MOV.B #O,&URCTL Receive Control Register BIS.B #UTXIE+URXIE,&IE2 Enable USART interrupts CLR.B TXCNT Disable transmi·t CLR.B RCCNT Disable receive Continue with initialization EINT Enable interrupt (GIE MAINLOOP = 1) Start Mainloop Preparation for the reception of m bytes. Buffer starts at address yyyy. R7 is a dedicated register for receive TST.B RCCNT JNZ L$l Ready? No, RCCNT > MOV #yyyy,R7 Receive buffer start address MOV.B #m,RCCNT Number of bytes ° L$l stop the reception of data. The actually received character is input completely CLR.B RCCNT Status is zero Preparation for the transmission of n bytes starting at address XXXX .• R6 is a dedicated register for transmit. The check for the empty TX buffer is faster, but needs more ROM bytes. TST.B 6-310 TXCNT Ready for next characters? The USART Module ° JNZ L$2 No, TXCNT > BIT,B #UTXIFG,&IFG2 TX part also ready? JZ L$2 No, busy MOV,B #n-l,TXCNT Ready, init, byte count MOV #xxxx+l,R6 Init, transmit buffer pointer MOV,B XXXX,&UTXBUF First info byte to TX buffer L$2 Continue in background Stop the transmission of data, The actually sent character is transmitted completely CLR,B TXCNT Status is zero After the completion of all tasks, the program enters LPM3 PLPM3 BIS #CPUoff+GIE+SCGl+SCGO,SR Enter LPM3 An interrupt handler cleared the CPUoff bit on the stack., Checks are made if activity is needed: Receive: Transmit: receive input buffer full transmit buffer output completely other interrupt handlers TST,B RCCNT Receive completed? JZ PROCRC Yes, process received data TST,B TXCNT Transmit completed? JZ NXTTX Yes, prepare next characters Other handlers? JMP PLPM3 Back to LPM3 Interrupt Handlers Interrupt handler for the UART Receive part, R7 is used only for the receive part On-Ch/p Peripherals 6-311 The USART Module RCINT RCRET TST.B RCCNT JZ RCRET Reception allowed? No, status is BIT.B #RXERR,&URCTL Error during receive? JNZ RCERR Yes DEC. B RCCNT Byte count -1 ° MOV.B &URXBUF,O(R7) Next byte to buffer INC R7 To next buffer byte TST.B RCCNT Buffer filled? JNZ RCRET No, proceed BIC #CPUoff+SCGl+SCGO,O(SP) ; Active Mode after RETI RETI RCERR ; Error handling BIC.B #FE+PE+OE+BRK+RXERR,&URCTL ; Clear error flags RETI Interrupt handler for the UART Transmit part. R6 is used only for the transmit part TXINT TXRET TST.B TXCNT Something to transmit? JZ TXRET No, buffer is empty DEC.B TXCNT Byte count -1 MOV.B @R6+,&UTXBUF Next byte for output TST.B TXCNT Buffer output? JNZ TXRET No, proceed BIC #CPUoff+SCG1+SCGO,O(SP) ; Active Mode after RETI RETI Interrupt Vectors 6-312 .sect "SCIVEC",OFFECh USART Interrupt Vectors . word TXINT Transmit Vector . word RCINT Receive Vector .sect "INITVEC",OFFFEh Reset Vector . word INIT Program Start Address The USART Module 6.9.3.3 Subroutines and .MACROs The subroutines and assembler .MACROs used with the previous examples are contained in this section. 6.9.3.3.1 Subroutines The initialization subroutine INITSR -which is explained in detail in the section TimecA - checks first if a power-up clear (PUC) or a power-on reset (POR) has occurred: o o Power-Up Clear - the supply voltage is switched on, the RAM is cleared Power-On Reset - a reset occurred (RST/NMI terminal or by watchdog) the RAM is not changed The two situations are distinguished by the content of the word INITKEY. If it contains OF05Ah, the power-on reset state is assumed. Otherwise the powerup clear state is assumed. The subroutine selects the correct current switch FN_x for the system clock generator and waits 30000 clock cycles to ensure that it has locked at the correct oscillator tap. Common Initialization Subroutine Check the INITKEY value first: If value is OFOSAh: a reset occurred, RAM is not cleared otherwise Vcc was switched on: complete initialization INITSR INO CMP #OFOSAh,INITKEY PUC or POR? JEQ INO Key is ok, continue program CALL #RAMCLR MOV #OFOSAh,INITKEY Restart completely: clear RAM MOV.B #FLLMPY-l,&SCFQCTL ; Define MCLK frequency .if FLLMPY < 48 Use the right DCO current: MOV.B #O,&SCFIO MCLK < 1.SMHz: FN_x off .if FLLMPY < 80 1.SMHz < MCLK < 2.SMHz? MOV.B #FN_2,&SCFIO Define "initialized staten .else On-Chip Peripherals 6-313 The USART Module .else .if FLLMPY < 112 2.SMHz < MCLK < 3.SMHz? MOV.B #FN_3,&SCFIO Yes, FN_3 on #FN_4,&SCFIO MCLK. > 3.SMHz: FN_4 on Allow the FLL to settle .else MOV.B .endif .endif .endif IN1 MOV nOOOO,RS DEC RS at the correct DCO tap JNZ IN1 during 30000 cycles RET Return from initialization Subroutine for the clearing of the RAM block .bss INITKEY,2,0200h RAMSTRT .equ 0200h Start of RAM RAMEND .equ OSFEh Highest RAM address (33x) RAMCLR CLR R5 Prepare index register RCL CLR RAMSTRT(RS) 1st RAM address Next word address INCD RS CMP #RAMEND-RAMSTRT+2,RS JLO RCL RET 6-314 OFOSAh: initialized state ; RAM cleared? No, once more Yes, return The USART Module 6.9.3.3.2 .MACROs The following two software macros calculate the values for the UART baud rate generator that fit best. They do not use ROM or RAM - they only define the three variables CUBR1, CUBRO, and CUMCTL that are used during the initialization of the UART registers UBR1, UBRO, and UMCTL. .mnolist ; Do not list macro calls The values for the Modulation Registers UBR1jUBRO are calculated: CUBR1 and CUBRO contain the truncated result of the division UARTCLK/Baudr ; Baud Rate Reg. High CUBRl .equ UARTCLK/(Baudr*256} CUBRO .equ (UARTCLK/Baudr}-256*CUBRl ; Baud Rate Reg. Low .endm The calculation for the content of the Modulation Register UMCTL follows. Seven bits of resolution are used . . macro Modulation Register content: the rounded fraction of CMOD = UARTCLK/Baudr is calculated Binary format of CMOD: O.XXXXXXX Then the 8 bits of UMCTL are built. Inputs: UARTCLK, Baudr Frequencies [Hz] Output: CUMCTL 8-bit UMCTL register value CMOD .equ M$OO ««256*UARTCLK}/Baudr}-256*(UARTCLK/Baudr}}+1}/2 .equ CMOD+CMOD Fraction x 2 .if M$00>127 Overflow to integer? M$10 .equ M$00-128+CMOD Yes, subtract 1.000000 C$O .equ 1 UMCTL.O = 1 .else M$10 .equ M$OO+CMOD No, add fraction C$O .equ o UMCTL.O = 0 On-Chip Peripherals 6-315 The USART Module .endif .if M$10>127 M$20 .equ M$10-128+CMOD Overflow to integer? Yes, subtract 1.000000 C$l .equ 2 UMCTL.l = 1 M$20 .equ M$10+CMOD No, add fraction C$l .equ 0 UMCTL.l = 0 .if M$20>127 Overflow to integer? M$30 .equ M$20-128+CMOD Yes, subtract 1.000000 C$2 .equ 4 UMCTL.2 = 1 .else . end if .else M$30 .equ M$20+CMOD No, add fraction C$2 .equ 0 UMCTL.2 = 0 .if M$30>127 Overflow to integer? M$40 .equ M$30-128+CMOD Yes, subtract 1.000000 C$3 .equ 8 UMCTL.3 = 1 . end if .else M$40 .equ M$30+CMOD No, add fraction C$3 .equ 0 UMCTL.3 = 0 .endif .if M$40>127 Overflow to integer? M$50 .equ M$40-128+CMOD Yes, subtract 1.000000 C$4 .equ 10h UMCTL.4 = 1 .else M$50 .equ M$40+CMOD No', C$4 .equ 0 UMCTL.4 Overflow to integer? add fraction = 0 .endif .if M$50>127 M$60 .equ M$50-128+CMOD Yes, subtract 1.000000 C$5 .,equ 20h UMCTL.5 = 1 .else M$60 .equ M$50+CMOD No, add fraction C$5 .equ 0 UMCTL.5 .endif 6-316 = 0 The USART Module .if M$60>127 Overflow to integer? M$70 .equ M$60-12S+CMOD Yes, subtract 1.000000 C$6 .equ 40h UMCTL.6 - 1 .e1se M$70 .equ M$60+CMOD No, add fraction C$6 .equ o UMCTL.6 - 0 .if M$70>127 Overflow to integer? .equ SOh UMCTL.7 - 1 o UMCTL.7 - 0 .endif C$7 .else C$7 .equ . end if CUMCTL .equ C$7+C$6+C$5+C$4+C$3+C$2+C$1+C$0 Add bits .endm On-Chip Peripherals 6-317 The 8-8lt Interval Timer/Counter 6.10 The 8-Blt Interval Timer/Counter .6.10.1 Introduction The 8-Bit Interval Timer/Counter peripheral is included in all members of the MSP430x3xx family. This timer/counter - its block diagram is shown in Figure 6-86 - can work, like its name suggests, in two different modes: the timer mode and the counter mode. This section describes software routines usable for the UART mode (SCI, RS232) that use the timer mode of the 8-Blt Timer/ Counter. The software examples shown in the subsequent sections adapt themselves to the needs defined by the user (number of data bits, number of stop bits, baud rate, error detection and handling, clock frequency, and so on). This self-adaptation is accomplished through the use of the conditional assembly feature of the MSP430 assembler. The hardware of the 8-Bit Interval Timer/Counter module supports the receive and transmit of UART data on a bit basis: one data bit is received or transmitted between two interrupts, not a complete frame consisting of a start bit, data bits, a parity bit and stop bits. This means that the interrupt overhead is relatively large due to the interrupt request after each received or transmitted data bit. On the other hand, the advantage is the complete flexibility of the data format - only software defines the number and meaning of.the transferred bits. Any protocol is possible. Figure 6-86 shows the block diagram of the complete MSP430 a-Bit Interval Timer/Counter module. The 8-Bit Interval Timer/Counter module allows only the half duplex mode. This means that the module can receive data or it can transmit data, but not receive and transmit data simultaneously. The user software must therefore determine which mode should be active. In the following software examples, this is accomplished by the initialization subroutines. 6-318 The 8-Bit Interval Timer/Counter Receive L_"':::::'::4~=~ PO.l-BbT/C 1n1..rupl Lagle TCDAT 044h TCPLD 043h MDB Transmit Figure 6-86. MSP430 8-Bit Interval Timer/Counter Module Hardware 6.10.1.1 Definitions Used With the Application Examples The abbreviations used for the hardware definitions are consistent with the MSP430 Architecture User's Guide. HARDWARE DEFINITIONS a-BIT TIMER/COUNTER TCCTL .equ 042h T/C Control Register RXD .equ OOlh Receive signal at PO.l TXD .equ 002h Next data bit for transmission On-Chip Peripherals 6-319 The B-Bit Interval Timer/Counter RXACT .equ 004h 1: detect start bit ENCNT .equ 008h Counter TCDAT enabled 0: off, reset FF TXE .equ 010h 1: TXD to PO.2 ISCTL .equ 020h Intrpt source: 0: PO.1 SSELO .equ 040h Clock source. 0: PO.1 SSEL1 .equ 080h 1: MCLK TCPLD .equ 043h TIC 8-Bit Pre-load Register TCDAT .equ 044h TIC 8-Bit Counter 0: POOUT.2 to PO.2 2: ACLK 1: Carry TCDAT 3: PO.1 .and. MCLK OTHER DEFINITIONS IE1 .equ 0 Interrupt Enable Register 1 POIE1 .equ 8 PO.l Interrupt Enable Bit (RCV) POlES .equ O14h PO Interrupt Edge Select Register SCG1 .equ 080h Low Power Mode bit 1 SCGO .equ 040h Low Power Mode bit 0 CPUoff .equ 010h GIE .equ 008h "Switches CPU off General Interrupt Enable Bit 6.10.1.2 Attributes of B UART Implemented with the B-Blt TImer/Counter A short overview to the UART mode of the 8-Bit Timer/Counter module appears below: D Half duplex mode - either transmit or receive mode is possible, but not both simultaneously. o Any data length and format is possible. This is due to the software controlled data sequence. D Error detection made by software: 6-320 • Frame error - The stop bits have space potential or the start bit has mark potential in its middle • Parity error - Parity is enabled and the parity bit has the wrong value. • Overrun error - The next character is read in before the last one is read out by the software. This is not possible with the given software. The 8-Bit Interval Timer/Counter, o Baud rate generation possible from the MCLK (500 kHz through 3.3 MHz) .and from the ACLK signal (32,768 kHz crystal). o o Interrupt-driven transmit and receive functions. o o o One interrupt vector for transmit and receive mode. Mode selection is made by software. Full functionality also during LPM3 (with ACLK only) Restricted baud rate range due to the length of the 8-Bit counter register TCDAT One full bit length (1/baud rate) is available for the read out or modification of the data. The time window for the reception and transmission of data is significantly enlarged compared to a pure software solution. 6.10.1.3 The Data Format The data format used with the software examples Is the RS232 format. Figure 6-87 shows how this format is seen at the MSP430 ports (PO.1 for receive and PO.2 for transmit) and Figure 6-88 shows how it is defined for the transmission line between the transmitter and the receiver. The data format used with the Figures 6-87 and 6-88 is: o o o o Name Seven data bits. The least significant bit follows the start bit Parity enabled. The parity bit follows the most significant bit of the data No address bit. This is the normal case Two stop bits Data Signal Level Vee Mark Stop Bits Space OV Figure 6-87. RS232 Format (Levels at the MSP430) On-Chip Peripherals 6-321 The lJ.Bit InteNa/ Timer/Counter The signal on the transmission line has the Inverted state as seen at the MSP430 ports and different voltage potentials. Figure 6-88 shows this. Name Signal Level Data Stop Bits I <-3V Figure 6-88. The RS232 Format (Levels on the Transmission Line) 6.10.2 Function of the UART Hardware 6.10.2.1 The Hardware Registers The 8-8it Timer/Counter module is controlled by one control register and two data registers. All are 8-bit registers and should therefore be accessed only with byte instructions. Figure 6-89 and Table 6-35 show an overview of these three registers, including the names, assembler mnemonics, hardware addresses, and the initial states. The detailed function of the control bits is described in the MSP430 Architecture Guide and Module Library. Note: When a write access to the Counter Register TCDAT is performed, then the Information stored in the Preload Register TCPLD is loaded to TCDAT - and not the data addressed by the instruction. The data contained in TCDAT can be read at address 044h. Table 6-35. UART Hardware Registers INITIAL STATE REGISTER NAME MNEMONIC ACCESS ADDRESS TIC Control Register TCCTL ReadIWrtte 042h Reset TIC Preload Register TCPLD ReadIWrite 043h Unchanged TIC Counter Register TCDAT Read Only 044h Unchanged The B-Bit Interval Timer/Counter 0 TCCTL 042h SSELl rw-O SSELO rw-O ISCTL TXE ENCNT RXACT rw-O rw-O rw-O rw-O TXD rw-O RXD r(-1) 0 TCPLD 043h rw rw rw rw rw rw rw rw r(w) r(w) r(w) r(w) r(w) r(w) r(W) 7 TCDAT 044h r(w) Figure 6-89. UART Hardware Registers On-Chip Peripherals 6-323 The 8-BIt InteNsl Timer/Counter 6. 10.2.2 The Tl'Bnsmlt Mode If the 8-Bit Timer/Counter module is switched to the transmit mode - done by the initializing software of the module - then the hardware of figure 6-86 works as shown in Figure 6-90. Active data lines are drawn solid. nonactive data paths are drawn in gray color. The MCLK is selected for the UART timing. POIES.l PO.l l> .._,;.;.R';.;.ji~,-,=-J.;...---H.'tq Not acUvt; Half Ouplwr. *-==-_ L...._ _ _ MDB PO. 1 - BbT/C Interrupt Logic Figure 6-90. The B-Bit Timer/Counter Transmit Mode 6-324 The 8-Bit InteNal Timer/Counter Initialization for the transmit mode is done by the subroutine TXINIT. The main steps for the transmission of a character are: o loading of the data word RTDATA with the character to be transmitted, including the address bit information (if defined) o Initializing of the a-Bit Timer/Counter and the RAM bytes RTERR and RTSTAT • Selecting of the clock frequency for the counter TCDAT (MClK or AClK) (SSELx bits) • Activation of the interrupt request by the carry of the a-bit counter register TCDAT (ISCTl = 1) • Selecting of the TXD output data instead of the PO.2 output register data for the PO.2 pin (TXE =1) • Setting of the TXD bit to mark (1) (TXD = 1). This value is transferred to the TXD output with the first counter interrupt. It guarantees a leading mark signal of at least one bit time. • Enabling of the B-Bit Timer/Counter: the counter starts with the selected clock (ENCNT = 1) • loading of the counter with one half of a bit time. After this time interval, the TXD output is set to mark (1) if not yet set • loading of the pre-load register TCPlD with a full bit time interval (1 /baud rate). This time interval is used for the leading mark before the start bit • loading ofthe transmit status byte RTSTATwith the status for the start bit • loading of the error byte RTERR with a start value (0 resp. 1) that dalivers the correct parity bit of the complete character • Enabling of the interrupt for the B-Bit Timer/Counter. Interrupt is requested now approximately after each time interval 1/baud rate. This time can change from bit to bit. See Section 6.1 0.3 Baud Rate Generation and Correction. o loading of the TXD bit during the interrupt handler with the information of the next but one bit to be output (start bit, data bits, address bit, parity bit, stop bits) o o Sampling of the information for the parity bit, if parity is enabled. Output of the nondata Signals (start bit, parity bit, stop bits) dependent on the selected format On-Chip Peripherals 6-325 The 8081t inteNai Timer/Counter o Start Bh Turning off of the hardware after the complete output of a character, to save energy. LSB MSB 0$3 i i 0$4 0$5 (1 Used Correction Bit Figure 6-91. Interrupt Timing for the Transmit Mode 6-326 Stop Bltls) C$10 i i 0$11 (1 Disable UART Interrupt The 8-811 InleNsl Timer/Counter 6.10.2.3 The Receive Mode If the 8-Bit Timer/Counter module is switched to the receive mode - done by the initializing software of the module - then the hardware of Figure 6-86 works like shown in Figure 6-92. As with Figure 6-90, active data lines are drawn solid, nonactive data paths are drawn in gray color. The ACLK is used for the UART timing. POIES.l '------+i---- MOB PO.1·-SbTIC ln1efrupl Logic Edge detect MCLK > - - - _........._...- ....._....... ACLK Mse PO.2 S8 Figure 6-92. The B-Bit Timer/Counter in Receive Mode On-Chip Peripherals 6-327 The B-Bit InteNaJ Timer/Counter Initialization for the receive mode is done by the subroutine RCINIT. The main steps for the reception of a character are: 0 Initializing of the 8-Bit Timer/Counter and the RAM bytes RTERR and RTSTAT: • • • • • • Selecting the clock frequency for the counter (MCLK or ACLK) (SSELx bits) Activation ofthe interrupt request by the carry ofthe 8-bit counter Register TCDAT (ISCTL = 1) Reset of the edge-detect flip-flop (RXACT =0) Preparing of the a-Bit Timer/Counter to start with the next negative transition of the PO.1 input signal from mark to space (1 to 0). The counter starts with the selected clock signal (ACLK or MCLK) after the next negative transition. (POIES.1 = 1) Loading of the counter with one half of a bit time. (If an input signal change at PO.1 occurs from mark to space, then after this time interval an interrupt is requested and the start signal is checked In its middle if it is still iow (0).) Loading of the pre-load Register TCPLD with a full bit time interval (1/baud rate). This time interval is used for the test in the middle of the LSB • Loading ofthe receive status byte RTSTATwith the status for the start bit • Loading of the error byte RTERR with a start value that delivers 0 if the parity of the complete character is correct • • • • Enabling of the interrupt for the 8-Bit Timer/Counter. Interrupt is requested now approximately after the time interval 1/baud rate. This time changes slightly from bit to bit. See Section 6.10.3 Baud Rate Generation and Correction. Setting the data word RTDATA to O. Activation of the edge-detect flip-flop: it detects the negative edge of the start bit and starts the counter (RXACT = 1). Enabling of the UART interrupt (POIE1 = 1). 0 Reading of the RXD bit during the interrupt handler with the information of all bits (start bit, data bits, address bit, parity bit, stop bits). The read information is shifted into the data word RTDATA. 0 Sampling of the information for the parity bit, if parity is enabled. 6-328 The 8-Bit IntelVal Timer/Counter o Check of the nondata signals (start bit, parity bit, stop bits), dependent on the selected format o Selling of the error bits TCPE and TCFE dependent on the bit check. If no error occurred, the error byte RTERR contains 0 o Turning off of the timer/counter hardware after the complete reception of a character: interrupt and clock are switched off. I~I~I I II I II-H = ii i i i i i i i i i i i rJ Initialization C$O x 1/(2 Baud JJ tInwrrup, in C$1 Middl. 01111. StartBft C$2 C$3 C$4 Us.d C$5 C$6 (!ectlon Bft C$7 csa C$9 C$10 rJ ~ :~. C$11 UA£ i Lrrupt Interrupt Program Time Interval ts Figure 6-93. Interrupt Timing for the Receive Mode On-Chlp Peripherals 6-329 The B-Bit Interval Timer/Counter I L l • .,.,"'1/...... ., ~ • 6.10.3 The Baud Rate Generation and Correction The short counter register TCDAT of the 8-bit timer/counter allows the use of the MCLK for only very few baud rates. For aU other baud rates, the maximum value 255 for the quotient MCLKlbaud rate is exceeded. Therefore, the use of the ACLK (32,768 Hz) is necessary for most of the usual baud rates. But the use of the ACLK frequency causes another problem: Generating the desired baud rate from a relatively high frequency (1 MHz to 5 MHz) is a simple task. The resulting baud rate error is small due to the large integer part of the quotient compared to the truncated fractional part. This changes completely if the time base is a crystal of only 32 kHz. Then the error due to the truncated fractional part of the quotient grows large and leads to the loss of synchrony at the trailing bits of the frame. The MSP430 UART software therefore uses a correction to keep the baud rate error small. The baud rate correction calculates correction information· (9 to 13 bits, dependent on the frame length) as to how to correct the baud rate of the received or transmitted UART signal. The calculated bits C$O to C$12 define how the predivlder information contained in the baud rate registers TCPLD and TCDAT is used: o o C$x =0 - the calculated time interval is used as is. C$x = 1 - the calculated time interval Is prolonged by one timer period (MCLK or ACLK) and used with this value. The value C$O is used for the start bit, the value C$1 for the LSB of the data, and so on. See Figure 6-94 for an explanation. Example 6-63. Baud Rate Generation A baud rate of 2400 baud is needed from a crystal frequency of 32,768 Hz. The frame length used is the minimum length: start bit, seven data bits, no address bit, no parity, and one stop bit. This results in a frame length of nine bits. The use of the ACLK is necessary due to two reasons: o The UART also needs to run during the low power mode 3, when the MCLK is not available. o The maximum MCLK frequency would be 255 x 2400 =612 kHz. This frequency is too low for most of the applications (and cannot be guaranteed for the system clock generator). With only the ACLK available, the theoretical division factor UBR - the truncated value is the base for one of the two contents of the Pre-Load Register TCPLD-is: UBR 6-330 32768 2400 13.653333 The 8-Bit InteNal Timer/Counter This means - because the register counts upward - that the pre-load register TCPLD normally contains -13 (OF3h). To get a rough value for the 9-bit baud rate correction C$O to C$8, the fractional part (0.653333) of the above division is multiplied by 9 (the number of calculated bits for the baud rate correction): Number o/Ones = 0.653333 x 9 = 5.88000 The rounded result, 6, is the number of 1sto be used with the baud rate correction. The resulting, corrected, baud rate with the 6 1s of the baud rate correction is (6 bits have a length of 14 ACLK periods, 3 have a length of 13 ACLK periods): BaudRate 32768 2397.6585 This results in an average baud rate error of: Baud Rate Error = 2397.6585-2400 00 2400 xl -fJ.0975% To get the bit sequence for the baud rate correction that fits best, the following algorithm can be used. The fractional part ofthe theoretical division factor USR is summed nine times and if a carry to the integer part occurs, the current C$x bit is set. Otherwise, it is cleared. An example for the calculation of 9 bits with the above fraction (0.653333) follows: Fraction Addition 0.653333 + 0.653333 = 1.306667 1.306667 + 0.653333 = 1.959999 1.959999 + 0.653333 = 2.613332 2.613332 + 0.653333 = 3.266667 3.266667 + 0.653333 = 3.919999 3.919999 + 0.653333 = 4.573331 4.573331 + 0.653333 =5.226664 5.226664 + 0.653333 = 5.879997 5.879997 + 0.653333 .. 6.533333 Carry to next Integer Yes No Yes Yes No Yes Yes No Yes Correction Bits C$O C$1 (;$2 C$3 C$4 C$5 C$6 C$7 C$8 1 0 0 1 1 0 On-Chip Peripherals 6-331 The 8-B1t Interval Timer/Counter The result of the calculated bits C$8... C$0 (1 0110 1101b) is 16Dh with six ones. The software example contains a macro loop (starting at label MODTAB) that uses the algorithm shown above and calculates, for every combination of the UART clock and the desired baud rate, the optimum value for the baud rate correction. For the above example (9 bit frame length), the macro also determines 16Dh with its six ones. Example 6-64. 2400 Baud From ACLK Figure 6-94 gives an example for a baud rate of 2400 baud generated with the ACLK frequency (32,768 Hz). The data format for figure 6-94 is: Eight data bits, parity enabled, no address bit, and two stop bits. Figure 6-94 shows three different frames: o The upper frame is the correct one with a bit length of 13.65333 ACLK cycles. (32,768/2400 .. 13.65333) o The middle frame uses a rough estimation with 14 ACLK cycles for the bit length o The lower frame uses a corrected frame with the best fit (C$11 •.. C$O .. OB6Dh) for the baud rate correction. It can be seen that the approximation with 14 ACLK cycles accumulates an error of more than 0.3 bit length after the second stop bit. The error of the corrected frame is only 0.001 bit length. The error of the crystal clock is not yet included, and it adds to the above errors. . 6-332 The B-Bit Interval Timer/Counter Precise Timing Vco I Stsrt LSB Bit 13.85 13.116 13.116 13.85 13.116 13.116 13.116 13.15 MSB Psrlty Bit 13.85 13.116 Stop Bits 13.116 13.116 OV - I Rough Approxlmatlon Stsrt Bit LSB 14 14 14 14 14 14 14 14 MSB Parity Bit 14 14 I Stop Bits 14 14 ~ Corrected Timing Start Bit LSB 14 13 14 14 13 14 14 13 14 14 C$O C$1 C$2 C$3 C$4 C$5 C$6 C$7 C$8 C$9 Baud Rste Correction Bits (B6Dh) I ODh 13 C$10 o o 06h or I ~~or Stop Bits MSB Parity Bit o L 14 C$11 o OBh Figure 6-94. Baud Rate Correction Tables 6-36 and 6-37 contain the average errors (full frame with maximum length. 13 bits) for the normally used baud rates resulting from the described baud rate generation. The software examples contain a looped macro. It calculates - dependent on the frame length used - for all the bits the optimum length. 6.10.3.1 Baud Rate Generation With the MCLK Table 6-36 shows the optimum values for the 8-bit counter register TCDAT. The UART clock is the MCLK (1,048 MHz). The crystal error is not included. The mean error is calculated for a medium frame length of eleven bits: start bit, eight data bits, parity enabled, and one stop bit. Table 6-36 contains the following columns: o Baud Rate - The baud rate for the data exchange (transmit and receive use the same baud rate) o Division Factor - The quotient UARTCLKlbaud rate. It indicates the number of MCLK cycles for a data bit o a-Bit Counter Register - The truncated 8-bit hexadecimal result of the diviSion factor (UARTCLKlbaud rate). The value that is loaded into the hardware register TCDAT is (1 OOh -table value). This is duetothe upward count of the 8-bit counter. On-Chip Peripherals 6-333 The 8-Bit Interval Timer/Counter o Baud Rate Correction - The 13-bit result that fits best for the baud rate correction. It is calculated by the software macro starting at label MODTAB. If frames with less than 13 bits are used, then-the MSBs of this number are omitted. o Used Fraction - The number of 1s in the baud rate correction sequence divided by eleven (the frame length used for the calculation). It is an approximation of the truncated fractional part of the division factor. o Mean Error - The resulting error of a complete character caused by the approximation of the division factor The length of the 8-bit counter register allows only a very limited range for the baud rate. An MCLI< frequency of 1.048 MHz is assumed. For other frequencies, the baud rates change accordingly (e.g. for 2.096 MHz the usable baud rates are 960'1 and 19200 baud). The reasons for this restriction are: o From 110 baud to 2400 baud, the 8-bit counter register is too small to hold the necessary number for the result of the division MCLKlbaud rate: the number contained in the column 8-Bit Counter Register is greater than OFFh. o Beginning at 9600 baud, the CPU cycles between two UART interrupts are too few for correct handling (e.g. only 54 CPU cycles @ 1.048 MHz for 19200 baud). See Section 4.4. The maximum baud rate depends strongly on the amount of interrupt activity due to the other peripherals. Note: The assembler outputs an error message if the resulting value for the TCDAT register is greater than 255. This is an indication of a baud rate that is too low. I .~i------------------------------------------~ Note: Baud rates that result in TCDAT register values lower than 100 make strictly real time processing rules necessary. Interrupt handlers must be as short as possible and interruptible. See Section 4.4 for hints how to speed-up the UART. 6-334 The 8-81t InteNal Timer/Counter Table 6-36. Baud Rate Register TCDAT Contents (MCLK = 1,048 MHz) BAUD RATE DIVISION FACTOR 8-BIT COUNTER REGISTER BAUD RATE CORRECTION - 110 9532.51 253Ch 300 3495.25 ODA7h 06D3h FRACTION USED MEAN ERROR(%) 600 1747.63 1200 873.81 0369h 2400 436.91 01B4h - 4800 218.45 OODAh 14AAh 0.4545 -0.002 9600 109.23 006Dh 1088h 0.1818 +0.044 19200 54.61 0036h - 38400 27.31 001Bh - 6.10.3.2 Baud Rate Generation With the ACLK With the relatively low ACLK frequency (32,768 Hz), the baud rate correction becomes much more important compared 10 the normally high MCLK frequency used for the UART liming. Table 6-37 shows the optimum values for Ihe counter register TCDAT and the correction values for commonly used baud rates generated with the ACLK (32,768 Hz). The table values are calculated by the macro starting at the label MODTAB. The crystal is assumed to be without frequency error. The meaning of the table columns is explained in Section 6.10.3.1. As for Table 6-36, the mean error is calculated for a medium frame length of eleven bits: start bit, eight data bits, parity enabled, and one stop bit. Table 6-37. Baud Rate Register TCDAT Contents (ACLK = 32,768 Hz) BAUD RATE DIVISION FACTOR 8-BIT COUNTER REGISTER BAUD RATE CORRECTION FRACTION USED MEAN ERROR(%) 110 297.8909 0129h - 300 109.2267 006Dh 1088h 0.1818 +0.04 600 54.6133 0036h 15DAh 0.6363 -0.04 1200 27.3067 001Bh 1124h 0.2727 +0.12 2400 13.6533 OOODh lB6Dh 0.6363 +0.12 4800 6.8267 0006h lBEFh 0.8181 +0.13 9600 3.4133 0003h 094Ah 0.3636 +1.46 19200 1.7067 - - - 38400 0.8533 - - - - On-Chip Peripherals 6-335 The 8-8it Interval Timer/Counter 1:1 1:1 d 6.10.4 Software Routines The following sections show proven software routines for the UART mode of the 8-Bit Timer/Counter. Note: The program sequences for the initialization of the UART software are important. The example code should not be modified. See the subroutines TXINIT and RCINIT. Note: Any protocol is possible due to the software control for the data sequence. It is only necessary to adapt the two tables RTTAB and MODTAB of the two software examples that follow. The software routines are shown for interrupt use only. It makes no sense to use the noninterrupt solution (polling) because the time intervals between two signal bits are relatively short - a 100% loading of the CPU would be the result. This is due to the bit orientation of the 8-Bit Timer/Counter hardware. The initialization subroutine INITSR and the RAM initialization subroutine RAMCLR are explained in detail in section The TimecA, paragraph Common Initialization Routine. 6.10.4.1 MCLK Used for UART Clock The following example is for use when MCLK used for the generation of the UART clock. For high baud rates - higher than 9600 baud @ 1 MHz - dedicated CPU registers may be necessary to lower the interrupt overhead. The time for the saving and restoring of the register is not necessary. See Section 6.10.4.4. Example 6-65. Half Duplex UART with Interrupt Half duplex UART software using the interrupt of the 8-Bit Timer/Counter is shown below. The software is designed for: o o o o 6-336 Baud rate: 4800 baud The MCLK (1,048 MHz) is used for the UART clock The active mode of the CPU is used . Seven data bits The 8-81/ Interval Timer/Counter o o o o o Parity enabled with even parity No address bit included One stop bit Reception of all characters (the error byte RTERR contains an error indication) UART signals like shown in figure 6-87 (mark = Vee. space = Vss) The following seven software switches and the value for the UARTCLK need to be defined for the UART operation (see also the examples in the software part). Functions that are not enabled. do not use memory space: the adjacent code is left out by Conditional Assembly. . UARTCLK If the MCLK is used for the UART timing. then the MCLK frequency must be given here. Normally the MCLK is defined by multiplication of the crystal frequency with the FLL multiplier. Baudr Baud rate used [Hz]. For 1.048 MHz MCLK frequency. the range is from 4800 baud to 9600 baud. With special care. 19200 baud is also possible. The range of usable baud rates increases linearly with the MCLK frequency used. CHARC Number of data bits. The UART software allows 7 and 8 data bits. but the table structure of the software eases the adaptation to other bit counts. ADDR Inclusion of an address bit (1) or not (0). See the MSP430 Architecture Guide for an explanation of this feature. PAR Enables (1) or disables (0) a parity check. A parity error sets bit TCPE (RTERR.O). PAREV If parity is enabled (PAR = 1). even (1) or odd (0) parity is used for the data check. STB Defines the number of stop bits. Possible values are 1 or 2 stop bits TCERRT Defines the treatment of detected errors. If the received character is correct. the byte RTERR contains O. The possible values for the switch TCERRT are: TCERRT = 0: the current. erroneous character is discarded and the receive function is initialized for a new start bit check. This means the software tries to find a valid start bit. TCERRT = 1: the error is indicated in byte RTERR. the reception of the current character continues. Possible errors are: TCPE (RTERR.O) = 1 - parity error. The sum of 1s contained in the data bits. the address bit. and the parity bit is not correct. It is not odd for odd parity OR even for even parity TCFE (RTERR.1) = 1 - frame error. This means the middle of the start bit is high. or one of the stop bits is low. This error is normally caused by a software start inside of a character frame. On-Chip Peripherals 6-337 The 8-Bit Interval Timer/Counter Transmit Mode: the data to be transmitted is loaded right-aligned into the RAM word RTDATA. The address bit - if enabled by ADDR = 1 - is included. No error is possible. Four examples forthe data in RTDATA are shown in figure 6-95. The completion of the transmission is indicated by a value of (TX6-RTTAB) in the status byte RTSTAT. A relative number (TX6-RTTAB) is necessary due to the many possible data formats. 15 0 7 7-BH Data No Address Bit o 7-Bit Data 0 I 15 I 0 7 7-Bit Data Address Bit o 15 IADRI 8 8-Bit Data No Address Bit 7 o 15 o 0 B-Bit Data 8 8-Bit Data Address Bit 7-Bit Data o 7 8--Bit Data Figure 6-95. Transmitted Data Format Receive Mode: the received data is loaded left-aligned into the RAM word RTDATA (see Figure 6-96). This means that, depending on the address bit and the number of data bits contained in the data word, a shift is necessary to get a single byte containing the received character. The input format used is necessary due to the address bit. The completion of the reception is indicated by a value of (RC6-RTTAB) in the status byte RTSTAT. A relative number is necessary due to the many possible data formats. If no error occurred, then the error byte RTERR contains 0, otherwise it contains the reason of the error in its LSBs: oBit TCPE (RTERR.O) is set: a parity error occurred O· Bit TCFE (RTERR.1) is set: a frame error occurred. This can be Caused by a start bit having a mark signal (1) or a stop bit having a space signal (0). 6-338 The 8-Bit Interval Timer/Counter 7-BitData 7-BitData No Address Bit Io a 15 I 7-Bit Data ADRI Address Bit 0 I 0 7 0 0 7-Bit Data 15 8-BitData 7 a 15 8 7 0 a-Bit Data No Address Bit 0 a 15 8--Bit Data IADRI Address Bit 7 0 B-BR Data 0 Figure 6-96. Received Data Format Definitions for the common part STACK .equ 0300h Stack start address FLLMPY .equ 32 FLL multiplier for 1,048MHz Definitions for the OART part Data format: 4800 Baud, even parity, 7 data bits, 1 stop bit MCLK for OART clock, also erroneous characters to input buffer Baudr .equ 4800 Baud rate is 4800 Baud OARTCLK .equ FLLMPY*32768 MCLK is used for OARTCLK a CHARC .equ 7 Length: ADDR .equ 0 Address bit: 1: yes 0: no PAR .equ 1 Parity 0: disabled 1 : enabled PAREV .equ 1 Parity 0: odd STB .equ 1 Stop bits: 1: one TCERRT .equ 1 0: error restart 7: 7 bits 8: bits 1: even 2: two 1: indication On-Chip Peripherals 6-339 The B-Bit Interval Timer/Counter TCPE .equ 1 Parity error: RTERR.O = 1 TCFE .equ :I Frame error: CUBR .equ -(UARTCLK/Baudr) Content B-Bit Counter .bss RTDATA,2 Data for receive/transmit .bss RTERR,l Error byte .bss RTSTAT,l status byte Word boundary . even . text INIT RTERR.l = 1 Software start address MOV #STACK,SP CALL #INITSR Initialize Stack Pointer Init. FLL and RAM Proceed with initialization EINT Enable interrupts MAINLOOP Mainloop starts here Prepare transmission of one character from RAM word RTDATA Info is. contained· right aligned in LSBs. No error possible MOV #xxx,RTDATA CALL #TXINIT Character xxx to RTDATA Initialize the transmit part Continue with background Check for completion: CMP.B #TX6-RTTAB,RTSTAT Character transmitted? JEQ CHARTX Yes, .prepare next one No, continue Prepare the reception of one character to RAM word RTDATA Info is contained left aligned in the LSBs. Errors in RTERR CALL #RCINIT Initialize the receive part Continue in background Check for completion: 6-340 The 8-Bit Interval Timer/Counter CMP.B #RC6-RTTAB,RTSTAT One character received? JNE NO_CHAR No, continue TST.B RTERR Yes, error? JNZ ERRHDL Yes, check reason RRC RTDATA RTDATA+l contains 7-bit data BR #MAINLOOP Back to main loop CLRC No, shift a 0 in MSB Process data in RTDATA+l Common interrupt handler for transmit and receive functions. The carry of TCDAT is switched to the PO.l interrupt request. Interrupt time interval of the 8-bit timer is: l/Baud rate The single status byte RTSTAT contains the actual status: Idle: RTSTAT 0 No UART activity Transmit: RTSTAT 1 ... TX6-RTTAB-1 Active TX6-RTTAB Character output Receive: RTSTAT RC-RTTAB ... RC6-RTTAB-1 Active RC6-RTTAB Char. received TXRCINT RTTAB PUSH RS Save R5 MOV.B RTSTAT,RS Receive/transmit status MOV.B RTTAB(RS), RS offset to handler address ADD RS,PC RTTAB+RTSTATx-RTTAB -> PC . BYTE RTSTATO-RTTAB Offset RTSTAT = 0 (inactive) Transmit states TX . BYTE TXSTAT1-RTTAB TX: Start bit . BYTE TXSTAT2-RTTAB TX: LSB . BYTE TXSTAT2-RTTAB TX: LSB+l .BYTE TXSTAT2-RTTAB TX: LSB+2 . BYTE TXSTAT2-RTTAB TX: LSB+3 . BYTE TXSTAT2-RTTAB TX: MSB-3 .BYTE TXSTAT2-RTTAB TX: MSB-2 .if CHARC=8 Data length 7 or.8 bits? . BYTE TXSTAT2-RTTAB TX: MSB-l On-Chip Peripherals 6-341 The B-Bit inteNaJ Tiiner/Counter .endif .BYTE TXSTAT2-RTTAB TX: MSB .if ADDR=l Address bit? . BYTE TXSTAT3-RTTAB TX: Address bit .endU .if PAR=l Parity enabled? . BYTE TXSTAT4-RTTAB TX: Parity bit .endif . BYTE TXSTATS-RTTAB TX: stop bit 1 .if STB=2 Two stop bits? . BYTE TXSTATS-RTTAB TX: stop bit 2 TXSTAT6-RTTAB TX: Frame output completed .endif TX6 . BYTE Receive states: interrupt occurs in the middle of the bits RC .BYTE RCSTAT1-RTTAB RC: start bit . BYTE RCSTAT2-RTTAB RC: LSB . BYTE RCSTAT2-RTTAB RC: LSB+1 . BYTE RCSTAT2-RTTAB ., RC: LSB+2 . BYTE RCSTAT2-RTTAB RC: LSB+3 . BYTE RCSTAT2-RTTAB RC: MSB-3 . BYTE RCSTAT2-RTTAB RC: MSB-2 .if CHARC=8 Data length 7 or 8 bits? . BYTE RCSTAT2-RTTAB RC: MSB-1 .endif .BYTE RCSTAT2-RTTAB RC: MSB .if ADDR=l Address bit? . BYTE RCSTAT3-RTTAB RC: Address bit .if PAR=l Parity enabled? . BYTE RCSTAT4-RTTAB RC: Parity bit . end if . end i f 6-342 . BYTE RCSTATS-RTTAB RC: stop bit 1, parity. check .if STB=2 Two stop bits? .BYTE RCSTAT6-RTTAB RC: stop bit 2 The 8-8;t inteNal Timer/Counter .endif RC6 .BYTE RC: Frame received TXSTAT6-RTTAB Transmit software part. Interrupt after output bit. The bit length and data of the next but one bit is defined TXSTAT1 BIC.B #TXD,&TCCTL Start bit: output space (0) JMP TXRET To common interrupt return TXSTAT 3 . equ $ Address bit (if defined) TXSTAT2 RRA RTDATA Data bit: next one to carry , JC TXO TX1 TX1 Data is 1 BIC.B #TXD, &TCCTL Output data 0: reset TXD JMP TXRET .equ $ .if PAR=l Output 1 with parity count Parity enabled? XOR.B n,RTERR Toggle LSB for parity .endif TXSTAT5 .equ $ Stop bit: output 1 wlo parity BIS.B #TXD,&TCCTL Data is 1: set TXD Tasks are made, the next but one bit length is loaded to the pre-load register TCPLD. The bit length for the current bit was loaded with the current interrupt. TXRET TXSTAT4 MOV.B RTSTAT,RS MOV.B MODTAB-1(R5),&TCPLD JMP RTRET ; ; Transmit status to RS ; Next but one bit length To common RETI part .if PAR=l Parity enabled? BIT.B #l,RTERR Yes, check parity value JNZ TX1 Output mark (1) . TCPE 0 JMP TXO Output space (0). TCPE 0 . end if On-Chip Peripherals 6-343 The 8-Bit Interval Timer/Counter One full character is received or transmitted. The UART hardware is switched off. The status for a completed character is: Receive Mode: RC6-RTTAB Transmit Mode: TX6-RTTAB TXSTAT6 BIC.B #POIEl,&IEl BIC.B #RXACT+ENCNT,&TCCTL ; Stop T/C, conserve power ; Disable TCDAT carry interrupt JMP RTSTATO ; To RETI w/o status change Receive software part. Interrupt occurs in the middle of the bit. The bit length of the next but one bit is defined BIT.B lIRXD,&TCCTL JZ RCRET Start bit is 0: ok .if TCERRT-l Error, indication wished? BIS.B #TCFE,RTERR Frame error bit TCFE set JMP RCERR Start bit is 1; error RCSTAT4 .equ $ Parity bit is received normally RCSTAT3 .equ $ Address bit too RCSTAT2 BIT.B #RXD,&TCCTL Data bits: info to carry RRC RTDATA Shift data into MSB RCSTATI Check middle of start bit .endif RCI .if PAR=l Parity enabled? IN RCI Data is a 1: adjust parity info JMP RCRET Data is a 0: all done XOR.B #l,RTERR Yes, adjust odd/even info .endif Tasks are made, the next but one bit length is loaded to the pre-load register TCPLD. The bit length for the next bit was loaded with the current interrupt. RCRET 6-344 MOV.B RTSTAT,RS MOV.B MODTAB-{RC-TX){RS),&TCPLD ; next but one bit ; Transmit status to RS. Length The 8-Bit InteNal Timer/Counter RTRET INC.B RTSTAT To next receive status RTSTATO POP RS Restore RS RETI Stop bit handling: RXD must be high. Parity is checked also: Parity bit RTERR.O (TCPE) must be 0 RCSTATS Parity check during stop bit 1 .equ $ .if PAR-1 Parity enabled? RLA RTDATA Shift out parity bit .if TCERRT-O Restart for error? BIT.B #l,RTERR Yes, check parity value TCPE JNZ RCERR Not 0: error. TCPE stays 1 BIT.B #RXD,&TCCTL Stop bit (1 or 2) high? JNZ RCRET Yes, Parity and stop bits ok .if TCERRT-I No, Error indication wished? BIS.B #TCFE,RTERR Yes, set frame error bit JMP RCRET Continue with frame .endif . end if RCSTAT6 .endif No, to error handler RCERR Error handling: two different ways can be selected: TCERRT 0: restart, start bit check. Current char. is discarded TCERRT 1: error indication in RTERR. Reception continues. RCERR .if TCERRT-O BIC.B #POIE1,&IE1 EINT Error indication wished? No, intrpt disabled: UART off Allow nesting CALL #RCINIT JMP RTSTATO Restart receive task .else RCERR .equ RCRET Yes, continue .endif Table MODTAB contains the calculated bit lengths that fit On-Chip Peripherals 6-345 The 808ft Interval TlmerlCounter best. Sequence: start bit, LSB ... MSB, (address bit), (parity), stop bits + one bit more for the turn-off Only the necessary bytes - dependent on the frame length are included. An bits are calculated individually. Resolution of the calculation is 10 bits MODTAB .equ $ CMOD .equ «(1024*UARTCLK)/Baudr)-1024*(UARTCLK/Baudr» ; Calculate fraction (UARTCLK/Baudr) .eval CMOD,M$OO .mnolist . loop 9+(ADDR=1)+(PAR=1)+(CHARC=8)+(STB=2)+1 Bit # CMOD+M$OO,M$OO .eval .if M$OO>1023 Carry to integer? .eval M$00-1024,M$00 Yes CUBR-1 C$x = 1: Bit one cycle longer CUBR C$x .mUst . byte .rnnolist .else .mlist . byte 0: Bit normal-length .mnolist .endif .endloop . even To word boundary Subroutines The subroutine prepares the 8-Bit Timer/Counter hardware to transmit data. Initialize control byte TCCTL: SSEL1/SSELO: 1/0 for MCLK frequency ISCTL: -1 Carry of TCDAT register causes PO.1 intrpt TXE: 1 Output PO.2 to TXD, disable POOUT.2 TXD 1 Set TXD (PO.2) to high (mark) ENCNT: 1 Enable clock to the TCDAT register TXINIT 6-346 MOV.B #SSEL1+ISCTL+TXE+TXD+ENCNT,&TCCTL MOV.B #TX-RTTAB,RTSTAT ; Transmit status for start bit The B-Bit Interval Timer/Counter JMP RTINIT To common part The subroutine prepares the 8-Bit Timer/Counter hardware to receive data. Initialize control byte TCCTL: SSEL1/SSELO: I/O for MCLK frequency ISCTL: 1 Carry of TCDAT register causes PO.1 intrpt TXE: 1 Enable output buffer for PO.2 TXD: 1 Set TXD (PO.2) to high (mark) ° RXACT: RCINIT MOV.B Reset Edge Detect Flip-Flop #SSEL1+ISCTL+TXD+TXE,&TCCTL MOV.B #RC-RTTAB,RTSTAT Receive status start bit CLR RTDATA Clear data word BIS.B #2,&POIES Neg. edge detect for PO.l Common part for transmit and receive. The parity bit RTERR.O is initialized in a way, that always zero is returned, if the parity is ok. RTINIT MOV.B #CUBR/2,&TCPLD Half bit time to 1st intrpt MOV.B #O,&TCDAT Load half bit time to TCDAT MOV.B MODTAB,&TCPLD Bit time for 1st bit .if (PAR=l) &(PAREV=O) Odd Parity enabled? MOV.B #l,RTERR Odd parity: RTERR.O #O,RTERR No parity .or . even parity BIS.B #POIE1,&IE1 TCDAT carry intrpt enabled BIS.B #RXACT,&TCCTL Receive: enable edge detect. 1 .else MOV.B . endif RET Interrupt Vectors . sect "SCIVEC",OFFF8h HW/SW UART Vectors . word TXRCINT Common TX/RC Vector .sect "INITVEC",OFFFEh Reset Vector . word INIT Program Start Address On-Chip Peripherals 6-347 The B-Bit Interval Timer/Counter 6.10.4.2 ACLK Used for the UART Clock With the ACLK used for the UART clock, two different methods are possible. o ACLK used with the active mode - the only difference to the last section is the use of the ACLK instead of the MCLK. o ACLK used with the low power mode 3 - The CPU is switched off normally (LPM3) but the UART activity continues. This method is necessary for low power applications. The two different methods are described in the next two sections. 6.10.4.2.1 ACLK With the Active Mode The ACLK can be used for the UART ciock in very much the same way as the MCLK (see Section 6.10.4.1 for details). The use of the ACLK may be necessary if the needed baud rate is too low for the MCLK frequency in use. For example, with an MCLK of 1.048 MHz, the lowest (usual) baud rate is 4800 baud. To use the ACLK with the active mode, it is only necessary to change two parts of the software example of Section 6.10.4.1: o UARTCLK .equ o The definition line for the UART clock: 32768 ; ACLK is used for UART.CLK The initialization subroutin.es TXINIT and RCINIT. Instead of the MCLK, the ACLK needs to be defined with the initialization subroutines (SSELO =1, SSEL1 =0). The simplest way is to use the subroutines of this Section (6.10.4.2). 6.10.4.2.2 ACLK With the Low Power Mode 3 This section shows another approach. With this example, the CPU is normally off and leaves .the LPM3 only for the interrupt handling and after a complete character is received or transmitted. Example 6-66. Half duplex UART With Interrupt Half duplex UART software using the UART interrupt is shown. It is designed for: o 6-348 Baud rate: 2400' baud The 8-Bit Interval Timer/Counter o o o o o o o o The ACLK (32,768 Hz) is used for the UART clock Eight data bits Parity enabled with odd parity Address bit included Two stop bits Reception of correct characters only (no error indication, restart instead) The CPU normally uses the low power mode 3 (LPM3) UART signals like shown in figure 6-87 (mark = Vee, space = Vss) The software switches have the same function as described in Section 6.10.4.1. The UARTCLK is defined with the crystal frequency. Also, this example uses a looped calculation for the correction of the bits. Not only eight different bits are calculated, but all ofthe bits of a frame (9 to 13) are calculated individually. See the software part starting at the label MODTAB. Transmit Mode: the data to be transmitted is loaded right-aligned into the RAM word RTDATA. The address bit - if enabled by ADDR =1 - is included. No error is possible. Four examples for the data in RTDATA are shown in figure 6-95. The completion of the transmission is indicated by the value (TX6-RTTAB) in the status byte RTSTAT. The interrupt routine outputs the character and resets after the completion the CPUoff bit and the SCG1 and SCGO bits of the stored status register on the stack. This manipulation omits the return to LPM3 and initializes the next transmit sequence. Receive Mode: the received data is loaded left-aligned into the RAM word RTDATA. This means that depending on the address bit and the number of data bits contained in the data word, a shift is necessary to get a single byte containing the received character. Examples for the data are shown in figure 6-96. The input format used is necessary due to the address bit. The completion of the reception is indicated by the value (RC6-RTTAB) in the status byte RTSTAT. After the reception of a complete character, the interrupt handler resets the CPUoff bit and the SCG 1 and SCGO bits of the stored status register on the stack. This manipulation omits the return to LPM3 and allows the processing of the received data. The error handling is the same as shown for the example in Section 6.10.4.1. On-Chip Peripherals 6-349 The .8-BIt Interval Timer/Counter Definitions for the common part STACK .equ 0300h Stack start address FLLMPY .equ 32 FLL multiplier for 1,048MHz Definitions for the UART. Data format: odd parity, 8 data bits, address bit, 2 stop bits ACLK for UART clock, only correct characters to input buffer Baudr .equ 2400 Baud rate is 2400 Baud UARTCLK .equ 32768 ACLK is used for UARTCLK CHARC .equ 8 Length: ADDR .equ 1 Address bit: 1 yes o PAR .equ 1 Parity 0: disabled 1: enabled PAREV .equ 0 Parity 0: odd 1: even STB .equ 2 Stop-bits: TCERRT .equ 0 0: error restart 7: 7 bits 8: 8 bits 1 : one no 2 : two 1: indication TCPE .equ 1 Parity error: RTERR.O = 1 TCFE .equ 2 Frame error: CUBR .equ -(UARTCLK/Baudr) Content 8-Bit Counter 1 Word boundary . even .bss RTDATA,2 Data for recei ve/tra'nsmi t .bss RTERR,l Error byte .bss RTSTAT,l Status byte . text INIT RTERR.1 Software start address MOV #STACK,SP CALL HNITSR Initialize Stack Pointer Init. FLL and RAM Proceed with initialization EINT Enable interrupts Prepare the transmission of one character from RAM word 6-350 The 8-8it Interval Timer/Counter RTDATA. Info is con~ained right aligned in the LSBs. No error is possible MOV #xxx,RTDATA CALL #TXINIT Character xxx to RTDATA Initialize the transmit part Continue with background Prepare the reception of one character to RAM word RTDATA #RCINIT CALL Initialize the receive part Continue in background After the completion of all background tasks, enter LPM3 PLPM3 BIS #CPUoff+GIE+SCGl+SCGO,SR Enter LPM3 An interrupt handler cleared the CPUoff, SCGl and SCGO bits of the SR on the stack. Checks are made if activity is needed; Receive Mode; one character is received Transmit Mode; one character is output completely other interrupt handlers CMP.B #RC6-RTTAB,RTSTAT One character received? JEQ CHAR_RC Yes, process character CMP.B #TX6-RTTAB,RTSTAT One character transmitted? JEQ CHAR_TX Yes, prepare next one JMP PLPM3 Check other reasons Back to LPM3 Common interrupt handler for transmit and receive functions. The carry of TCDAT is switched to the PO.l interrupt request Interrupt time interval of the B-bit timer is: l/Baud rate The single status byte RTSTAT contains the actual status; o Idle: RTSTAT Transmit: RTSTAT = 1 ... TX6-RTTAB-l No activity Active On-Chip Peripherals 6-351 The 8-Bit Interval Timer/Counter Character output TX6-RTTAB Receive: RTSTAT - RC-RTTAB ... RC6-RTTAB-l RC6'-RTTAB TXRCINT RTTAB Active Char. received PUSH RS Save RS MOV.B RTSTAT,RS Receive/transmit status MOV.B RTTAB{RS),RS Offset to handler -> RS ADD RS,PC RTTAB+RTSTATx-RTTAB -> PC .BYTE RTSTATO-RTTAB Offset RTSTAT = a (inactive) Like shown for MCLK version Note: The Interrupt handler for the UART when using the ACLK for the the UART clock is the same as the handler for when the MCLK is used. Only the small software part after the completion of a received or sent character (at label TXSTAT6) is slightly different. It resets the CPUoff, SCG1, and also SCGO bits (SR.4 to SR.6) to allow a software activity after the return from interrupt RETI. Also, the first instructions of the initialization subroutines are different. These parts are shown below. ! One full character is received or transmitted. The UART hardware is switched off, the LPM3 is terminated to wake-up the CPU after the RETr. The status for a completed character is: Receive Mode: RC6 - RTTAB Transmit Mode: TX6 - RTTAB TXSTAT6 BIC.B #POIE1,&IEl BIC.B #RXACT+ENCNT,&TCCTL ; Stop T/C, conserve power ; Disable TCDAT carry interrupt BIC #SCG1+SCGO+CPUoff,2(SP) ; Terminate LPM3 JMP RTSTATO ; To RETI Subroutines The subroutine prepares the a-Bit Timer/Counter hardware to transmit data. Initialize control byte TCCTL: SSEL1/SSELO: 0/1 for ACLK frequency 6-352 The 8-Bit Interval Timer/Counter ; 'ISCTL: 1 TXE: 1 Enable output buffer for PO.2 TXD 1 Set TXD (PO.2) to high (mark) ENCNT: 1 Enable clock to the TCDAT register TXINIT MOV.B Carry of TCDAT register causes PO.1 intrpt #SSELO+ISCTL+TXE+TXD+ENCNT,&TCCTL MOV.B #TX-RTTAB,RTSTAT Transmit status, start bit JMP RTINIT To common part The subroutine prepares the 8-Bit Timer/Counter hardware to receive data. 'Initialize control byte TCCTL: SSEL1/SSELO: 0/1 for ACLK frequency ISCTL: 1 TXE: 1 Enable output buffer for PO.2 TXD: 1 Set TXD (PO.2) to high (mark) RXACT: 0 Reset the Edge Detection Flip-Flop RCINIT MOV.B Carry of TCDAT register causes PO.1 intrpt #SSELO+ISCTL+TXD+TXE;&TCCTL; Control byte MOV.B #RC-RTTAB,RTSTAT Receive status, start bit CLR RTDATA Clear data word BIS.B #2,&POIES Neg. edge detection on PO.1 Common part for transmit and receive. The parity bit RTERR.O is initialized in a way, that always zero is returned, if the parity is ok. RTINIT MOV.B #CUBR/2,&TCPLD MOV.B #O,&TCDAT Load half bit time to TCDAT MOV.B MODTAB,&TCPLD Bit time for 1st bit .if (PAR=l)&(PAREV=O) Odd Parity enabled? MOV.B #l,RTERR Odd parity: RTERR.O #O,RTERR No parity .or . even parity BIS.B #POIE1,&IE1 TCDAT carry intrpt enabled BIS.B #RXACT,&TCCTL Receive: enable edge detect. Half bit time to 1st intrpt 1 .else MOV.B . endif On-Chip Peripherals 6-353 The B-Bit Interval Timer(Counter RET Interrupt Vectors . sect "SCIVEC",OFFF8h HW/SW UART Vectors . word TXRCINT Common TX/RC Vector . sect "INITVEC",OFFFEh Reset Vector . word INIT Program Start Address 6.10.4.3 CPU Loading and Memory Space 6.10.4.3.1 CPU Loading The CPU loading due to the UART activity can be calculated with simple formulas. The formulas are slightly different for the transmit and the receive mode, because they have different medium cycles per bit. The numbers are given for a frame with 8 data bits, parity enabled, no address bit, and two stop bits. This results in 13 interrupts per frame (the turn off of the 8-Bit Timer! Counter is included). The transmitted [resp.] received character is OAAh with its sequence of ones and zeros. The cycle count includes: cycles to get to the 1st instruction of the interrupt handler cycles for the interrupt handler itself cycles for the RETI instruction 6 n 5 Not included are: the initialization subroutines, the data preparation for the transmit mode, and the data processing for the receive mode. Transmit Mode - the sum of cycles for a complete frame is 708 cycles. The medium cycle count per transmitted bit is 708/13 = 54.46 cycles. Receive Mode - the sum of cycles for a complete frame is 699 cycles. The medium cycle count per received bit is 699!13 =53.77 cycles. The formula to calculate the percentage for the CPU load due to the UART activity is: CPULoad 6-354 BaudRatex c x 100 !MeL!( The 8-Bit InteNal Timer/Counter =-------------~--------~~~------------- Where: CPULoad fMCLK BaudRate c Loading of the MSP430 CPU by the UART system clock used for the UART Used baud rate of the UART MCLK cycles per bit used by the interrupt handler If MCLK = 1.048 MHz and the baud rate approximately 24.7%. [%] [Hz] [Hz] = 4800 Hz, then the CPU loading is 6.10.4.3.2 Memory Space The memory space needed by the 8-Bit Timer/Counter UART depends on the UART format used and the enabled options. The minimum version is shown first and the additional bytes due to the enabled functions afterward. The numbers given include the interrupt handler TXRCINT and the two initialization subroutines TXINIT and RCINIT. Minimum Version: (7 data bits, no address bit, no parity, one stop bit, error indication). 8 data bits Address bit included Parity enabled Two stop bits Error restart enabled 202 ROM bytes, 4 RAM bytes + 4 bytes + 2 bytes +30 bytes + 2 bytes +16 bytes Maximum Version: 256 ROM bytes, 4 RAM bytes. 6.10.4.4 UART Speed-Up Possibilities The following ideas on how to speed up the UART come from Mark Buccini TI/Atlanta. It must be determined for each application if these possibilities can be used. 6.10.4.4.1 Dedicated CPU Register for the Status The use of a dedicated CPU register for the status makes the saving and restoring of the needed register unnecessary. If it is incremented by two, it can step through a word table with minimum overhead. ; Initialization for transmit TXINIT Like described before MOV #TX-RTTAB,R5 Initialize transmit status On-Chip Peripherals 6-355 Interrupt handler: R5 contains the status in steps of two TXRCINT MOV RTTAB(R5) ,PC Start of handler to PC RTTAB ,WORD RTSTATO Address for R5 - 0 (inactive) TX ,WORD TXSTATI TX: start bit ,WORD TXSTAT2 TX: LSB Transmit states: Return from interrupt RTRET INCD RTSTATO RETI R5 To next status (steps of 2) The autoincrement addressing mode may also be used to speed up the interrupt handler: Initialization for transmit TXINIT Like described before MOV #TX,R5 Initialize transmit status R5 contains the address of the current table word TXRCINT MOV @R5+,PC start of handler to PC RTTAB ,WORD RTSTATO Address - RTTAB (inactive) TX ,WORD TXSTATI TX: Start bit ,WORD TXSTAT2 TX: LSB Transmit states: Return from interrupt RTRET RETI RTSTATO DECD RETI 6-356 Next status yet in R5 R5 Completed: last status The B-Bit InteNal Timer/Counter 6.10.4.4.2 No Baud Rate Correction No baud rate correction is needed if the MCLK is used for the baud rate Generation. This allows a shorter interrupt handler with fewer cycles and less program space. 6.10.4.4.3 Word Table Instead of a Byte Table If a word table instead of the byte table is used for the distribution at the start of the interrupt handler, then more program space is needed, but the execution is faster. See Section 6.10.4.4.1. 6.1 0.4.4.4 Mixture of the Methods The two sources for the UART clock are detailed in sections 6.10.4.1 (MCLK) and 6.10.4.2 (ACLK) may be mixed to get the best of both worlds: Transmit Mode - the program normally uses the LPM3. If a character needs to be output, then the active mode with its MCLK is used. The software is identical to the transmit mode shown in Section 6.10.4.1. Receive Mode - the program normally uses the LPM3 with the interrupt of the PO.1 pin activated on negative edges (start bit). o The initialization subroutine is the same as shown in Section 6.1 0.4.1 with the exception of: • o o The bit ISCTL in the control register TCCTL is reset to enable the interrupt at pin PO.1 for negative edges. The next start bit wakes up the MSP430, which starts the following activities: • The control loop of the system clock generator is closed to get a controlled MCLK frequency (SCGO = 0) • The interrupt source is switched from the input pin PO.1 to the carry of the 8-bit counter (ISCTL =1) The MCLK stays active until the complete character Is received. The LPM3 is activated again after the processing of the received data. On-Chip Peripherals 6-357 The Comparato,-A 6.11 The Comparator_A The Comparator_A module is contained in some members of the MSP430xl xx family. It can be used for precise analog measurements. Figure 6-97 shows the versatile hardware of the module. Figure 6-97. Comparator_A Hardware 6-358 The Comparator A 6.11.1 Definitions Used With the Application Examples The abbreviations used for the hardware definitions are consistent with the MSP430 Architecture User's Guide. HARDWARE DEFINITIONS COMPARATOR_A CACTL1 .equ OS9h Control Register 1 CAIFG .equ 001h Interrupt Flag CAIE .equ 002h Interrupt Enable Flag CArES .equ 004h Edge Select 0: rising 1: falling CAON .equ OOSh Supply CAREFO .equ 010h 00: off 0: off 01: 0.5xVcc 1: off CAREF1 .equ 020h 10: 0.2SxVcc 11: Vref CARSEL .equ 040h Reference to: 0: CAD CAEX .equ OSOh 0: CAO -> + CACTL2 .equ OSAh Control Register 2 CAOUT .equ 001h CA Output CAF .equ 002h Output Filter 0: off P2CAO .equ 004h Switch CAO 0: off 1: CAO on P2CA1 .equ OOSh Switch CAl 0: off 1: CAl on CACTL24 .equ 010h Software Bits CACTL2S .equ 020h CACTL26 .equ 040h CACTL2? .equ OSOh 1: CAl 1: CAl -> + 1: on CAPD .equ OSBh CAPDO .equ 001h Input Buffer Switches Port 2 CAPD1 .equ 002h 0: Input Buffer enabled CAPD2 .equ 004h 1: Input Buffer disabled CAPD3 .equ OOSh CAPD4 .equ 010h Avoid current through input buffers CAPDS .equ 020h with analog signals CAPD6 .equ 040h CAPD? .equ OaOh Control Register 3 On-Chip Peripherals 6-359 The Comparator_A 6.11.1.1 Attributes of the Comparatof_A The hardware allows all combinations of comparisons. The bit CAOUT (CACTL.O) contains the result of the comparison: o o o o o 6-360 Comparison of two external inputs Comparison of each external input with 0.25 x Vee or 0.5 x Vee Comparison of each external input with an internal reference voltage An analog filter can be switched to the CAOUT output The module has interrupt capability for the leading and the trailing edge of the output signal CAOUT . The Comparator A 6.11.2 Fast Comparator Input Check Often a very fast sampling of sequential input values is necessary. The following measurement sequence is the fastest way to do this with the ComparatoeA inputs. After the n input checks, a majority test - or something equivalent - can be made for a decision. Figure 6-98 shows the hardware used for the example. The software samples the voltage generated by the current Imeas through resistor Rm. A voltage drop higher than 0.25 x Vee sets CAOUT, a lower voltage drop resets CAOUT. After n samples, the number of sampled 1s is checked. Any other input combination may also be used. Figure 6-98. Fast Comparator Input Check Circuitry On-Chip Peripherals 6-361 The ComparalOf-.A Fast test for the state of the Comparator_A input MOV.B #CARSEL+CAREFl+CAON,&CACTLl MOV.B #PCAO,&CACTL2 MOV #CACTL2,Rl5 Define Comp~ Prepare pointer to reg. CACTL2 MOV.B @Rl5,R5 sample CAOUT (CAOUT ADD.B @Rl5,R5 Add next sample ADD.B @Rl5,R5 = CACTL2.0) Add following samples Add sample n Test if CAOUT showed more than n/2 times a positive result SUB #n*PCAO,R5 CMP.B #1+ (n/2) , R5 Correct result R5 - (1+n/2) JHS POS More samples are 1 More samples are 0 or an even faster decision: Test if CAOUT showed more than n/2 times a positive result CMP.B #n*PCAO+l+(n/2),RS RS-n*PCAO+(1+n/2) JHS POS More samples are 1 More samples are 0 6-362 mode The Comparator_A 6.11.3 Voltage Measurement Figure 6-99 shows hardware that can be used for the measurement of external voltages. The supply voltage is used for reference. The measurement principle is the same one as shown in section Voltage Measurement with the Universal Timer Port/Module. 0.25xVccx m+~+~ 2 R +R3 < Yin R81R7 MACUF CLR RRA JNC ADD ADDC L$01 ,. 7-4 RLA RLC OOOOOOOOOh 03A763E02h OFFFEOOOlh by signed and unsigned R6 MSSs MULTIPLIER R4 L$Ol R5,R7 R6,R8 RS R6 ; LSS to carry IF ZERO: SKIP ADD IF ONE: ADD MULTIPLIER TO RESULT MULTIPLIER x 2 Hints and Recommendations L$02 RRA JNC ADD ADDC RLA RLC R4 L$02 R5,R7 R6,R8 R5 R6 LSB+1 to carry same way for bits 2 to 12 L$014 RRA JNC ADD ADDC RET o R4 L$014 R5,R7 R6,R8 MSB to carry (here bit13) No shift for multiplier necessary Return with result in R81R7 Emulation of Jump If Positive: No jump if positive is provided, only a jump if negative. But after several instructions it is possible to use the jump If greater than or equal (JGE) for this purpose. But it must be certain that the instruction preceding the JGE resets the overflow bit V. The following instructions ensure this: TST, SXT, RRA, BIT, AND. The use of this emulation should be noted in the comment field to ease software modifications. o Special Use of the Carry Bit: The following instructions have a special feature that is valuable during serial to parallel conversion. The carry acts as an inverted zero bit. This means ifthe result of an operation is zero then the carry is reset and vice versa. The instriJctions having this feature are: XOR, SXT, INV, BIT, AND. Without using this feature a typical sequence for the conversion of an 110port bit to a parallel word would look like the following: RLA BIT JZ INC R5 #l,&IOIN L$l1l R5 L$111 Free bit 0 for next info PO.O high? Yes, set bit 0 Info in bit 0 Using this feature, the previous sequence is shortened to two instructions: BIT RLC #l,&IOIN R5 PO.o high? .NOT.Zero -> carry ; Shift bit (in Carry) into R5 Hints and Recommendations 7-5 Hm~andR~me~ffoos I lrIIihl U :II 1:1: o The Carry Bit Used for Increments: The carry bit can be used if increments by one are necessary. EXAMPLE: If the RAM word COUNT is greater than or equal to the value 1000 then a word COUNTER is.to be incremented by one. CMP ADC o Immediate Addition of the Carry Bit: The carry bit can be added immediately. No conditional jumps are necessary for counters longer than 16 bits. A 48-bit counter is incremented. R5,COUNT COUNT+2 COUNT+4 ADD ADC ADC o ; COUNT >= 1000 ; If yes, (C = 1) incr. COUNTER nOOO,COUNT COUNTER Low part of COUNT ; Medium part ; High part of 48-bit counter Fall Through Programming: ROM space is saved if a subroutine call that is located immediately before a RET instruction is changed. The called subroutine is located after the instruction before the CALL. and the program falls through it. This saves 6 bytes of ROM: The CALL itself and the RET instruction. The 12C handler uses this mode. Normal way: SUBR2 is called, afterwards returned SUBR1 MOV CALL RET R5,R6 #SUBR2 Call subroutine "Fall Through" solution: SUBR2 is located after SUBR1 SUBR1 MOVR5,R6 Fall through to SUBR2 Start of SUBR2 subroutine SUBR2 RET 0 Shift Operations for 32-8lt Numbers: If shifts with numbers greater than 16 bits are necessary. the shift operations for the upper words must be RLC or RRC. If RLA or RRA are used then only zeroes are shifted in RLA RLC RRA RRC RII Rl2 Rl2 R11 MSB RLA LSB RRA of is of is low byte to carry wrong here! high byte to carry wrong here! 0 Interrupt Handlers: The length of interrupt handlers should be kept as short as possible. All necessary calculations should be made in the background program (main program). The activation and control can be made easily with status bytes. 7-6 Hints and Recommendations o Decimal Subtraction: No instruction is provided, but a simple way is possible. The copy instruction is only necessary if the minuend may not be modified. EXAMPLE: OP1 is subtracted from OP2 decimally MOV ADD INV SETC DADO o OP1,R5 #6666h,R5 R5 Copy Opl OPl into range 6666h to FFFFh Build 9999 complement R5,OP2 OP2 - OPl -> OP2 (dec. ) Timer Wake-Up Out of Low Power Modes: The two 8-bit counters of the universal timer/port can also be used during the low power modes 3 and 4. If a counter is incremented by an external signal (inputs CIN, CMP, or TPIN.5) from OFFh to Oh, then the appertaining RCxFG-flag is set. If an interrupt is enabled, the CPU wakes up. Hints and Recommendations 7-7 ~ign Checklist 7.2 Design Checklist Several steps are necessary to complete a system consisting of an MSP430 and its peripherals with the necessary performance. Typical and recommended development steps are shown in the following. All of the tasks mentioned should be done carefully in order to prevent trouble later on. 1) Definition of the tasks to be performed by the MSP430 and its peripherals 2) Selection of the MSP430 version that fits best 3) Worst case timing conSiderations for all of the tasks to be done (interrupt timing, calculation times, I/O etc.) 4) Drawing of a complete hardware schematic. Deciding which hardware options are used (supply voltage, pull-downs at the I/O-ports, etc.) 5) Worst case design for all of the external components 6) Organization of the RAM and - if present - of the external EEPROM 7) Flowcharting of the complete software 8) Coding of the software with an editor 9) Assembling of the program with the ASM430 Assembler 10) Removing of the logical errors found by the ASM430 Assembler 11) Testing of the software with the SIM430 Simulator and an emulation board 12) Repetition of the steps 7 to 10 until the software is free of errors 7-8 Most Frequent Software E"ors 7.3 Most Frequent Software Errors During software development, the same errors are made by nearly all assembler programmers. The following list contains the errors which are most often heard of and experienced. o Missing Housekeeping During Stack Operations: If items are removed from or placed onto the stack during subroutines or interrupt handlers, it is mandatory to keep track of these operations. Any wrong positioning of the stack pointer will lead to a program crash, due to the wrong data written into the program counter. o Missing Initialization of the Stack Pointer: The stack painter needs to be initialized before the EINT instruction is executed or a CALL is used. The normal instruction to be used is: o Use of the Wrong Jump Instructions: The conditional jump instructions JLO and JLT, or JHS, and JGE, give different results if used for numbers above 07FFFh. It is therefore necessary to always distinguish between signed and unsigned jump instructions. o Wrong Completion Instructions. Despite their virtual similarity, subroutines and interrupt handlers need completely different actions for completion. MOV #0300h,SP ; Locate stack at high RAM • Subroutines end with the RET instruction. Only the address ofthe next instruction (the one following the subroutine call) is popped from the stack. • Interrupt handlers end with the RETI instruction. Two items are popped from the stack, first the status register is restored and afterwards the address (the address of the next instruction after the interrupted one) is popped from the stack to the program counter. • If RETI and RET are used incorrectly, a wrong item is written into the PC. This means that the software will continue at random addresses and will hang-up. o Addition and Subtraction of Numbers With Differently Located Decimal Points: if numbers with virtual decimal points are used the addition or subtraction of numbers with different fractional bits leads to errors. It is necessary to shift one of the operands in a way to aChieve fractional parts of aquallength. See "Rules for the Integer Subroutines." o Byte Instructions Applied to Working Registers: byte instructions always clear the upper byte of the used working registar (except CMP.B, TST.B, BIT. B). It is necessary therefore to use word instructions if operations in working registars can exceed the byte range. Hints and Recommendations 7-9 Most Frequent ,Software Errors o Use of Byte Instructions With the Program Counter as Destination Register: if the PC is the destination register byte instructions do not make sense. The clearing of the PC high byte is certainly wrong in any case. Instead, a register is to be used before the modification of the PC with the byte information. See 9.2.5. o Use of Falsely Addressed Branches and Subroutine Calls: The destination of branches and calls is used indirectly, and this means the content of the destination is used as the address. These errors occur most often with the symbolic mode and the absolute mode: CALL MAIN ; Subroutine's address is stored in MAIN CALL iMAIN ; Subroutine starts at address MAIN The real behavior is easily seen when looking to the branch instruction. It is an emulated instructton using the MOV instruction: BR MAIN ; Emulated instruction BR MOV MAIN,PC ; Emulation by MOV instruction The addressing for the CALL instruction is exactly the same as for the BR instruction. o Counters and TImers Longer Than 16-Bits: if counters or timers longer than 16 bits are modified by the foreground (interrupt routines) and used by the background, it is necessary to disable the timer interrupt (most simply with the GIE bit in SR) during the reading of these words. If this is not done, the foreground can modify these words between the reading of two words. This would mean that one word read contains the old value and the other one the modified value. EXAMPLE: The timer interrupt handler increments a 32-bit timer. The background software uses this timer for calculations. The disabling of the interrupts prevents the timer interrupt that occurs between the reading of TIMLO and TIMHI, which can falsify the read information. This can be the case if TIMLO overflows from OFFFFh to OOOOh during the interrupt routine. TIMLO is read with the old information OFFFFh and TIMHI contains the new information x+ 1. INC TIMLO Incr. LO word ADC TIMHI Incr. HI word RETI Background part copies TIMxx for calculations DINT 7-10 ; GIE <- 0 Most F,~uent Software Errors NOP MOY MOY EINT o ; TIMLO,R4 TIMHI,R5 DINT needs 2 cycles Copy LSDs COPY MSDs Enable interrupt again Counters Used by Foreground and Background: If counters are modified by the foreground and read and cleared by the background, care is to be taken that no counts are lost. With the following example. it is possible to loose a count if the interrupt occurs between the MOV and the CLR instruction. The additional count is not recognized because CNTR (with its content 1) is cleared. First the WRONG sequence is shown: I NT_HAN INCCNTR RET! CNTR, STORE CNTR MOY CLR Incr. counter CNTR WRONG! by interrupts Background program Read CNTR A count may be lostl To avoid loosing a count, the following solutions are possible for the background part. Background part switches off the interrupt during reading DINT MOY CLR EINT CNTR,STORE CNTR GIE <- 0 (inactive after MOY) Read CNTR Clear unmodified CNTR Enable interrupt again Background part uses difference of contents. If interrupt occurs after the PUSH instruction, 1 remains in CNTR. PUSH SUB POP CNTR @SP,CNTR STORE Copy CNTR Subtract read number from CNTR Place read info to STORE Simplified version of above: if CNTR is yet changed it contains despite correct value (1) MOY SUB o CNTR, STORE STORE,CNTR ; Copy CNTR to STORE ; Subtract STORE of current CNTR Use of the PUSH Instruction: When using sophisticated stack processing. it is often overlooked that the PUSH instruction decrements the stack pOinter first and moves the item afterwards. Hints and Recommendations 7-11 M?st Frequent Software Errors EXAMPLE: The return address stored at TOS is to be moved one word down to free space for an argument. PUSH @SP PUSH 2 (SP) WRONG! 1st free word (~OS-2) is copied ; on itself ; Correct, old TOS is pushed 1 word down EXAMPLE: The stored SP does not point to the same stack address after the restoring. It points to the (address -2) afterwards. PUSH POP SP SP ; Store SP-2 on stack ; Restore SP-2 to SP !! D Use of the Autoincrement Mode: The source register is incremented immediately after the reading of the source operand. This means if the source register is also used for the addressing of the destination operand, it contains the incremented value when used. D Register Overflow: If registers do not have the necessary length, negative numbers (MSB = 1) or too small numbers (register is reset to zero by overflow) can result. The length of registers needs to be evaluated with worst case methods. o Interrupt Blocking: Long interrupt routines should be avoided. If they are necessary, the GIE bit located in the SR should be set (instruction EINT) at the start of these routines. Otherwise, the disabled interrupt blocks all other interrupt sources. D Real Time Processing: If the algorithm used is longer than the time slot that is available, errors will occur. Worst case evaluations are necessary to ensure the algorithm fits into the time slot. D Write-Only Registers: The complete information always needs to be written to these registers. Otherwise, the bits not included in the source of the instruction are reset. The crystal buffer control register (CBCTL) is an example for this register type. D Port Select Registers: I/O ports with dual functions -like the Port3 forthe Timer_A (MSP430C33x) - must be switched to the second function. Otherwise, the normal port function is active. To switch Port3 completely to the Timer_A functions, the following code is needed during the initialization routine. If the BaSic Timer is not initialized, the LCD will not work correctly. MOV.B #TACLK+TA4+TA3+TA2+TA1+TAO,&P3SEL D If the basic timer is not initialized, the LCD will not work properly. 7-12 Most Frequent Hardware Errors 7.4 Most Frequent Hardware Errors o Crystal Connection: The crystal oscillator is connected to AVCC and AVSS. This means that these two terminals must be connected to DVCC and DVSS, otherwise the crystal will not oscillate. o Open Inputs: Every input must have a defined potential. Otherwise, hum and noise will influence the program flow. In addition, the supply current increases. See Section 4.9.4, Correct Termination of Unused Terminals. o Crystal Turnon Time: If woken-up from the low power mode 4, the crystal needs a relatively long time until it runs with the correct frequency. This can last up to four seconds. Correct timing is not possible until the crystal reached its nominal frequency. Until this, the DCO steps down to its lowest frequency ('" 500 kHz). See Section 6.5, The System Clock Generator. o BIC Frequency-lockedloop considerations • FLL Turnon TIme: If woken-up from LPM3, the FLL needs approximately 6 cycles to reach the nominal frequency. This also means, the 1st instruction of an interrupt handler is executed with the correct frequency. • Setting Time: The FLL needs a certain non-interrupted time to set the control value of the digitally-controlled oscillator (DCO). If this time is not provided, no control forthe DCO is possible. It remains at the same tap. This time is best spent during initialization by a software loop with a worst case length of 28 x 32 x 30.5 !IS = 27.3 ms. To allow the system clock the adaptation of the DCO to the eventually changed tap, the FLL-Ioop should be closed during longer calculations. This is done simply with the instruction: #SCGO,SR ; Turn on FLL-loop control o Supply Voltage for Battery-Powered Systems: if certain batteries are used the supply voltage may fall below the lower voltage limit during Active Mode (especially if the ADC is used) due to the high internal resistance of these batteries. A capacitor is necessary then in parallel with the battery. o Supply Voltage for AC-Powered Systems: No hum, noise, or spikes are allowed. If these are present, the reliability of the system and the accuracy of the ADC will decrease. o EEPROM Clocking: For some EEPROMs, the minimum clock duration is longer than one MSP430 instruction. This means that NOPs have to be included into the clock timing. See the specification of the EEPROM used. Hints and Recommendations 7-13 Checklist for Problems 7.5 Checklist for Problems 7.5.1 Hardware Related Problems 1) Initialization circuit connected? An RC circuit is not sufficient in most cases. 2) Fan-out of bus or outputs taken into account? 3) Open inputs (interrupt, init, inputs etc.): every input must be connected to a defined voltage level. Otherwise, undefined signals (normally the ac frequency) are seen at the inputs. See Section 4.9.4, Correct Termination of Unused Terminals. 4) Crystal turn-on time not taken into account (may be upto seconds for lowpower devices)? 5) Correct levels at all inputs? (low and high levels) 6) Input signals in specified limits: thresholds, frequency and edges? 7) Supply voltage in specified limits, no spikes, no noise etc. 8) External interrupt signals too short (no response from interrupted system) 9) External EEPROM, clock out of the MSP430 too fast or too short? See EEPROM specification. 10) RESET signals with spikes or false voltage levels? This is an often occurring reason for problems. 7.5.2 Software RelatedProblems 1) Register overflow (registers, memory and peripheral registers) causes negative numbers or sawtooth characteristic of results (numbers are too small then) 2) PWMapplications: loading of the pulse length register needs to be synchronized to the output change. Otherwise, undefined pulses are output during the change of this register 3) Output frequency too high? (register load time longer than pulse length?) 4) Real-time applications: is used algorithm shorter than the available time interval also under worst case conditions? 5) Conditional jumps: signed and unsigned jumps used correctly? For example JHS and JGE are completely different instructions. The same is true for JLO and JLT. 7-14 Run Time Estimation 6) Missing housekeeping during stack operations? If the return values for the SR and the PC - stored on the stack during an interrupt - are overwritten with data: this can cause the setting of the OSCoff bit in the SR during the RETI instruction. Which means, the program execution ceases. 7) Read-out of two-word-registers without disabling the interrupt? (if overflow occurs one word may contain the old number, the other one the new number) 8) Multiple word shifts: correct shift instruction used for the MSBs(no arithmetic shifts: they shift in always zeroes) 9) SP Initialization: forgotten or made after the interrupt enabling with EINT? 10) Interrupt handlers: long lasting parts without enabling the interrupt again (blocks all other interrupt activities)? 11) If the second function of a port register is used: are the select bits in the PxSEL register set? 12) Are all the peripherals initialized? 7.6 Run Time Estimation To get a quick overview concerning the speed of a given piece of software, the following estimations may be used: o If the code contains all addressing modes then the estimation for the needed runtime trun is: trun '" 0.75 cycles/byte o If the code contains only or predominant register mode addressing then the estimation for the needed runtime t run is: !run '" 0.5 cycles/byte Hints and Recommendations 7-15 Run Time Estimation 7-16 Chapter 8 Architecture and Instruction Set 8-1 Introduction 8.1 Introduction The Instruction set of the ultra low power-microcomputer MSP430 family differs strongly from the instruction sets used by other 8-bit and 16-bit microcomputers. The reasons why this instruction set is appreciated though, are explained in the following pages in detail. It is the return to clarity and especially the return to orthogonality, an attribute of microcomputer architectures that has disappeared more and more during the last 20 years. A customer commented that it is an instruction set to fall in love with. The MSP430 Family was developed to fulfill the ever increasing requirements of Texas Instruments Ultra Low Power microcomputers. It was not possible to increase the computing power and the real-time processing capability of the MSP430 predecessor (TSS400) as far as was needed. Therefore, a complete new 16-bit architecture was developed to stay competitive and be viable for several years. The benchmark numbers shown in relation to competition's products (bytes used, number of program lines) are taken from an unbiased comparison executed by a British software consultant. 8-2 Reasons for the Popularity of the MSP430 8.2 Reasons for the Popularity of the MSP430 The following sections are intended to explain the different reasons why the MSP430 instruction set, which closely mirrors the architecture, has become so popular. 8.2.1 Orthogonality This notation of computer science means that a single operand instruction can use any addressing mode or that any double operand instruction can use any combination of source and destination addressing modes. Figure 8-1 shows this graphically: tlie existing combinations fill the complete possible space. t Addressing Modes Source Addressing Modes Destination Instructions Figure B-1. Orthogonal Architecture (Double Operand Instructions) The opposite of orthogonal, a non-orthogonal architecture is shown in Figure B-2. Any instruction can use only a part ofthe existing addressing modes. The possible combinations are arranged like small blocks in the available space. Architecture and Instruction Set ~easo,!!! f?' the ~OPU/a'ity of the MSP430 t Addressing Modes Source ~ Instructions Figure B-2. Non-Drthogonal Architecture (Dual Operand Instructions) 8.2.2 Addressing Modes The MSP430 architecture has seven possibilities to address its operands. Four of them are implemented in the CPU, two of them result from the use of the program counter (PC) as a register, and a further one is claimed by indexing a register that always contains a zero (status register). The single operand instructions can use all of the seven addressing modes, the double operand instructions can use all of them for the source operand, and-four of them for the destination operand. Figure 8-3 shows this context: Double Operand Instructlons- Single Operand Instructions Mnemonic Mnemonic Source,Destination tv l1 Register Indexed Absolute Symbolic 1m-mediate Register indirect Register indirect autoincrement Register Register Indexed Indexed Absolute Absolute Symbolic Symbolic Immediate Register indirect Register indirect autoincrement 12 Instructions 28 Combinations Figure 8--3. Addressing Modes Des~tion 7 Instructions 7 Addressing Modes Reasons for the Popularity of the MSP430 8.2.2.1 Register Addressing The operand is contained in one of the registers RO to R15. This is the fastest addressing mode and the one that needs the least memory. Example: Add the contents of R7 to the contents of R8 R7,R8 ADD 8.2.2.2 ; ( R7) + (R8) --t (R8) Indirect Register Addressing The register used contains the address of the operand. The operand can be located anywhere in the entire memory space (641<). Example: Add the byte addressed by R8 to the contents of R9 ADD.B 8.2.2.3 @R8,R9 ; ((R8» + (R9) --t (R9) Indirect Register Addressing With Autolncrement The register used contains the address of the operand. This operand can be located anywhere in the entire memory space (64K). After the access to the operand the used register is incremented by two (word instruction) respective one (byte instruction). The increment occurs immediately after the reading of the source operand. Example: Copy the byte operand addressed by R8 to R9 and increment the pointer register R8 by one afterwards MOV.B 8.2.2.4 @R8+,R9 ; ((R8» --t (R9), (R8) + 1 --t (R8) Indexed Addressing The address of the operand is the sum of the index and the contents of the register used. The index is contained in an additional word located after the instruction word. Example: Compare the 2nd byte of a table addressed by RS with the low Byte of R1S. Result to the Status Register SR CMP.B 1(R5),R1S ; (R1S) - (1 + (RS» If the register in use is the program counter then two additional, important addressing modes result: Architecture and Instruction Set 8-5 Reasons f?' the Popularity of the MSP430 8.2.2.5 ImmedIate Addressing Any 16-bit or 8-bit constant can be used with an instruction. The PC pOints to the following word after reading the instruction word. By the use of the register indirect autoincrementaddressing mode, this word (the immediate value) can be read and the PC is incremented by two afterwards. The word after the instruction word is treated this way as an 8-bit or a 16-bit immediate value. Example: Test bit 8 in the 3rd word of a table RIO points to. start address of the table is O(RIO), 3rd word is 4(RIO) BIT lI0100h,4(RIO) ; Bit 8 - I? The assembler inserts for the instruction above: BIT @PC+,4(RIO) OIOOh 0004h ,WORD ,WORD Executed instruction Source constant OIOOh Index 4 of the destination 8.2.2.6 Symbolic Addressing This is the normal addressing mode for the random access to the entire 64K memory space. The word located after the instruction word contains the differ.ence in bytes to the destination address relative to the PC. This difference can be seen as an index to the PC. Any address in the 64K memory map is addressable this way, both as a source and as a destination. Example: $ =address the PC points to Subtract the contents of the ROM word EDE from the contents ,. of the RAM word TONI SUB EDE,TONI ; (TONI) - (EDE) --t (TONI) The assembler inserts for the instruction above: SUB X(PC) ,Y(PC) .WORD X ,WORD Y 8-6 Executed instruction Index X - EDE-$ Index Y - TONI-$ Reasons for the pop~/arity ,O! the MSP430 8.2.2.7 Absolute Addressing Addresses that are fixed (e.g., the hardware addresses of the peripherals like ADC, UART) can be addressed absolutely. The absolute addressing mode is a special case of the indexed addressing mode. The register used (SR) always contains a zero in this case (without loosing its former information!). Example: set the Power Down Bit in the ADC Control Register ACTL '#PD, &ACTL BIS ; Power Down Bit ADC <- 1 The assembler inserts for the instruction above: BIS . WORD . WORD @PC+,X(SR) OlOOOh 00114h Executed instruction PD Bit Hardware Address X: Hardware Address of ACTL 8.2.3 RiSe Architecture Without RiSe Disadvantages Classic RISC architectures provide several addressing modes only for the LOAD ano STORE instructions; all other instructions can only access the (numerous) registers. The MSP430 can be programmed this way too. An example of this programming style is the floating point package FPP4. The registers are loaded during the initialization, the calculations are made exclusively in the registers, and the result is placed onto the stack. In real time applications, this kind of programming is less usable, here it is important to access operands at random addresses without any delays. An example of this is the incrementing of a counter during an interrupt service routine: Pure RISC program sequence for the incrementing of a counter INT_HND PUSH LOAD INC STORE POP RETI RS RS,COUNTER RS R5 , COUNTER R5 Save register Load COUNTER to register Increment this register Store back the result Restore used register Return from interrupt The MSP430 program sequence for the incrementing of a counter INT_HND INC RETI COUNTER ; Increment COUNTER ; Return from interrupt As shown in the previous example, the pure RISC architecture is not optimal in cases with few calculations, but necessary for fast access to the memory. Architecture and Instruction Set 8-7 Reasons for the Popularity of the MSP430 Here, the MSP430 architecture is advantageous due to the random access to the entire memory (641<) with any instruction, seven source addressing modes and four destination addressing modes. 8.2.4 Constant Generator One of the reasons for the high code efficiency of the MSP430 architecture is the constant generator. The constants, appearing most often in assembler software, are small numbers. Out of these, six were chosen for the constant generator: Table 8-1. Constants implemented in the Constant Generator CONSTANT HEX REPRESENTATION -1 0 +1 +2 OFFFFh OOOOOh 0OOO1h 00OO2h 0OOO4h 0OOO8h +4 +8 USE Constant, all bits are one Constant, all bits are zero Constant. Increment for byte addresses Constant, Increinent for word addresses Constant, value for bit tests Constant, value for bit tests These six constants can also be used for byte processing. Only the lower byte is in use then. The use 6f numbers out of the constant generator has two advantages: Memory Space: The constant does not need an additional 16 bit word as it is the case with the normal immediate mode. Two useless addressing modes of the status registers SR and all four addressing modes of the otherwise unserviceable register R3 are used. Speed: The constant generator is implemented inside the CPU which results in an access time similar to a general purpose register (shortest access time). Most of the emulated instructions use the constant generator. See Chapter The MSP430 InstructIon Set for examples. 8.2.5 Status Bits The influence of the instructions to the status bits contained in SR is not as uniform as the instructions appear. Dependent on the main use of the instruction, the status bits are influenced in one of the following three ways shown: 1) Not at all, the status bits are not affected. This is, for example, the case with the instructions bit clear, bit set and move. 8-8 Reasons for the Pop~/srity of the MSP430 2) Normal: the status bits reflect the result of the last instruction. This is used with all arithmetical and logical instructions (except bit set and bit clear) 3) Normal, but the carry bit contains the inverted zero bit. The logical instructions XOR (exclusive or), BIT (bit test) and AND use the carry bit for the non-zero information. This feature can save ROM space and time. No preparations or conditional jumps are necessary. The tested information, which is contained in the carry bit, is simply shifted into a register or a RAM word respective byte. 8.2.6 Stack Processing The stack processing capability of the MSP430 allows any nesting of interrupts, subroutines, and user data. It is only necessary to have enough RAM space. Due to the function of the SP as a general purpose register, it is possible to use all seven of the addressing modes for the SP. This allows any needed manipulation of data on the stack. Any word or byte on the stack can be addressed and may therefore be read and written. (The addressing modes implemented for the MSP430 were chosen primarily for the addressing of the stack; but they proved to be very effective also for the other registers). 8.2.7 Usability of the Jumps Remarkable is the uncommonly wide reach of the jumps which is ±512 words. This value is eight times the reach of other architectures that use normally ±128 bytes. Inside program parts it is, therefore, necessary only very rarely to use the branch instruction with its normal two memory words and longer execution time. The implemented eight jumps are classified in three categories: 1) Signed jumps: Numbers range from -32768 to +32767 (word instructions) respective -128 to +127 (byte instructions) 2) UnSigned jumps: Numbers range from 0 to 65535 respective 0 to 255 3) Unconditional jump: (replaces the branch instruction normally) 8.2.8 Byte and Word Processor Any MSP430 instruction is implemented for byte and word processing. Exceptions are only the instructions where a byte instruction would not make sense (subroutine call CALL, return from interrupt RETI) or instructions that are used as an interface between words and bytes (swap bytes SWPB, sign extension SXT). The addressable memory ofthe MSP430 is divided into bytes and words as shown in Figure 8-4. Architecture and Instruction Set 8-9 Reasons for th~ Popular,ity of the MSP430 o 15 Byte Address n+ 1 Byte Address n Word Address n Byte Address n+3 Byte Address n+2 Word Address n+2 Byte Address n+5 Byte Address n+4 Word Address n+4 Figure 8-4. Word and Byte Addresses of the MSP430 This way, the entire 64K address space is organized. The planned memory extension will be addressed in the same clear manner. Due to this memory organization, any table can be allocated in the most favorable manner. Dependent on the maximum value of the operands, the table can be implemented as a byte table or a word table. Any general purpose register from R4 to R15 can be used as a pointer to the tables. The implemented addressing modes indexed, indirect, and indirect with autoincrement are intended for table processing. 8.2.9 High Register Count In addition to the PC andthe SP, which are usable for several purposes, twelve identical general purpose registers (R4 to R15) are available. Anyone of these registers can be used as a data register, as an address pOinter, as an auto-incrementing address pointer, and as an index register. The bottleneck olthe accumulator architectures, which have to pass any operation through the accumulator (with corresponding LOAD arid STORE instructions), does not exist for the MSP430. o 15 PC RO Program Counter SP R1 Stack Pointer SR R2 Status Register and CG1 CG2 R3 Constant Generator 2 R4 R4 General-Purpose Register R4 General-Purpose Registers R5 to R14 R15 General-Purpose Register R15 Figure 8-5. Register Set of the MSP430 8-10 Reasons f~r the Populari!y of the MSP430 8.2.10 Emulation of Non-Implemented Instructions The 27 implemented instructions allow the emulation of additional 24 instructions. This is normally reached with the help of the constant generator, but other ways are used also. As the constants used are taken from the constant generator, no additional memory space is needed. The assembler automatically inserts the correct instructions if emulated instructions are used. The emulation of the 24 instructions led to a remarkable smaller central processing unit. The MSP430 CPU is even smaller than some 4-bit CPUs. The emulated instructions are completely listed in Section 8.4.2, Emulated Instructions. 8.2.11 No Paging The 16-bit architecture of the MSP430 allows the direct addressing of the entire 64K memory bytes without paging of the memory. This feature greatly simplifies the development of software. Architecture and Instruction Set 8-11 Effects and Advantages of the MSP430Archltecture 8.3 Effects and Advantages of the MSP430 Architecture The reasons for the popularity of the MSP430 instruction set (and by it its architecture) shown in Section B.2, have effects and advantages that also result in money saved. These effects and advantages are shown and explained in the following. 8.3.1 Less Program Space The direct access to any address, without loading of the previous address into a register, together with the constant generator results in program lengths for a given task that are between 55% and 90% compared to other microcomputers. This means that with the MSP430, a 4K version may be sufficient where with other microcomputers a 6K or BK version is needed. 8.3.2 Shorter Programs Any necessary code line is a source of errors. The less code lines that are necessary for a given task, the simpler a program is to read, understand, and service. The MSP430 needs between 33% and 55% of the code lines compared. to its competition's products. The reason for this is the same as described previously. Any address can be accessed directly and that both for the source op- . erand and for the destination operand. It is not necessary to create troublesome 16-bit addresses, handle the operands byte-wise, and store the final result afterwards indirectly via a composed destination address. All this happens with only one MSP430 instruction. 8.3.3 Reduced Development Time The clearly smaller program length and the less troublesome access to ROM, RAM, and other peripherals reduce the necessary development time. In addition to that advantage, the considerations omit completely how the actual problem can be solved at all with the given architecture. A part that can take up to one third of the development time with other architectures. (Whoever has developed with 4-bit microcomputers knows what is meant). 8.3.4 Effective Code Without Compressing The clear assembler language ofthe MSP430 allows, from the start, the writing of dense and legible code. If the developed program is well prepared and coded clearly, it is nearly impossible to reduce the program length seriously afterwards by compressing. This is no disadvantage, It simply means that optimized code was developed from the start. 8-12 Effects and Advantages of the MSP430 Architecture 8.3.5 Optimum C Code The C compiler of a microcomputer can use only the instructions that have a regular structure. Typical CISC (complex instruction set computer) instructions, which normally show strong addressing mode restrictions, are not used by the compilers. Instead, the compilers emulate the complex instructions with several ofthe simple instructions, resulting in a use of only 30% (!) of the implemented instructions. This is completely different with the MSP430. As the instructions (apart from the executed operation) are completely uniform, 100% ofthem are used by the compiler and not just 30%. As logical and arithmetical operations are executed directly and not by composed instructions, the execution time of the compiled code is shorter and less memory space is needed. Therefore, the same advantages that are valid for assembler programming are valid also for high-level language programming. Architecture and Instruction Set 8-13 The MSP430 Instruct/on Set ijb 8.4 The MSP430 Instruction Set In the following are all implemented and emulated instructions. @ * o 1 V N Z C src dst xx.B Label 8.4.1 Description of the used abbreviations: Logical NOT-Function Status Bit is affected by the instruction Status Bit is not affected by the instruction Status Bit is cleared by the instruction Status Bit is set by the instruction Overflow Bit in Status Register SR Negative Bit in Status Register SR Zero Bit in Status Register SR Carry Bit in Status Register SR Source Operand with,] Addressing Modes Destination Operand with 4 Addressing Modes Byte Operation of the Instruction xx Label of the source or destination Implemented Instructions The instructions that are implemented in the CPU follow. 8.4.1.1 Two Operand Instructions Status Bits V N Z ADD ADDC AND BIC BIS ~IT CMP DADO MOV SUB SUBC XOR 8-14 ADD.B ADDC.B AND.B BIC.B BIS.B BIT.B CMP.B DADD.B MOV.B SUB.B SUBC.B XOR.B src,dst src,dst src,dst src,dst src,dst src,dst src,dst src,dst src,dst src,dst src,dst src,dst Add src to dst Add src + Carry to dst src .and. dst ~ dst @src .and. dst ~ dst src .or. dst ~ dst src .and. dst ~ SR Compare src and dst (dst - src) Add src + Carry to dst (dec.) Copy src to dst Subtract src from dst Subtract src with Carry from dst src .xor. dst ~ dst C 0 *@Z 0 *@Z *@Z The MSP430 Instruction Set 8.4.1.2 Single Operand Instiuctlons The operand (src or dst) can be addressed with all seven addressing modes. Status Bits V N Z CALL PUSH RETI RRA RRC SWPB SXT PUSH.B RRA.B RRC.B dst src dst dst dst dst Subroutine call Copy operand onto stack Interrupt return Rotate dst right arithmetically Rotate dst right through Carry Swap bytes Sign extension into high byte C 0 0 *@Z 8.4.1.3 CondlflonalJun1ps The status bits are not affected by the jumps. With the signed jumps (JGE, JLT), the overflow bit is evaluated also, so that the jumps are executed correctly even in the case of overflow. Some jumps are the same (JC/JHS, JZlJEQ, JNC/JLO, JNElJNZ) but two mnemonics are used to get a better understanding of the program code. In case ofa comparison JHS gives a better understanding of the code than JC. JC JHS JEQ JZ JGE JLT JMP IN JNC JLO JNE JNZ Label Label . Label Label Label Label Label Label Label Label Label Label Jump if Carry = 1 Jump if dst is higher or same than src. (C = 1) Jump if dst equals src (Z = 1) Jump if Zero Bit =1 Jump if dst is greater than or equal to src (N .xor. V =0) Jump if dst is less than src (N .xor. V = 1) Jump unconditionally Jump if Negative Bit = 1 Jump if Carry = 0 Jump if dst is lower than src (C =0) Jump if dst is not equal to src (Z = 0) Jump if Zero Bit = 0 Architecture and Instruction Set 8-15 8-16 Benefits 8.5 Benefits The specification for the architecture of the MSP430 CPU contains the following requirements in order of importance: 1) 2) 3) 4) 5) 6) 7) High proceSSing speed Small CPU area on-chip High ROM efficiency Easy software development Usable into the future High flexibility Usable for modern programming techniques The following shows the finding of the optimum architecture out of the previous list of priorities. Several of the listed solutions affect more than one item of the list of priorities; these are shown at the item where they have the biggest impact. 8.5.1 High Processing Speed To increase the processing speed to a multiple of the speed of 4-bit or a-bit microcomputers, software and hardware related attributes were chosen. Hardware related attributes o Using 16-bit words, the analog-to-digital converter result can be processed immediately. Two operands (source and destination) are possible in one instruction. o No microcoding: every instruction is decoded separately and allows onecycle instructions. This is the case for register-to-register addressing, the normal addressing mode used for time critical software parts. o Interrupt capability for anyone of the a I/O-Ports: The periodical polling of the inputs is not necessary. o Vectored interrupts: This allows the fastest reaction to interrupts. Software related attributes o Implementation of the constant generator: The six most often used constants (-1. 0, 1. 2. 4, 8) are retrieved from the CPU with the highest possible speed. o High register count: Twelve commonly usable registers allow the storage of all time critical values to achieve the fastest possible access. Architecture and Instruction Set 8-17 Benefits u 8.5.2 Small CPU Area To get low overall cost for the MSP430, the smallest CPU without limiting its processing capability was achieved: D Use of a RISC structure: With few but strong instructions, any algorithm can be processed. Together with the constant generator, all commonly used instructions, not contained in the implemented instructions, are executable. D Use of 100% orthogonality: Every instruction inside one of the three instruction formats is completely similar to the other ones. This results in a strongly simplified CPU. D Only three instruction formats: Restriction to dual operand instructions, single operand instructions, and conditional jumps. 8.5.3 High ROM Efficiency To solve a given task with a small ROM, the following steps were taken: D Implementation of seven addressing modes: The possibility to select out of seven addressing modes for the source and out of four addressing modes for the destination allows direct access to all operands without any intermediate operations necessary. D Placing of PC, SP, and SR inside of the register set: The possibility to address these as registers saves ROM space. D Wide reach of the conditional jumps: Due to the eightfold jump distance of the MSP430 compared to other microcomputers, in most cases a branch instruction, that normally needs two words, is not necessary. D Use of a bytelword structure: ROM and RAM are addressable both as bytes and as words. This allows the selection of the most favorable format. 8.5.4 Easy Software Development Nearly all of the previously mentioned attributes of the architecture ease the development of software for the MSP430. 8.5.5 Usability on Into the Future The chosen von-Naumann-architecture allows a simple system expansion far beyond the currently addressable 64K bytes. If necessary, memory expansion up to 16M bytes is possible. 8-18 Conclusion 8.5.6 Flexibility of the Architecture To ensure that all intended peripheral modules, including currently unknown ones, can be connected easily to the MSP430 system. The following definitions were made: o Placing of the peripheral control registers into the memory space (memory mapped I/O). The use of the normal instructions for the peripheral modules makes special peripheral instructions superfluous. o All of the control registers and data registers of the peripheral modules can be read and written to. 8.5.7 Usable for Modern Programming Techniques Programming techniques like position independent coding (PIC), reentrant coding, recursive coding, or the use of high-level languages like C force the implementation of a stack pointer. The system SP is therefore implemented as a CPU register. 8.6 Conclusion This section demonstrates that the instruction set and the architecture of the MSP430 are easy to understand and that it is easy too to write software for the MSP430. Everyone who has written large program parts with the MSP430 as.sembler language has an antipathy to adapt again to the more or less unstructured architectures of the other 4-bit, 8-bit, and 16-bit microcomputers. Architecture and Instruction Se,t 8-19 8-20 Chapter 9 CPU Registers 11.1 f 9-1 CPU Registers 9.1 CPU Registers All of the MSP430 CPU registers can be used with all instructions. 9.1.1 The Program Counter PC One of the main differences from other microcomputer architectures relates to the Program Counter (CPU register RO) that can be used as a normal register with the MSP430. This means that all of the instructions and addressing modes can be used with the Program Counter too. A branch, for example, is made by simply moving an address into the PC: MOV MOV MOV #LABEL,PC LABEL, PC @R14,PC Branch to address LABEL Branch to the address contained in address LABEL Branch indirect, indirect R14 Note: The Program Counter always points to even addresses. This means that the LSB is always zero. The software has to ensure that no odd addresses are used if the Program Counter is involved. Odd PC addresses will result in nonpredictable behavior. 9.1.2 Stack Processing 9. 1.2. 1 .use of the System Stack Pointer (SP) The system stack pointer (CPU register R1) is a normal register like the others. This means it can use the same addressing modes. This gives good access to all items on the stack, not only to the one on the top of the stack. The system stack pointer (SP) is used for the storage of the following items: o o o o Interrupt return addresses and status register contents Subroutine return addresses Intermediate results Variables for subroutines, floating point package etc. When using the system stack, remember that the microcomputer hardware also uses the stack painter for interrupts and subroutine calls. To ensure the error-free running of the program it Is necessary to do exact housekeeping for the system stack. Note: The Stack Pointer always paints to even addresses. This means the LSB is always zero. The software has to ensure that no odd addresses are used if the Stack Pointer is involved. Odd SP addresses will end up in non-predictable results. 9-2 CPU Registers If bytes are pushed on the system stack, only the lower byte is used, the upper byte is not modified. !lOSh !lOSh l(SP),RS PUSH PUSH.S MOV.B OOOSh -> TOS xxOSh -> TOS Address odd byte 9.1.2.2 Software Stacks Every register from R4 to R15 can be used as a software stack pointer. This allows independent stacks for jobs that have a need for this. Every part of the RAM can be used for these software stacks. EXAMPLE: R4 is to be used as a software stack pointer. MOV #SW_STACK,R4 Init. SW stack pointer DECD MOV R4 item,O(R4) Decrement stack pointer Push item on stack Proceed Pop item from stack MOV @R4+,item2 Software stacks can be organized as byte stacks also. This is not possible for the system stack, which always uses 16-bit words. The example shows R4 used as a byte stack pointer: Init. SW stack pointer DECR4 MOV.B MOV.B @R4+,item2 Decrement stack pointer item,O(R4) ; Push item on stack Proceed ; Pop item from stack 9.1.3 Byte and Word Handling Every memory word is addressable by three addresses as shown In the Figure 9-1: o o o The word address: An even address N The lower byte address: An even address N The upper byte address: An odd address N+ 1 If byte addressing is used, only the addressed byte Is affected. No carry or overflow can affect the other byte. Note: Registers RD to R15 do not have an address but are treated in a special way. Byte addressing always uses the lower byte of the register. The upper byte is set to zero if the instruction modifies the destination. Therefore, all instructions clear the upper byte of a destination register except CMP.B, TST.B, BIT.B and PUSH.B. The source is never affected. CPU Registers 9-3 CPU Registers The wayan instruction treats data is defined with its extension: o o The extension .B means byte handling The extension .W (or none) means word handling EXAMPLES: The next two software lines are equivalent. The 16-bit values read in absolute address 050h are added to the value in R5. &OSOh,RS ; ADD 16-BIT VALUE TO RS ADD.W &OSOh,RS ; ADD 16-BIT VALUE TO RS ADD The 8-bit value read in the lower byte of absolute address 050h is added to the value contained in the lower byte of R5. The upper byte of R5 is set to zero. ADD.B &OSOh,RS Bit ; ADD a-BIT VALUE TO RS 8 7 15 I Upper Byte Odd Address N+ 1 I 0 Lower Byte Even Address N Word Address N Figure 9-1. Word and Byte Configuration If registers are used with byte instructions the upper byte of the destination register Is setto zero for all instructions except CMP.B, TST.B, BIT.B and PUSH.B. It is therefore necessary to use word instructions if the range of calculations can exceed the byte range. . . EXAMPLE: The two signed bytes OP1 and OP2 have to be added together and the result stored in word OP3. MOV.B SXT MOV.B SXT ADD.W OP1,R4· R4 OP2,OP3 OP3 R4,OP3 Fetch 1st operand Change to word format Fetch 2nd operand Change to word format 16-bit result to OP3 9.1.4 Constant Generator A statistical look at the numbers used with the Immediate Mode shows that a few small numbers are in use most often. The six most often used numbers can be addressed with the four addressing modes of R3 (constant generator 2) and with the two not usable addressing modes of R2 (status register). The six constants that do not need an additional 16-bit word when used with the immediate mode are: 9-4 Table 9-1. Constant Generator NUMBER EXPLANATION HEXADECIMAL REGISTER FIELD AD +0 Zero OOOOh R3 00 +1 Positive one 0001h R3 01 +2 Positive two 0002h R3 10 +4 Positive four 0004h R2 10 +8 Positive eight 0008h R2 11 -1 Negative one FFFFh R3 11 The assembler inserts these ROM-saving addressing modes automatically when one of the previously described immediate constants is encountered. But, only immediate constants are replaceable this way, not (for example) index values. If an immediate constant out of the constant generator is used, the execution time is equal to the execution time of the register mode. The most often used bits of the peripheral registers are located in the bits addressable by the constant generator whenever possible. 9.1.5 Addressing The MSP430 allows seven addressing modes for the source operand and four addressing modes for the destination. The addressing modes used are: Table 9-2. Addressing Modes ADDRESS BITS src dst SOURCE MODES DESTINATION MODES EXAMPLE 00 0 Register Register R5 01 1 Indexed Indexed TAB(R5) 01 1 Symbolic SymboUc TABLE 01 1 Absolute Absolute &BTCTL 10 - Indirect - @R5 Indirect autoincrement - @R5+ Immediate - #TABLE 11 11 The three missing addressing modes for the destination operand are not of much concern for the programming. The reason is: Immediate Mode: Not necessary forthe destination; immediate operands can always be placed into the source. Only in a very few cases it is necessary to have two immediate operands in one instruction CPU Registers 9-5 CPUReg~ers Indirect Mode: If necessary, the Indexed Mode with an index of zero is usable. For example: ADD #l6,O(R6) ; @R6 + 16 -> @R6 CMP R5,O(SP) ; R5 equal to TOS? The second previously shown example can be written in the following way, saving 2 bytes of ROM: CMP @SP,R5 ; R5 equal to TOS? (R5-TOS) Indirect Autoincrement Mode: With table processing, a method that saves ROM space and reduces the number of used registers to one can be used: EXAMPLE: The content of TAB1 is to be written into TAB2. TAB1 ends at the word preceding TAB1 END. LOOP MOV MOV.B CMP JNE #TABI, R5 @R5+,TAB2-TABI-I(R5) #TAB1END,R5 LOOP Initialize pointer Move TAB1 -> TAB2 End of TABI reached? No, proceed Yes, finished The previous example uses only one register instead of two and saves three words due to the smaller initialization part. The normally written, longer loop is shown in the following LOOP MOV MOV MOV.B INC CMP JNE #TABI,R5 #TAB2,R6 @R5+,O(R6) R6 #TABIEND,R5 LOOP ;Initialize pointers ;Move TAB1 -> TAB2 ;End of TAB1 reached? ;No, proceed ;Yes, finished In other cases it can be possible to exchange source and destination operands to have the auto increment feature available for a pointer. Each of the seven addressing modes has its own features and advantages: Register Mode: Fastest mode, least ROM requirements Indexed Mode: Random access to tables Symbolic Mode: Access to random addresses without overhead by loading of pOinters Absolute Mode: Access to absolute addresses independent of the current program address 9-6 CPU Registers Indirect Mode: Table addressing via register; code saving access to often referenced addresses Indirect Autolncrement Mode: Table addressing with code saving automatic stepping; for transfer routines Immediate Mode: Loading of pointers, addresses or constants within the instruction, With the use of the symboliC mode an interrupt routine can be as short as possible. An interrupt routine is shown that has to increment a RAM word COUNTER and to do a comparison if a status byte STATUS has reached the value 5. If this is the case, the status byte is cleared. Otherwise, the interrupt routine terminates: INTRPT INC COUNTER ;Increment counter CMP.S #5,STATUS ;STATUS = 5? JNE INTRET CLR. B STATUS ; STATUS =, 5: clear i t INTRET RETI No loading of pointers or saving and restoring of registers is necessary. The action is done immediately, without any overhead. 9.1.6 Program Flow Control 9.1.6.1 Computed Branches and Cslls The branch instruction is an emulated instruction that moves the destination address into the program counter: MOV dst, PC, ; EMULATION FOR BR @dst The ability to access the program counter in the same way as all other registers provides interesting options: 1) The destination address can be taken from tables: see Section 9.2.5 2) The destination address can be calculated 3) The destination address can be a constant. This is the usual method of getting the address. 9.1.6.2 Nesting of Subroutines Due to the stack orientation of the MSP430, one of the main problems of other architectures does not playa role here at all. Subroutine nesting can proceed as long as RAM is available. There is no need to keep track of the subroutine calls as long as all subroutines terminate with the Return from Subroutine inCPU Registers 9-7 CPU Rep!sters struction RET. If subroutines are left without the RET instruction, some housekeeping is necessary; popping of the return address or addresses from the stack. 9.1.6.3 Nesting of Interrupts Nesting of interrupts gives no problem at all, provided there is enough RAM for the stack. For every occurring interrupt, two words on the stack are needed for the storage of the status register and the return address. To enable nested interrupts, it is necessary to only include an EINT instruction into the interrupt handler. If the interrupt handlers are as short as possible (a good real-time practice), nesting may not be necessary. EXAMPLE: The basic timer interrupt handler is woken-up with 1 Hz only, but has to do a lot of things. The interrupt nesting is therefore used. The latency time is 8 ciock cycles only. Interrupt handler for Basic Timer: Wake-up with 1Hz BT_HAN EINT INC,B SECCNT CMP.B lI60,SECCNT MIN1 JHS RETI Enable interrupt for nesting Counter for seconds +1 1 minute elapsed? Yes, do necessary tasks No return to LPM3 One minute elapsed: Return is removed from stack, a branch to the necessary tasks is made, There it is decided how to proceed MIN1 INC CLR MINCNT SECCNT RETI Minute counter +1 o -> SECCNT Star.t of necessary tasks Tasks completed 9.1.6.4 Jumps Jumps allow the conditional or unconditional leaving of the linear program flow. Jumps cannot reach every address of the address space. But they have the advantage of needing only one word and only two MeL!( cycles. The 10-bit offset field allows jumps of 512 words maximum forward and 511 words, maximum, backwards. This is four to eight times the normal reach of a jump. Only in a few cases, the 2-word branch is necessary. Eight Jumps are possible with the MSP430; four of them have two mnemonics to allow better readability: 9-8 Table 9-3. Jump Usage MNEMONIC CONDITION JMP label Unconditional Jump APPUCATIONS JEQlabel JumpifZ=1 After comparisons: src = dst Test lor zero contents Program control transler JZlabel Jump il Z = 1 JNE label Jump il Z = 0 After comparisons: src # dst JNZ label JumpilZ=O Test lor nonzero contents JHS label Jump ilC = 1 After unsigned comparisons: dst ~ src JClabel JumpilC-1 Test lor a set carry JLO label JumpilC- 0 After unsigned comparisons dst < src JNC label JumpilC=O Test lor a reset carry JGE label Jump il N .xOR. V - 0 After signed comparisons: dst ~ src JLTlabel Jump il N .XOR. V = 1 After signed comparisons: dst < src IN label JumpilN=1 Test lor the sign of a result: dst < 0 Note: It is important to use the appropriate conditional jump for signed and unsigned data. For positive data (0 to 07FFFh or 0 to 07Fh) both signed and unsigned conditional jumps operate similarly. This changes completely when used with negative data (OaOOOh to OFFFFh or OaOh to OFFh): the signed conditional jumps treat negative data as smaller numbers than the positive ones, and the unsigned conditional jumps treat them as larger num" bers than the positive ones. No Jump if Positive is provided, only a Jump if Negative. But after several instructions, it is possible to use the Jump if Greater Than or Equal for this purpose.lt must be ensured that only the instruction preceding the JGE resets the overflow bit V. The following instructions ensure this: AND BIT RRA SXT TST src,dst src,dst dst dst dst v <- 0 v <- 0 v <- 0 V <- 0 V <- 0 If this feature is used, it should be noted within the comment for later software modifications. For example: MOV TST JGE ITEM,R7 R7 ITEMPOS FETCH ITEM V <- 0, ITEM POSITIVE? V=O: JUMP IF >= 0 CPU Registers 9-9 CPU Reg/sters Note: If addresses are computed only the unsigned jumps are adeql,late. Addresses are always unsigned, positive numbers. No Jump if Overflow is provided. If the status of the overflow bit Is needed from the software, a simple bit test can be used (the BIT instruction clears the overflow bit, but Its state Is read correctly before): OV 9-10 .EQU OlOOh Bit address in SR BIT JNZ #OV,SR OVFL Test Overflow Bit and clear it If OV = 1 branch to label OVFL If OV = 0 continue here Special Coding Techniques 9.2 Special Coding Techniques The flexibility of the MSP430 CPU together with a powerful assembler allows coding techniques not available with other microcomputers. The most important ones are explained in the following sections. 9.2.1 Conditional Assembly For a detailed description of the syntax please refer to MSP430 Family Assembler Language Tools User's Guide. Conditional assembly provides the ability to compile different lines of source into the object file depending on the value of an expression that is defined in the source program. This makes it easy to alter the behavior of the code by modifying one single line in the source. The following example shows how to use of conditional assembly. The exam, pie allows easy debugging of a program that processes input from the ADC by pretending that the input of the ADC is always 07FFh. The following is the routine used for reading the input of the ADC. It returns the value read from ADC input AO in RB. DEBUG ACTL ADAT IFG2 ADIFG .set .set .set .set .set 1 01l4h 01l8,h ;1= debugging mode; 0= normal mode 3 4 get-fiDC_value: WAIT .IF DEBUG=l #07FFh,R8 MOV . ELSE BIC #60,&ACTL BIC.B #ADIFG,&IFG2 BIS #l,&ACTL BIT.B #ADIFG,&IFG2 JZ WAIT MOV &ADAT,R8 .ENDIF RET Input channel is AO Start conversion Wait until conversion' is ready With a little further refining of the code, better results can be achieved. TI1e following piece of code shows more built-in ways to debug the written code. The second debug code, where debug=2, returns 0700h and OBOOh alternating. CPU Registers 9-11 ~peclal Coding Techn~ues DEBUG .SET ACTL ADAT IFG2 ADIFG ; 1= debug mode 1; 2= deb. mode 2; 0= normal mode 1 01l4h 01l8h .SET .SET .SET . SET 3 4 get_ADC_value: VAR OSC WAIT . SECT . WORD, "VAR"'0200h 0700h .IF MOV .ELSEIF MOV SUB MOV .ELSE BIC BIC BIS BIT JZ MOV .ENDIF RET DEBUG=l #07FFh,R8 DEBUG=2 '#OFOOh,R8 OSC,R8 R8,OSC #60h,&ACTL #ADIFG,&IFG2 #l,&ACTL #ADIFG,&IFG2 WAIT &ADAT,R8 Return a constant value Return alternating values Input channel is AO Start conversion Wait until conversion is ready Conditional assembly is not restricted to the debug phase of software development. The main use is normally to get different software versions out of one source. For every version only the necessary software parts are assembled and the unneeded parts are left out by conditional assembly. The big advantage is the single source that is maintained. An example of this is the MSP430 floating point package with two different number lengths (32 and 48 bits) contained in one source. Before assembly the desired length is defined by an .EQU directive. See Section 5.6, The Floating Point Package for details. 9.2.2 Position Independent Code , The architecture of the MSP430 allows the easy implementation of position independent code (PIC). This is a code, which may run anywhere in the address space of a computer without any relocation needed. PIC is possible with the MSP430 because of the allocation of the PC inside of the register bank. The addressability of the PC is often used. Links to other PIC blocks are possible only by references to absolute addresses (pointers). 9-12 Special Coding Techniques EXAMPLE: Code is transferred to the RAM from an outside storage (EPROM, ROM, or EEPROM) and executed there at full speed. This code needs to be PIC. The loaded code may have several purposes: a a a 9.2.2.1 Application specific software that is different for some versions Additional code that was not anticipated before mask generation Test routines for manufacturing purposes Referencing of Code Inside Position Independent Code The referenced code or data is located in the same block of PIC as the program resides. Jumps Jumps are position independent anyway: their address information is an offset to the destination address. Branches ADD @PC,PC .WORD DESTINATION-$ Branch to label DESTINATION Address pointer Subroutine Calls ; Calling a subroutine starting at the label SUBR: SC MOV ADD CALL PC,Rn #SUBR-$,Rn Rn Address SC+2 -> Rn Add offset (SUBR - (SC+2» SC+2+SUBR-(SC+2» = SUBR Operations on Data The symbolic addressing mode is position independent. An offset to the PC is used. No special addressing is necessary MOV CMP DATA,Rn DATAl,DATA2 DATA is addressed symbolically Jump Tables The status contained in Rstatus decides where the SW continues. Rstatus contains a multiple of 2 (0,2,4 ... 2n). Range: +512 words, -511 words ADD JMP JMP Rstatus,PC STATUSO STATUS2 Rstatus - (2x status) Code for status = 0 Code for status 2 JMP STATUSn Code for status 2n CPU Registers 9-13 ~al Coding Techniques Branch Tables The status contained in Rstatus decides where the SW continues. Rstatus contains a multiple of 2 (0, 2, 4 ... 2n). Range: complete 64K Rstatus = status Offset for status 0 .WORp STATUS2-TABLE Offset for status 2 . WORD STATUSn-TABLE Offset for status 2n ADD TABLE (RstatuS) ,PC TABLE . WORD STATUSO-TABLE 9.2.2.2 Referencing of Code Outside of PIC (Absolute) The referenced code or data is located outside the block of PIC. These addresses can be absolute addresses only (e.g. for linking to other blocks or peripheral addresses). Branches Branching to the absolute address DESTINATION: BR #DESTINATION ; #DESTINATION -> PC Subroutine Calls Calling a subroutine starting at the absolute address SUBR: CALL #SUBR ; IISUBR -> PC Operations on Data Absolute mode (indexed mode with status register SR = 0). SR does not loose its information! CMP ADD PUSH &DATA1,&DATA2 &DATAl,Rn &DATA2 DATAl + 0 = DATAl DATA2 -> stack Branch Tables The status contained in Rstatus decides where the SW continues. Rstatus steps in increments of 2. The table is located in absolute address space: MOV TABLE(Rstatus) ,PC .sect xxx TABLE .WORD STATUSO 9-14 Rstatus - status Table in absolute address space Code for status = 0 Special.~oding Techniques .WORD STATUS2 Code for status = 2 .WORD STATUSn Code for status = 2n Table is located in PIC address space, but addresses are absolute: MOV ADD L$l ADD MOV TABLE . WORD . WORD Rstatus,Rhelp PC,Rhelp #TABLE-L$l,Rhelp @Rhelp,PC STATUSO STATUSl . WORD STATUSn Rstatus contains status Status + L$l -> Rhelp Status+L$l+TABLE-L$l Computed address to PC Code for status = 0 2 Code for status Code for status - 2n The previously shown program examples can be implemented as MACROs if needed. This would ease the usage and enhance the legibility. 9.2.3 Reentrant Code If the same subroutine is used by the background program and interrupt routines, then two copies of this subroutine are necessary with normal computer architectures. The stack gives a method of programming that allows many tasks to use a single copy of the same routine. This ability of sharing a subroutine for several tasks is called reentrancy. Reentrancy allows the calling of a subroutine despite the fact that the current task has not yet finished using the subroutine. The main difference of a reentrant subroutine from a normal one is that the reentrant routine contains only pure code. That is, no part of the routine is modified during the usage. The linkage between the routine itself and the calling software is possible only via the stack (i.e. all arguments during calling and all results after completion have to be placed on the stack and retrieved from there). The following conditions must be met for reentrant code: o o No usage of dedicated RAM; only stack usage If registers are used, they need to be saved on the stack and restored from there. EXAMPLE: A conversion subroutine Binary to BCD needs to be called from the background and the interrupt part. The subroutine reads the Input number from TOS and places the 5-digit result also on TOS (two words). The subroutines save all registers used on the stack and restore them from there or compute directly on the stack. CPU Registers 9-15 Special Coding Techniques POSH CALL MOV MOV R7 #BINBCD @SP+,LSD @SP+, MSD R7 CONTAINS THE BINARY VALUE TO BE CONVERTED TO BCD BCD-LSDs FROM STACK BCD-MSD ' FROM STACK 9.2.4 Recursive Code Recursive subroutines are subroutines that call themselves. This is not possible with typical architectures; stack processing is necessary for this often used feature. A simple example for recursive code is a line printer handler that calls itself for the inserting of a form feed after a certain number of printed lines. This self-calling allows the use all of the existent checks and features of the handler without the need to write it more than once. The following conditions must be met for recursive code: o o o No use of dedicated RAM; only stack usage A termination item must exist to avoid infinite nesting (e.g., the lines per page must be greater than 1 with the above line printer example) If registers are used, they need to be saved and restored on the stack EXAMPLE: The line printer handler inserts a form feed after 70 printed lines LPHAND POSH CMP JLT CALL ,BYTE R4 #70,LINES L$500 #LPHAND CR,FF Save R4 70 lines printed? No, proceed Yes, output Carriage Return and Form Feed L$500 9.2.5 Flag Replacement by Status Usage Flags have several disadvantages when used for program control: o Missing transparency (flags may depend on other flags) o Possibility of nonexistent flag combinations if not handled very carefully o ' Slow speed: the flags can be tested only serially The MSP430 allows the use of a status (contained in a RAM byte or register), which defines the current program part to be used. This status is very descrip9-16 Special Coding Techniques tive and prohibits nonexistent combinations. A second advantage is the high speed of the decision. Only one instruction is needed to get to the start of the appropriate handler (see Branch Tables). The program parts that are used currently define the new status dependent on the actual conditions. Normally the status is only incremented, but it can be changed to be more random too. EXAMPLE: The status contained in register Rstatus decides where the software continues. Rstatus contains a multiple of 2 (0, 2, 4 ... 2n) Range: Complete 64K MOV TABLE(Rstatus),PC ;Rstatus - status TABLE .WORD STATUSO Address handler for status 0 . WORD STATUS 2 Address handler for status = 2 . WORD STATUSn Address handler for status = 2n STATUSO INCD JMP Rstatus HEND start handler status 0 Next status is 2 Common end The previous solution has the disadvantage of using words even if the distances to the different program parts are small. The next example shows the use of bytes for the branch table. The SXT instruction allows backward references (handler starts at lower addresses than TABLE4). BRANCH TABLES WITH BYTES: Status in R5 (0, 1, 2, Usable range: TABLE4-128 to TABLE4+126 TABLE4 PUSH.B SXT ADD . BYTE TABLE4(R5) @SP @SP+,PC STATUSO-TABLE4 .BYTE STATUSI-TABLE4 . BYTE STATUSn-TABLE4 .. n) STATUSx-TABLE4 -> STACK Forward/backward references TABLE4+STATUSx-TABLE4 -> PC DIFFERENCE TO START OF HANDLER ; Offset for status = n If only forward references are possible (normal case), the addressing range can be doubled. The next example shows this: Stepping is forward only (with doubled forward range) Status is contained in R5 (0, 1, .. n) CPU Registers 9-17 Special Coding Techniques Usable range: TABLES to TABLES+2S4 TABLES . BYTE ; STATUSx-TABLE -> STACK TABLES (RS) Hi byte <- 0 l(SP) @SP+,PC TABLE+STATUSx-TABLE -> PC STATUSO-TABLES DIFFERENCE TO START OF HANDLER STATUSl-TABLES . BYTE STATUSn-TABLES PUSH.B CLR.B ADD . BYTE ; Offset for status = n The previous example can be made shorter and faster if a register can be used: Stepping is forward only (with doubled forward range) Status is contained in R5 (0, 1, 2 .. n) Usable range: TABLES to TABLES+2S4 TABLES MOV.B ADD . BYTE TABLE5(R5),R6 R6,PC STATUSO-TABLE5 . BYTE STATUSl-TABLE5 . BYTE STATUSn-TABLE5 STATUSx-TABLE5 -> R6 TABLE5+STATUSx-TABLE5 -> PC DIFFERENCE TO STA'RT OF HANDLER ; Offset for status = n The addressable range can be doubled once more with the following code. The status (0, 1, 2, .. n) is doubled before its use. The addressable range may be doubled with the following code: The "forward only" version with an available register (R6) is shown: Status 0, 1, 2 ... n Usable range: TABLE6 to TABLE6+510 MOV.B TABLE6(RS),R6 (STATUSx-TABLE6)/2 RLA R6 STATUSx-TABLE6 ADD R6,pC TABLE6+STATUSx-TABLE6 -> PC TABLE6 .BYTE (STATUSO-TABLE6)/2 Offset for Status - 0 .BYTE (STATUSl-TABLE6)/2 .BYTE (STATUSn-TABLE6)/2 Offset for Status - ri 9.2.6 Argument Transfer With Subroutine Calls Subroutines often have arguments to work with. Several methods existfor the passing of these arguments to the subroutine: 9-18 o o o o On the stack In the words (bytes) after the subroutine call In registers The address is contained in the word after the subroutine call The passed information itself may be numbers, addresses, counter contents, upper and lower limits etc. It only depends on the application. 9.2.6.1 Arguments on the Stack The arguments are pushed on the stack and read afterwards by the called subroutine. The subroutine is responsible for the necessary housekeeping (here, the transfer of the return address to the top of the stack). o o Advantages: • Usable generally; no registers have to be freed for argument passing • Variable arguments are possible Disadvantages: • Overhead due to necessary housekeeping • Not easy to understand EXAMPLE: The subroutine SUBR gets its information from two arguments pushed onto the stack before being called. No information is given back and a normal return from subroutine is used. SUBR PUSH PUSH CALL argumentO argument1 #SUBR 1st ARGUMENT FOR SUBROUTINE 2nd ARGUMENT SUBROUTINE CALL MOV MOV MOV 4 (SP), Rx 2(SP),Ry @SP,4(SP) #4,SP COPY ARGUMENTO TO Rx COpy ARGUMENT1 TO Ry RETURN ADDRESS TO CORRECT LOC. PREPARE SP FOR NORMAL RETURN PROCESSING OF DATA NORMAL RETURN ADD RET CPU Registers 9-19 Special Coding Techniq~~ After the subroutine call, the stack looks as follows: After the RET, it looks like this: TOS before CALL SP ~ Argumento AddreuN+4 Argument1 AddreBSN+2 Return Addreu SP ~ AddreseN Figure 9-2. Argument Allocation on the Stack EXAMPLE: The subroutineSUBR gets its information from two arguments pushed onto the stack before being called. Three result words are returned on the stack. It is the responsibility of the calling program to pop the results from the stack. SUBR 9-20 PUSH PUSH CALL POP POP POP argumentO argumentl #SUBR R15 R14 R13 1st ARGUMENT FOR SUBROUTINE 2nd ARGUMENT SUBROUTINE CALL RESULT2 -> R15 RESULTl -> R14 RESULTO -> R13 MOV MOV 4(SP),Rx 2(SP),Ry PUSH MOV MOV MOV RET 2(SP) RESULTO,6(SP) RESULT1,4(SP) RESULT2,2(SP) COpy ARGUMENTO TO Rx COpy ARGUMENTl TO Ry PROCESSING CONTINUES SAVE RETURN ADDRESS 1st RESULT ON STACK 2nd RESULT ON STACK 3rd RESULT ON STACK SPSC;iaJ Codin~ Te;hniqu~ After the RET, it looks like this: After the subroutine call, the stack looks as follows: TOS before CALL SP ~ Argumento AddressN+4 ResultO Argument1 AddressN+2 Result1 Return Address AddressN SP ~ Result2 Figure 9-3. Argument and Result Allocation on the Stack Note: If the stack is involved during data transfers, it is very important to have in mind that only data at or above the top of stack (TOS, the word the SP pOints to) is protected against overwriting by enabled interrupts. This does not allow the SP to move above the last item on the stack. Indexed addressing is needed instead. 9.2.6.2 Arguments Following the Subroutine Call The arguments follow the subroutine call and are read by the called subroutine. The subroutine is responsible for the necessary housekeeping (here, the adaptation of the return address on the stack to the 1st word after the arguments). o Advantages: • o Very clear and easily readable interface Disadvantages: • Overhead due to necessary housekeeping • Only fixed arguments possible EXAMPLE: The subroutine SUBR gets its information from two arguments following the subroutine call. Information can be given back on the stack or in registers. CALL #SUBR .WORD START .BYTE 24,0 SUBROUTINE CALL START OF TABLE LENGTH OF TABLE, FLAGS CPU Registers 9-21 Special CodIng Techniques SUBR MOV MOV MOV MOV @SP, RS @RS+,R6 @RS+,R7 RS,O(SP) RET 1st instruction after CALL COPY ADDRESS 1st ARGUMENT TO RS MOVE 1st ARGUMENT TO R6 MOVE ARGUMENT BYTES TO R7 ADJUST RETURN ADDRESS ON STACK PROCESSING OF DATA NORMAL RETURN 9.2.6.3 Arguments In Registers The arguments are moved into defined registers and used afterwards by the subroutine. CI Advantages: • • • Simple interface and easy to understand Very fast Variable arguments are possible CI Disadvantages: • Registers have to be freed EXAMPLE: The subroutine SUBR gets its information from two registers which' are loaded before the calling. Information can be given back, or not with the same registers. MOV MOV CALL argO,RS arg1,R6 #SUBR SUBR 1st ARGUMENT FOR SUBROUTINE 2nd ARGUMENT SUBROUTINE CALL PROCESSING OF DATA NORMAL RETURN RET 9.2.7 Interrupt Vectors in RAM If the destination address of an interrupt changes with the program run, it is valuable to have the ability to modify the pointer. The vector itself (which resides in ROM) cannot be changed but a second pOinter residing in RAM can be used for this purpose. EXAMPLE: The interrupt handler for the basic timer starts at location BTHAN 1 after initialization and at BTHAN2 when a certain condition is met (for example, when a calibration is made). BASIC TIMER INTERRUPT GOES TO ADDRESS BTVEC. THE INSTRUCTION 9-22 Special Coding Techniques "MOV @PC,PC" WRITES THE ADDRESS IN BTVEC+2 INTO THE PC: THE PROGRAM CONTINUES AT THAT ADDRESS .sect "VAR",0200h BTVEC .word 0 .word 0 RAM START OPCODE "MOV @PC,PC" ACTUAL HANDLER START ADDR. ; THE SOFTWARE VECTOR BTVEC IS INITIALIZED: INIT MOV MOV #04020h,BTVEC #BTHANl,BTVEC+2 ; OPCODE "MOV @PC,PC ; START WITH HANDLER BTHANI ; INITIALIZATION CONTINUES THE CONDITION IS MET: THE BASIC TIMER INTERRUPT IS HANDLED AT ADDRESS BTHAN2 STARTING NOW MOV #BTHAN2,BTVEC+2 ; CONT. WITH ANOTHER HANDLER THE INTERRUPT VECTOR FOR THE BASIC TIMER CONTAINS THE RAM ADDRESS OF THE SOFTWARE VECTOR BTVEC: .sect "BTVect",OFFE2h .WORD BTVEC VECTOR ADDRESS BASIC TIMER FETCH ACTUAL VECTOR THERE CPU Registers 9-23 Instruction Execution Cycles 9.3 Instruction Execution Cycles 9.3.1 Double Operand Instructions With the following scheme, it is relatively easy to remember how many cycles a double operand instruction will need to execute. Figure 9-4 shows the number of cycles for all 28 possible combinations of the source and destination addressing modes. All similar addressing modes are condensed. Rdst X(Rdst) SYMBOLIC &ABSOLUT Rsrc 1t 4 @Rsrc, @Rsrc+, #N 2t 5 3 6 X(Rsrc), SYMBOLIC, &ABSOLUT t: Add one cycle If Rds! is PC Figure 9-4. Execution Cycles for Double Operand Instructions EXAMPLE: the instruction execution. ADD #500h, 16 (R5) needs 5 cycles for the 9.3.2 Single Operand Instructions The simple and clear scheme of the double operand instructions is not applicable to the six single operand instructions. They differ too much. Figure 9-5 gives an overview. 9-24 Instruction Execution Cycles SWPB SXT RRx PUSH Rdst 1 3 4 @Rdst 3 4 4 @Rdst+, #N 3 4 5 X(Rdst), SYMBOLIC, &ABSOLUT 4 5 5 CALL Figure 9-5. Execution Cycles for Single Operand Instructions EXAMPLE: the instruction 9.3.3 PUSH # 5 0 ah needs 4 cycles for the execution. Jump Instructions All seven conditional jump Instructions need two cycles for execution, independent if the jump condition is met or not. The same is true for the unconditional jump instruction, JMP. 9.3.4 Interrupt Timing An enabled interrupt sequence needs eleven cycles overhead: o Six cycles for the storage of the PC and the SR on the stack until the first instruction of the interrupt handler is started o Five cycles for the return from interrupt-by the instruction RETI-until the first instruction of the interrupted program is started. If the interrupt is requested during the low power modes 3 or 4, then additional two cycles are needed. CPU Registers 9-25 TI Worldwide Technical Support Internet TI Semiconductor Home Pege www.ti.com/sc TI Distributors www.ti.com/sc/docS/generaVdistrib.htm Product Information Centers Americas Phone Fax Internet +1(972) 644-5580 +1(972) 480-7800 www.ti.com/sc/ampic Europe. Middle East. and Africa Asia Phone Belgium (English) France Germany Israel (English) Italy Netherlands (English) Spain Sweden (English) United Kingdom Fax Email Internet Phone International Domestic Australia China Hong Kong India Indonesia Korea Malaysia New Zealand Philippines Singapore Taiwan Thailand Fax Email Internet +32 to) 27 45 55 32 +33 to) 1 30 70 11 64 +49 to) 816180 3311 18009490107 800 791137 +31 to) 546 87 95 45 +34 902 35 40 28 +46 to) 8587 555 22 +44 to) 1604 66 33 99 +44 to) 1604 66 33 34 epic@ti.com www.ti.com/sc/epic Japan Phone International "Domestic Fax International Domestic Intenet International Domestic +81-3-3344-5311 0120-81-0026 +866-2-23786800 Local Access Code 1-800-881-011 10810 800-96-1111 000-117 001-801-10 080-551-2804 1-800-800-011 000-911 105-11 800-0111-111 080-006800 0019-991-1111 886-2-2378-6808 tiasia@ti.com www.ti.com/sc/apic +81-3-3344-5317 0120-81-0036 www.ti.com/sc/jpic www.tij.co.jp/pic ~ 2000 Texas Instruments Incorporated 11.2 ~TEXAS INSTRUMENTS illIlIm.!li!: -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 -800-800-1450 .J!} TEXAS INSTRUMENTS Copyright © 2000, Texas Instruments Printed in UK SLAA024


Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.6
Linearized                      : No
Create Date                     : 2017:08:30 20:54:55-08:00
Modify Date                     : 2017:08:30 21:41:22-07:00
Has XFA                         : No
XMP Toolkit                     : Adobe XMP Core 4.2.1-c041 52.342996, 2008/05/07-21:37:19
Metadata Date                   : 2017:08:30 21:41:22-07:00
Producer                        : Adobe Acrobat 9.0 Paper Capture Plug-in
Format                          : application/pdf
Document ID                     : uuid:40f912b6-498d-e040-acd9-2113fc8aac14
Instance ID                     : uuid:aae683f1-5079-d342-97f4-b376c304c727
Page Layout                     : SinglePage
Page Mode                       : UseNone
Page Count                      : 1095
EXIF Metadata provided by EXIF.tools

Navigation menu