Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Metering Application Report

Download as pdf or txt
Download as pdf or txt
You are on page 1of 428

Metering Application Report

Lutz Bierl Version 3.0 April 1997

Metering Application Report

MSP430 Family

1 INTRODUCTION____________________________________________________________ 12
1.1 Notation ________________________________________________________________________ 12 1.2 The MSP430 Family ______________________________________________________________ 13
1.2.1 MSP430x31x _________________________________________________________________________ 14 1.2.2 MSP430x32x _________________________________________________________________________ 15 1.2.3 MSP430x33x _________________________________________________________________________ 16

1.3 Some Advantages of the MSP430 Concept ____________________________________________ 16


1.3.1 1.3.2 1.3.3 1.3.4 RISC Architecture without RISC-Disadvantages ______________________________________________ Realtime Capability ____________________________________________________________________ Stability of the System Clock Generator_____________________________________________________ Stack Processing Capability ______________________________________________________________ 16 17 17 17

1.4 The Operating Modes used for Metering Applications __________________________________ 18


1.4.1 The Active Mode ______________________________________________________________________ 18 1.4.2 The Low Power Mode 3 _________________________________________________________________ 18 1.4.3 The Low Power Mode 4 _________________________________________________________________ 20

2 THE ANALOG-TO-DIGITAL CONVERTERS ____________________________________ 22


2.1 The 14-bit Analog-to-Digital Converter ______________________________________________ 22
2.1.1 The Current Source_____________________________________________________________________ 2.1.2 The 14-bit Analog-to-Digital Converter used in 14-bit Mode ____________________________________ 2.1.2.1 ADC with signed signals_____________________________________________________________ 2.1.2.2 Four-Wire Circuitry for Sensors _______________________________________________________ 2.1.2.3 Referencing with Reference Resistors __________________________________________________ 2.1.2.4 Interrupt Handling__________________________________________________________________ 2.1.2.5 Enlargement to 16-bit Mode __________________________________________________________ 2.1.3 The 14-bit Analog-to-Digital Converter used in 12-bit Mode ____________________________________ 2.1.3.1 ADC with signed signals_____________________________________________________________ 2.1.3.2 Interrupt Handling__________________________________________________________________ 2.1.4 Connection of long Sensor Lines __________________________________________________________ 2.1.5 Grounding____________________________________________________________________________ 2.1.6 Connection of Current consuming Loads to SVcc _____________________________________________ 2.2.1 2.2.2 2.2.3 2.2.4 Interrupt Handling _____________________________________________________________________ Connection of long Sensor Lines __________________________________________________________ Grounding____________________________________________________________________________ Voltage Measurement with the Universal Timer Port/Module ____________________________________ 23 24 25 28 30 31 33 35 37 38 40 41 42 46 52 52 53

2.2 The Universal Timer/Port Module used as an ADC ____________________________________ 43

3 HARDWARE APPLICATIONS_________________________________________________ 56
3.1 I/O-Port Usage ___________________________________________________________________ 56
3.1.1 General Usage ________________________________________________________________________ 3.1.2 Zero Crossing Detection _________________________________________________________________ 3.1.3 Output Buffering_______________________________________________________________________ 3.1.4 Universal Timer/Port I/Os _______________________________________________________________ 3.1.4.1 I/Os used with the Analog-to-Digital Converter ___________________________________________ 3.1.4.2 I/Os used without ADC______________________________________________________________ 3.1.5 I/Os used for fast serial Transfer___________________________________________________________ 56 58 59 60 61 61 62

3.2 Storage of Calibration Constants____________________________________________________ 64


3.2.1 External EEPROM for Calibration Constants ________________________________________________ 64 3.2.2 Internal RAM for Calibration Constants_____________________________________________________ 66

3.3 M-BUS Connection _______________________________________________________________ 67 3.4 I2C BUS Connection ______________________________________________________________ 68

10

MSP430 Family

Metering Application Report

3.5 Hardware Optimization ___________________________________________________________ 72


3.5.1 Use of unused Analog Inputs _____________________________________________________________ 3.5.1.1 Analog Inputs used for Digital Inputs ___________________________________________________ 3.5.1.2 Analog Inputs used for Digital Outputs _________________________________________________ 3.5.2 Use of unused Segment Lines for Digital Outputs _____________________________________________ 3.6.1 R/2R Method _________________________________________________________________________ 3.6.2 Weighted Resistors Method ______________________________________________________________ 3.6.3 Digital-to-Analog Converters connected via the I2C Bus________________________________________ 3.6.4 PWM-Digital-to-Analog Converter with the Universal Timer/Port Module _________________________ 3.6.5 PWM-Digital-to-Analog Converter with the Timer_A__________________________________________ 3.6.5.1 PWM-DAC with Timer_A running in Continuous Mode ____________________________________ 3.6.5.2 PWM-DAC with Timer_A running in Up Mode __________________________________________ 3.6.5.3 PWM-DAC with Timer_A running in Up-Down Mode _____________________________________ 72 72 73 74 76 77 78 78 84 85 86 86

3.6 Digital-to-Analog Converters _______________________________________________________ 76

3.7 Connection of large external Memories ______________________________________________ 88 3.8 Power Supplies for MSP430 Systems ________________________________________________ 91
3.8.1 Battery Driven Systems _________________________________________________________________ 91 3.8.2 Accumulator Driven Systems _____________________________________________________________ 92 3.8.3 Mains Driven Systems __________________________________________________________________ 94 3.8.3.1 Transformer Power Supplies__________________________________________________________ 94 3.8.3.1.1 Half-Wave Rectification _________________________________________________________ 94 3.8.3.1.2 Full-Wave Rectification _________________________________________________________ 97 3.8.3.2 Capacitor Power Supplies ____________________________________________________________ 99 3.8.3.2.1 Capacitor Supplies for a Single Voltage ____________________________________________ 100 3.8.3.2.2 Capacitor Supplies for two Voltages_______________________________________________ 101 3.8.4 Supply from other System DC-Voltages____________________________________________________ 103 3.8.4.1 Zener Diode _____________________________________________________________________ 103 3.8.4.2 Zener Diode and Operational Amplifier ________________________________________________ 103 3.8.4.3 Reference Diode with Operational Amplifier ____________________________________________ 103 3.8.4.4 Integrated Voltage Regulator ________________________________________________________ 104 3.8.5 Supply from the M-Bus ________________________________________________________________ 105 3.8.5.1 M-BUS Supply ___________________________________________________________________ 105 3.8.5.2 Mixed Supply ____________________________________________________________________ 105 3.8.6 Supply via Glass Fiber Cable ____________________________________________________________ 106 3.8.6.1 Description of the Hardware _________________________________________________________ 107 3.8.6.2 Working Sequence ________________________________________________________________ 107 3.8.7 Conclusion __________________________________________________________________________ 108

11

Metering Application Report

MSP430 Family

1 INTRODUCTION
The MSP430 is a 16-bit microcomputer having special features not commonly available with other microcomputers: Complete system on-chip (LCD, ADC, I/Os, ROM, RAM, Watchdog, UART, Basic Timer) Extremely low power consumption: only 4.2nWs/instruction max. High speed (300ns/instruction @ 3.3MHz with register, register addressing mode) RISC structure (27 core instructions) 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 crystal necessary due to a Frequency Locked Loop (FLL) oscillator Full real time capability: the stable, nominal system clock frequency is reached after only six clocks when woken-up from Low Power Mode 3: this means no waiting for the coming-up of the main crystal.

These features make it very easy to program the MSP430 in assembler or in C-language. For example, despite the low instruction count of only 27, the MSP430 is capable of emulating almost the complete instruction set of the legendary PDP11. NOTES It is advised to have the "MSP430 Architecture Users Guide and Module Library" readily available. This book contains valuable information, illustrations and a detailed description of the MSP430 hardware. Additionally the "MSP430 Software Users Guide" is recommended. It contains further information regarding the instruction set, besides other more common software information. All the examples given refer to the "MSP430 Family Architecture Users Guide 1996". It can not be guaranteed that new revisions will behave exactly in the same manner as described in this Users Guide. See "Important Notice" above. All the given software examples are tested for functionality. They may be used freely for the customers software developments.

1.1 Notation The following abbreviations and special notations are used: R4|R3 R1||R2 AGND .or. .and. .xor. .not. src 32-bit number. MSBs in CPU register R4, LSBs in R3 Resistor R1 is connected in parallel with resistor R2 Ground connection for the Analog-to-Digital Converter (Vss resp. AVss) Logical Or function Logical And function Logical Exclusive Or function Logical Inversion Source (location where data is read from)

12

MSP430 Family dst SP PC TOS MSB LSB DCO BCD ADC CPU LCD I/O ROM RAM MCLK ACLK ACTL.1 Foreground Background [ns]

Metering Application Report Destination (location where data is written to) Stack Pointer (R1 of register set) Program Counter (R0 of register set) Top of Stack (data word the Stack Pointer SP points to) Most significant bit (or byte) Least significant bit (or byte) Digitally Controlled Oscillator Binary Coded Decimal (numbers 0 to 9 coded binary with 4 bits) Analog-to-Digital Converter Central Processing Unit Liquid Crystal Display Input and Output Line Read Only Memory (program memory) Random Access Memory (data memory) Master Clock (output of the FLL oscillator) for the CPU Auxiliary Clock (output of the 32kHz oscillator) Bit 1 (value 21) of the register ACTL Interrupt driven software parts (interrupt handlers) Normal program Square brackets contain the used unit for a value (here nanoseconds)

NOTE If no units are defined for the shown equations then the standard units are used. This means Volt, Ampere, Farad, Seconds and Ohm and not millivolt, microamps, nanofarads and kiloohms a.s.o.

1.2 The MSP430 Family The MSP430 family currently consists currently of three sub-families: 1. The MSP430x31x sub-family 2. The MSP430x32x sub-family 3. The MSP430x33x sub-family All three sub-families are described in depth in the "MSP430 Family Architecture Users Guide and Module Library". The hardware features of the different sub-families are:

13

Metering Application Report Table 12.1: Differences between the MSP430 Sub-families Hardware Item MSP430x31x MSP430x32x LCD Segment lines 23 21 14-Bit ADC No Yes Universal Timer/Port Module Yes Yes I/Os with Interrupt 8 8 I/Os without Interrupt 0 0 16-Bit Timer_A No No USART (SCI or SPI) No No HW/SW UART Yes Yes Watchdog Timer Yes Yes HW-Multiplier No No Basic Timer Yes Yes Oscillator FLL Yes Yes Package 56SSOP 64QFP

MSP430 Family

MSP430x33x 30 No Yes 24 16 Yes Yes Yes Yes Yes Yes Yes 100QFP

If not mentioned otherwise, the examples and explanations are valid for all categories. 1.2.1 MSP430x31x
XIN XOut XBUF VCC VSS RST/NMI P0.0 P0.7

Oscillator FLL
System Clock

ACLK MCLK

4/8/12kB ROM 8kB OTP


C: Rom P: OTP

TXD

256/512B RAM
SRAM

PoweronReset

8b Timer/ Counter
Serial Protocol RXD Support

I/O Port
8 I/O's, all with interr. capability 3 Int. Vectors

TDI TDO MAB, 16bit

CPU incl. 16 reg.

Test JTAG

MAB,4bit MCB Bus conv. MDB,8bit

MDB, 16bit TMS TCK Watchdog Timer 15bit Timer/Port Applications: A/D Conv. Timer, O/P
f LCD

Basic Timer 1

LCD
92 Segment Lines 1, 2, 3, 4 Mux

Com0..3 Seg 0..18,22,23,26 Seg 27

6 TP.0 .. 5 CIN R13 R23

Figure 12.1: MSP430C31x with its Peripherals

14

MSP430 Family 1.2.2 MSP430x32x


XIN XOut XBUF VCC VSS RST/NMI

Metering Application Report

P0.0

P0.7

Oscillator FLL
System Clock

ACLK MCLK

8/16kB ROM 16kB OTP


C: Rom P: OTP

TXD

256/512B RAM
SRAM

Power onReset

8b Timer/ Counter
Serial Protocol RXD Support

I/O Port
8 I/Os, all with interr. capability 3 Int. Vectors

TDI TDO MAB, 16bit

CPU incl. 16 reg.

Test JTAG

MAB,4bit MCB Bus conv. MDB,8bit

MDB, 16bit TMS TCK ADC 12+2bit 6 Channels Current S. 6 A0..5 RI SVCC Watchdog Timer 15bit Timer/Port Applications: A/D Conv. Timer, O/P
f LCD

Basic Timer1

LCD
84 Segments

Com0..3 Seg 0..19 Seg 20

1, 2, 3, 4 Mux

6 TP.0 .. 5 CIN R33 R23 R13 R03

Figure 12.2: MSP430C32x with its Peripherals

15

Metering Application Report 1.2.3 MSP430x33x


XIN XOut XBuf VCC1 VCC2 VSS1 VSS2 VSS3 RST/NMI P4.0 P4.7 P2.x 8 Oscillator FLL
System Clock

MSP430 Family

P1.x P3.0 8

P3.7 P0.0

P0.7

ACLK MCLK

TDI TDO

24kB ROM 32kB ROM 32kB EPROM

1024B RAM
SRAM

PoweronReset

I/O Port
1x8 dig. I/Os

I/O Port
2x8 I/Os all with interr. cap. 2 Int. Vectors

I/O Port
1x8 dig. I/Os

I/O Port
8 I/Os, all with interr. cap. 3 Int. Vectors

UART MAB, 16bit CPU incl. 16 reg. Test JTAG MDB, 16bit TMS TCK MPY MPYS MAC 16x16bit 8x8bit Watchdog Timer 15bit TimerA 16bit PWM UTX URX UCK USART
UART or SPI

MAB,4bit MCB Bus conv. MDB,8bit

TimerA

RXD, TXD

8bit Timer/ Counter

Timer/Port
Appl.s: ADC Timer, O/P

Basic Timer 1
f CMPI

LCD
30 Segment Lines

Com0..3 S0..28/O2..28 S29/O29/CMPI

function TXD RXD 6

LCD

1,2,3,4 Mux

SIMO SOMI TACLK TA0.0..5 STE

TP.0 .. 5

CIN

R03 R23 R13 R33

Figure 12.3: MSP430C33x with its Peripherals 1.3 Some Advantages of the MSP430 Concept The MSP430 concept differs strongly from the concepts used for other microcomputer families. This section will shortly explain why the MSP430 was developed this way. 1.3.1 RISC Architecture without RISC-Disadvantages Normal RISC architectures proof their capabilities best when running in an environment for calculations: the (numerous) registers are loaded with input data at the beginning, all calculations are made within the registers and the result is stored back into the RAM. This concept makes memory accesses - and this means addressing modes - necessary only for the STORE and the LOAD instructions. The MSP430 may be programmed this way; an example for this is the floating point package, doing a pure calculation task without any I/O access. But the pure RISC architecture shows disadvantages when running in real time applications: here it is wasting of time if any operand needs to be loaded first, modified then and stored back finally. Therefore the MSP430 architecture uses the best of two worlds: The RISC concept with its few, strong instructions, the numerous registers and the single cycle execution times. The microcomputer concept with its addressing modes provided for all instructions not only for the load and store instructions. This concept is brought to a top with the 100% orthogonality used, which means all seven addressing modes are usable with all instructions.

16

MSP430 Family 1.3.2 Real-time Capability

Metering Application Report

The complete concept of the MSP430 family was developed to get full real time capability additional to its Ultra Low Power Consumption. The main reason for this capability is the way the system clock generation is made: No second high frequency crystal is used, with its inherent time delay until the full oscillator amplitude is reached (20 to 200ms) Instead a sophisticated Frequency Locked Loop (FLL) system clock generator is used whose output frequency MCLK is at the nominal frequency within 6 cycles if woken-up from Low Power Mode 3 (LPM3 or Sleep Mode)

The above mentioned concept allows real time capability also out of the low power modes as if the CPU is active all the time. Only two additional MCLK cycles (2s for 1MHz) are necessary to get out of the LPM3 to the first instruction of the interrupt handler. 1.3.3 Stability of the System Clock Generator The used Digitally Controlled Oscillator (DCO) is voltage and temperature dependent; but this does not mean that its frequency is not stable. During the Active Mode every 30.5s (2-15s) the integral error is corrected to nearly zero. This is made by an adequate switching between two different DCO frequencies: one of them is higher than the programmed MCLK frequency and one is lower. The overall error is nearly zero this way. The two DCO frequencies are interlaced as much as possible to get the smallest possible error at any time. See section The System Clock Generator for more information. 1.3.4 Stack Processing Capability The MSP430 is a true stack processor: most of the seven addressing modes were implemented first for the Stack Pointer SP. It proved later that these addressing modes are very useful for the other CPU registers (PC, R4 to R15) too. The capabilities of the stack cover: Free access to all items on the stack (not only to the top of the stack TOS) Possibility to modify subroutine and interrupt return addresses located on the stack Possibility to modify the stored Status Register of interrupt returns located on the stack No special stack instructions: all of the implemented instructions may be used for the stack and the Stack Pointer Byte and word capability for the stack Free mix of subroutine and interrupt handling: as long as no stack modification is made (PUSH, POP a.s.o.) no errors can occur.

For more information concerning the stack see Appendix A.

17

Metering Application Report 1.4 The Operating Modes used for Metering Applications

MSP430 Family

The MSP430 metering applications fall into two main classes depending on the power supply: Mains driven applications like electricity meters. The microcomputer needs to be active all the time, but due to the low current consumption of the MSP430 (max. 1.4mA @ 5V/1MHz ) this is not a problem, despite the need for low power consumption (system consumption < 40mA). Battery driven applications such as gas meters, water flow meters, heat volume counters etc. For these applications the power consumption plays an overwhelming role because these applications have to run from one battery for more than 10 years. The current drawn by the MSP430 needs to be in the range of the self discharge current of the battery, which means 1 to 3 A.

The MSP430 offers six operating modes, with different current consumption. Three of them are important for battery-driven applications: 1. The Active Mode with running CPU. 2. The Low Power Mode 3 (LPM3): the normal mode for all applications during 99% to 99.9% of the time. This mode is also called Done Mode or Sleep Mode. 3. The Low Power Mode 4 (LPM4): the mode used during storage times. This mode is also called Off Mode. 1.4.1 The Active Mode This mode is used for calculations, decisions, I/O-functions and other activities that make a running CPU necessary. All of the peripherals may be used provided that they are enabled. All of the examples shown in this guide use the Active Mode. 1.4.2 The Low Power Mode 3 The most important mode for all battery driven applications. The CPU is disabled, but enabled peripherals stay active: LCD driver, Basic Timer, I/O-ports, 8-bit Timer. The running Basic Timer allows a precise time base. Enabled interrupts wake-up the CPU, switch on MCLK and start normal operation. Table 14.1 shows the status of the complete MSP430 system when in Low Power Mode 3 (LPM3): Table 14.1: System during Low Power Mode 3 Active Not Active RAM CPU ACLK MCLK 32768Hz Oscillator Disabled Peripherals LCD Driver (if enabled) Disabled Interrupts Basic Timer (if enabled) FLL I/O-Ports 8-bit Timer Enabled Peripherals RESET Logic To enter the Low Power Mode 3 the following code is necessary: ; ; Definitions for the Operating Modes

18

MSP430 Family

Metering Application Report

; GIE .EQU 008h ; General Interrupt enable in SR CPUOFF .EQU 010h ; CPU off bit in SR OSCOFF .EQU 020h ; Oscillator off bit in SR SCG0 .EQU 040h ; System Clock Generator Bit 0 SCG1 .EQU 080h ; System Clock Generator Bit 1 HOLD .EQU 080h ; 1: Hold Watchdog CNTCL .EQU 008h ; Watchdog Reset Bit ; ; Enter Low Power Mode 3, enable interrupts. The Watchdog ; must be held if the ACLK is used for timing ; MOV #05A00h+HOLD+CNTCL,&WDTCTL ; Define WD BIS #CPUOFF+GIE+SCG1+SCG0,SR ; Enter LPM3 ; After the completion of the interrupt routine the software returns to the instruction that set the CPUoff bit. The normal wake-up for the LPM3 comes from the Basic Timer: it is programmed to wake-up the CPU at regular intervals (ranging from 0.5Hz to 64Hz or higher) to maintain a software timer. This software timer controls all necessary system activities. EXAMPLE: The MSP430 system runs normally in LPM3. The enabled interrupt of the Basic Timer wakes-up the system every second. If one minute elapses, measurements are made and afterwards the system returns to LPM3. ; ; Interrupt handler for Basic Timer: Wake-up with 1Hz ; BT_HAN MOV #05A00h+CNTCL,&WDTCTL ; Reset watchdog INC.B SECCNT ; Counter for seconds +1 CMP.B #60,SECCNT ; 1 minute elapsed? JHS MIN1 ; Yes, do necessary tasks RETI ; 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 MINCNT ; Minute counter +1 CLR SECCNT ; 0 -> SECCNT ADD #4,SP ; House keeping: SR, PC off Stack BR #TASK ; Do tasks ... ; TASK ... ; Start of necessary tasks ; ; All measurements and calculations are made: Return to LPM3 ; MOV #05A00h+HOLD+CNTCL,&WDTCTL ; Hold WD BIS #CPUOFF+GIE+SCG0+SCG1,SR ; Enter LPM3 The Low Power Mode 3 is the mode with the lowest current consumption that allows the use of a real time clock: the Basic Timer can interrupt the LPM3 at relatively long time intervals (up to 2s) and update the real time clock. If the Status Register is not changed during the interrupt routines then the RETI instruction returns to the instruction that set the CPUoff bit (and moved the CPU 19

Metering Application Report

MSP430 Family

into LPM3). The Program Counter points to the next instruction but this instruction is not executed unless the interrupt routine resets the CPUoff bit during its run. If woken-up from LPM3 two additional cycles are needed until the PC is loaded with the interrupt vector address and the interrupt handler is started (8 cycles instead of 6 when in Active Mode). EXAMPLE: The MSP430 system runs normally in LPM3. The enabled interrupt of the Basic Timer wakes-up the system every second. If one minute elapsed, measurements are made and afterwards the system returns to LPM3. The branch to the task is made by resetting the CPU0ff bit inside the interrupt routine. ; Interrupt handler for Basic Timer: Wake-up with 1Hz ; BT_HAN MOV #05A00h+CNTCL,&WDTCTL ; Reset watchdog INC.B SECCNT ; Counter for seconds +1 CMP.B #60,SECCNT ; 1 minute over? JHS MIN1 ; Yes, do necessary tasks RETI ; No return to LPM3 ; ; One minute elapsed: CPUoff is reset, the program continues ; after the instruction that set the CPUoff bit (label TASK) ; MIN1 CLR SECCNT ; 0 -> SECCNT INC MINCNT ; Minute counter + 1 BIC #CPUOFF,0(SP) ; Reset CPUoff-bit to continue RETI ; at label TASK ; ; Background part: Return to LPM3 ; DONE MOV #05A00h+HOLD+CNTCL,&WDTCTL ; Hold WD BIS #CPUOFF+GIE+SCG0+SCG1,SR ; Enter LPM3 ; ; Program continues here if CPUoff bit was reset inside of the ; Basic Timer Handler. ; TASK ... ; Tasks made every minute JMP DONE ; Back to LPM3 1.4.3 The Low Power Mode 4 The Low Power Mode 4 (LPM4) is used if the lowest supply current is necessary or if no timing is needed or desired (no change of the RAM content allowed). This is normally the case for storage times preceding or following the calibration process. Table 14.2 shows the status of the complete MSP430 system when in LPM4:

20

MSP430 Family

Metering Application Report

Table 14.2: System during Low Power Mode 4 Active Not Active RAM CPU I/O-Ports MCLK Enabled Interrupts ACLK RESET Logic FLL Disabled Peripherals Disabled Interrupts Watchdog Timers

When woken-up the software has to decide if it is necessary to enter the LPM4 again (if the wakeup was caused by EMI e.g.) or if one of the other operating modes is to be entered. To ensure this decision a code can be given to a port that can be checked by the MSP430 software: only if this code is present, the Active Mode is entered. The start-up frequency of the DCO is approx. 500kHz; it may last up to 4s until a stable MCLK frequency is reached. To enter the Low Power Mode 4 the following code is necessary: ; Enter LPM4, enable GIE ; BIS #CPUOFF+OSCOFF+GIE+SCG1+SCG0,SR The way out of the LPM4 is principally the same as shown with LPM3. The software of the interrupt handler has to decide if the CPU stays active or if a return to a low power mode is necessary. When entering the LPM4 the information in the control registers SCFI0 and SCFI1 of the System Clock Frequency Integrator remains stored. If at this time the ambient temperature is high, the register SCFI1 contains a relatively high value to compensate the negative temperature dependence of the DCO. If the LPM4 is left afterwards with a very low ambient temperature then it is possible that the resulting DCO frequency is outside of the oscillators range. Therefore it is a good programming practice to set the System Clock Frequency Integrator to a low value before entering the LPM4. ; Enter LPM4, enable GIE ; CLRC ; Ensure that new MSB is 0 RRC &SCFI1 ; Use halved tap number BIS #CPUOFF+OSCOFF+GIE+SCG1+SCG0,SR ; Enter LPM4

21

Metering Application Report

MSP430 Family

2 THE ANALOG-TO-DIGITAL CONVERTERS


Two completely different Analog-to-Digital Converters (ADCs) are used, depending on the MSP430 device type: The MSP430C32x contains a successive approximation ADC with 14 and 12-bit resolution Nearly all of the MSP430s contain a capacitor discharge unit which allows the comparison of discharge times measured with resistive sensors (Universal Timer/Port Module) 2.1 The 14-bit Analog-to-Digital Converter The 14-bit ADC of the MSP430 is usable in two different modes: 14-bit ADC with an input range of the complete voltage SVcc. The ADC searches automatically which one of the four ranges is currently appropriate to the input voltage. This searching adds 36 ADCLK cycles to the conversion time. The complete conversion time for a 14-bit conversion is 132 ADCLK cycles. (An ADCLK cycle is equal to 1, 2, 3 or 4 MCLK cycles dependent on the bits ACTL.13 and ACTL.14) 12-bit ADC with four ranges. Each range covers one fourth of the voltage SVcc. This conversion mode is used if the voltage range of the input signal is known. The conversion needs 96 ADCLK cycles. The sampling of the ADC input takes 12 ADCLK cycles, this means the sampling gate is open during this time (12s@1MHz). The input of an ADC pin can be seen as an RC low pass filter: 2k in series with 42pF. The 42pF capacitor (the sample-and-hold capacitor) must be charged during the 12 ADCLK cycles to the final value to be measured. This means within 2-14 of this value. This time limits the internal resistance Ri of the source to be measured:
(Ri + 2k ) 42pF < 12 ln2 14 ADCLK

Solved for Ri with ADCLK = 1MHz this results in:


Ri < 27.4k

This means: for the full resolution of the ADC the internal resistance of the input signal must be lower than 27.4k. If a resolution of n bits is sufficient then the internal resistance Ri of the ADC input source can be higher (ADCLK = 1MHz):
Ri < 12 s 285714 2k Ri < 2k ln2 42pF ln2 n
n

EXAMPLE: To get a resolution of 13 bits, what is the maximum internal resistance of the input signal?
Ri < 285714 285714 2k = 2k = 31.7k 2k = 29.7k 13 ln2 9.0109

22

MSP430 Family

Metering Application Report

The internal resistance of the input signal must be lower than 29.7k. The next figure shows different methods how to connect analog signals to the MSP430: 1. 2. 3. 4. 5. Current supply for resistive sensors Voltage supply for resistive sensors Direct connection of input signals 4-Wire circuitry with current supply 4-Wire circuitry with voltage supply (Rsens1 at A0) (Rsens2 at A1) (Vin at A2) (Rsens3 at A3 to A5 (Rsens4 at A6 to A7

SVcc Rv Vin R1 Rsens2 R2 Rsens1 Rext Ri A2 A1 A0

SVcc A3 A6 A4

Ics

A5 A7 MSP430

Rsens3

Rsens4

AGND Vss

AGND Vcc

0V

+5V

Figure 21.1: Possible Sensor Connections to the MSP430 NOTE If the SVcc-pin is used as an input (external ADC supply, ACTL.1 = 0) then the external source must be able to deliver a current of max. 80A to supply the ADC.

2.1.1 The Current Source A stable, programmable Current Source is available at the analog inputs A0 to A3. With a programming resistor Rext between pins SVcc and Ri it is possible to get defined currents out of the programmed analog input An: the current is directly related to the voltage SVcc. The analog input to be measured and the analog input for the Current Source are independent of each other: this means that the Current Source may be programmed to A3 and the measurement taken from A4, as shown in the example above (see figure 21.1). 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 usable (0.5SVcc in Revision 0.44, which means only ranges A and B). 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 an other ADC input. The current ICS defined by the external resistor Rext is:

23

Metering Application Report


IC S = 0.25 SVcc Rext

MSP430 Family

The input voltage Vin at the analog input with the current ICS and a sensor Rsens is:
Vin = Rsens IC S = Rsens 0.25 SVcc Rext

2.1.2 The 14-bit Analog-to-Digital Converter used in 14-bit Mode The 14-bit mode is used if the range of the input voltage exceeds one ADC range. The input signal range is from analog ground (AVss) to SVcc (AVcc).
ADC Value 03FFFh 03000h 02000h 01000h 00000h 0 0.25 SVcc 0.5 SVcc 0.75 SVcc SVcc Input Voltage

Figure 21.2: Complete 14-Bit ADC Range The nominal ADC formulas for the 14-bit conversion are:
N= N Vref VAx 2 14 VAx = Vref 2 14

Where:

N VAx Vref

14-bit result of the ADC conversion Input voltage at the selected analog input Ax Voltage at pin SVcc (external reference or internal AVcc)

If the current source is used, the above equation changes to:


N= 0.25 Vref Rx Rx 2 14 = 2 12 Rext Vref Rext

This gives for the resistor Rx:


Rx =

N Rext 2 12

Where:

Rext Rx

Resistor between SVcc pin and Ri pin (defines current Ics) Resistor to be measured (connected between Ax and AGND)

24

MSP430 Family 2.1.2.1 ADC with signed signals

Metering Application Report

The ADC of the MSP430 measures unsigned signals from AVss to AVcc. 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. Three possibilities for a virtual zero-point are shown: Virtual Ground IC Split power supply Use of the current source

The chapter Electricity Meters shows applications for signed measurements with the ADC. Virtual Ground IC With the "Phase Splitter" TLE2426 a common reference is built which lies exactly in the middle of the voltage SVcc. All signed input voltages are connected to this virtual ground with their reference potential (0V). The virtual ground voltage (at A0) is measured at regular time intervals and the measured ADC value is stored and subtracted from the measured signal (at A1). This gives a signed, offset corrected result for the input A1. The Virtual Ground method is used with some electronic electricity meters shown in chapter Electricity Meters.

+5V

SVcc A1

U1 -2V...+2V I O C TLE2426 0V AGND DVss DVcc +2.5V A0 MSP430

0V

+5V

Figure 21.3: Virtual Ground IC for Level Shifting NOTE The ADC definitions given in the next example are valid for all ADC examples which follow. They are in accordance with the "MSP430 Family Architecture User's Guide 1995". EXAMPLE: The virtual ground voltage at A0 is measured and stored in VIRTGR. The value of VIRTGR is subtracted from the ADC value measured at input A1: this gives the signed value for the A1 input. ; HARDWARE DEFINITIONS FOR THE ANALOG-TO-DIGITAL CONVERTER ; AIN .EQU 0110h ; INPUT REGISTER (FOR DIGITAL INPUTS) AEN .EQU 0112h ; 0: ANALOG INPUT 1: DIGITAL INPUT ;

25

Metering Application Report ACTL CS VREF A0 A1 A2 CSA0 CSA1 CSOFF CSON RNGA RNGB RNGC RNGD RNGAUTO PD ADCLK1 ADCLK2 ADCLK3 ADCLK4 .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU 0114h 01h 02h 00h 04h 08h 00h 40h 100h 000h 00h 200h 400h 600h 800h 1000h 0000h 2000h 4000h 6000h ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;

MSP430 Family ADC CONTROL REGISTER: Control Bits CONVERSION START 0: EXT. REFERENCE 1: SVCC ON INPUT A0 INPUT A1 INPUT A2 CURRENT SOURCE TO A0 CURRENT SOURCE TO A1 CURRENT SOURCE OFF Current Source on RANGE SELECT A (0 ... 0.25SVCC) RANGE SELECT B (0.25..0.50SVCC) RANGE SELECT C (0.5...0.75SVCC) RANGE SELECT D (0.75..SVCC) 1: RANGE SELECTED AUTOMATICALLY 1: ADC POWERED DOWN ADCLK = MCLK ADCLK = MCLK/2 ADCLK = MCLK/3 ADCLK = MCLK/4

; ADAT .EQU 0118h ; ADC Data Register (12 or 14-bit) IFG2 .EQU 03h ; INTERRUPT FLAG REGISTER 2 ADIFG .EQU 04h ; ADC "EOC" Bit (IFG2.2) ; IE2 .EQU 01h ; Interrupt Enable Register 2 ADIE .EQU 04h ; ADC interrupt enable bit (IE2.2) ; VIRTGR .EQU R6 ; Virtual Ground ADC value ; ; MEASURE VIRTUAL GROUND INPUT A0 AND STORE VALUE FOR REFERENCE ; MCLK = 3MHz: DIVIDE MCLK BY 3 ; BIC.B #ADIFG,&IFG2 ; Reset ADC-Flag MOV #ADCLK3+RNGAUTO+CSOFF+A0+VREF+CS,&ACTL L$101 BIT.B #ADIFG,&IFG2 ; CONVERSION COMPLETED? JZ L$101 ; IF Z=1: NO MOV &ADAT,VIRTGR ; STORE A0 14-BIT VALUE ... ; ; MEASURE INPUT A1 (0 ...03FFFh) AND COMPUTE A SIGNED, ; OFFSET CORRECTED VALUE FOR A1 (0E000h ...01FFFh). ; BIC.B #ADIFG,&IFG2 ; Reset ADC-Flag MOV #ADCLK3+RNGAUTO+CSOFF+A1+VREF+CS,&ACTL L$102 BIT.B #ADIFG,&IFG2 ; CONVERSION COMPLETED? JZ L$102 ; IF Z=1: NO MOV SUB &ADAT,R5 VIRTGR,R5 ; READ ADC VALUE FOR A1 ; R5 CONTAINS SIGNED ADC VALUE

Split Power Supply With two power supplies, for example with +2.5V and -2.5V, a potential in the middle of the ADC range of the MSP430 can be created. All signed input voltages are connected to this voltage with

26

MSP430 Family

Metering Application Report

their reference potential (0V). The mid range voltage (at A0) is measured at regular time intervals and the measured ADC value is stored and subtracted from the measured signal (at A1). This gives a signed, offset corrected result for the input A1. The Split Power Supply method is used with some of the Electronic Electricity Meters shown in chapter Electricity Meters.
. +2.5V SVcc A1 V1 -2V...+2V 0V A0 MSP430

-2.5V AGND DVss DVcc

-2.5V

+2.5V

Figure 21.4: Split Power Supply for Level Shifting The same software can be used as shown with the Virtual Ground IC. Use of the Current Source With the Current Source a voltage which is partially or completely below the AGND potential can be shifted to the middle of the usable ADC range of the MSP430. This is accomplished by a resistor Rh whose voltage drop shifts the input voltage accordingly. This method is useful especially if differential measurements are necessary, because the ADC value of the signal's midpoint is not available as easily as with the methods shown previously. The example below shows an input signal V1 ranging from -1V to +1V. To shift the signal's midpoint (0V) to the midpoint of the usable ADC range (SVcc/4) a current ICS is used. The necessary current ICS to shift the input signal is:
IC S = SVcc / 4 Rh Rh = SVcc / 4 IC S

Rh includes the internal resistance of the voltage source V1. The current ICS of the current source is defined by:
IC S = 0.25 SVcc Rext

Therefore the necessary shift resistor Rh is:


Rh = SVcc / 4 Rext Rh = Rext 0.25 SVcc

The voltage VA1 at the analog input A1 is: 27

Metering Application Report

MSP430 Family

VA1 = V1 + Rh

0.25 SVcc Rext

Therefore the unknown voltage V1 is:


V1 = VA1 Rh 0.25 SVcc N Rh 0.25 = SVcc 14 2 Rext Rext

SVcc Rext V1+(Iadc x Rh) Rh V1 Iadc Ri A1 MSP430

-1V ...+1V AGND DVss

DVcc

0V

+5V

Figure 21.5: Current Source for Level Shifting The method described is used with the current path of the MSP430 Battery Charge Meter shown in chapter 4. 2.1.2.2 Four-Wire Circuitry for Sensors A proven method of eliminating the error coming from the voltage drop on the connection lines to the sensor is the 4-wire circuitry: instead of 2 lines, 4 lines are used, 2 for the measurement current and 2 for the sensor voltages. These 2 sensor lines do not carry current (the input current of the analog inputs is only some nanoamps) which means that no voltage drop falsifies the measured values. The formula for voltage supply is:
Rsens = R1 + R2 2 1 N
14

N ( R1 + R2 ) 2 14 N

Where:

ADC result of input A1 - ADC result of input A0

28

MSP430 Family

Metering Application Report

SVcc R1 A1 Rsens A0 R2 AGND DVss DVcc MSP430

0V

+5V

Figure 21.6: 4-Wire Circuitry with Voltage Supply EXAMPLE: The sensor Rsens at A0 and A1 is measured and the ADC value of its resistance computed by the difference of the two results measured at A1 and A0. The result is stored in R5 for further calculations. ; MEASURE UPPER ; BIC.B MOV L$103 BIT.B JZ ; MOV ; ; MEASURE INPUT ; BIC.B MOV L$104 BIT.B JZ ; SUB ; ADC VALUE OF Rsens AT INPUT A1 AND STORE VALUE #ADIFG,&IFG2 ; Reset ADC-Flag #RNGAUTO+CSOFF+A1+VREF+CS,&ACTL #ADIFG,&IFG2 ; CONVERSION COMPLETED? L$103 ; IF Z=1: NO &ADAT,R5 ; STORE A1 VALUE

A0 AND COMPUTE ADC VALUE OF Rsens #ADIFG,&IFG2 ; Reset ADC-Flag #RNGAUTO+CSOFF+A0+VREF+CS,&ACTL #ADIFG,&IFG2 ; CONVERSION COMPLETED? L$104 ; IF Z=1: NO &ADAT,R5 ; R5 CONTAINS Rsens ADC VALUE

The next figure shows the more common 4-wire circuitry with Current Supply:
Rsens =

N Rext 2 12

The same software as shown before can be used for this hardware too, only the Current Source must be switched on additionally.

29

Metering Application Report

MSP430 Family

Rext SVcc Ri A2 A1 Rsens A0 R2 AGND DVss MSP430

DVcc

0V

+5V

Figure 21.7: 4-Wire Circuitry with Current Supply 2.1.2.3 Referencing with Reference Resistors 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 different methods can be used, depending on the type of sensor: 1. Platinum sensors: these are sensors with a precisely known temperature-resistance characteristic. Precision resistors are used with the sensor resistances of the temperatures at the two limits of the range. 2. Other sensors: nearly all other sensors have insufficiently close tolerances. This makes it necessary to group sensors with similar characteristics, and to select the two reference resistors according to the upper and lower limits of these groups. If the two reference resistors have precisely the values of the sensors at the range limits (or at other well-defined points) then all tolerances are eliminated during calculation. The formula is shown below.

SVcc Rext Ri A0 A1 A2 A3 MSP430 AGND DVss

Rref1

Rsens1 Rsens2 Rref2

DVcc

0V

+5V

Figure 21.8: Referencing with Precision Resistors The nominal formulas given in the previous section need to be changed if offset and slope are considered. The ADC value Nx for a given resistor Rx is now:

30

MSP430 Family
Nx =

Metering Application Report


0.25 Rx 2 14 Slope + O ffset Rext

With two known resistors Rref1 and Rref2 it is possible to calculate slope and offset and to get the values of unknown resistors exactly. The result of the solved equations gives:
Rx = Nx Nref2 (Rref2 Rref1) + Rref2 Nref2 Nref1

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

As shown only known or measurable values are needed for the computation of Rx from Nx. Slope and offset influences of the ADC disappear completely. 2.1.2.4 Interrupt Handling All of the ADC software examples shown above use polling techniques for the check of the conversion completion. This takes up computing power which can be used otherwise if interrupt techniques are used. EXAMPLE: Analog input A0 (without Current Source) and A1 (with Current Source) are measured alternately. The measured 14-bit results are stored in address MEAS0 for A0 and MEAS1 for A1. The background software uses these measured values and sets them to 0FFFFh after use. The time interval between two measurements is defined by the 8-bit timer: every timer interrupt starts a new conversion for the prepared analog input. ; HARDWARE DEFINITIONS SEE 1st ADC EXAMPLE ; ; ANALOG INPUT A0 A1 ; CURRENT SOURCE OFF ON ; RESULT TO MEAS0 MEAS1 ; RANGE SELECTION AUTO AUTO ; REFERENCE SVCC SVCC ; ; INITIALIZATION PART FOR THE ADC: ; MOV #RNGAUTO+CSOFF+A0+VREF,&ACTL BIS.B #ADIE,&IE2 ; ENABLE ADC INTERRUPT MOV #0FFh-3,&AEN ; ONLY A0 AND A1 ANALOG INPUTS ... ; INITIALIZE OTHER MODULES ; ; ADC INTERRUPT HANDLER: A0 AND A1 ARE MEASURED ALTERNATING ; The next measurement is prepared but not started. ; AD_INT BIT #A1,&ACTL ; A1 RESULT IN ADAT? JNZ ADI ; YES MOV &ADAT,MEAS0 ; A0 VALUE IS ACTUAL 31

Metering Application Report MOV RETI ADI MOV MOV RETI #RNGAUTO+CSON+A1+VREF,&ACTL

MSP430 Family ; A1 NEXT MEAS.

&ADAT,MEAS1 ; A1 VALUE IS ACTUAL #RNGAUTO+CSOFF+A0+VREF,&ACTL ; A0 NEXT MEAS.

; ; 8-BIT TIMER INTERRUPT HANDLER: THE ADC CONVERSION IS STARTED ; FOR THE PREPARED ADC INPUT ; T8BINT BIS #CS,&ACTL ; START CONVERSION for the ADC ... ; Do other tasks RETI ; .SECT "INT_VEC0",0FFEAh ; INTERRUPT VECTORS .WORD AD_INT ; ADC INTERRUPT VECTOR; .SECT "INT_VEC1",0FFF8h .WORD T8BINT ; 8-BIT TIMER INTERRUPT VECTOR EXAMPLE: for best results the CPU may be switched off during the measurements. The measurement subroutine starts the conversion and switches off the CPU afterwards. The interrupt routine called by the conversion completion resets the CPUoff bit of the stored SR and allows the CPU to continue with the measured ADC-result. CPUoff ; .equ ... EINT BIS.B BIC.B MOV CALL MOV ... 010h ; SR: CPU off bit

; Enable interrupt #ADIE,&IE2 ; ADC Intrpt Enable #ADIFG,&IFG2 ; Reset ADC-Flag #RNGAUTO+CSOFF+A1+VREF,&ACTL ; Define ADC #MEASURE ; Measure with ADC &ADAT,R5 ; Result to R5 ; Process result

; ; Subroutine: CPU is switched off to minimize noise ; MEASURE BIS.B #CS,&ACTL ; Start ADC conversion BIS.B #CPUoff,SR ; Switch CPU off NOP ; Wait for completion of ADC RET ; ; ; Interrupt Handler for the Analog-to-Digital Converter ; The CPUoff bit of the saved SR is cleared to allow the ; software to continue after the RETI ; ADC_INT BIC.B #CPUoff,0(SP) ; Allow SW run (CPUoff = 0) RETI ; ; Interrupt Vectors ; .sect "INT_VEC1",0FFEAh .WORD ADC_INT ; ADC Vector

32

MSP430 Family 2.1.2.5 Enlargement to 16-bit Mode

Metering Application Report

With the use of two additional output pins (I/O-ports or TP.x) the 14-bit ADC may be enlarged to 16 bits. The principle is simple: the resistor Rext of the Current Source is modified by the paralleling of two additional resistors (see figure 21.10). These resistors have values that represent one half and one quarter of one ADC-step. Due to the fact that these fractions of a step are accurate only at one point of the ADC-range, this enlargement 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 result of these four measurements are added together, a 16-bit result is reached. The following figure shows this.
ADC Value XXXX+1

XXXX

00000h 0 V0 V1 V2 V3

ADC Input Voltage

Figure 21.9: Dividing of an ADC-Step into four Steps Table 21.1 shows the different results of these four measurements depending on the four possible input voltages V0 to V3 inside of one ADC-step: the table refers to the hardware shown in figure 21.10. Table 21.1: Measurement Results of the 16-Bit Method Measurem. 1 Measurem. 2 Measurem. 3 Measurem. 4 TP.1 Hi-Z TP.1 Hi-Z TP.1 Hi Out TP.1 Hi Out TP.0 Hi-Z TP.0 Hi Out TP.0 Hi-Z TP.0 Hi Out XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX+1 XXXX XXXX XXXX+1 XXXX+1 XXXX XXXX+1 XXXX+1 XXXX+1

Input Voltage

Mean Value (Binary)

V0 V1 V2 V3

XXXX.00 XXXX.01 XXXX.10 XXXX.11

33

Metering Application Report

MSP430 Family

Vcc TP.x Vss

R15

R14

Rext

TP.0 TP.1 SVcc

Rx Ri A1 Rsens MSP430C32x

AGND DVss DVcc

0V

+5V

Figure 21.10: Hardware for a 16-bit ADC The values for the resistors R14 and R15 are:
Rx = 2 14 0.25 Rsens0 2 12 Rsens0 = n n

Where:

Rx Rsens0 n

Parallel resistor to Rext [] Value of the sensor at the point of the highest accuracy [] Fraction of ADC step (0.25 or 0.5) caused by Rx alone

Theoretical Accuracy of the 16-bit Mode To give an impression how much better the results of the 16-bit mode can be compared to the 14bit mode of the ADC, the results of four different calculations are shown in table 21.2. The table shows the statistical results for the deviations of the correct result in ADC-steps:

The first column shows the statistical results for the normal 14-bit ADC The second column shows the statistical results for measurements that have the highest accuracy at the lowest sensor value: Rsens0 = 1000 The third column shows the statistical values if the point of highest accuracy is moved to the midpoint of the sensor resistance: Rsens0 = 1190 The fourth column shows the same as before if the highest sensor value is used for the highest accuracy: Rsens0 = 1380

Calculation values and explanations: Rsensmax: Rsensmin: Rsens: Rext: Rsens0: R14: R15: 1380.0 1000.0 0.01 690.0000 Highest sensor resistance (+100C for PT1000) Lowest sensor resistance (0C for PT1000) Step width for resistance value during calculation Calculated external resistor for the current source Sensor resistance for highest accuracy (3 different values) Calculated resistor for the 15th bit Same as above for 16th bit

34

MSP430 Family

Metering Application Report

Item

Table 21.2: Measurement Results for different 16-Bit Corrections 14-Bit Rsens0 = Rsens0 = 1000 1190 n.a. R14 8.2M 9.7M n.a. R15 16.4M 19.5M -0.5001 -0.0538 -0.1250 Mean Value 0.2887 0.1019 0.0841 Standard Deviation 0.0833 0.0104 0.0071 Variance

Rsens0 = 1380 11.3M 22.6M -0.1767 0.0898 0.0081

Table 21.2 shows the better resolution especially if the best resolution is programmed for the lowest sensor resistance (Rsens0 = 1000). The result is derived from 38,000 measurements with a step width of 0.01. The 14-bit results show the (correct) inherent error of minus one half step that is enhanced with the three 16-bit modes by a factor of 3 to 9. EXAMPLE: With the hardware shown in figure 21.10 a 16-bit measurement is made. The result is placed into R5. The software may be written with a loop too. The software assumes ascending order for the two TP outputs. ; CSA1 .EQU 040h ; Current Source to A1 TPD .EQU 04Eh ; Address data register TPE .EQU 04Fh ; Address of enable register TP0 .EQU 1 ; Bit address of TP.0 TP1 .EQU 2 ; Bit address of TP.1 ; BIC.B #TP1+TP0,&TPE ; TP.0 and TP.1 to Hi-Z BIS.B #TP1+TP0,&TPD ; Set TPD.0 and TPD.1 to Hi CALL #MEASA1 ; Measure with R14 = R15 = Hi-Z MOV &ADAT,R5 ; 14-bit value to result ADD.B #TP0,&TPE ; Set R15 to Hi-Out CALL #MEASA1 ; Measure ADD &ADAT,R5 ; Add 14-bit value to result ADD.B #TP0,&TPE ; Set R14 to Hi-Out, R15 to Hi-Z CALL #MEASA1 ; Measure ADD &ADAT,R5 ; Add 14-bit value to result ADD.B #TP0,&TPE ; Set R14 and R15 to Hi-Out CALL #MEASA1 ; Measure ADD &ADAT,R5 ; Add 14-bit value to result BIC.B #TP1+TP0,&TPE ; 16-Bit result in R5, TP.n off ; ; Measurement Subroutine for input A1 ; MEASA1 BIC.B #ADIFG,&IFG2 ; Reset ADC-Flag MOV #RNGAUTO+CSA1+A1+VREF+CS,&ACTL ; Start + Def. L$101 BIT.B #ADIFG,&IFG2 ; CONVERSION COMPLETED? JZ L$101 ; IF Z=1: NO RET ; Return with result in ADAT 2.1.3 The 14-bit Analog-to-Digital Converter used in 12-bit Mode This 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 C), then the 12-bit mode is

35

Metering Application Report

MSP430 Family

the right selection. The measurement time with MCLK = 1MHz is only 96s compared with 132 s if the auto ranging mode is used. The following figure shows the four ranges compared to SVcc.

ADC Value 0FFFh 0C00h A 0800h 0400h 00000h 0 Underflow 0.25 SVcc 0.5 SVcc 0.75 SVcc SVcc Input Voltage Vax B C D Overflow

Figure 21.11: The four Single ADC Ranges NOTE The ADC results 0000h and 0FFFh mean underflow and overflow: the voltage at the measured analog input is below or above the limits of the addressed range. Figure 21.12 shows how one of the ADC ranges appears to the software:
ADC Value 0FFFh

n = 0,1,2,3 Range Constant 0800h

Range n-1 0000h 0

Range n

Range n+1 Input Voltage

(n-1) x 0.25 SVcc

n x 0.25 SVcc

SVcc

Figure 21.12: Single ADC Range The possible ways to connect sensors to the MSP430 are the same as shown for the 14-bit ADC:

36

MSP430 Family

Metering Application Report

SVcc Rv Vin R1 Rsens2 R2 Rsens1 Rext Ri A2 A1 A0

SVcc A3 A6 A4

A5 A7 MSP430

Rsens3

Rsens4

AGND DVss

AGND DVcc

0V

+5V

Figure 21.13: Possible Sensor Connections to the MSP430 for the 12-bit ADC The nominal ADC formulas for the 12-bit conversion are:
N = N VAx n 0.25 Vref 2 14 VAx = Vref 14 + n 0.25 2 Vref

where:

N VAx Vref n

12-bit result of the ADC conversion [V] Input voltage at the selected analog input Ax [V] Voltage at pin SVcc (external reference or internal AVcc) [V] Range constant (n = 0,1,2,3 for ranges A,B,C,D)

The ADC formula for a resistor Rx (Rsens2 in the above figure) which is connected to Vref via a resistor Rv is:
N = Rx Vref n 0.25 Vref Rv + Rx 2 14 Rx = Rv Vref N +n 2 12 N 4 12 + n 2

If the current source is used (as for Rsens1 in the above figure), the above equation changes to:
0.25 Vref Rx n 0.25 Vref Rx Rext N = 2 14 = n 2 12 Rext Vref

This gives for the unknown resistor Rx:

N Rx = + n Rext 212
where: Rext Rx Resistor between SVcc pin and Ri pin (defines current ICS) [] Resistor to be measured (connected to Ax and AGND) []

2.1.3.1 ADC with signed signals Only the Current Source method is applicable if signed signals have to be measured:

37

Metering Application Report

MSP430 Family

Normal phase splitter circuits are not able to shift the virtual ground into the middle of range A (0.125 SVcc) or B (0.375 SVcc), as is necessary here. The split power supply method would need two different voltages to get the zero point into the middle of range A (0.625V/4.375V) or range B (1.875V/3.125V)

For signed signals it is necessary to shift the input signal V1 to the middle of the range A or B. If range B (0.375 SVcc) is used the necessary shift resistor Rh is. See figure 21.14.

SVcc Rext V1+(Iadc x Rh) Rh V1 Iadc Ri A1 MSP430

-1V ...+1V AGND DVss

DVcc

0V

+5V

Figure 21.14: Current Source for Level Shifting


Rh = 0.375 SVcc Rext Rh = 1.5 Rext 0.25 SVcc

The unknown voltage V1 referred to its zero point in the middle of range n is:
V1
=

VAx Rh ICS

With the above equations for Vax this leads to:


V1
=

N Rh 0.25 SVcc 12 + n 2 Rext

2.1.3.2 Interrupt Handling The software is the same as for the 14-bit conversion. The only difference is the omission of the RNGAUTO bit during the initialization of ACTL. Instead the desired range is included into the initialization part of each measurement. EXAMPLE: Analog input A0 (without Current Source, always range B, external reference at pin SVcc) and A1 (with Current Source, always range A) have to be measured alternately. The measured 12-bit results have to be stored in address MEAS0 for A0 and MEAS1 for A1. The background software uses these measured values and sets them to 0FFFFh after use. The time interval between two measurements is defined by the 8-bit timer: Every timer interrupt starts a new conversion for the prepared analog input.

38

MSP430 Family

Metering Application Report

; HARDWARE DEFINITIONS SEE 1st ADC EXAMPLE ; ; ANALOG INPUT A0 A1 ; CURRENT SOURCE OFF ON ; RESULT TO MEAS0 MEAS1 ; RANGE B A ; REFERENCE EXTERNAL SVCC ; ; INITIALIZATION PART FOR THE ADC: ; MOV #RNGB+CSOFF+A0,&ACTL BIC.B #ADIFG,&IFG2 ; Reset ADC-Flag BIS.B #ADIE,&IE2 ; ENABLE ADC INTERRUPT MOV #0FFh-3,&AEN ; ONLY A0 AND A1 ANALOG INPUTS ... ; INITIALIZE OTHER MODULES ; ; ADC INTERRUPT HANDLER: A0 AND A1 ARE MEASURED ALTERNATING ; The next measurement is prepared but not started ; AD_INT BIT #A1,&ACTL ; A1 MEASURED ? JNZ ADI ; YES MOV &ADAT,MEAS0 ; A0 VALUE IS ACTUAL MOV #RNGA+CSA1+A1+VREF,&ACTL ; A1 NEXT MEAS. RETI ADI MOV MOV RETI &ADAT,MEAS1 ; A1 VALUE #RNGB+CSOFF+A0,&ACTL ; A0 NEXT MEASUREMENT

; ; 8-BIT TIMER INTERRUPT HANDLER: THE ADC CONVERSION IS STARTED ; FOR THE addressed ADC INPUT ; T8BINT BIS #CS,&ACTL ; START CONVERSION ... RETI ; .SECT "INT_VECT",0FFEAh ; INTERRUPT VECTORS .WORD AD_INT ; ADC INTERRUPT VECTOR; .SECT "INT_VECT",0FFF8h .WORD T8BINT ; 8-BIT TIMER INTERRUPT VECTOR EXAMPLE: for best results the CPU may be switched off during the measurements. The measurement subroutine starts the conversion and switches off the CPU afterwards. The interrupt routine caused by the conversion completion resets the CPUoff bit of the stored SR and allows the CPU to continue with the measured ADC-result. CPUoff GIE RNGB ; .equ .equ .equ ... EINT BIS.B MOV 010h 008h 0200h ; SR: CPU off bit ; SR: General Intrpt enable ; ACTL: Select Range B

; Enable interrupt #ADIE,&IE2 ; ADC Intrpt Enable #RNGB+CSOFF+A1+VREF,&ACTL ; Define ADC

39

Metering Application Report CALL MOV ... #MEASURE &ADAT,R5 ; Measure with ADC ; Result to R5 ; Process result

MSP430 Family

; ; Subroutine: CPU is switched off to get minimum noise ; MEASURE BIS.B #CS,&ACTL ; Start ADC conversion BIS.B #CPUoff,SR ; Switch CPU off NOP ; Wait for completion of ADC RET ; ; ; Interrupt Handler for the Analog-to-Digital Converter ; The CPUoff bit of the saved SR is cleared to allow the ; software to continue after the RETI ; ADC_INT BIC.B #CPUoff,0(SP) ; Allow SW run (CPUoff = 0) RETI ; ; Interrupt Vectors ; .sect "INT_VEC1",0FFEAh .WORD ADC_INT ; ADC Vector 2.1.4 Connection of long Sensor Lines If the distance from the MSP430 to the sensor is long (>30cm) then it is recommended to use a shielded cable between the microcomputer and the sensor. This is to avoid spikes at the ADC input that will cause measurement errors and also gives protection to the ADC input. Figure 21.15 shows this schematic at the left hand side. The same way Four-Wire-Circuitry may be connected to the MSP430. If a shielded cable cannot be used the circuitry shown at the right hand side of Figure 21.15 should be used: the AGND line in parallel to the signal line gives a relative good screening. Twisting of the two lines increases the protection. To protect the measurement against spikes, hum and other unwanted noise see chapter "Signal Averaging and Noise Cancellation": this chapter shows possibilities for the minimization of these influences by software.

40

MSP430 Family

Metering Application Report

SVcc Rv/2 Long Cable Rsens Rp A1

SVcc Rv Rp A2 Rsens Long Cable

MSP43032x Shield Shield Rv/2 C AGND DVss AGND DVcc C

No Shield, twisted pair

0V

+5V

Figure 21.15: Sensor Connection via Long Cables with Voltage Supply 2.1.5 Grounding The correct grounding is very important for ADCs with high resolution. There are some basic rules that need to be observed. Rules for separated analog and digital ground pins: AVss and DVss pins are existent 1. Use of a separate analog and digital ground plane wherever possible: no thin connections from battery to pin DVss and AVss 2. The AVss pin is a star point for all analog ground connections. The DVss pin is a star point for all digital ground connections. 3. Battery and storage capacitor Cb are connected close together (this capacitor is needed for batteries with a relatively high internal resistance). From this capacitor two different paths go to the analog and the digital supply pins. Two small capacitors are connected across the digital (Cd) and the analog (Ca) supply pins. See figure 21.16. 4. All mentioned points 1 to 3 above are also true for the Vcc pathes (DVcc and AVcc). 5. The AVss and DVss pins must be connected together externally, they are not connected internally. The same is true for the AVcc and DVcc pins. 6. The coil L is needed only in very difficult cases.

41

Metering Application Report

MSP430 Family

SVcc Rv Rext Ri A1 Rsens2 Rsens1 A0 MSP430C32x

AVss AVcc

DVss

DVcc

Ca To other analog parts 0V AGND To Metallization

Cd

To other digital parts

+3V Cb Battery

Figure 21.16: 14-Bit ADC Grounding (Separate Supply Connections) 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 (0V) of the board. Otherwise the behavior is worse than without the metallization. 2.1.6 Connection of Current consuming Loads to SVcc If the current drawn by the analog part exceeds 8mA by far then an external switch for the switched analog voltage should be considered. A simple PNP transistor can be used for this purpose. The external analog voltage which is reduced by the saturation voltage VCEsat of the PNP transistor (approx. 200mV) is connected to the SVcc pin of the MSP430C32x. The SVcc pin is used as an input pin for the external reference voltage (ADC control bit ACTL.1 = 0). This method allows the full accuracy of the analog-to-digital converter also with current consuming loads. Output TP.0 switches off and on the power to the current consuming loads. The schematic shown in figure 21.17 is simplified for clearness. The connection principle shown in figure 21.16 needs to be applied especially with the larger currents used here.

42

MSP430 Family

Metering Application Report

+5V/3V

SVcc Rv Rext Analog Circuit Rsens2 Rsens1 Ri TP.0 A0 A1 A2

AVcc

DVcc

MSP430C32x

AVss

DVss 0V

Current consuming analog parts (I >> 8mA)

Figure 21.17: Connection of current consuming Loads to SVcc

2.2 The Universal Timer/Port Module used as an ADC The function of the Universal Timer/Port Module is completely different from the 14-bit ADC: the discharge times of a capacitor for different resistors are measured and compared.

Vc SVcc

Vth 0 tc tref tc tsens Time

Figure 22.1: Timing for the Universal Timer/Port Module ADC where: Vth tref tsens tc Threshold voltage of the comparator Discharge time with the reference resistor Rref Discharge time with the sensor Rsens Charge time for the capacitor [V] [s] [s] [s]

The solving of the exponential equation leads to the simple equation below:

43

Metering Application Report


Rsens tsens tsens = Rsens = Rref Rref tref tref

MSP430 Family

With two known reference resistors Rref1 and Rref2 it is possible to compute slope and offset and to get the values of the unknown resistors exactly. The result of the solved equations gives:
Rsens = tsens tref2 (Rref2 Rref1) + Rref2 tref2 tref1

where:

tsens tref1 tref2 Rref1 Rref2

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] [s] [] []

As shown only known or measurable values are needed for the computation of Rsens from tsens. Slope and offset of the measurement disappear completely. To get a resolution of n bits, the capacitor Cm must have a minimum capacity:

Cm >

2 n Rxm in f ln Vth max Vcc


[Hz] [] [V]

Where:

f Rxmin Vthmax

Measurement frequency (ACLK or MCLK) Lowest resistance of sensor or reference resistor in Ohms Maximum value for threshold voltage Vth

EXAMPLE: Use of the Universal Timer Port as an ADC without interrupt. The measured tdc 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, 0FFFFh is written to the RAM location.

MSP430
Enable Control TPIN.5 TPD.5 TPE.5 TPD.4 TPE.4 TPD.3 TPE.3 TPD.2 TPE.2 TPD.1 TPE.1 TPD.0 TPE.0

CIN

TP.5

TP.4 Rref1

TP.3

TP.2

TP.1

TP.0 Rref2

Cm 0V

Rsens1

Rsens2

Figure 22.2: Schematic of Example

44

MSP430 Family

Metering Application Report

; DEFINITION PART FOR THE UT/PM ADC ; TPCTL .EQU 04Bh ; TIMER PORT CONTROL REGISTER TPSSEL0 .EQU 040h ; TPSSEL.0 ENB .EQU 020h ; CONTROLS EN1 OF TPCNT1 ENA .EQU 010h ; AS ENB EN1 .EQU 008h ; ENABLE INPUT FOR TPCNT1 RC2FG .EQU 004h ; RIPPLE CARRY TPCNT2 EN1FG .EQU 001h ; EN1 FLAG BIT ; TPCNT1 .EQU 04Ch ; LO 8-BIT COUNTER/TIMER TPCNT2 .EQU 04Dh ; HI 8-BIT COUNTER/TIMER ; TPD .EQU 04Eh ; DATA REGISTER B16 .EQU 080h ; 0: SEPARATE TIMERS 1: 16-BIT TIMER CPON .EQU 040h ; 0: COMP OFF 1: COMP ON TPDMAX .EQU 008h ; BIT POSITION OUTPUT TPD.MAX ; TPE .EQU 04Fh ; DATA ENABLE REGISTER ; MSTACK .EQU 0240h ; Result stack 1st word NN .EQU 011h ; TPCNT2 VALUE FOR CHARGING OF C ; ; MEASUREMENT SUBROUTINE WITHOUT INTERRUPT. TPD.4 AND TPD.5 ; ARE NOT USED AND THEREFORE OVERWRITTEN ; INITIALIZATION: STACK INDEX <- 0, START WITH TPD.3 ; 16-BIT TIMER, MCLK, CIN ENABLES COUNTING ; ; Call: CALL #MEASURE ; ; Return: Results for TP.3 to TP.0 in MSTACK to MSTACK+6 ; Result 0FFFFh if error ; MEASURE PUSH.B #TPDMAX ; START WITH SENSOR AT TPD.MAX CLR R5 ; INDEX FOR RESULT STACK MEASLOP MOV.B #(TPSSEL0*3)+ENA,&TPCTL ; Reset flags ; ; CAPACITOR C IS CHARGED UP FOR > 5 TAU. N-1 OUTPUTS ARE USED ; MOV.B #B16+TPDMAX-1,&TPD ; SELECT CHARGE OUTPUTS MOV.B #TPDMAX-1,&TPE ; ENABLE CHARGE OUTPUTS MOV.B #NN,&TPCNT2 ; LOAD NEG. CHARGE TIME ; MLP0 BIT.B #RC2FG,&TPCTL ; CHARGE TIME ELAPSED? JZ MLP0 ; 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 ; ALLOW NEXT 2 INSTRUCTIONS CLR.B &TPCNT1 ; CLEAR LO BYTE TIMER BIC.B @SP,&TPD ; SWITCH ACTUAL SENSOR TO LO 45

Metering Application Report MOV.B EINT

MSP430 Family

#(TPSSEL0*3)+ENA+ENB,&TPCTL ; Reset flags ; COMMON START TOOK PLACE

; ; Wait until EOC (EN1 = 1) or overflow error (RC2FG = 1) ; MLP1 BIT.B #RC2FG,&TPCTL ; Overflow (broken sensor)? JNZ MERR ; Yes, go to error handling BIT.B #EN1,&TPCTL ; CIN < Ucomp? JNZ MLP1 ; NO, WAIT ; ; EN1 = 0: End of Conversion: Store 2 x 8 bit result on MSTACK ; Address next sensor, if no one addressed: End reached ; MOV.B &TPCNT1,MSTACK(R5) ; STORE RESULT ON STACK MOV.B &TPCNT2,MSTACK+1(R5) ; HI BYTE L$301 INCD R5 ; ADDRESS NEXT WORD RRA.B @SP ; NEXT OUTPUT TPD.x JNC MEASLOP ; IF C=1: FINISHED INCD SP ; HOUSEKEEPING: TPDMAX OFF STACK RET ; ; ERROR HANDLING: ONLY OVERFLOW POSSIBLE (BROKEN SENSOR ?) ; 0FFFFh IS WRITTEN FOR RESULT AND SUBROUTINE CONTINUED ; MERR MOV #0FFFFh,MSTACK(R5) ; Overflow JMP L$301 2.2.1 Interrupt Handling If the Universal Timer/Port Module is used as an ADC for applications that need an accuracy greater than 10 bits then the digital noise generated by the running CPU has strong influence on the result. If the flag EN1 in the hardware register TPCTL is polled by software for the indication of a completed conversion then the results are normally different: they show a wide distribution that reflects the length of the polling loop i.e. 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 an adequate hardware, results with much better accuracy are possible. The influence of the digital noise is shown in Figure 22.3. The exponential discharge curve is relatively flat nearby the comparator threshold Vth. Therefore noise coming from the CPU (or other sources of non-wanted noise) can undergo the threshold voltage and terminate the conversion: the result is a too low timer value tdcw. The correct value would be tdcc. The resulting error Ecnv is:
tdcw tdcc 100 tdcc Resulting measurement time caused by CPU noise Correct measurement time Ecnv =

Where:

tdcw tdcc

[s] [s]

46

MSP430 Family

Metering Application Report

Vc Vcc

Vth 0 tc tdcw tdcc Time

Figure 22.3: Noise Influence during Measurement EXAMPLE: The hardware schematic is shown in Figure 22.4. Two resistive temperature sensors are used (Rmeas0 and Rmeas1) two reference resistors (Rref0 and Rref1) that have the resistance of the sensors at the lower resp. upper end of the measurement range and a resistor Rcharge that is used only for the charge-up of the capacitor Cm. This charge resistor is only necessary if the sensors have low resistance (100 approx.) otherwise the reference resistors may be used for the charging.

Rref0 TP.0 Rmeas0 TP.1 Rmeas1 TP.2 Rref1

MSP430x3xx
TP.3

Rcharge TP.4 CIN Cm Vss Vcc

0V AGND

+3V

Figure 22.4: 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: Rref0 first, then Rmeas0, then Rmeas1 and finally Rref1. The measured discharge times (a direct measure for the relative resistance) are placed in successive RAM words starting at label ADCRESULT.

47

Metering Application Report

MSP430 Family

First these RAM words are set to zero (a value impossible as measurement result). If an error occurs the zero value indicates an erroneous result. The Basic Timer is programmed to 0.5s interrupt timing. The measurement sequence is shown in figure 22.5. This sequence may 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 according 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 shown software is usable for the MSP430C31x 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 MSP430C31x is used otherwise the MSP430C32x is used.
0.5s CPUoff = 1 MOD = 1 Measure No activity Charge Cm Rref0 Measure Charge Cm Rmeas0 Measure Charge Cm Rmeas1 Measure Charge Cm Rref1 Conversions made

Status 0

9/0

Figure 22.5: Measurement Sequence ; Definitions of the MSP430 hardware ; Type .equ 310 ; 310: MSP43C31x 0: others BTCTL .equ 040h ; Basic Timer: Control Reg. BTCNT1 .equ 046h ;..............Counter BTCNT2 .equ 047h ; Counter BTIE .equ 080h ; : Intrpt Enable DIV .equ 020h ; BTCTL: xCLK/256 IP2 .equ 004h ; BTCTL: Clock Divider2 IP0 .equ 001h ; Clock Divider0 ; SCFQCTL .equ 052h ; FLL Control Register MOD .equ 080h ; Modulation Bit: 1 = off ; CPUoff .equ 010h ; SR: CPU off bit GIE .equ 008h ; SR: General Intrpt enable ; TPCTL .equ 04Bh ; Timer Port: Control Reg. TPCNT1 .equ 04Ch ; Counter Reg.Lo TPCNT2 .equ 04Dh ; Counter Reg.Hi TPD .equ 04Eh ; Data Reg. TPE .equ 04Fh ; Enable Reg. ; .if Type=310 ; MSP430C31x? TPIE .equ 004h ; ADC: Intrpt Enable Bit .else TPIE .equ 008h ; MSP430C32x configuration

48

MSP430 Family .endif .equ .equ .equ .equ .equ .equ .equ .equ .equ .equ

Metering Application Report

IE2 TPSSEL1 TPSSEL0 ENB ENA EN1 RC2FG RC1FG EN1FG B16

001h 080h 040h 020h 010h 008h 004h 002h 001h 080h

; ; ; ; ; ; ; ; ; ;

Intrpt Enable Byte Selects clock input (TPCTL) Selects clock gate (TPCTL) Gate for TPCNTx (TPCTL) Carry of HI counter (TPCTL) Carry of LO counter (TPCTL) End of Conversion Flag Use 16-bit counter (TPD)

; Rref0 .equ 001h ; TP.0: Reference Resistor Rmeas0 .equ 002h ; TP.1: Sensor0 Rmeas1 .equ 004h ; TP.2: Sensor1 Rref1 .equ 008h ; TP.3: Reference Resistor Rcharge .equ 010h ; TP.4: Charge Resistor ; ; RAM Definitions ; ADCRESULT .equ 0200h ; ADC results (4 words) MEASSTAT .equ ADCRESULT+8 ; Measurement Status Byte ; ;========================================================= ; .sect INIT,0F000h ; Initialization Section ; INIT MOV #0300h,SP ; Initialize Stack Pointer MOV.B #DIV+IP2+IP0,&BTCTL ; Basic Timer: 2Hz BIS.B #BTIE,&IE2 ; Basic Timer Intrpt Enable CLR.B &BTCNT1 ; Clear Basic Timer Regs. CLR.B &BTCNT2 CALL #CLRRAM ; Clear RAM ... ; Initialize other Modules ; MAINLOOP ... ; Main loop of program ; ; Its 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 the stack. ; MEASURE CLR ADCRESULT ; Clear result buffers CLR ADCRESULT+2 ; 0 indicates error CLR ADCRESULT+4 ; CLR ADCRESULT+6 ; 49

Metering Application Report MOV NOP ...

MSP430 Family

#CPUoff+GIE,SR ; CPU off, but MCLK on ; Wait for end of meas. ; Process meas. data

; ; Interrupt Handler for the Basic Timer Interrupt: 2Hz ; BT_INT PUSH R5 ; Save Help Register CALL #INCRWTCH ; Incr. Watch MOV.B MEASSTAT,R5 ; Calculate Handler MOV.B TABLE(R5),R5 ; Offset for PC ADD R5,PC ; Add Offset to PC TABLE .BYTE MSTAT0-TABLE ; 0: No activity .BYTE MSTAT1-TABLE ; 1: Charge for Rref0 .BYTE MSTAT2-TABLE ; 2: Measure Rref0 .BYTE MSTAT1-TABLE ; 3: Charge for Rmeas0 .BYTE MSTAT4-TABLE ; 4: Measure Rmeas0 .BYTE MSTAT1-TABLE ; 5: Charge for Rmeas1 .BYTE MSTAT6-TABLE ; 6: Measure Rmeas1 .BYTE MSTAT1-TABLE ; 7: Charge for Rref1 .BYTE MSTAT8-TABLE ; 8: Measure Rref1 .BYTE MSTAT9-TABLE ; 9: Finished, go on ; MSTAT1 MOV.B #B16+Rcharge,&TPD ; Charge Cm for 0.5s MOV.B #Rcharge,&TPE ; Use Rcharge JMP BT_RET ; MSTAT2 MOV #Rref0,R5 ; Measure Rref0 JMP MEASCOM ; To common Part ; MSTAT4 MOV #Rmeas0,R5 ; Measure Rmeas0 JMP MEASCOM ; To common Part ; MSTAT6 MOV #Rmeas1,R5 ; Measure Rmeas1 JMP MEASCOM ; To common Part ; MSTAT8 MOV #Rref1,R5 ; Measure Rref1 MEASCOM BIS.B #MOD,&SCFQCTL ; Switch off FLL Modulation CLR.B &TPE ; TP.x to HI-Z MOV.B #B16,&TPD ; TP.x LO (disabled!) ; ; No MCLK for ADC, Clear Flags RC2FG, RC1FG, EN1FG ; MOV.B #TPSSEL1+ENB+ENA,&TPCTL CLR.B &TPCNT1 ; Reset Counter LO CLR.B &TPCNT2 ; Reset Counter HI BIS.B R5,&TPE ; Enable selected TP.x ; ; MCLK on, Comparator on: Intrpt for Ucm < Vth ; MOV.B #TPSSEL1+TPSSEL0+ENB+ENA+EN1,&TPCTL BIS.B #TPIE,&IE2 ; Enable ADC Intrpt ; BT_RET INC MEASSTAT ; To next Status

50

MSP430 Family MSTAT0 POP RETI R5

Metering Application Report ; If no activity necessary

; ; MSTAT9: Measurements are completed, CPU is switched on, ; MSTAT is set to zero: no activity ; MSTAT9 BIC #CPUoff,2(SP) ; Stored SR on stack CLR.B MEASSTAT ; No activity BIC.B #MOD,&SCFQCTL ; Switch on FLL Modulation JMP MSTAT0 ; Return ; ; End of Basic Timer Handler ;---------------------------------------------------------; Interrupt Handler for the Analog-to-Digital Converter ; The results in TPCNT1 and TPCNT2 are stored starting at ; label ADCRESULT (result for Rref0) ; ADC_INT PUSH R5 ; Save Help Register MOV.B MEASSTAT,R5 ; Build offset for results SUB #3,R5 ; Status for Rref0 JN ADC_F ; MEASSTAT < 3: error ; ; Check for correct result: ; If RC2FG = 1: Overflow of the counter (Rx too high) ; If EN1 = 1: False interrupt, conversion not finished ; BIT.B #RC2FG+EN1,&TPCTL ; Error? JNZ ADC_RET ; Yes, let 0h for error MOV.B &TPCNT1,ADCRESULT(R5) ; Store result MOV.B &TPCNT2,ADCRESULT+1(R5) ; ADC_RET BIC.B #TPIE,&IE2 ; Disable ADC Intrpt BIC.B #RC2FG+RC1FG+EN1FG,&TPCTL ; Flags = 0 ADC_F POP R5 ; Restore R5 RETI ; ; End of Universal Timer/Port Module Handler ;---------------------------------------------------------; Interrupt vectors ; .sect INT_VECT,0FFE2h .WORD BT_INT ; Basic Timer Vector .if Type=310 .sect INT_VEC1,0FFEAh ; MSP430C31x .else .sect INT_VEC1,0FFE8h ; Others .endif .WORD ADC_INT ; Timer Port Vector (31x) .sect INT_VEC2,0FFFEh .WORD INIT ; Reset Vector

51

Metering Application Report 2.2.2 Connection of long Sensor Lines

MSP430 Family

If the distance from the MSP430C31x to the sensor is long (>30cm) then it is recommended to use a shielded lead between the microcomputer and the sensor. This is to give protection to the ADC input. Figure 22.6 shows the schematic. The protection resistors Rv/2 need to be included into the calculation: they are connected in series with the sensor. To protect the measurement against spikes, hum and other unwanted noise see chapter "Signal Averaging": here some possibilities for the minimization of these influences are shown. Depending on the actual application the omission of the two resistors Rv/2 can give best results: the relatively low internal resistance of the TP.x output and the capacitor alone may get this. If a shielded cable is not possible then a twisted cable or a three-core cable should be used: the unused wire is connected to Vss as shown in figure 22.6 with Rsens2.
Cm 0V Rref Shield Rv/2 Rsens1 Shield Rsens2 TP.2 3rd Line No shield, twisted wires 0V +5V Rv/2 TP.0 MSP430C31x TP.1 Cin

Vss

Vcc

Figure 22.6: Connection of long Sensor Lines 2.2.3 Grounding The correct grounding is very important if ADCs with high resolution are used. There are some basic rules that need to be observed. With the MSP430C31x and the MSP430C33x only the Vss pin exists as a common reference point. 1. Use of separate analog and digital ground planes wherever possible: no thin connections from battery to pin Vss 2. The Vss pin is a star point for all 0V connections 3. Battery and capacitor are connected together at this star point. See figure 22.7. 4. No common path for analog and digital signals

52

MSP430 Family

Metering Application Report

Rref TPD.0 Rsens1 TPD.1 Battery Replacement 5V Vcc Vss To other parts 0V To metallization AGND +3V Cm Rsens2 MSP430C31x TPD.2 CIN Vss Vcc To other parts

Figure 22.7: Grounding for the Universal Timer/Port ADC Figure 22.7 shows also the use of a mains driven power supply: its Vcc and Vss connections are connected where the battery is connected normally. The capacitor across the MSP430 pins may be smaller if 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 (0V) of the board. Otherwise the behavior is worse than without the metallization. 2.2.4 Voltage Measurement with the Universal Timer Port/Module The measurement of a restricted voltage range is possible too with the Universal Timer/Port Module: normally a second circuit is used for this purpose. The application is shown for the measurement of an accumulator voltage. The output TP.4 and the SCHMITT-Trigger input TP.5 (having the same characteristic like the input CIN) are used. Due to this separation the sensitive measurement of the temperature is not disturbed. The circuitry is shown in figure 22.8 at the right hand side.
Vbatt (7 - 14.5V) 32kHz 1M TP.0 TP.1 MSP430 Rref Rsens TP.4 Battery Circuit CIN Temperature Circuit TXD RCV C1 TP.5 P0.2 P0.1 R2 500k Cm 0V R Vin Vcc R1 +5V

Vss

Figure 22.8: Measurement of the Battery Voltage and the Temperature

53

Metering Application Report

MSP430 Family

The measurement sequence is as follows (the numbers refer to the Conversion States shown in figure 22.9): 1. TP.4 is switched to Hi-Z, TP.5 to input direction 2. If input TP.5 does not have Hi potential then the capacitor Cm is charged with the resistor R until TP.5 shows Hi potential 3. Cm is discharged to 1/3 of Vbatt by the resistors R1 and R2 4. Cm is discharged to the lower threshold voltage VT- by the resistor R; the necessary time tVbatt is measured by the 16-bit timer of the Timer Port Module 5. Cm is charged to Vcc by the resistor R 6. Cm is discharged to VT- by the resistor R; the necessary time tVcc is measured by the 16bit timer of the Timer Port Module 7. The battery voltage Vbatt is calculated with the formula:

Vc 2 Vcc VT+ (R1+R2)/R2 x Vbatt 3 4 5 6 7 Conversion States

VT0 td tbatt tcharge tVcc Time

Figure 22.9: States of the Voltage Measurement


R1 + R2 Vbatt = Vcc e R2
tbatt tVcc

Where:

Vcc Vbatt tbatt tVcc VT-

Supply voltage of the MSP430 (used as reference) Voltage of the accumulator Discharge time from divided Vbatt to VTDischarge time from Vcc to VTTime constant of the discharge circuit: = R Cm Lower threshold voltage of input TP.5

[V] [V] [s] [s] [s] [V]

For the interesting voltage range of the battery (7V to 14.5V) and a supply voltage Vcc of 5V the exponential characteristic of the above function can be simulated by a hyperbolic function (with only one division necessary):
Vbatt = A +C (tbatt tVcc) + B

For the hardware shown in figure 22.8 the formula results in:
Vbatt = 2.2277E + 6 10.49435 (tbatt tVcc) + 8.738E + 4

54

MSP430 Family

Metering Application Report

The MSP430 Floating Point Package may be used for the calculation. The restriction for the input voltage range of the voltage Vin (seen after the resistor divider) is:
VT - < Vin Vcc

55

Metering Application Report

MSP430 Family

3 HARDWARE APPLICATIONS
3.1 I/O-Port Usage The I/Os of Port0, Port1 and Port2 have a very useful feature: each one has interrupt capability for the leading and for the trailing edge of an input signal. This has the following advantages: 1. More than one interrupt input is available 2. Eight resp. 24 external events can wake-up from Low Power Modes 3 or 4 3. 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. 4. Wake-up is possible out of any input state (high or low) 5. Due to the edge-triggering of the interrupts no external switch-off logic is necessary for input signals that are of long duration: no multiple interrupt is possible therefore. 3.1.1 General Usage Six peripheral registers control the activities of each one of the I/O-ports Port0, Port1 and Port2: Table 31.1: I/O-Port0 Registers Usage Signals at I/O-pins Content of output buffer 0: Input 1: Output 0: No interrupt pending 1: Interrupt pending 0: Low to high causes Intrpt 1: High to low causes Intrpt 0: Disabled 1: Enabled

Register Input Register Output Register Direction Register Interrupt Flags Interrupt Edges Interrupt Enable

State after Reset Signals at I/O-pins Unchanged Reset to input direction Reset Unchanged Reset

The interrupt vectors, flags and peripheral addresses of I/O-port 0 are: Table 31.2: I/O-Port0 Hardware Addresses Name Mnemonic Address Contents Input Register P0IN 010h P0IN.7 ... P0IN.0 Output Register P0OUT 011h P0OUT.7 ... P0OUT.0 Direction Register P0DIR 012h P0DIR.7 ... P0DIR.0 Interrupt Flags P0IFG 013h P0IFG.7 ... P0IFG.2 IFG1.3 002h P0IFG.1 IFG1.2 002h P0IFG.0 Interrupt Edges P0IES 014h P0IES.7 ... P0IES.0 Interrupt Enable P0IE 015h P0IE.7 ... P0IE.2 IE1.3 000h P0IE.1 IE1.2 000h P0IE.0 The other ports are organized the same way except the following items: Port3 and Port4 do not have interrupt capability: PxIFG, PxIES and PxIE do not exist

Vector ----0FFE0h 0FFF8h 0FFFAh

56

MSP430 Family

Metering Application Report

Port1 and Port2 contain eight equal I/Os, the special hardware for the bits 0 and 1 is not implemented.

EXAMPLE: The I/O-ports P0.0 to P0.3 are used for input only. P0.4 to P0.7 are outputs, initially at low level. The conditions are: P0.0 Every change is counted P0.1 Any Hi-Lo change is counted P0.2 Any Lo-Hi change is counted P0.3 Every change is counted ; ; RAM definitions ; .BSS P0_0CNT,2 ; Counter for P0.0 .BSS P0_1CNT,2 ; Counter for P0.1 .BSS P0_2CNT,2 ; Counter for P0.2 .BSS P0_3CNT,2 ; Counter for P0.3 ; ; Initialization for Port0 ; MOV.B #000h,&P0OUT ; Output register low MOV.B #0F0h,&P0DIR ; P0.4 to P0.7 outputs MOV.B #00Bh,&P0IES ; P0.0 to P0.3 Hi-Lo, P0.2 Lo-Hi MOV.B #00Ch,&P0IE ; P0.2 to P0.3 interrupt enable BIS.B #00Ch,&IE1 ; P0.0 to P0.1 interrupt enable ; ; Interrupt handler for P0.0. Every change is counted ; P0_0HAN INC P0_0CNT ; Flag is reset automatically XOR.B #1,&P0IES ; Change edge select RETI ; ; Interrupt handler for P0.1. Any Hi-Lo change is counted ; P0_1HAN INC P0_1CNT ; Flag is reset automatically RETI ; ; Interrupt handler for P0.2 and P0.3 ; The flags of all read transitions are reset. Transitions ; occurring during the interrupt routine cause interrupt after ; the RETI ; P0_23HAN PUSH R5 ; Save R5 MOV.B &P0FLG,R5 ; Copy interrupt flags BIC.B R5,&P0FLG ; Reset read flags BIT #4,R5 ; P0.2 flag to carry ADC P0_2CNT ; Add carry to counter BIT #8,R5 ; P0.3 flag to carry JNC L$304 INC P0_3CNT ; P0.3 changed XOR.B #8,P0IES ; Change edge select L$304 POP R5 ; Restore R5 RETI 57

Metering Application Report ; .SECT .WORD .WORD ; .SECT .WORD "INT_VECT1",0FFE0h P0_23HAN "INT_VECT",0FFF8h P0_1HAN P0_0HAN

MSP430 Family

; P0.1 INTERRUPT VECTOR; ; P0.0 INTERRUPT VECTOR; ; P0.2/7 INTERRUPT VECTOR

3.1.2 Zero Crossing Detection With the external components shown in figure 31.1 it is possible to build a zero crossing input for the MSP430. The components shown are designed for an external voltage Vmains = 230V. With a circuit capacitance C (wiring, diodes) of 30pF as shown, the following delays will occur (all values for Vmains = 230V, f = 50Hz, Vcc = +5V) (timing is in s):
Vcc 1 Vmains R Protection Diodes C MSP430 30pF Vportx to Portx

GND GND

Figure 31.1: MSP430 Input for Zero-Crossing

Port Input Voltage

Vmains Vportx

Vmains Vportx

VT+max VT-max VT-min

VT+min

0 30 54 65 6 16 30 Time

Figure 31.2: Timing for the Zero Crossing Delay caused by RC (1M x 30pF): 30s or 0.54 (same value for leading and trailing edges). Delay caused by input thresholds: Leading edge: 24 to 35s. (VT+ = 2.3 to 3.4V) Trailing edge: 14 to 24s. (VT- = 2.3 to 1.4V)

58

MSP430 Family The resulting delays are: Leading edge: 54 to 65s. Trailing edge: 6 to 16s.

Metering Application Report

These small deviations do not play a role for 50Hz or 60Hz phase control applications with TRIACs. If other input conditions than 230V and 50Hz are used then the resulting delays can be calculated with the following formulas:

tD =
Where: tD VT SV U

VT ; SV

SV =

d( U sin t) = U cost dt
[s] [V] [V/s] [1/s] [V]

Delay time caused by the input threshold voltage Threshold voltage of an input Slope of the input voltage Angular frequency 2f Peak value of the input voltage Umains

For t = 0 (zero crossing time) the above equation becomes:


tD = VT VT = U 1 U

3.1.3 Output Buffering The outputs of the MSP430 (P0.x, P1.x, P2.x, P3.x, P4.x, Ox) have nominal internal resistances depending on the supply voltage Vcc: Vcc = 3V: max. 333 Vcc = 5V: max. 266 (V = 0.4V max. @ 1.2mA) (V = 0.4V max. @ 1.5mA)

These internal resistances are non-linear and are valid only for small output currents (see above). If larger currents are drawn then saturation effects will limit the output current. These outputs are intended for driving digital inputs and gates and they normally have a too high impedance for other applications such as the driving of relays, lines etc. If output currents greater than the above mentioned ones are needed then output buffering is necessary. Figure 31.3 shows some possibilities. The resistors shown for the limitation of the MSP430 output current are minimum values. The design is made for Vcc: = 5V; values in brackets are for Vcc:= 3V.

59

Metering Application Report

MSP430 Family

32kHz SVcc 2.7k (1.6k) P0.x,Oy MSP430 8.2k (3.3k) P0.x,Oy

+5V Ic = 1.5mA x (Ic = 1.2mA x)

0V Ic = 350mA

ULN2001A P0.x,Oy Ic =200mA ULN2003A +5V 3.0k (2k) P0.x,Oy TRIAC Vss Vcc Mains

0V

+5V

0V

0V

Figure 31.3: Output Buffering 3.1.4 Universal Timer/Port I/Os If the Universal Timer/Port is not used for analog-to-digital conversion, or is only partially used for this purpose, then the unused pins are available as outputs that may be switched to HI-Z. The Universal Timer/Counter Port may be used in three different modes: Two 8-bit timers, one input, one I/O and 5 output pins One 16-bit timer, one input, one I/O and 5 output pins An Analog-to-digital converter with two to six output pins

The ports TP.0 to TP.5 are completely independent of the analog-to-digital converter. Which ports are used for the sensors and reference resistors does not matter. Power-up resets the data register to zero and switches all TP.x ports to HI-Z.

60

MSP430 Family

Metering Application Report

MSP430
Enable Control TPIN.5 TPD.5 TPE.5 TPD.4 TPE.4 TPD.3 TPE.3 TPD.2 TPE.2 TPD.1 TPE.1 TPD.0 TPE.0

CIN

TP.5

TP.4

TP.3

TP.2

TP.1

TP.0

Figure 31.4: The Output Section of the Universal Timer/Port Module 3.1.4.1 I/Os used with the Analog-to-Digital Converter The analog-to-digital conversion uses the pins CIN and at least two of the TP.x pins (one for the reference and one for the sensor to be measured): therefore up to 4 outputs are available for other purposes. It is only possible to use bit instructions (BIS.B, BIC.B, XOR.B) 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 next section. NOTE For precise ADC results it is recommended to avoid changes of the TP-ports during the measurement. The board layout and the physical distance of the switched port define the influence to the pin CIN. Spikes coming from the switching of ports can alter the result of a measurement especially if they occur near to the crossing of the threshold voltage. 3.1.4.2 I/Os used without ADC This mode allows 5 outputs with the possibility of being switched to HI-Z (TP.0 to TP.4) and one I/O-pin (TP.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, XOR.B) are possible for the manipulation of the port: four control bits of the timers are located within the Data Register TPD and Data Enable Register TPE. If the MOV.B instruction is used, all bits are affected. EXAMPLE: All six ports are used as outputs. The possibilities of the port are shown: ; ; Definitions for the Counter Port ; TPD .EQU 04Eh ; Data Register TPE .EQU 04Fh ; Data Enable Register. 1: output enabled TP0 .EQU 001h ; TP.0 bit address TP1 .EQU 002h ; TP.1 bit address TP2 .EQU 004h ; TP.2 bit address TP3 .EQU 008h ; TP.3 bit address TP4 .EQU 010h ; TP.4 bit address TP5 .EQU 020h ; TP.5 bit address ; ; Reset all ports and switch all to output direction ; 61

Metering Application Report BIC.B BIS.B #TP0+TP1+TP2+TP3+TP4+TP5,&TPD #TP0+TP1+TP2+TP3+TP4+TP5,&TPE

MSP430 Family ; Data to low ; Enable outputs

; ; Toggle TP.0 and TP.4, set TP.5 and TP.2 afterwards ; XOR.B #TP0+TP4,&TPD ; Toggle TP.0 and TP.4 BIS.B #TP5+TP2,&TPD ; Set TP.5 and TP.2 ; ; Switch TP.1 and TP.3 to HI-Z state ; BIC.B #TP1+TP3,&TPE ; HI-Z state for TP.1 and TP.3 3.1.5 I/Os used for fast serial Transfer The combination of hardware and software shown below allows a fast serial transfer with the MSP430 family. The data line needs to be Px.0, for the clock line any other Portx line may be used. The adaptation to any data length is possible. The LSB is transferred at the beginning; this can be changed easily: RLC instead of RRC. ; P0OUT .EQU 011h ; Port0 Output register P0DIR .EQU 012h ; Port0 Direction register P00 .EQU 01h ; Bit address of P0.0: Data P01 .EQU 02h ; Bit address of P0.1: Clock ; MOV DATA,R5 ; 1st 16bit data to R5 CALL #SERIAL_FAST_INIT ; 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 #P00+P01,&P0OUT ; Reset P0.0 and P0.1 BIS.B #P00+P01,&P0DIR ; P0.0 and P0.1 to output dir. ; ; Part for 2nd and all following transfers ; SERIAL_FAST ; Initialization is made RRC R5 ; LSB to carry 1 cycle ADDC.B #P01,&P0OUT ; Data out, set clock 4 cycles BIC.B #P00+P01,&P0OUT ; Reset data and clock 5 cycles ; RRC R5 ; LSB+1 to carry 1 cycle ADDC.B #P01,&P0OUT ; Data out, set clock 4 cycles BIC.B #P00+P01,&P0OUT ; Reset data and clock 5 cycles ; ...... ; Output all bits the same way ; RRC R5 ; MSB to carry 1 cycle ADDC.B #P01,&P0OUT ; Data out, set clock 4 cycles BIC.B #P00+P01,&P0OUT ; Reset data and clock 5 cycles

62

MSP430 Family

Metering Application Report

RET ; Each bit needs 10 cycles for the transfer, this results in a maximum Baud rate for the transfer:
Baudratem ax = MC LK 10

This means if MCLK = 1.024MHz then the maximum Baud rate is 102.4kBaud.

"1"
Data P0.0 MSP430 Clock P0.1 Vss Vcc 10 MCLK

"0"

"1"

"0"

0V

+5V

Figure 31.5: Connections for fast serial Transfer

63

Metering Application Report 3.2 Storage of Calibration Constants

MSP430 Family

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, mains) it is necessary or possible to have them stored in the on-chip RAM or in an external EEPROM. Both methods are explained below. 3.2.1 External EEPROM for Calibration Constants The storage of calibration constants, energy values, meter numbers and device versions in external EEPROMs is necessary if the metering device is supplied by the mains. This is due to the possible power failures that may occur. The EEPROM is connected to the MSP430 by dedicated inputs and outputs. Three (two) control lines are necessary for proper function: Data line SDA: an I/O-port is needed for this bi-directional line. Data can be read from and written to the EEPROM Clock line SCL: an output line is sufficient for the clock line. This clock line may be used for other peripheral devices too if it is ensured that no data is present on the data line during use. Supply line: if the current consumption of the EEPROM when not in use is too high then switching of the EEPROMs Vcc is necessary. Three possible solutions are shown: 1. The EEPROM is connected to SVcc. This is a very simple way to have the EEPROM switched off when not in use 2. The EEPROM is switched on and off by an external PNP-transistor driven by an output port. 3. The EEPROM is connected to +5V permanently, if its power consumption does not play a role.

SVcc +5V +5V P0.z,Oy MSP430 Vcc SCL X24LCxx Ax Vss 0V 0V +5V SDA
Data Clock

P0.y,Ox

P0.x Vss Vcc

Figure 32.1: External EEPROM Connections

64

MSP430 Family

Metering Application Report

An additional way to connect an EEPROM to the MSP430 is shown in section 3.4 describing the I2C-Bus. NOTE The next 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 of 1MHz each one of the control instructions needs 5s. EXAMPLE: The EEPROM with the dedicated I/O-lines is controlled with normal I/O-instructions. The SCL line is driven by O17, the SDA line is driven by P0.6. The line is driven high by a resistor, and low by the output buffer. P0OUT .EQU 011h ; Port0 Output register P0DIR .EQU 012h ; Port0 Direction register SCL .EQU 0F0h ; O17 controls SCL, 039h LCD Address SDA .EQU 040h ; P0.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 ; BIC.B #SDA,&P0DIR ; SDA TO INPUT DIRECTION BIS.B #SCL,&LCDM+9 ; SET CLOCK HI BIC.B #SDA,&P0OUT ; SDA LOW IF OUTPUT ... ; ; START CONDITION: SCL AND SDA ARE HIGH, SDA IS SET LOW, ; AFTERWARDS SCL GOES LO ; BIS.B #SDA,&P0DIR ; SET SDA LO (SDA GETS OUTPUT) BIC.B #SCL,&LCDM+9 ; SET CLOCK LO ; ; DATA TRANSFER: OUTPUT OF A "1" ; BIC.B #SDA,&P0DIR ; SET SDA HI BIS.B #SCL,&LCDM+9 ; SET CLOCK HI BIC.B #SCL,&LCDM+9 ; SET CLOCK LO ; ; DATA TRANSFER: OUTPUT OF A "0" ; BIS.B #SDA,&P0DIR ; SET SDA LO BIS.B #SCL,&LCDM+9 ; SET CLOCK HI BIC.B #SCL,&LCDM+9 ; SET CLOCK LO ; ; STOP CONDITION: SDA IS LOW, SCL IS HI, SDA IS SET HI ; BIC.B #SDA,&P0DIR ; SET SDA HI BIS.B #SCL,&LCDM+9 ; Set SCL HI ; The examples shown above for the different conditions can be implemented into a subroutine which outputs the contents of a register. This shortens the necessary ROM code significantly. 65

Metering Application Report

MSP430 Family

Instead of line Ox for the SCL line another I/O-port P0.x may be used. See section I2C Bus Connection for more details of such a subroutine. 3.2.2 Internal RAM for Calibration Constants The internal RAM can be used for 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 this kind of applications to get battery life times reaching from 8 to 12 years.

66

MSP430 Family 3.3 M-BUS Connection

Metering Application Report

The MSP430 connection is shown in the next figure. Three supply modes are possible when used with the TSS721: Remote Supply: The MSP430 is fully powered from the TSS721 Remote Supply/Battery support: The MSP430 is supplied normally from the TSS721. In case of a bus power fail the battery powers the MSP430 Battery Supply: The MSP430 is always supplied from its battery

All these operating modes are described in detail in the "TSS721 M-Bus Transceiver Applications Book".

32kHz

METER BUS

P0.1 RXD P0.2 TXD Ay/RST/P0.y MSP430 Ax/P0.x TP.x/Oy/P0.y Az/RST/P0.z

TXI RXI PF TSS721

BUSL1 BUSL2

TXI RXI PF

BUSL1 TSS721 BUSL2

Figure 33.1: TSS721 Connections to MSP430 Two different TSS721 connections are shown in the figure above: If the 8-bit Interval Timer with its UART is to be used then the upper connection is necessary. TXI or TX are connected to RXD (P0.1) and RXI or RX are connected to TXD (P0.2). If a pure software UART or an individual protocol is to be used, then any input and output combination may be used

For more details see also chapter Power Supplies for the MSP430.

67

Metering Application Report 3.4 I2C BUS Connection

MSP430 Family

If more than one device is to be connected to the I2C-Bus then two I/O-ports are needed for the control of the I2C-peripherals. The reason for this is the need to switch SDA and SCL to the high impedance state. The figure below shows the connection of three I2C-peripherals to the MSP430: 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 (P0.x is switched to input direction) and low by the output ports itself (P0.x is switched to output direction).
+5V

Rp

Rp

TP.x/P0.a

SCL

P0.b MSP430 SCL SDA A2 EEPROM A1 128x8 A0 Vdd +5V Vss 0V SCL SDA A2 EEPROM A1 2048x8 A0 Vdd +5V Vss 0V SCL SDA Ax ADC/DAC AINx AOUT Vdd +5V Vss 0V

SDA

3 4

Vcc +5V

Vss 0V

. Figure 34.1: I2C-Bus connections NOTE The next software example does not contain the necessary delay times between the setting and resetting of the clock and data bits. These delay times can be seen in the specifications of the peripheral device. The complete I2C-Handler for one byte of data follows. The data pin SDA needs an I/O-pin (Port0); the clock pin SCL may be an I/O-pin or an output pin that can be switched to HI-Z (TP-Port e.g.).
Bit 15 Slave Address 8 R/W 7 Data 0

Figure 34.2: Word Format for I2C-Handler Call

68

MSP430 Family

Metering Application Report

SCL .EQU 080h ; P0.7 CONTROLS SCL SCLDAT .EQU 011h ; P0OUT register address SCLEN .EQU 012h ; P0DIR register address SDA .EQU 040h ; P0.6 CONTROLS SDA SDAIN .EQU 010 ; P0 input register P0IN SDADAT .EQU 011h ; P0 output direction register P0DIR SDAEN .EQU 012h ; P0 direction register ; ; INITIALIZATION FOR THE I2C BUS PORTS: ; INPUT DIRECTION: BUS LINES GET HIGH BY PULL-UPS ; OUTPUT BUFFERS LOW: PREPARATION FOR LOW ACTIVE SIGNALS ; Initialization for SDA and SCL from Port0 ; BIC.B #SCL+SDA,&SDAEN ; SCL AND SDA TO INPUT DIRECTION BIC.B #SCL+SDA,&SDADAT ; SCL AND SDA OUTPUT BUFFER LOW ... ; ; Initialization for SDA at Port0, SCL at TP.x (MSP430C31x) ; BIC.B #SDA,&SDAEN ; SDA TO INPUT DIRECTION (HI) BIC.B #SDA,&SDADAT ; SDA OUTPUT BUFFER LOW ; BIC.B #SCL,&SCLEN ; SCL to input direction (HI) BIC.B #SCL,&SDADAT ; SCL OUTPUT BUFFER LOW ... ... ; ; I2C-Handler: Outputs or reads 8-bit data ; ; WRITE: R/@W = 0. R6 contains slave address and 8-bit data ; Return: C = 0: Transfer ok (R6 unchanged) ; C = 1: Error (R6 unchanged) ;Call MOV.B data,R6 ; 8-bit data to R6 ; BIS (2*addr)*0100h,R6 ; Address and function ; CALL #I2CHND ; Call handler ; JC ERROR ; C = 1: Error occurred ; ;READ: R/@W = 1. R6 contains slave address , low byte undefined ; Return: R6 contains 8-bit data in low byte, hi byte = 0 ;Call MOV (2*addr+1)*0100h,R6 ; Address and function ; CALL #I2CHND ; Call handler ; ... ; 8-bit info in R6 lo ; I2CHND PUSH R5 ; Handler Start: Save register ; ; I2C START CONDITION: SCL AND SDA ARE HIGH, SDA GOES LOW ; THEN SCL GOES LOW ; BIS.B #SDA,&SDAEN ; SET SDA LO BIS.B #SCL,&SCLEN ; SET SCL LINE LO ; ; Sending of the address bits (7) and R/@W-bit ; MOV #8000h,R5 ; Bit mask MSB 69

Metering Application Report I2CCL BIT CALL CLRC RRC CMP JNE R5,R6 #I2CSND R5 #080h,R5 I2CCL ; Bit -> carry ; Send carry ; Next address bit ; R/@W sent? ; No, continue

MSP430 Family

; ; Address and R/@W sent: Receive of an acknowledge bit, ; Decision if read or write ; CALL #I2CACKN JC I2CERR ; No acknowledge, error BIT #100h,R6 ; Read or Write? JNZ I2CRI ; ; Write: Continue with 8-bit data in low byte of R6 ; I2CWL BIT R5,R6 ; Write: continue with data CALL #I2CSND CLRC RRC R5 ; If testbit in carry: finished JNC I2CWL CALL #I2CACKN ; Acknowledge bit -> carry ; ; Carry information: 0: Ok 1: Error ; I2CEND .EQU $ I2CERR BIC.B #SCL,&SCLEN ; Stop condition BIC.B #SDA,&SDAEN ; SET SDA HI POP R5 ; Restore R5 RET ; Carry info valid ; ; Read: read 8 data bits to R6 low byte. R5 = 080h ; I2CRI CALL #I2CRD ; Read bit -> carry RLC.B R6 ; Carry to LSB R6 RRA R5 ; Bit mask used for count JNC I2CRI ; Bit mask in carry: finished CALL #I2C0 ; Acknowledge bit = 0 JMP I2CEND ; Carry = 0 ; ; Subroutines for I2C-Handler ; ; Send routine: Info in Carry is sent out. ; Acknowledge bit subroutine is used for clock output ; I2CSND JNC I2C0 ; Info in carry BIC.B #SDA,&SDAEN ; Info = 1 JMP I2CACKN I2C0 BIS.B #SDA,&SDAEN ; Info = 0 ; ; Reading of acknowledge (or data) bit to carry ;

70

MSP430 Family I2CACKN .EQU I2CRD BIC.B BIT.B BIS.B RET $ #SCL,&SCLEN #SDA,&SDAIN #SCL,&SCLEN

Metering Application Report

; Set clock hi ; Read data to carry ; Clock lo

71

Metering Application Report 3.5 Hardware Optimization

MSP430 Family

The MSP430 permits the use of unused analog inputs (A7 to A0) and segment lines (S29 to S2) for inputs and outputs respectively. The next 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 (ADC) inputs can be used as digital inputs or, with some restrictions, as digital outputs. 3.5.1.1 Analog Inputs used for Digital Inputs Any ADC input A7 to A0 can be used as a digital input. It is only necessary to program it (for example during the initialization) for this function. Three things are important if this feature is used: Any activity at these digital inputs has to be stopped during ongoing sensitive ADC measurements. This activity will cause noise which will falsify the ADC results. Activity means in this case: - No change of the AEN register (switching between digital and analog mode) - No input change at the digital ADC inputs (this allows only rarely changing input signals at these inputs). All bits which are switched to ADC inputs will read zero when read. Therefore it is not necessary to clear them by software after the reading. Not all analog inputs are implemented in a given device Software Example: A0 to A4 are used as ADC inputs, A5 to A7 as digital inputs. ; AIN .EQU 0110h ; Address DIGITAL INPUT REGISTER AEN .EQU 0112h ; Address DIGITAL INPUT ENABLE REG. A7EN .EQU 080h ; Bits in Dig. Input Enable Reg.: A6EN .EQU 040h ; 0: ADC 1: Digital Input A5EN .EQU 020h ; ; INITIALIZATION: A7 TO A5 ARE SWITCHED TO DIGITAL INPUTS ; A4 TO A0 ARE USED AS ANALOG INPUTS ; MOV #A7EN+A6EN+A5EN,&AEN ; A7 TO A5 DIGITAL MODE ... ; NORMAL PROGRAM EXECUTION: ; CHECK IF A7 OR A5 ARE HIGH. IF YES: JUMP TO LABEL L$100 ; BIT #A7EN+A5EN,&AIN ; A7 .OR. A5 HI? JNZ L$100 ; YES ... ; NO, CONTINUE ; ; CHECK IF ALL DIG. INPUTS A7 TO A5 ARE LOW. IF YES: Go to L$200 ; TST &AIN ; A7 TO A5 LO? JZ L$200 ; YES, (ANALOG INPUTS READ ZERO)

72

MSP430 Family ; 3.5.1.2 Analog Inputs used for Digital Outputs

Metering Application Report

If outputs are missing then the unused ADC inputs with the Current Source connection can be used if the following restrictions are considered: Only one ADC input can be high at a given time (1 out of n principle) Only the ADC inputs A0 to A3 are usable (only they are connected to the Current Source) The outputs can get high only during the time the ADC does not use the Current Source The output current is directly related to the supply voltage Vcc The output voltage is only about 50% of the supply voltage Vcc. Logic levels have to be checked carefully therefore. A transistor stage may perhaps be necessary (if not there anyway, e.g. for a relay) The output current is given by the current of the Current Source. The same considerations as with the point before have to be made. The pull-down resistor has to be high enough to allow the maximum output level.

The example below shows the ADC part which uses the ADC inputs A0 and A1 as digital outputs driving two stages: a transistor stage (energy pulse e.g.with an electricity meter) and a 3.3V gate (3.3V guarantees that the input levels are sufficient).
32kHz Ics = 0.25 x SVcc/Rext SVcc Ics Rext RI Energy Output A0 MSP430 A1 To 3V Logic 0V 0V 0V 0V +3.3V +5V

Figure 35.1: Unused ADC inputs used as Outputs EXAMPLE. To control the two outputs shown above the following software part is necessary: ACTL .EQU 0114h ; ADC CONTROL REGISTER ACTL VREF .EQU 02h ; 0: Ext. Reference 1: SVCC ON A0 .EQU 0000h ; AD INPUT SELECT A0 A1 .EQU 0004h ; A1 CSA0 .EQU 0000h ; CURRENT SOURCE TO A0 CSA1 .EQU 0040h ; A1 CSOFF .EQU 0100h ; CURRENT SOURCE OFF BIT ; ; SET A0 HI FOR 3ms: SELECT A0 FOR CURRENT SOURCE AND INPUT 73

Metering Application Report

MSP430 Family

MOV CALL BIS

#VREF+A0+CSA0,&ACTL #WAIT3MS #CSOFF,&ACTL

; PD = 0, SVCC = on ; WAIT 3ms ; CURRENT SOURCE OFF;

; ; SET A1 HI FOR 3ms: SELECT A1 FOR CURRENT SOURCE AND INPUT MOV CALL BIS ... #VREF+A1+CSA1,&ACTL #WAIT3MS #CSOFF,&ACTL ; PD = 0, SVCC = on ; WAIT 3ms ; CURRENT SOURCE OFF

3.5.2 Use of unused Segment Lines for Digital Outputs The LCD-driver of the MSP430 provides additional digital outputs if segment lines are not used. Up to 28 digital outputs are possible by the hardware design, but not all of them will be implemented for a given chip. The addressing scheme for the digital outputs O2 to O29 is as illustrated in table 35.1. The table shows the dependence of the segment/output lines on the 3-bit value LCDP. Only if LCDP = 7 then all lines are switched to the LCD Mode (segment lines). Only groups of four segment lines can be switched to digital output mode. LCDP is set to zero by PUC (O6 to O29 are in use). NOTES Table 35.1 shows the digit environment for a 4MUX LCD display. The outputs O0 and O1 are not available: S0 and S1 are always implemented as LCD outputs. (digit 1). The digital outputs Ox have always to be addressed with all four bits. This means that 0Fh is to be used for the addressing of one output. Only byte addressing is allowed for the addressing of the LCD controller bytes. PUC switches the LCD-outputs to the digital output mode (LCDP = 0) except S0 and S1.

74

MSP430 Family

Metering Application Report Table 35.1: LCD and Output Configuration 6 5 4 3 2 1 0 Digit Nr. O29 O28 Digit 15 O27 O26 Digit 14 O25 O24 Digit 13 O23 O22 Digit 12 O21 O20 Digit 11 O19 O18 Digit 10 O17 O16 Digit 9 O15 O14 Digit 8 O13 O12 Digit 7 O11 O10 Digit 6 O09 O08 Digit 5 O07 O06 Digit 4 O05 O04 Digit 3 O03 O02 Digit 2 g f e d c b a Digit 1

Address 03Fh 03Eh 03Dh 03Ch 03Bh 03Ah 039h 038h 037h 036h 035h 034h 033h 032h 031h

LCDP 6 to 0 6 to 0 5 to 0 5 to 0 4 to 0 S20/S21 4 to 0 3 to 0 3 to 0 2 to 0 2 to 0 S10/S11 1 to 0 1 to 0 0 0 S0/S1

Software example: S0 to S13 drive a 4MUX LCD (7 digits). O14 to O17 are digital outputs. ; LCD Driver definitions: ; LCDM .EQU 030h ; ADDRESS LCD CONTROL BYTE LCDM0 .EQU 001h ; 0: LCD off 1: LCD on LCDM1 .EQU 002h ; 0: high 1: low Impedance MUX .EQU 004h ; MUX: static, 2MUX, 3MUX, 4MUX LCDP .EQU 020h ; Segment/Output Definition LCDM7/6/5 O14 .EQU 00Fh ; O14 Control Definition O15 .EQU 0F0h ; O15 O16 .EQU 00Fh ; O16 O17 .EQU 0F0h ; O17 ; ; INITIALIZATION: DISPLAY ON: LCDM0 = 1 ; HI IMPEDANCE LCDM1 = 0 ; 4MUX: LCDM4/3/2 = 7 ; O14 TO O17 ARE OUTPUTS: LCDM7/6/5 = 3 ; MOV.B #(LCDP*3)+(MUX*7)+LCDM0,&LCDM ; INIT LCD ... ; NORMAL PROGRAM EXECUTION: ; SOME EXAMPLES HOW TO MODIFY THE DIGITAL OUTPUTS O14 TO O17: ; BIS.B #O14,&LCDM+8 ; SET O14, O15 UNCHANGED BIC.B #O15+O14,&LCDM+8 ; RESET O14 AND O15 MOV.B #O15+O14,&LCDM+8 ; SET O14 AND O15 MOV.B #O17,&LCDM+9 ; RESET O16, SET O17 XOR.B #O17,&LCDM+9 ; TOGGLE O17, O16 STAYS UNCHANGED

75

Metering Application Report 3.6 Digital-to-Analog Converters

MSP430 Family

The MSP430 does not contain a Digital-to-Analog Converter (DAC) on-chip in its current versions, but it is relatively simple to implement the DAC function if needed. Five different solutions with distinct hardware and software requirements are shown below: 1. 2. 3. 4. 5. The R/2R method The Weighted Resistors method Integrated Digital-to-Analog Converters connected to the I2C-Bus Pulse Width Modulation (PWM) with the Universal Timer/Port Module Pulse Width Modulation with the Timer_A

3.6.1 R/2R Method With a CMOS shift register a Digital-to-Analog Converter can be built with any length. The outputs Qx of the shift register switch the 2R-resistors to 0V or Vcc according to the digital input. The voltage at the non-inverting input and also at the output voltage Vout of the operational amplifier is: Vout = Where: k n Vcc k Vcc 2n

Value of the digital input word with n bits length Number of Q outputs, maximum length of input word Supply voltage

Signed output is possible by level shifting or by splitting of the power supply (+Vcc/2 and -Vcc/2). With split power supplies the voltage at the output of the operational amplifier is: Vout = Advantages of the R/2R-Method: - 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
k Vcc 1 k Vcc = Vcc n n 2 2 2 2

76

MSP430 Family

Metering Application Report

LSB Ox,P0.a Oy,P0.b MSP430 0V 2R Vcc Vss R Clock Data QA 2R

Shift Register

MSB

To Length Expansion QB 2R R QC . 2R R QH 2R + Vout DAC Output to System 0 to Vcc

+5V

0V

Figure 36.1: R/2R 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 if the performance of the DAC may be low. The example shown in figure 36.2 delivers 2n+1 different output voltage steps. They may be seen as signed if the voltage Vcc/2 is seen as a zero point. The output voltage Vout of this DAC is:
Vout = Vninv In R = Vcc 1 + (a 2 1 + b 2 2 + c 2 3 + ...+ x 2 (n +1) ) 2

where:

Vout Vninv Vcc R a...x

Output voltage of the DAC Voltage at the non inverting input of the operational amplifier (Vcc/2) Supply voltage of the MSP430 and periphery Normalized resistor used with the DAC Multiplication factors for the weighted resistors R to 2n R: +1 if port is switched to Vss 0 if port is switched to input direction (HI-Z) -1 if port is switched to Vcc

Normally all of the ports are switched to the same potential (Vss or Vcc) or are disabled. This allows signed output voltages referenced to Vcc/2. Advantage of the Weighted Resistor-Method: Simplicity Disadvantage: Monotony not possible due to resistor tolerances

77

Metering Application Report

MSP430 Family

Vcc R 2R 4R n 2 R R/2 Rp 0V Vcc Vss Rp


Vcc/2

P0.a P0.b P0.c P0.x MSP430

+ Vout DAC Output to System 0 to Vcc

+5V

0V

Figure 36.2: Weighted Resistors Method for Digital-to-Analog Conversion 3.6.3 Digital-to-Analog Converters connected via the I2C Bus The figure below shows two different DACs which are connected to the MSP430 via the I2C-Bus: A single output 8-bit Digital-to-Analog Converter (with additional 4 ADC inputs): one analog output AOUT is provided. An octuple 6-bit DAC: eight analog outputs DAC0 to DAC7 are provided for the system

The generic software to handle these devices is contained in the section explaining the I2C-Bus.
+5V

Rp

Rp

TP.x,P0.a

SCL

P0.b MSP430 SCL SDA ADC from system 3 Vcc Vss AINx Ax AGND AOUT +5V 0V Vdd +5V Vss 0V to system Vp +5V Vss 0V 4 0V 3 Vmax Ax DACx SCL SDA DAC

SDA

max. DAC output voltage 8 Outputs to system

Figure 36.3: I2C-Bus for Digital-to-Analog Converter Connection 3.6.4 PWM-Digital-to-Analog Converter with the Universal Timer/Port Module The two timers contained in the Universal Timer/Port Module may be used for one or two independent PWM generators. The ACLK frequency is used for the timing of these PWMs. The Basic Timer defines the period of the PWM signals; its interrupt handler sets the programmed outputs and loads the two timer registers TPCNT2 and TPCNT1 with the negated pulse length

78

MSP430 Family

Metering Application Report

(values see table below). The Universal Timer/Port Module terminates the pulses; its interrupt handler resets the outputs when the counters TPCNTx overflow from 0FFh to 00h. The length of one step is always 1/ACLK which is 30.51758s if a 32.768kHz crystal is used. The next table shows the necessary Basic Timer frequency dependent on the used PWM resolution. Table 36.1: Resolution of the PWM-DAC Resolution Bits Resolution Basic Timer Steps Frequency 8 256 128 7 128 256 6 64 512 5 32 1024 The table below shows the values to be written into the timer registers TPCNT1 or TPCNT2 to get a certain PWM output value (related to Vcc): it is the wished value subtracted from the resolution value. The PWM Switch (a RAM byte) defines if the output is enabled (1) or disabled (0). Table 36.2: Register Values for the PWM-DAC TPCNTx TPCNTx TPCNTx TPCNTx Value Value Value Value 256 Steps 128 Steps 64 Steps 32 Steps x x x x C0h E0h F0h F8h 80h C0h E0h F0h 40h A0h D0h E8h 00h 80h C0h E0h

PWM Output (relative to Vcc) 0 0.25 0.50 0.75 1.00

PWM Switch 0 1 1 1 1

NOTE The interrupt latency time plays an important role for this kind of PWMgeneration. Real time programming is necessary therefore: the first instruction of each interrupt handler must be the EINT instruction. EXAMPLE: Two PWM outputs with 8 bit resolution are realized. To get the highest speed TP.2 and TP.1 are used as outputs (they have the same bit addresses like the interrupt flags RC2FG and RC1FG). The schematic is shown in figure 36.4. The output ripple is shown in an exaggerated manner. If the PWM information is needed (as for DMC) then the signal at TP.x is used directly.

79

Metering Application Report

MSP430 Family

TUT PWM output TP.x PWM output TP.1 DC output 1/fBT T x fBT x Vcc UT MSP430 0V DC output TP.2 + Buffered DC output

Vcc

Vss

0V PWM output

+5V

0V

Figure 36.4: PWM for Digital-to-Analog Converter Figure 36.5 illustrates the counting of the 8-bit counter during the PWM generation. The interrupt handler of the Basic Timer sets the 8-bit counter to the negative number of counts (-n1) and sets the output to high; the interrupt handler of the Universal Timer/Port resets the output to zero when it overflows.

TPCNTx 0FFh -n1

1/128Hz

f TCNTx = 32768 Hz 256 Steps Resolution 128 Hz Repetition Rate

0h No PWM Free Run

t1 td

t1

t1

t1 = n1/ACLK
td: Interrupt Latency and SW execution time

Output

Basic T. starts PWM

RCxFG

Basic T.

RCxFG

Basic T.

RCxFG

Interrupts generated

Figure 36.5: PWM-Timing by Universal Timer/Port Module and Basic Timer ; MSP430 Software for 8 bit PWM with Universal/Timer Port ; Definitions of the MSP430 hardware ; Type .equ 310 ; 310: MSP43C31x 0: others BTCTL .equ 040h ; Basic Timer: Control Reg. BTCNT1 .equ 046h ;..............Counter BTCNT2 .equ 047h ; Counter BTIE .equ 080h ; : Intrpt Enable SSEL .equ 080h ; DIV .equ 020h ; BTCTL: xCLK/256 IP2 .equ 004h ; BTCTL: Clock Divider2 IP1 .equ 002h ; IP0 .equ 001h ; Clock Divider0 ; SCFQCTL .equ 052h ; FLL Control Register MOD .equ 080h ; Modulation Bit: 1 = off

80

MSP430 Family ; CPUoff GIE ; TPCTL TPCNT1 TPCNT2 TPD TPE TP1 TP2 TP3 TP4 TP5 ; TPIE TPIE IE2 TPSSEL3 TPSSEL2 TPSSEL1 TPSSEL0 ENB ENA EN1 RC2FG RC1FG EN1FG B16

Metering Application Report

.equ .equ .equ .equ .equ .equ .equ .equ .equ .equ .equ .equ .if .equ .else .equ .endif .equ .equ .equ .equ .equ .equ .equ .equ .equ .equ .equ .equ

010h 008h 04Bh 04Ch 04Dh 04Eh 04Fh 002h 004h 008h 010h 020h

; SR: CPU off bit ; SR: General Intrpt enable ; Timer Port: ; ; ; ; ; Bit address ; ; ; Control Reg. Counter Reg.Lo Counter Reg.Hi Data Reg. Enable Reg. TP.1 TP.2 TP.3 TP.4 TP.5

Type=310 ; MSP430C31x? 004h ; ADC: Intrpt Enable Bit 008h 001h 080h 040h 080h 040h 020h 010h 008h 004h 002h 001h 080h ; MSP430C32x configuration ; Intrpt Enable Byte ; ; ; ; ; ; ; ; ; ; Selects clock input (TPCTL) Selects clock gate (TPCTL) Gate for TPCNTx (TPCTL) Carry of HI counter (TPCTL) Carry of LO counter (TPCTL) End of Conversion Flag " Use 16-bit counter (TPD)

; RAM Definitions ; SW_PWM .equ 0200h ; Enable bits for TP.2 and TP.1 TIM_PWM1 .equ 0201h ; Calc. PWM result PWM1 TIM_PWM2 .equ 0202h ; Calc. PWM result PWM2 ; ;========================================================= ; .sect "INIT",0F000h ; Initialization Section ; INIT MOV #0300h,SP ; Initialize Stack Pointer MOV.B #IP2+IP1+IP0,&BTCTL ; Basic Timer 128Hz ; MOV.B #TPSSEL0+ENA,&TPCTL ; ACLK, EN1=1, TPCNT1 CLR.B &TPCNT1 ; Clear PWM regs CLR.B &TPCNT2 CLR.B &TPD ; Output Data = Low MOV.B #TPSSEL2+TP2+TP1,&TPE ; TPCNT2: ACLK BIS.B #TPIE+BTIE,&IE2 ; INTRPTS on CLR.B SW_PWM ; No PWM output 81

Metering Application Report BIC.B EINT ... #RC2FG+RC1FG,&TPCTL ; Reset flags

MSP430 Family

; Continue with SW ; ; Start both PWMs: calculation results in R6 and R5 ; MOV.B R6,TIM_PWM1 ; (256 - result1) MOV.B R5,TIM_PWM2 ; (256 - result2) BIS.B #TP2+TP1,SW_PWM ; Enable PWM2 and PWM1 ... ; Continue ; ; Disable PWM2: Output zero ; BIC.B #TP2,SW_PWM ; Disable PWM2 ... ; ; Interrupt Handler for the Basic Timer Interrupt: 128Hz ; BT_INT BIC.B #RC2FG+RC1FG,&TPCTL ; Clear flags MOV.B TIM_PWM2,&TPCNT2 ; (256 - time2) MOV.B TIM_PWM1,&TPCNT1 ; (256 - time1) BIS.B SW_PWM,&TPD ; Switch on enabled PWMs RETI ; ; End of Basic Timer Handler ;---------------------------------------------------------; Interrupt Handler for the Universal Timer/Port Module ; For max. speed TP.2 and TP.1 are used (same bit locations ; as RC2FG and RC1FG). 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+RC1FG,0(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",0FFE2h .WORD BT_INT ; Basic Timer Vector .if Type=310 .sect "INT_VEC1",0FFEAh ; MSP430C31x .else .sect "INT_VEC1",0FFE8h ; Others .endif .WORD UT_HNDL ; UTP Vector (31x) .sect "INT_VEC2",0FFFEh .WORD INIT ; Reset Vector EXAMPLE: Two PWM outputs with 7 bit resolution are realized. TP.4 and TP.3 are used as PWM outputs (this makes shifting necessary). The schematic is shown in figure 36.6. Due to the inverting

82

MSP430 Family

Metering Application Report

filters at the PWM outputs the outputs at the MSP430 are also inverted to compensate this. The output ripple is shown in an exaggerated manner. If the PWM information is needed (as for DMC) then the signal at TP.x is used directly.
TUT Filter TP.x PWM output TP.3 + MSP430 0.5Vcc 0V DC output 1/fBT TUT x fBT x Vcc DC output

TP.4

DC output +

Vcc

Vss

0V

0.5Vcc PWM output

+5V

0V

Figure 36.6: PWM for Digital-to-Analog Converter Figure 36.7 illustrates the counting of the 8-bit counter during the PWM generation. The interrupt handler of the Basic Timer sets the 8-bit counter to the negative number of counts (-n1) and sets the output to high; the interrupt handler of the Universal Timer/Port resets the output to zero when it overflows.

TPCNTx 0FFh -n1

1/256Hz

f TCNTx = 32768 Hz 128 Steps Resolution 256 Hz Repetition Rate


0h

t1
Output

t1

t1 = n1/ACLK td: Interrupt Latency and SW execution time Interrupts

td

Basic T.

RCxFG

Basic T.

RCxFG

Figure 36.7: 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 ; .sect "INIT",0F000h ; Initialization Section ; INIT MOV #0300h,SP ; Initialize SP MOV.B #IP2+IP1,&BTCTL ; Basic Timer 256Hz ; MOV.B #TPSSEL0+ENA,&TPCTL ; ACLK, EN1=1, TPCNT1 CLR.B &TPCNT1 ; Clear PWM regs CLR.B &TPCNT2 BIS.B #TP4+TP3,&TPD ; Output Data = high 83

Metering Application Report

MSP430 Family

MOV.B #TPSSEL2+TP2+TP1,&TPE ; TPCNT2: ACLK BIS.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 ; MOV.B R6,TIM_PWM1 ; (128 - result) BIS.B #TP3,SW_PWM ; Enable PWM1 MOV.B R5,TIM_PWM2 ; (128 - result) BIS.B #TP4,SW_PWM ; Enable PWM2 ; ... ; Disable PWMs: Output is zero ; BIC.B #TP4+TP3,SW_PWM ; No output ; ; Interrupt Handler for the Basic Timer Interrupt: 256Hz ; The enabled PWMs are switched on ; BT_INT BIC.B #RC2FG+RC1FG,&TPCTL ; Clear flags MOV.B TIM_PWM2,&TPCNT2 ; (128 - time2) MOV.B TIM_PWM1,&TPCNT1 ; (128 - time1) 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 R6 ; Save R6 MOV.B &TPCTL,R6 ; INTRPT from where? AND #RC2FG+RC1FG,R6 ; Isolate flags BIC.B R6,&TPCTL ; Clear set flag(s) RLA R6 ; To TP.4/TP.3 RLA R6 BIS.B R6,&TPD ; Set actual I/O(s) POP R6 ; Restore R6 RETI ; ; End of Universal Timer/Port Module Handler ;---------------------------------------------------------; Vectors like with the example before 3.6.5 PWM-Digital-to-Analog Converter with the Timer_A The 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 PWM modes. The PWM generation depends mainly on the used mode of the Timer_A: Continuous Mode: the Timer Register runs continuously upwards and continues at zero after the value 0FFFFh. The Capture/Compare Register 0 is used like the other

84

MSP430 Family

Metering Application Report

Capture/Compare Registers. This mode allows up to five independent timings. The Continuous Mode is not intended for PWM applications but it may be used for relatively slow PWM applications if other timings are needed too: 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, reset). 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 has reached this value. Capture/Compare Register 0 contains the period information for all other Capture/Compare Registers. 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 has reached 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 for Timer_A. The same output filters may be used like shown in the previous section if DC output is needed, the only difference is the high, possible speed of the Timer_A (input frequency up to MCLK). 3.6.5.1 PWM-DAC with Timer_A running in Continuous Mode Up to five completely different PWM generations 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 a.s.o.) and interrupt is requested. Figure 36.8 illustrates the generation of a PWM signals with the Capture/Compare Registers 0. The interrupt handler is responsible for the following tasks: The time difference (represented by the clock count nx) to the next interrupt is added to the used Capture/Compare Register by software: once t0, once t1 The Output Unit is programmed to the appropriate mode: set TA0 if t1 is added, reset TA0 if t0 is added. 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.

85

Metering Application Report

MSP430 Family

0FFFFh

n1 n0 0h

Interrupt Events: Example EQU0

t0

t1

EQU0 Interrupts Add t0 to CCR0 Set Output Unit to "Reset" Add t1 to CCR0 Set Output Unit to "Set"

Figure 36.8: PWM Generation with Continuous Mode 3.6.5.2 PWM-DAC with Timer_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 a.s.o.) and interrupt is requested. During the execution of the interrupt handler the necessary software task is completed; no re-loading 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 36.9 illustrates the generation of two independent PWM signals with the Capture/Compare Registers 1 and 2.
0FFFFh

CCR0

CCR1

CCR2 0h TA1 Output (CCR1): Output Mode 2: PWM Toggle/Reset or Output Mode 3: PWM Set/Reset TA2 Output (CCR2): Output Mode 6: PWM Toggle/Set or Output Mode 7: PWM Reset/Set EQU2 EQU0 EQU1 EQU0 EQU2 EQU1 EQU0 EQU2 Interrupts generated

Figure 36.9: PWM Generation with Up Mode 3.6.5.3 PWM-DAC with Timer_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 a.s.o.) and interrupt is requested. During the interrupt handler the necessary software task is completed; no re-loading 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

86

MSP430 Family

Metering Application Report

is made by the Output Unit and interrupt is requested again. When reaching zero, 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 36.10 illustrates the generation of two independent PWM signals with the Capture/Compare Registers 1 and 3.
0FFFFh CCR0 CCR1

CCR3

0h TA3 Output (CCR3): Output Mode 6: PWM Toggle/Set or Output Mode 4: Toggle TA1 Output (CCR1): Output Mode 6: PWM Toggle/Set or Output Mode 4: PWM Toggle TIMOV EQU3 EQU0 EQU3 EQU3 TIMOV EQU3 EQU0 EQU1 EQU1 EQU1 EQU1 Interrupts generated

Figure 36.10: PWM Generation with Up-Down Mode

87

Metering Application Report 3.7 Connection of large external Memories

MSP430 Family

For a lot of MSP430 application it is necessary to have the possibility to store large amounts of measured data. For this purpose external memories may be used: Dynamic RAMs like the TMS44460 (1M 4 bit) Synchronous Dynamic RAMs like the TMS626402 (2M 4 bit) Flash memories like the TMS28F512A (512K 8-bit) EEPROMs

DRAM versions with self-refresh feature are recommended, otherwise the necessary refresh cycles would waste to much of the processing time. Figure 37.1 shows the most simple way: the unused LCD segment lines are used for the addressing and the control of the external memory. Four bi-directional I/O lines of the port 0 (or another available port) are used for the exchange of data in both directions. The necessary steps to read from or to write to the shown DRAM TMS44460 memory are: 1. 2. 3. 4. 5. 6. Output row address to address lines A9 to A0 Set low RAS control line Output column address to address lines A9 to A0 Set low CAS control lines and reset it back to high If a read is wished: set low OE and high W control lines and read data from DQ4 to DQ1 If a write is wished: let OE high, set low W and write information to DQ4 to DQ1

The proposal shown in figure 37.1 needs approximately 200 MCLK cycles for each block of 4-bit nibbles if O-output lines are used.
Control

TP.x/Ox TP.x/Ox TP.x/Ox TP.x/Ox MSP430 O12..O21 10 4 P0.z

OE W CAS4..1 RAS TMS44460

Address

A9..0

Data

DQ4..1

Figure 37.1: External Memory Control with MSP430 Ports EXAMPLE: For the circuit shown in figure 37.1 the 10 address lines of an external memory are connected to the O-outputs O12 (LSB) to O21 (MSB). The subroutine O_HNDLR is used for the row and for the column addressing. The driver software and the subroutine call follows: N O_STRT ; .EQU .EQU MOV CALL ... MOV 10/2 037h ; 10 O-outputs are controlled (O13 to O4) ; Control byte for O12 and O13 (1st byte) ; Start with row addressing ; Output @RAS signal ; Column address in R9

#03FFh,R5 #O_HNDLR R9,R5

88

MSP430 Family CALL ... #O_HNDLR

Metering Application Report ; Output column address ; Output @CAS signals

; ; Subroutine outputs address info in R5 to O-outputs ; Bit 0 is written to the MSB of the O-outputs. R5 is destroyed ; Execution time: 69 cycles for 8 O-outputs (including CALL) ; 129 cycles for 16 O-outputs (like above) ; O_HNDLR CLR R6 ; Clear counter O_HN MOV R5,R4 ; Copy actual info AND #3,R4 ; Isolate next two address bits MOV.B TAB(R4),O_STRT(R6) ; Write address bits RRA R5 ; Prepare next two address bits RRA R5 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 0,0Fh,0F0h,0FFh ; Patterns 00, 01, 10, 11 Figure 37.2 shows a way if the LCD segment lines are not available: two 8-bit shift registers are used for the addressing and the control of the external memory. Four bi-directional I/O lines of the port 0 (or another available port) are used for the exchange of data in both directions. Instead of outputting the address and control signals in parallel, with this solution the signals are output in series. The output enable signals G2 and G1 are used to omit wrong signals due to the shifting of the information. The proposal shown in figure 37.2 needs approximately 500 cycles for each block of 4-bit nibbles.

COM SEL TP.x/Ox TP.x/Ox TP.x/Ox TP.x/Ox Error

xx299

ms

h Control S1 S0 G2..1 CLK SR S1 QH F E D C B..A OE W CAS4..1 RAS A9..8

MSP430
TP.x/Ox 4 P0.z Serial Data In S0 G2..1 CLK SR Data H..A

TMS44460
Address A7..0 DQ4..1

Figure 37.2: External Memory Control with Shift Registers With nearly the same two hardware solutions other external memories can be controlled too: Synchronous Dynamic RAM (TMS626402 2M 4 bit): 12 address lines and 6 control lines. Row and column addressing is used. Four data bits.

89

Metering Application Report

MSP430 Family

Flash memory (TMS28F512A 512K 8-bit): 16 address lines and 3 control lines. Direct addressing is used. Eight data bits.

Any combination of unused outputs (port, TP.x, Oy) and shift registers may 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. The MSP430C33x versions allow a much simpler and faster solution due to the five available I/O ports. Figure 37.3 illustrates the connection of an EEPROM AT29LV010A (128K 8) to the MSP430C33x. The proposal shown in figure 37.3 needs approximately 30 to 50 MCLK cycles for each byte read or written. The control lines at the MSP430 are I/Os with no second function: all peripheral functions are available; they may be changed freely. The MSP30C31x and 32x can address this type of memory by its TP.x and Ox ports.

COM SEL

Error

xx299

ms

P3.0 P3.1 P4.1 P4.0 MSP430C33x P0 P2 P1

Control

OE WE CE A16

8 8 8

Address Address Data

AT29LV010A A15..A7 A7..A0 I/O7 ..I/O0

Figure 37.3: EEPROM Control with direct Addressing by I/O-Ports

90

MSP430 Family 3.8 Power Supplies for MSP430 Systems

Metering Application Report

Various different ways to generate the supply voltage(s) for MSP430 systems are shown. Due to the extremely low power consumption of the MSP430 family this is possible with batteries, accumulators, the M-Bus, glass fiber lines and the mains. Every method uses a completely different hardware and is explained in depth. Wherever possible, the formulas necessary for the hardware design are given too. 3.8.1 Battery Driven Systems Due to the extremely low current consumption of the MSP430 family it is possible to run an MSP430 system with a 0.5Ah battery more than 10 years. This opens the door for 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 switch-off the CPU always when its computing power is not needed (e.g. after the calculations are completed). This reduces the current consumption from the anyway low - 400A further down to 1.6A. The figures 38.1 and 38.2 are drawn in a special way that makes it better visible how the battery needs to be connected to the MSP430 to get the highest accuracy out of the analog-to-digital converter. Figure 38.1 illustrates the MSP430C32x with its separated digital and analog supply pins. This allows a very strictly electrical separation of the noise generating digital parts and the noise sensitive analog parts. Figure 38.2 shows the way how to separate best the two parts for the MSP430 family members with common supply pins for the analog and the digital parts of the chip. If the used battery 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 mainly by Cch; the equation includes the small current coming from the battery:

1 IAM Cchmin tmeas Vch Ri


Between two measurements the capacitor Cch needs a time tch to get charged-up to Vcc 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 Vcc is:

tchmin 5 Cchmax Rimax


Where: IAM tmeas Vch 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 [A] [s] [V] []

91

Metering Application Report

MSP430 Family

SVcc Rv Rext Ri A1 Rsens2 Rsens1 A0 P0.x,TP.y I/Os MSP430C323 COM SEL


Error ms h

AVss AVcc

DVss

DVcc

Ca To other analog parts 0V AGND

Cd

To other digital parts

+3V Cch

Figure 38.1: Battery Driven MSP430C32x-System

Rref TPD.0 Rsens1 TPD.1 Rsens2 MSP430C31x TPD.2 CIN C To other system parts 0V AGND Cch Vss Vcc To other system parts +3V P0.x,TP.y I/Os COM SEL
Error ms h

Figure 38.2: Battery Driven MSP430C31x System NOTE The way the battery is connected to the MSP430 shown in figures 38.1 and 38.2 is not restricted to battery driven MSP430-systems: the shown decoupling of the analog and the digital parts is necessary for all methods of supply. The following schematics are only drawn in a simpler way to give better readability. 3.8.2 Accumulator Driven Systems The MSP430 may be supplied also from an accumulator. An advantage of this solution is that the MSP430 can take over also the battery management for the accumulator: 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 used accumulator type (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 MSP430s internal Current Source - that flows through the resistor Rc. This method allows signed current measurements

92

MSP430 Family

Metering Application Report

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. The MSP430s Current Source is used: the voltage drop of its current Ics across the sensor resistance is measured with the ADC input A2. Voltage Measurement: the voltage of an accumulator pack is an indication for the states full charge and complete discharge. Therefore the voltage of the pack is measured with the voltage divider consisting of R1 and R2. 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 can be made also in PWM (Pulse Width Modulation) mode. Figure 38.3 shows three possible charge modes in the right, lower corner. If replaceable accumulators are used, the charge control is not needed. Rest Mode Handling: During periods the MSP430 system is not used, the Low Power Mode 3 of the MSP430 allows the control of the rest mode with nearly no current consumption (in fact the supply current has the same magnitude as the self-discharge current of the accumulator). All system peripherals are switched off; the MSP430 wakesup in regular intervals - controlled by its Basic Timer - and calculates every few hours the amount of self discharge of the accumulator. This calculated value is subtracted from the actual charge level. Figure 38.3 illustrates an MSP430-system driven by an accumulator. The complete battery management is made by the MSP430 too. The necessary, simple hardware - a few resistors and a temperature sensor - are shown. 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 of the actual charge are contained in an external EEPROM with typically 128 8 bits. NOTE The hardware shown in figure 38.3 may be used also for an intelligent accumulator controller: only the hardware necessary for this task is used then. The measurement parts for voltage, current and temperature are exactly the same as shown.

93

Metering Application Report

MSP430 Family

COM SEL From System P0.x SVcc Keyboard P0.y Ri Vcc RCV TXD P0.1 P0.2 A2 R1 Clk EEPROM Data P0.3 P0.4 MSP430C32x TP.0 Vss VTP.0 A1 A0
Voltage Current Temperature Empty

Error

ms h Full

Ics Rext

To System +5V

Voltage Regul.

To Charger

Ics Accus

Rc

Ics R2 Shunt

0V

Full Charge

PWM Charge

Trickle Mode

Time

Figure 38.3: Accumulator driven MSP430-System with Battery Management 3.8.3 Mains Driven Systems The current consumption of microcomputer systems gets more and more important also for mains driven systems: the lower the power consumption of a microcomputer system the simpler and cheaper the power supply can be. 3.8.3.1 Transformer Power Supplies Transformers have two big advantages: Complete isolation from the mains: an important security attribute for most systems Very good adaptation to the needed supply voltage and resulting from this a good power efficiency Most mains driven applications are possible only due to the isolation from the mains a transformer provides. 3.8.3.1.1 Half-Wave Rectification Half-wave rectification uses only one half-wave of the transformers secondary voltage Vsec for the powering of the application. Figure 38.4 illustrates the voltages used with the equations.

94

MSP430 Family

Metering Application Report

Vch Vch Vsec x 2 = Vchmax Vcc

tdis T

Figure 38.4: Voltages and Timing for the Half Wave Rectification Advantages: Disadvantages: Simple hardware Rectification with the voltage drop of only one diode Charge capacitor Cch must have doubled capacity compared to full-wave rectification Higher ripple on the DC supply voltage DC flows through the transformers secondary winding

Figure 38.5 shows the most simple mains driven power supply: the positive half-wave of the transformers secondary side charges the load capacitor Cch. The capacitors 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:
Vsecm in 2 Vch > Vz

and: T Vsecmin 2 Vch Vz < Rv < 2 Cchmin IAMmax The charge capacitor Cch must have a minimum capacity: Cchmin T 1 IAM + 2 Rv Vsecmin 2 Vz

The peak-to-peak ripple voltage Vnpp of the supply voltage Vcc is:
Vcc | | Rz IAM Vch Vcc Rv + | | Rz IAM

Vn pp

The final necessary secondary voltage Vsec of the mains transformer is (Vch = 0.1Vchmax): 1 0.45 T IAM + Vz 2 Cchmin 0.45 T Rv

Vsecmin Where:

95

Metering Application Report IAM T Vch Vcc Vz Rz Rv Vsec

MSP430 Family

Medium system current (MSP430 and peripherals) [A] Period of the mains frequency [s] Discharge of Cch during time tdis [V] Supply voltage of the MSP430 system [V] Voltage of the Zener diode [V] Differential resistance of the Zener diode [V/A] Resistance of the series resistor [] Secondary (effective) voltage of the transformer (full load conditions) [V]
Non-regulated voltage Rv VC +5V IAM Mains Vsec Cch Dz Vss MSP430 To peripherals

Vcc

0V

Figure 38.5: Half Wave-Rectification for one Voltage with a Zener Diode Figure 38.6 shows a simple power supply that uses a voltage regulator like the uA78L05. The charge capacitor Cch must have a minimum capacity:

Cchmin

IAM tdis Vch

The peak-to-peak ripple Vnpp 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 mains transformer under full load conditions is:

Vsecmin

I Vreg + Vr + Vd + tdis AM Cchmin 2

The discharge time tdis used with the above equations is:

tdis

Vch arcos 1 Vsec 2 = T 1 2

Where: tdis Vd Vr Vreg

Discharge time of Cch [s] Voltage drop of one rectifier diode [V] Dropout voltage (voltage difference between output and input) of the voltage regulator for function [V] Nominal output voltage of the voltage regulator [V]

For first estimations the value of tdis is calculated for two different discharge values: 10% discharge of Cch during tdis tdis = 0.93T

96

MSP430 Family 30% discharge of Cch during tdis


Non-regulated voltage VC Vreg +5V +5V IAM Mains Vsec Cch 0V

Metering Application Report tdis = 0.88T


To peripherals

Vcc

MSP430 Vss

Figure 38.6: Half-Wave Rectification for one Voltage with a Voltage Regulator Figure 38.7 shows an MSP430 system that uses two supply voltages: +5V and -5V. The negative supply voltage is used for analog interfaces. Simple resistor dividers interface the 10V analog part into the 5V 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 38.6. The same circuitry may be used for a system with +2.5V and -2.5V (see figure 38.13 for details).

Non-regulated voltage Vreg +5V IAM


+5V

To peripherals +5V Vcc R A1 R 0V Vss MSP430

Mains

Vsec

Cch

A1:

+2.5V 0V

+5V + Cch -5V -5V


+5V 0V -5V

-5V To system

Non-regulated voltage

Input

Figure 38.7: Half-Wave Rectification for two Voltages with Voltage Regulators 3.8.3.1.2 Full-Wave Rectification Full-wave rectification uses both half-waves of the secondary voltage Vsec for the powering of the application.
Vch Vch Vsec x 2 = Vchmax Vcc

tdis T

Figure 38.8: Voltages and Timing for the Full Wave Rectification

97

Metering Application Report Advantages: Smaller charge capacitor Cch Lower ripple voltage No DC current through transformers secondary winding

MSP430 Family

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)

Figure 38.9 shows a simple power supply that uses a A78L05 voltage regulator. The charge capacitor Cch must have a minimum capacity: C ch m in IAM tdis

Vch

The peak-to-peak ripple Vnpp on the voltage Vcc depends on the used voltage regulator. The ripple rejection value can be seen in its specification. The necessary secondary voltage Vsec of the mains transformer is for the upper rectifier with four diodes (full load conditions):
Vsecmin I 1 Vreg + Vr + 2 Vd + tdis AM 2 Cchmin

For the center tap transformer, Vd in the above equation is multiplied by one (1 Vd). The discharge time tdis used with the above equations is:

tdis

Vch arcos 1 Vsec 2 0.5 = T 2

For first estimations the value of tdis is calculated for two different discharge values: 10% discharge of Cch during tdis 30% discharge of Cch during tdis tdis = 0.43T tdis = 0.38T

Mains

Vsec

Non-regulated voltage Cch 0V Non-regulated voltage Vreg +5V +5V IAM Cch 0V

To peripherals

Vcc

Vsec Mains

MSP430 Vss

Figure 38.9: Full Wave Rectification for one Voltage with a Voltage Regulator Figure 38.10 shows an MSP430 system that uses two supply voltages: +2.5V and -2.5V. The formulas for the calculation of the charge capacitor Cch and the necessary secondary voltage Vsec

98

MSP430 Family

Metering Application Report

are the same as given for the circuitry in figure 38.9. The circuitry of figure 38.10 may be used also for a system with +5V and -5V supply (see figure 38.7 for details). It is also shown how to connect a TRIAC that is used for the control of an AC motor. The needed relatively high gate current 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 zero volt (measured at A0) is subtracted from the current ADC value and results in a signed, offset corrected value. If a single supply voltage is used (+5V only) then the Current Source can be used to shift the signed current information into the range of the ADC. See also figure 38.3: circuit for the current measurement.
Non-regulated voltage To peripherals Vsec Mains +2.5V IAM Cch
+2.5V

A.C. Mains +2.5V

Vreg

Vcc

M
A1:
0V -2.5V

+2.5V 0V + Cch -2.5V -

A0 MSP430 A1 Vss

-2.5V

TP.0 0V
Current Measurement

Non-regulated v.

Figure 38.10: Full-Wave Rectification for two Voltages with Voltage Regulators 3.8.3.2 Capacitor Power Supplies Applications that do not need isolation from the mains or that have a defined connection to the mains (like electricity meters) can use capacitor power supplies: the costly transformer is not needed; only the series capacitor Cm must have a high voltage rating due to the voltage spikes possible on the mains voltage. The AC-resistance of the series capacitor Cm 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 Cm. This protection resistor Rm is necessary to limit the current spikes due to voltage spikes and high frequency parts overlaid to the mains voltage. The current Imains through the circuitry is:
Imains Vmains Cm Rm
AC DC

IAM Vc

Imains =

Vmains 1 + Rm j Cm

Vmains 1 + Rm 2 2 2 Cm

Where: Vmains fmains Cm

Voltage of the mains Nominal frequency of the mains Circle frequency of the mains: = 2f Series capacitor

[V] [Hz] [1/s] [F]

99

Metering Application Report Rm Series resistor []

MSP430 Family

The above formula for Imains is valid for all shown capacitor power supplies. The formula assumes low voltages to be generated (< 5% of the mains voltage). For a DC-current IAM the necessary mains current Imains is: Imains IAM = IAM 2.221 2 The capacitor Cm is: 1 1 Cmmin 2 fmainsmin 2 Vmainsmin 2 2 Rmmax IAM This formula for Cm is valid for all shown capacitor supplies. The calculated value for Cm includes the tolerances for the mains voltage and the mains frequency; the minimum values used for Vmains and fmains ensure this. The protection resistor Rm for a maximum spike current Imax generated by a voltage spike Vspike is: Vspike Rm Imax The charge capacitor Cch must have a minimum capacity: Cchmin Advantages: Disadvantages: No transformer necessary Very simple hardware No isolation from mains IAM T 2 Vch

3.8.3.2.1 Capacitor Supplies for a Single Voltage Figure 38.11 shows the most simple form of a capacitor power supply; the Zener diode used for the limiting of the voltage of the charge capacitor Cch is used for the voltage regulation too. The peakto-peak ripple voltage Vnpp on the voltage Vcc is:
Vnpp IAM T Cch 2

The voltage of the Zener diode Dz is:

Vz Vcc + Vd
Cch is calculated like shown in section 3.8.3.2

100

MSP430 Family

Metering Application Report

To peripherals Cm VC Rm Mains
Vz=5.6V

+5V Vcc IAM MSP430 Vss

Cch Dz 0V

Figure 38.11: Simple Capacitor Power Supply for a Single Voltage Figure 38.12 shows a hardware proposal for a regulated output voltage Vcc. The voltage Vz of the Zener diode Dz must be:

Vz Vd + Vreg + Vr + T
Cch is calculated like shown in section 3.8.3.2

IAM 2 Cchmin

Cm VC Rm Mains Dz 0V Vss Cch +5V 5V IAM Vcc

To peripherals

MSP430

Figure 38.12: Capacitor Power Supply for a Single Voltage 3.8.3.2.2 Capacitor Supplies for two Voltages Applications that need two voltages (e.g. +2.5V and -2.5V) can also use a capacitor supply. Figure 38.13 shows a split power supply with two regulated output voltages; together they deliver the supply voltage Vcc. The split power supply allows to measure the voltage of the zero volt line at A0: this measured value can be subtracted from all other measured analog inputs which results in offset corrected, signed values. The voltage Vz of each one of the two Zener diodes Dz must be: IAM Vz Vr + Vreg + T 2 Cchmin The two charge capacitors Cch must have the values:

Cchmin

IAM T Vch 2

101

Metering Application Report

MSP430 Family

Cm +VC 2.5V Rm Mains Cch Dz 0V Dz A0 +2.5V IAM

To peripherals Vcc MSP430

-2.5V -VC

-2.5V

Vss To peripherals

Figure 38.13: Split Capacitor Power Supply for two Voltages Figure 38.14 shows a split power supply for +2.5V and -2.5V made in a completely different way. It is capable to deliver relatively large output currents due to the buffer transistors. If the high current capability is not needed then the transistors are omitted and the loads are connected to the outputs of the two operational amplifiers directly. The reference for all voltages is a reference diode LMx85: the highly stable 1.25V of this diode are multiplied by two (for +2.5V) resp. multiplied by -3 and added to the reference value (delivers -2.5V). The voltage drop of each one of the two diodes D is compensated by the series connection of the two Zener diodes Dz. The necessary Zener voltage Vz of the two diodes Dz is:
Vz Vcc IAM + VBE + (Vcc Vom) + T 2 2 Cchmin

Where: VBE Vom

Basis-Emitter voltage of a transistor Max. peak output voltage swing of the operational amplifier with VC

[V] [V]

The two charge capacitors Cch are calculated the same way as shown above for figure 38.13.
Mains Cm Rm -VC D Dz Cch Dz LMx85 R R 0V + -VC To peripherals R 0V 2R -2.5V Vss A0 D +VC + Cch +2.5V Vcc MSP430 To peripherals

0V

Figure 38.14: Split Capacitor Power Supply for two Voltages with discrete Components

102

MSP430 Family 3.8.4 Supply from other System DC-Voltages

Metering Application Report

Existing DC-voltages of the controlled system, like +12V or +24V may be used for the supply of the MSP430-system. This is possible due to the low current consumption of the MSP430: so nearly no power is wasted in the voltage regulator for Vcc. If relays and other power consuming peripherals need to be powered, this can be done with the system DC voltage Vsys (see figure 38.16). This solution has two advantages: 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 38.15 and 16 show four different possibilities to supply an MSP430-system from an existing +12V (or +24V) 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 +3V or +5V. The resistor Rv is: Vsysmin Vz Rvmax < Izmin + IAM Where: Vz Zener voltage of the Zener diode [V] Iz Current through the Zener diode [A] Vsys Nominal system voltage [V] 3.8.4.2 Zener Diode and Operational Amplifier If larger currents or a higher degree of decoupling is necessary, 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 < Vsysmin Vz Izmin

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 buffered too. 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. The output voltage Vout is calculated with: R1 + R2 Vout = Vz R2

103

Metering Application Report

MSP430 Family

Vsys (+12V .. +24V)

Rv

Rv Vsys +5V + 0V +5V


Vz = 1.25V

Rv + LMx85

R1 (3xR) Vsys +5V 0V

Dz

Vz = 5V

Dz

Vz = 5V

R2 (R) 0V

Zener Diode Supply

Zener Diode with Opamp Supply

Reference Diode with Opamp Supply

Figure 38.15: Simple Power Supply from other DC-Voltages

3.8.4.4 Integrated Voltage Regulator Figure 38.16 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 to use the RST/NMI-pin of the MSP430 like described in chapter Battery Check and Power Fail Detection: the RST/NMI-pin is used during the normal program run as an NMI (NonMaskable Interrupt). This gives the possibility to save important data in an external EEPROM in case of power fail. This is possible because the PG-pin outputs a negative signal starting at Vcc = 4.75V which allows a lot of activities until Vccmin of the MSP430 (2.5V) is reached.
Vsys D Rv IN VCb EN Cb GND
10 F

TP73050 +5V OUT SENSE PG

IAM Vcc MSP430 Reset/NMI TP.x Vss Dz


Vz = Vsys+3V

0V

Figure 38.16: 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 a certain bridging of supply voltage dropouts is possible. The diode D protects the capacitor Cb against discharge during the dropout of the voltage Vsys. The series resistor Rv is:
Rvmax <

(Vsysmin Vd Vcc Vr )
IAM + Iregmax

The minimum capacity of Cb is:


Cbmin >

Vsysmin (IAM + Iregmax ) Rvmax Vrmax Vccmin

t (IAM + Ireg )

Where: IAM Ireg Vsys Vd

System current (medium value MSP430 and peripherals) Supply current of the voltage regulator System voltage (e.g. +12V) Diode forward voltage ( < 0.7V)

[A] [A] [V] [V]

104

MSP430 Family Vr Vcc t Dropout voltage of the voltage regulator for function Supply voltage of the complete MSP430 system Dropout time of Vsys to be bridged

Metering Application Report [V] [V] [s]

3.8.5 Supply from the M-Bus If the MSP430 system is connected to the M-Bus then three possibilities exist for the supply of the MSP430: Battery Supply: the supply of the MSP430 is completely independent of the M-Bus. This method is not shown in figure 38.17, because it is the normal way the MSP430 is powered. See chapter Battery driven Systems. M-Bus Supply: the MSP430-system is always supplied by the M-Bus. During off-phases of the M-Bus the MSP430 is not powered. Mixed Supply: normally the M-Bus supplies the MSP430, only during off-phases of the M-Bus the battery of the MSP430 provides the supply 3.8.5.1 M-BUS Supply The MSP430 is powered always from the M-Bus. The power fail signal PF of the TSS721 signals the MSP430 the dropout of the bus voltage. This early warning enables the MSP430 to save important data in an external EEPROM. The capacitor Cch must have a capacity that allows this storage: IMA tstore Cchmin Vdd Vccmin Where: IMA System current (MSP430 and EEPROM) [A] tstore Processing time to store important data into the EEPROM [s] Vdd Supply voltage delivered from the TSS721 [V] Vccmin Minimum supply voltage of the complete MSP430 system [V] 3.8.5.2 Mixed Supply The MSP430 is powered from the M-Bus while the bus voltage is available; during times without bus voltage the battery powers the MSP430. Therefore a smaller battery may be used if the bus is available normally. The MOS-transistor switches on the battery in case of a dropout of the M-Bus voltage. Details are described in the TSS721 M-Bus Transceiver Application Report.

105

Metering Application Report

MSP430 Family

METER BUS Cch 0V 215 Vss Vcc RX TX P0.0 TXI RXI BAT Vdd VS BUSL1

MSP430 EEPROM
CTRL/DATA

TSS721 PF GND STC SC RIS RIDD BUSL2

215

M- BUS Supply 0V Vbat 1N6263 BSS84 0V 215 Vss Vcc P0.0 TX RX PF RXI BAT Vdd VS BUSL1

MSP430

TSS721 TXI GND STC SC RIS RIDD BUSL2

215

Mixed Supply 0V

Figure 38.17: Supply from the M-Bus 3.8.6 Supply via Glass Fiber Cable The MSP430 needs a supply current Icc of only 400A if supplied with a voltage Vcc of 3V and operating with an MCLK of 1MHz. This low energy can be transmitted via a glass fiber cable and allows therefore completely isolated measurement systems not possible with other microcomputers. This transmission mode is a real advantage for the application in strong electric or magnetic fields. Because the data transmitted from the host to the MSP430 is used also for the supply of the MSP430 system, a certain amount of light is needed continuously, independent of the transmitted data. Possibilities to reach this are: Use of extended charge periods between the transmitted data from the host to the MSP430. The MARK-level of the RS232 protocol is used for this purpose. This method is shown in figure 38.18: every logical one, stop bit and MARK-level is used for the supply. Use of a transmission code that transmits always the same amount of ones and zeroes independent of the transmitted data. (e.g. the Bi-Phase-Code)

To achieve a positive current balance a few conditions must be met: The complete hardware design uses ultra-low-power devices (operational amplifiers, reference diode, measurement parts aso.) The MSP430 is in Low Power Mode 3 during all periods where no processing power is necessary The measurement unit is switched on only during the measurement itself All applicable hints given in chapter Ultra-Low-Power Design with the MSP430 are used.

106

MSP430 Family

Metering Application Report

3.8.6.1 Description of the Hardware The host sends approx. 15mW of optical power into the glass fiber cable. This is made with a laser diode consuming 30mW of electrical power. At the other end of the glass fiber cable the optical power is converted into 6mW of electrical power with a power converter diode. The open-circuit voltage of the power converter - approx. 6V - decreases to 5V with the load represented by the MSP430. The received electrical energy is used to charge the capacitor Cch. The needed charge-up time is approx. 300ms for a capacitor with 30F. The uppermost operational amplifier is used for the voltage regulation of the system supply voltage Vcc (+3V to +4V). If a stabilized supply voltage is not necessary, then this operational amplifier may be omitted as well as the diodes and pull-up resistors at the RST/NMI and P0.1 inputs. The reference for the complete system is an LMx85 reference diode. This reference voltage (1.25V) is used for several purposes: trigger threshold for the Schmitt-triggers, reference for the calculation of Vcc 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 the high level when VC reaches approx. +4V. It sets low the RST/NMI input when VC falls below +2.5V. The undermost operational amplifier decodes the information out of the charge voltage and data of the power converters 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 RS-232 protocol to have 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 charge capacitor Cch 2. When this capacitor got enough charge - which means a capacitor voltage VC of approx. 4V is reached - then the reset-Schmitt-trigger switches the RST/NMI input of the 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 (the second glass fiber 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. 6. The items 4 and 5 are repeated as often as wished by the host

107

Metering Application Report

MSP430 Family

MARK SPACE Charge

Data

Data

Charge

+VC 2.4R
Glass Fiber Cable Light From Host PPC-6E-SMA Power Converter

+ Cch R

+3V

SVcc Vcc MSP430 Ax Vss


Analog Data

Meas. Unit P0.x XBUF


32kHZ

0V +VC
Glass Fiber Cable IR-LED 1N229-SMA

Reset

RST/NMI

Control Clock

Vref

To Host

Light

A0 AGND P0.1 (RCV)

LT1078CN
Data

Data

SPACE MARK

P0.2 (TXD)

0V

Figure 38.18: Supply via Glass Fiber Cable 3.8.7 Conclusion The shown concepts for the supplying of the MSP430 family with power demonstrate the numerous ways to do that: due to the extremely low power consumption of the Ultra Low Power Microcomputer Family MSP430 it is possible to supply them with all known power sources. Even glass fiber cables may be used for the powering of MSP430 systems. 4 APPLICATION EXAMPLES _________________________________________________ 112
4.1 Electricity Meters _______________________________________________________________ 113
4.1.1 Overview ___________________________________________________________________________ 4.1.2 The Measurement Principle _____________________________________________________________ 4.1.2.1 The Inherent Error of the Reduced Scan Principle ________________________________________ 4.1.2.2 The Advantages of the Reduced Scan Principle __________________________________________ 4.1.2.3 Measurement Errors for some Sampling Frequencies______________________________________ 4.1.2.4 Measurement Error for Deviations of the Mains Frequency_________________________________ 4.1.2.5 Measurement Error in Dependence of the Interrupt Latency Time____________________________ 4.1.2.6 Measurement Error due to Overvoltage and Overcurrent ___________________________________ 4.1.3 The Analog-to-Digital Converter of the MSP430C32x ________________________________________ 4.1.3.1 Methods to reduce the Error of the Energy Measurement __________________________________ 4.1.3.1.1 Use of a second Hardware Range _________________________________________________ 4.1.3.1.2 Use of a second Calibration Range ________________________________________________ 4.1.3.1.3 Measurement of the Analog-to-Digital Converters Characteristic ________________________ 4.1.3.2 Dependence on the Voltage and the Phase Angle _______________________________________ 4.1.3.3 Derivation of the Measurement Formulas_______________________________________________ 4.1.4 Analog Interfaces to the MSP430_________________________________________________________ 4.1.4.1 Analog and Digital Grounding _______________________________________________________ 4.1.4.2 Analog-to-Digital Converter Input Considerations ________________________________________ 4.1.4.3 Offset Treatment __________________________________________________________________ 4.1.4.4 Adaptation to the Range of the Analog-to-Digital Converter ________________________________ 4.1.4.4.1 Split Power Supply ____________________________________________________________ 4.1.4.4.2 Use of a Virtual Ground IC______________________________________________________ 4.1.4.4.3 Resistor Interface (Software Offset) _______________________________________________ 4.1.4.5 Current Measurement ______________________________________________________________ 4.1.4.5.1 Shunt _______________________________________________________________________ 4.1.4.5.2 Current Transformer ___________________________________________________________ 113 113 115 117 117 118 119 120 120 123 123 123 124 124 125 126 127 127 127 128 128 129 130 131 131 132

108

MSP430 Family

Metering Application Report


133 134 135 135 135 136 136 137 138 139 140 141 142 143 144 145 146 147 149 150 150 150 150 150 151 151 152 153 153 153 153 154 154 154 154 155 155 155 155 156 156 156 157 157 157 158 158 159

4.1.4.5.3 Ferrite Core __________________________________________________________________ 4.1.4.5.4 Compensated Ferrite Core_______________________________________________________ 4.1.4.6 Voltage Measurement ______________________________________________________________ 4.1.4.6.1 Resistor Divider ______________________________________________________________ 4.1.4.6.2 Voltage Transformer ___________________________________________________________ 4.1.5 Single Phase Electricity Meters __________________________________________________________ 4.1.5.1 Current Measurement with a Shunt____________________________________________________ 4.1.5.2 Current Measurement with a Current Transformer ________________________________________ 4.1.5.3 Calculations _____________________________________________________________________ 4.1.6 Dual Phase Electricity Meters____________________________________________________________ 4.1.6.1 Current Measurement with Current Transformers and Virtual Ground IC ______________________ 4.1.6.2 Current Measurement with Current Transformers and Software Offset ________________________ 4.1.6.3 Calculations _____________________________________________________________________ 4.1.7 Three Phase Electricity Meters___________________________________________________________ 4.1.7.1 Current Measurement with Ferrite Cores and Software Offset _______________________________ 4.1.7.2 Current Measurement with Current Transformers and Split Power Supplies ____________________ 4.1.7.3 Calculations _____________________________________________________________________ 4.1.7.4 Timing and Software_______________________________________________________________ ; ________________________________________________________________________________ 4.1.8 Measurement of Voltage, Current, Apparent Power and Reactive Power __________________________ 4.1.8.1 Measurement of Voltage and Current __________________________________________________ 4.1.8.2 Measurement of the Apparent Power __________________________________________________ 4.1.8.3 Measurement of the Reactive Power___________________________________________________ 4.1.8.3.1 Delay of Samples _____________________________________________________________ 4.1.8.3.2 Calculation out of the Apparent Power _____________________________________________ 4.1.9 Calculation of the System Current Consumption _____________________________________________ 4.1.10 System Components __________________________________________________________________ 4.1.10.1 The Microcomputer MSP430 _______________________________________________________ 4.1.10.2 The Liquid Crystal Display_________________________________________________________ 4.1.10.3 The EEPROM___________________________________________________________________ 4.1.10.4 The Range Switches ______________________________________________________________ 4.1.10.5 Power Supplies __________________________________________________________________ 4.1.10.6 The M-Bus Interface TSS721 (Option) _______________________________________________ 4.1.10.7 The Infrared Interface _____________________________________________________________ 4.1.10.8 The Voltage Reference ____________________________________________________________ 4.1.10.9 Peripherals _____________________________________________________________________ 4.1.11 Summary___________________________________________________________________________ 4.1.12 Error Simulation for an MSP430C32x-Based Electricity Meter ________________________________ 4.1.12.1 Abstract________________________________________________________________________ 4.1.12.2 Common Measurement Conditions___________________________________________________ 4.1.12.3 Calibration _____________________________________________________________________ 4.1.12.4 Conditions for the Load Curve ______________________________________________________ 4.1.12.5 Energy Calculation _______________________________________________________________ 4.1.12.5.1 Calculation of the Voltage Sample _______________________________________________ 4.1.12.5.2 Calculation of the Current Samples_______________________________________________ 4.1.12.5.3 Calculation of the Energy Value _________________________________________________ 4.1.12.6 Explanation Figures ______________________________________________________________ 4.1.12.7 Conclusion _____________________________________________________________________

4.2 Gas Meter ______________________________________________________________________ 160 4.3 Water Flow Meter _______________________________________________________________ 162 4.4 Heat Allocation Counter __________________________________________________________ 163 4.5 Heat Volume Counter ____________________________________________________________ 165 4.6 Battery Charge Meter ____________________________________________________________ 167 4.7 Connection of Sensors ___________________________________________________________ 169

109

Metering Application Report

MSP430 Family
169 169 169 170 170 172 173 173 174 174 175 175 177 178 179 180 181 182 183 184 186 186 186 187 189

4.7.1 Sensor Connection and Linearization ______________________________________________________ 4.7.1.1 Voltage Supply __________________________________________________________________ 4.7.1.2 Current Supply___________________________________________________________________ 4.7.1.3 Use of Reference Resistors _________________________________________________________ 4.7.1.4 Connection of Bridge Assemblies ____________________________________________________ 4.7.1.5 Fixing of Bridge Assemblies into one ADC-Range _______________________________________ 4.7.2 Connection of Special Sensors ___________________________________________________________ 4.7.2.1 Gas Sensors______________________________________________________________________ 4.7.2.2 Digital Sensors ___________________________________________________________________ 4.7.2.3 Sensors with Frequency Output ______________________________________________________ 4.7.2.4 Time Measurements _______________________________________________________________ 4.7.2.5 Hall Sensors _____________________________________________________________________ 4.8.1 4.8.2 4.8.3 4.8.4 4.8.5 4.8.6 MSP430 Electricity Meter ______________________________________________________________ MSP430 Electricity Meter with Frontend___________________________________________________ MSP430 Ferraris Wheel Electricity Meter with RF-Readout ____________________________________ RF-Interface Module __________________________________________________________________ Protocol ____________________________________________________________________________ RF-Readout with other Metering Applications_______________________________________________

4.8 RF Readout ____________________________________________________________________ 177

4.9 Ultra-Low-Power-Design with the MSP430-Family ___________________________________ 183


4.9.1 The Ultra-Low-Power-Concept of the MSP430 ______________________________________________ 4.9.2 Current Consumption and Battery Lifetime _________________________________________________ 4.9.3 Minimization of the System Consumption __________________________________________________ 4.9.3.1 Consumption of the MSP430 ________________________________________________________ 4.9.3.2 Self Discharge of the Battery ________________________________________________________ 4.9.3.3 Current Consumption of other System Components _______________________________________ 4.9.4 Correct Termination of unused Pins _______________________________________________________

4.10 Controller for a Heating Installation_______________________________________________ 191 4.11 Digital Motor Control ___________________________________________________________ 193
4.11.1 Introduction ________________________________________________________________________ 4.11.1.1 The MSP430 Family______________________________________________________________ 4.11.1.1.1 The Low Power Modes ________________________________________________________ 4.11.1.2 The 16-Bit Timer_A ______________________________________________________________ 4.11.1.3 The Universal Timer/Port Module ___________________________________________________ 4.11.1.4 The Basic Timer _________________________________________________________________ 4.11.1.5 The Watchdog Timer _____________________________________________________________ 4.11.2 Digital Motor Control with Pulse Width Modulation (PWM) __________________________________ 4.11.2.1. Single Output Stages _____________________________________________________________ 4.11.2.1.1 Single Output Stage with a Bipolar Power Transistor_________________________________ 4.11.2.1.2 Single Output Stage with a MOSFET Power Transistor _______________________________ 4.11.2.2 H-Bridge Output Stages ___________________________________________________________ 4.11.2.2.1 H-Bridges for low Motor Voltages _______________________________________________ 4.11.2.2.1.1 Output Stage with a MOSFET Bridge_________________________________________ 4.11.2.2.1.2 H-Bridge for a Brushless DC Motor __________________________________________ 4.11.2.2.1.3 H-Bridge with integrated Output Stages _______________________________________ 4.11.2.2.2 H-Bridge for high Motor Voltages _______________________________________________ 4.11.2.3 Three Phase Motor Control_________________________________________________________ 4.11.2.4 Low Frequency Pulse Width Modulation ______________________________________________ 4.11.2.5 Bandwidth of the MSP430 Solutions for PWM Control___________________________________ 4.11.3 Digital Motor Control with TRIACs______________________________________________________ 4.11.3.1 Motor Connection and Control ______________________________________________________ 4.11.3.2 TRIAC Control __________________________________________________________________ 4.11.3.3 Control Algorithms _______________________________________________________________ 4.11.3.4 Cost Reduction __________________________________________________________________ 4.11.3.4.1 Non-Regulated Voltage for the TRIAC Control _____________________________________ 4.11.3.4.2 Use without Crystal___________________________________________________________ 193 193 194 194 195 196 196 197 197 197 198 199 199 199 200 202 204 206 208 209 210 210 210 213 213 213 214

110

MSP430 Family

Metering Application Report


214 215 215 215 215 216 216 217 217 217 218

4.11.3.5 Bandwidth of the MSP430 Solutions for TRIAC Control _________________________________ 4.11.4 Motor Measurements _________________________________________________________________ 4.11.4.1 Overcurrent Detection_____________________________________________________________ 4.11.4.1.1 Threshold Detection __________________________________________________________ 4.11.4.1.2 Current Measurement _________________________________________________________ 4.11.4.2 Voltage Measurement _____________________________________________________________ 4.11.4.3 Zero Crossing Detection ___________________________________________________________ 4.11.4.4 Measurement of the Motor Speed ____________________________________________________ 4.11.4.5 Supervision of the Motor Temperature ________________________________________________ 4.11.4.6 Change of the Direction of Rotation __________________________________________________ 4.11.5 Conclusion _________________________________________________________________________

111

Metering Application Report

MSP430 Family

4 APPLICATION EXAMPLES
Several metering examples are given in the next sections. Common for nearly all of them is the storage of calibration data, tables, constants etc. in external EEPROMs. External EEPROMs are used for safety reasons: if the microcomputer fails completely then it is relatively easy to read out the accumulated consumption values. This is normally impossible if these values reside in internal EEPROMs. These EEPROMs can store also tables that describe the principal errors of a given measurement principle 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 next 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. The appertaining table contains 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.
Error %

1%

10%

100% Measured Value %

Figure 40.1: Segmentation of the Measured Value

112

MSP430 Family 4.1 Electricity Meters 4.1.1 Overview

Metering Application Report

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 = U I dt is measured: 1. 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 energy (Ws, kWs, Wh). All family members may be used. 2. The electrical energy is calculated by the MSP430 itself, using its 14-bit analog-to-digital converter (ADC) for the measurement of current and voltage. Only the MSP430C32x can be used. The two different methods are shown in figure 41.1

32kHz

32kHz

SVcc

COM SEL

SVcc
Error kW kWh

COM SEL

LCD

Voltage P0.x Frontend Pulses P0.y MSP430C31x Current Current Peripherals Voltage

A1 P0.x Peripherals MSP430C32x A0

Vss

Vcc

Vss

Vcc

Figure 41.1: Two Measurement Methods for Electronic Electricity Meters Only the second method is used with the electricity meters described in this chapter: the unnecessary front-end gives a cost advantage when compared to the two-chip solution. An example for the 1st method is shown in chapter RF-Readout. 4.1.2 The Measurement Principle The used principle (Reduced Scan Principle) measures current and voltage in regular time intervals and multiplies the current and voltage samples. The multiplication results are summed up: the sum represents the consumed energy (Ws, kWh). While the normally used method measures voltage and current at exactly the same time, the Reduced Scan Principle (a protected TI method) measures voltage and current samples alternating. Every sample is used twice: Once it is multiplied with the 113

Metering Application Report

MSP430 Family

value measured before and once with the value measured afterwards. To reduce further the necessary multiplications these two multiplications are reduced to one by using the sum of the two voltage samples. This measurement principle is shown in figure 41.3. The repetition of the measurement sequence follows. It is shown for a single phase measurement. Every second measurement the same input value is measured (current or voltage). The time represents the angle between appertaining voltage and current samples.

Voltage Current Voltage Current

1/ARR Repetition Time

Time

Figure 41.2: Timing for the Reduced Scan Principle (Single Phase) Where: Repetition Time 1/ARR Inherent Phase Shift of the Measurement Method [rad] Length of a complete Measurement Cycle [s] Time Distance between two ADC-Conversions [s]

NOTE The Reduced Scan Principle is intellectual property of TEXAS INSTRUMENTS. This measurement principle may be used only with the microcomputers produced by TEXAS INSTRUMENTS.

114

MSP430 Family

Metering Application Report

Voltage

Current

Power + +

Sampling Point

Time

Figure 41.3: Reduced Scan Measurement Principle The measured energy W (for a single phase) is:
W = 0.5 in (un 1 + u n + 1 ) t
t=0 t =

Where: W in un-1 un+1 t

Accumulated energy [Ws] Current sample at time tn [A] Voltage sample at time tn-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 t, 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 between voltage and current. The value e of this error is:
e = [cos (t f 2 ) 1] 100

where: e

Error in per cent 115

Metering Application Report t Sampling interval between voltage and current measurements [s] f Mains frequency [Hz]

MSP430 Family

For example: With the values (f = 60Hz, t = 300s) 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 cos( t f 2 )

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 appertaining chapters. Derivation of the inherent error The flawless equation (except the quantization error) for the electric energy W is:
W = in un t
t =0 t =

The equation used for the Reduced Scan Principle is:


W = 0.5

i
t =0

t =

(un 1 + un+1 ) t

Where: un = U sint in = I sin(t+) un-1 = U sin(t-) un+1 = U sin(t+) t

Voltage sample at time t Current sample at time t Voltage sample at time t - t Voltage sample at time t + t Angle in radians between current and voltage samples ( = t = 2ft) 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:
0.5 I sin(t + ) (U sin(t ) + U sin(t + ))

e=

erroneous 1 correct

e=

e=

U sin t I sin(t + ) 0.5 (sin(t ) + sin(t + ))

sin t

e=

0.5 (sin t cos sin cos t + sin t cos + sin cos t ) 1 sin t

e=

0.5 (2 sin t cos ) 1 = cos 1 sin t

116

MSP430 Family or in per cent

Metering Application Report


e = (cos 1) 100 = (cos(2 f t ) 1) 100

This result means that the error of each energy sample calculated with the Reduced Scan Principle shows a constant value e. This inherent error e depends only on the angle between the current and the voltage samples; it is independent of the phase angle and of the sample point of the measurement inside the sine wave. So for all samples the same correction can be used. 4.1.2.2 The Advantages of the Reduced Scan Principle 1. Only 50% of the measurements are necessary because every measured current or voltage sample is used twice 2. Only 50% of the multiplications are necessary because two voltage samples are added before the multiplication 3. Only one analog-to-digital converter is needed compared to up to six ones with the normal method. 4. The computing power gained by reducing the number of multiplications can be used by the microcomputer for other system tasks: the MSP430 is able to do the task of the frontend and of the host computer. 5. The Reduced Scan Principle is nearly independent of frequency deviations of the mains. See section 4.1.2.4 for results. 6. The Reduced Scan Principle is also nearly independent of the interrupt latency time of the microcomputer. See section 4.1.2.5 for results. The Reduced Scan Measurement Principle is implemented in an evaluation board for a 3-phase meter which shows a typical error of 0.2%. 4.1.2.3 Measurement Errors for some Sampling Frequencies Table 41.1 gives an overview for the measurement errors in dependence of the sampling frequency. The inherent error shows the error for the mains frequency (50Hz or 60Hz). The 3rd harmonics error shows the corrected measurement error for the 3rd harmonic of the mains frequency (150Hz resp. 180Hz). The 5th harmonics error shows the corrected measurement error for the 5th harmonic of the mains frequency (250Hz resp. 300Hz). For any number of measurements (current and voltage samples together) per full period a rough error estimation can be made with this table.

117

Metering Application Report Table 41.1: Errors dependent on the Sampling Frequency Sample Frequencies Errors Single Phase 50Hz 1000 1500 2000 2500 3000 3500 4000 4500 5000 5500 6000 6500 7000 8000 9000 10000 Two Phase 60Hz 2400 3600 4800 6000 7200 8400 9600
1)

MSP430 Family

Measurements per full Period 20 30 40 50 60 70 80 90 100 110 120 130 140 160 180 200

Three Inherent 3rd Harm. 2) Phase Error 50Hz 3000 -4.89% -36.4% 4500 -2.19% -16.9% 6000 -1.23% -9.7% 7500 -0.78% -6.2% 9000 -0.55% -4.3% 1) -0.40% -3.2% -0.30% -2.4% -0.24% -1.9% -0.20% -1.6% -0.16% -1.3% -0.13% -1.1% -0.11% -0.9% -0.10% -0.8% -0.08% -0.6% -0.06% -0.5% -0.05% -0.4%

5th Harm.

2)

-95.2% -47.8% -28.0% -18.3% -13.4% -9.5% -7.3% -6.0% -4.7% -3.9% -3.2% -2.7% -2.4% -1.9% -1.5% -1.2%

1) Sampling frequencies above 10000Hz are not possible due to the speed of the ADC (132 ADCLKs/conversion) 2) The errors of the harmonics are corrected by the value of the inherent error

4.1.2.4 Measurement Error for Deviations of the Mains Frequency If the mains frequency deviates from the nominal value used during the calibration, then a small error is generated. Table 41.2 shows this error in dependence of the sample frequency and the mains frequency deviation. The introduced error Fmd is:
cos( t ( f + f ) 2 ) Fmd = 1 100 cos( t f 2 )

Where: Fmd t f f

Error due to the mains frequency deviation from the nominal frequency [%] Time between appertaining current and voltage samples [s] Nominal mains frequency (used during calibration) [Hz] Frequency deviation of the mains frequency during runtime [Hz]

118

MSP430 Family

Metering Application Report

Meas. per full Period 20 40 80 130

Table 41.2: Errors dependent on the Mains Frequency Deviation Sample Frequencies Errors Single Two Three f/f = f/f = Phase Phase Phase +0.5% +1.0% 50Hz 60Hz 50Hz 1000 2400 3000 -0.051% -0.103% 2000 4800 6000 -0.012% -0.025% 4000 -0.003% -0.006% 6500 -0.001% -0.002%

f/f = +5.0% -0.523% -0.127% -0.030% -0.010%

The errors for negative frequency deviations are the same as shown in table 4.1b but with positive signs. The ADC is assumed to be error-free, this way only the influence of the frequency deviation is shown. The additional error due to the deviation of the mains frequency can be reduced to nearly zero by the measurement of the actual mains frequency and an appropriate correction of the calculated energy. 4.1.2.5 Measurement Error in Dependence of the Interrupt Latency Time The calibration of an electricity meter is made normally in an environment without interrupt activity. This can be completely different to the real time environment where the meter has to measure the electric energy later. Therefore the interrupt latency time (here the time the interrupt request of the sampling time base is delayed by other interrupts) can have an influence on the accuracy of the measurement. Table 41.3 shows the errors introduced by different interrupt latency times. The calibration is made with a maximum interrupt latency time of 5s (due to missing interrupt activities): this is the maximum delay caused by the completion of the current instruction (indexed,indexed mode) with MCLK = 1MHz. The conditions used for the simulations of table 41.3 are: The simulation conditions are the same ones as described in section 4.1.3 except where noted otherwise. The given interrupt latency times are the maximum values; each voltage and current sample is delayed by a random time interval ranging between zero and this maximum value. The ADC is assumed to be error-free (except the range transition error), this way only the influence of the interrupt latency time is shown. For other values of MCLK than 1MHz , the shown latency times are not given in microseconds but CPU cycles. The used current is 100% except for the last line (1%) The measurement time is 20 seconds

119

Metering Application Report

MSP430 Family

Meas. per full Period 20 40 80 130 cos=0.5 1% In


1)

Table 41.3: Errors dependent on the Interrupt Latency Time Single Maximum Interrupt Latency Time Phase 5s 20s 40s 80s 50Hz (Calibr.) 1000 -0.0013% -0.0010% +0.0023% +0.0052% 2000 -0.0010% +0.0010% -0.0005% -0.0053% 4000 +0.0007% +0.0002% -0.0035% -0.0053% 6500 -0.0011% +0.0002% -0.0006% -0.0025% 6500 -0.0011% 0% +0.0001% -0.0055% 6500 -0.0098% -0.0175% +0.0170% -0.0786%

160s +0.0103% -0.0113% -0.0292% - 1) - 1) - 1)

Interrupt latency time is greater than sampling interval

Table 41.3 shows the extreme low influence of the interrupt latency time: even non-realistic high latency times like 160s result in negligible influence. This means that the Reduced Scan Principle is not sensitive to the interrupt latency time of the system. NOTE The errors shown in table 41.3 are won by the use of random values for the interrupt latency time. Despite the relatively long simulation time (20 seconds) every simulation made under exactly the same conditions returned therefore a slightly different error. 4.1.2.6 Measurement Error due to Overvoltage and Overcurrent With the simulation conditions described in section 4.1.3 the ADC measures up to 111% of the maximum current or voltage without additional error. It is important to know how the electricity meter behaves if the input values are above these limits: there must be a smooth transition and no oscillations or sudden changes. Due to the saturation the ADC shows for overflow and underflow, the errors shown in table 41.4 result. The ADC is assumed to be error-free (with the exception of the range transition error), so only the effect of the overflow is shown. Table 41.4: Errors dependent on Overvoltage and Overcurrent 100% Vnom 110% Vnom 120% Vnom 0% 0% -2.4% 0% 0% -2.4% -2.4% -2.4% -4.7% -6.5% -6.5% -8.6%

Load Current 100% 110% 120% 130%

130% Vnom -6.5% -6.5% -8.6% -12.3%

4.1.3 The Analog-to-Digital Converter of the MSP430C32x The Analog-to-Digital-Converter (ADC) of the MSP430 measures the voltage between its AVss and SVcc connections with a resolution of 14 bits. The signed voltages coming from the current and voltage interfaces are shifted into the unsigned range of the ADC by simple interfaces described below. The MSP430 subtracts the measured or calculated offset value from every measured current or voltage sample: this enables signed, offset corrected measurements.

120

MSP430 Family

Metering Application Report

ADC Value [steps] 3FFFh 100% SVcc 95% SVcc

100% Current

Time 100% Voltage 5% SVcc 0000h AVss

Figure 41.4: Allocation of the ADC-Range Figure 41.4 shows the placement of the current and voltage coming from the voltage dividers and the current interfaces into the analog-to-digital converters range. All calculations and proposals base on a use of 90% of the ADC range for nominal (100%) values of current and voltage. This means up to 111% of the nominal values are still measured correctly. This allocation may be changed if necessary. Table 41.5 shows the influence of the analog-to-digital converters performance to the accuracy of the measurement of the electric energy. Two influences are involved: 1. The deviation of the ADC from the linearity. Each one of the four ranges A, B, C and D has calculated deviations up to 20 ADC-steps compared to the two ranges bordering on it. 2. The saturation effect at the range limits: if the sample for the definition of the range is taken in another range than the sample for the 12-bit conversion (36 ADCLKs later) than the result is xFFFh for increasing input signals and x000h for decreasing input signals (x denotes the number of the range where the range sample was taken). As the results show, the two saturation effects compensate nearly to zero. NOTE The deviations of the analog-to-digital converter used with the examples below (20 steps) are greater than the specified ones. These large deviations are used only to show the relative independence of the overall accuracy from the ADC error. The actual, specified deviations are 10 steps. It is recommended not to use the exact midpoint of the supply voltage Vcc (Vcc/2) for the common reference point. This is due to the possible slight slope deviation at the border of two ADC ranges (here B and C). This may influence the accuracy for the lowest currents. Table 41.5 shows also the influence for some extreme deviations of the analog-to-digital converter characteristic. Figure 41.5 explains the meaning of the used graphics: it shows the second deviation curve in detail.

121

Metering Application Report

MSP430 Family

ADC Error [steps] +20

Range C

Range D

1FFFh

3FFFh

ADC Value

Range A

Range B

-20

Figure 41.5: Explanation of ADC Deviation The function shows the deviation at any point of the four ADC ranges. Due to the monotony of the ADC the errors at the range limits are always equal. The errors shown in table 41.5 were calculated with a PASCAL program. The following steps were taken: 1. 2. 3. 4. Measurement and calculation of the error at 5% of the nominal current. Measurement and calculation of the error at 100% of the nominal current Calculation of the slope and offset for the correction (calibration) Simulation of voltage and current samples: any sample is modified with the ADC-error (exactly like during calibration). 5. Correction of all measured values with the calculated slope and offset 6. Calculation of the resulting error The saturation effect at the range limits is always included. The first column of table 41.5 with an ideal ADC-characteristic (zero deviation) shows only this effect and the finite ADC-resolution. This column can be used as a reference for the errors of the other five columns. The calculations are made with the following conditions: Virtual Ground location in the ADC range: Measurement time for calibration points: Measurement time for different loads: Mains frequency: Cosine : Sample frequency: Voltage: Current: 8190 steps (1FFEh) 49.98% of full ADC-range 5s (calibration points are measured this time) 9s 50Hz 1 (0) 2048Hz (488.3s sample distance) 100% Vpp uses 90% of the ADC-range 100% Ipp uses 90% of the ADC-range

122

MSP430 Family

Metering Application Report

Table 41.5: Errors with one Current Range and single Calibration Load Current 0.1% 1% 2% Calibr. P. 5% 10% 25% 50% 75% Calibr. P. 100% +0.7771% -0.0114% +0.0620% -0.0001% +0.0005% 0% -0.0001% +0.0001% -0.0002% +7.79% +0.83% +0.50% 0% -0.19% -0.27% -0.31% -0.17% 0% -2.93% -0.24% +0.01% 0% -0.01% -0.01% -0.01% 0% 0% +0.45% 0% +0.01% 0% 0% 0% 0% 0% 0% +0.57% +0.01% 0% 0% 0% 0% 0% 0% 0% +3.94% +0.38% +0.24% 0% -0.09% -0.13% -0.15% -0.09% 0%

The large errors at 0.1% of the nominal current result from the relatively far distance 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 shown how to reduce the error of the energy measurement. In any case, the used values for the correction are stored in the EEPROM and are loaded into the RAM during the initialization. 4.1.3.1.1 Use of a second Hardware Range This method is shown with all hardware examples. An analog switch like the TLC4016 switches a second resistor in parallel to the one used for the low current range. Both ranges use an 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. 4.1.3.1.2 Use of a second Calibration Range This method uses only 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 makes necessary two calibrations per phase, but with only three measurements (one is common for both ranges). The table below shows the enhancement of the accuracy if 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 as used for table 41.5: the enhancement can be seen by a comparison of the two tables. The errors for the range 5% to 100% of the nominal current are the same ones as shown in table 41.3.

123

Metering Application Report

MSP430 Family

Table 41.6: Errors with one Current Range and two Calibration Ranges Load Current Calibr. P. 0.1% 0.5% 1% 2% 3% 4% Calibr. P. 5% +0.004% -0.236% -0.075% -0.018% -0.006% -0.010% 0.000% +0.004% -0.002% +0.190% +0.262% +0.062% -0.035% 0.000% +0.002% -0.251% -0.003% +0.098% +0.024% -0.025% 0.000% +0.005% -0.163% -0.041% -0.005% -0.013% -0.009% 0.000% +0.005% -0.161% -0.040% -0.012% -0.012% -0.007% 0.000% +0.003% -0.119% +0.058% +0.122% +0.022% -0.023% 0.000%

4.1.3.1.3 Measurement of the Analog-to-Digital Converters 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 anyone of the 8 to 32 software sub-ranges of the ADC. These correction constants are written into the EEPROM and loaded into the RAM for use. For every sub-range 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 41.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 in figure 41.6, the sub-ranges B1 and C0 may be corrected in a way omitting this.
ADC Deviation [steps] +20 ADC Characteristic without Correction

Range C

Range D

3FFFh

ADC Value

Range A

Range B Corrected ADC Characteristic

Correction Value Subrange D1

Subrange A0 Subrange A1

Subrange D1

-20 Correction Values for the Subranges

Figure 41.6: Use of the actual ADC-Characteristic for Corrections (8 Sub-Ranges used) 4.1.3.2 Dependence on the Voltage and the Phase Angle Table 41.7 shows the dependence of the MSP430 using the Reduced Scan Principle on the load current, the mains voltage and the phase angle between current and voltage. The analog-to-digital converter is assumed to be error-free; the saturation effect at the range limits is included. Single calibration with one range only 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 table 41.5.

124

MSP430 Family

Metering Application Report

Table 41.7: Errors in Dependence on Current, Voltage and Phase Angle Load Current Mains Voltage Angle 1% 10% 100% 80% 90% 110% +0.447% +0.046% +0.048% +0.047% +0.045% ind. -80 +4.119% +0.099% +0.010% +0.009% +0.010% +0.010% -60 +0.857% +0.032% +0.003% +0.003% +0.003% +0.004% -40 +0.257% +0.009% +0.001% 0.000% +0.001% +0.001% -20 +0.047% +0.001% 0.000% 0.000% 0.000% 0.000% 0 -0.011% +0.004% 0.000% +0.001% +0.001% 0.000% +20 +0.043% +0.021% 0.000% +0.004% +0.003% +0.001% +40 +0.248% +0.844% +0.075% +0.007% +0.012% +0.009% +0.005% +60 +0.376% +0.037% +0.056% +0.046% +0.031% cap. +80 +4.051%

4.1.3.3 Derivation of the Measurement Formulas The equivalent to the meter constant of a Ferraris wheel meter (revolutions per kWh) is for electronic electricity meters the meter constant CZ that defines (ADC steps)2 per Ws. The used corrected equation for the electric energy W is:
W =
t = 1 0.5 in (un 1 + un +1 ) t cos(2 f t ) t =0

[Ws]

With the ADC-results ADCi (current sample) ADCu (voltage sample) and ADC0u and ADC0i (zero volt samples) the above equation gets:
W =
t = 1 0.5 ki (ADCin ADC 0i ) ku (ADCu n1 + ADCun +1 2 ADC 0u) t cos(2 f t ) t =0

Separation into variable and constant values results in:


W =
t = 1 0.5 t ki ku (ADCin ADC 0i) (ADCun 1 + ADCun +1 2 ADC 0u) cos(2 f t ) t =0

Where:

f t ki ku ADCin ADCun-1 ADCun+1 ADC0u ADC0i

Mains frequency [Hz] Sampling interval between appertaining voltage and current samples [s] Current multiplication factor [A/step]. See section 4.1.4.5 for explanation Voltage multiplication factor. [V/step]. See section 4.1.4.6 for explanation ADC value of current sample taken at time tn ADC value of voltage sample taken at time tn-1 (tn - t) ADC value of voltage sample taken at time tn+1 (tn + t) 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:

125

Metering Application Report


cos(2 f t ) [Steps2/Ws] 0.5 t ki ku

MSP430 Family

CZ =

The values for ki 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 above equation gets:
W = 1 SVcc wsec SVcc ( Rm + Rc) 0.5 t 14 2 w prim R sec 214 Rc cos(2 f t ) (ADCin ADC 0i) (ADCun 1 + ADCun +1 2 ADC 0u)
t=0 t =

Where:

Rsec wsec wprim SVcc Rm Rc

Load resistor (secondary) of the current transformer [] Secondary windings of the current transformer Primary windings of the current transformer Voltage at pin SVcc (AVcc or external reference voltage) [V] Voltage divider: resistor between mains connection and analog input [] Voltage divider: resistor between analog input and zero volts []

The first, constant part of the equation is the inverse value of the meter constant CZ:
CZ = cos(2 f t ) 2 29 w prim R sec Rc t SVcc 2 wsec ( Rm + Rc)

[Steps2/Ws]

With the above value of CZ the equation for the energy W gets:

W =

(ADCi
t=0

t =

ADC 0i ) (ADCun 1 + ADCun +1 2 ADC 0u) CZ

[Ws]

If the energy W is to be expressed in kWh:

W =

(ADCi
t=0

t =

ADC 0i ) (ADCun 1 + ADCun +1 2 ADC 0u) 3.6 10 9 C Z

[kWh]

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 may affect the overall accuracy of the electricity meter.

126

MSP430 Family 4.1.4.1 Analog and Digital Grounding

Metering Application Report

The following schematics are drawn in a simplified manner to hold them clear. In reality it is necessary to decouple the analog and the digital part as shown in figure 41.7. This is to avoid digital noise on the analog signals to be measured.
230V

Reference

SVcc

Rext Rext Isec


Voltage

A1 A0 A5 MSP430C323

Current

AVss AVcc To AVcc Ca To other analog parts 0V AGND

DVss

DVcc

Cd

To other digital parts

+5V

Power Supply

Figure 41.7: MSP430 14-Bit ADC Grounding

4.1.4.2 Analog-to-Digital Converter Input Considerations The analog-to-digital converter (ADC) operates up to 1.5MHz with the full accuracy. If the processor clock MCLK is higher than this frequency it is advised to use one of the prescaled ADC clocks (ADCLK). The possible prescaled frequencies for the ADCLK are: MCLK, MCLK/2, MCLK/3 and MCLK/4. The sampling of the ADC to get the range information takes 12 ADCLK cycles; this means, the sampling gate is open during this time (12s @ ADCLK = 1MHz). The input of an ADC pin can be seen as an RC low pass filter: 2k together with 42pF. The 42pF capacitor must be charged during the 12 ADCLK cycles to the final value to be measured. This means within 2-14 of this value. This time limits the internal resistance Ri of the source to be measured:
(Ri + 2k ) 42pF < ln2
14

12 ADCLK

Solved for Ri, the result is 27.4k. This means: to get the full 14-bit resolution of the ADC, the internal resistance of the input signal must be lower than 27.4k. The given examples use lower source resistances at the ADC inputs. 4.1.4.3 Offset Treatment If the voltage and current samples contain offsets then the equation for the measured energy W gets:

127

Metering Application Report

MSP430 Family

W = (un + Ou ) (in + Oi ) t
t =0 t = t =0

t =

W = (un in + un Oi +in Ou + Oi Ou ) t

Where:Ou Offset of voltage measurement [V] Oi Offset of current measurement [A] un Sum of the two voltage samples un-1 and un+1 [V] The terms (un Oi) and (in Ou) get zero when summed-up over one full period (the integral of a sine curve from 0 to 2 is zero) but the term (Oi 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 Ou) is eliminated: this is the case for all proposals. Two different ways are used: Either the voltage representing 0V is measured (see 4.1.4.4.1 and 4.1.4.4.2) or the summed-up ADC value for a full period is used for this purpose (see 4.1.4.4.3). 4.1.4.4 Adaptation to the Range of the Analog-to-Digital Converter The analog-to-digital 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 also the chapter Power Supplies for the MSP430. 4.1.4.4.1 Split Power Supply To get a common reference voltage in the middle of the analog-to-digital converters voltage range, two voltage regulators with output voltages of +2.5V and -2.5V may 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 (A0 in figure 41.8). The measured ADC value of this reference voltage is subtracted from every voltage and current sample. This way signed, offset corrected measurement values are gotten. The schematic is shown in figure 41.8.

128

MSP430 Family

Metering Application Report


+2.5V SVcc A1 U1 -2.3V...+2.3V 0V A0 MSP430C32x -2.5V AVss DVss DVcc AVcc

+2.5V

-2.5V

+2.5V

Figure 41.8: Split Power Supply for Level Shifting 4.1.4.4.2 Use of a Virtual Ground IC 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 possibility to measure the ADC value of this reference without the necessity to switch off the voltage and current inputs. The measured value (at analog input A0) is subtracted from every measured current or voltage sample which gives signed, offset corrected results. See figure 41.9. Typical electrical characteristics of the TLE2426: Supply Current Output Impedance Output-Current Capability Power Rating @ 25C Derating Factor above 25C 170A 0.0075 20mA 725mW 5.8mW/C No load connected For sink and source For the Small Outline Package

+5V +5V SVcc A1 U1 -2.3V...+2.3V I O C TLE2426 0V AVss DVss DVcc +2.5V A0 MSP430C32x AVcc

0V

+5V

Figure 41.9: Virtual Ground IC for Level Shifting

129

Metering Application Report 4.1.4.4.3 Resistor Interface (Software Offset)

MSP430 Family

This method uses the fact that the integral of a sine curve is zero if integrated over the angle 2. 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 mains 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 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 used for the adaptation of the mains voltage to the ADC range too. The current part allows two (or more) current ranges. With the closed range switch high currents may be measured, with the opened switch a better resolution for the small currents is possible. No DC flows through the current transformer due to the high input resistance of the ADC inputs.
I load

230V +5V SVcc 1.6M 22k A0 AVcc

A1 TLC4016I Range Switch 22k MSP430C32x AVss 0V DVss DVcc

0V

+5V

Figure 41.10: Resistor Interface without Current Source With Current Source: Four ADC inputs can be used with the internal Current Source: a current, defined by an external resistor Rext, is switched to the ADC input and the voltage drop at the external circuitry is measured with the ADC. 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, then a reed relay is needed to switch the second load resistor of the current transformer (the signal at the current transformer has a negative going part - outside of the ADC voltage range - therefore a TLC4016 cannot be used). The current Ics flows through the current transformers secondary windings. It needs to be checked if this is tolerable.

130

MSP430 Family

Metering Application Report

I load

230V +5V SVcc 1.6M Rext Rext A0 Ics A1


(+1.25V)

AVcc

5.6k

MSP430C32x AVss

Ics =

SVcc 4 x Rext

0V

DVss

DVcc

0V

+5V

Figure 41.11: Resistor Interface with Current Source NOTE If the Current Source is used, only the ADC-ranges A and B may be used. This is due to the supply voltage the Current Source needs for function. The resolution is therefore only one half of the normal value. The midpoint of the ADC range is 01000h then. 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 to solve this problem are shown in figure 41.12 and are explained below. If range switches are used, it is recommended to use a hysteresis for the range selection criteria. 4.1.4.5.1 Shunt The load current Iload flows through a resistor Rshunt (0.3 m to 3.0m) 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 may have only a very small phase shift (0.1) for getting the necessary accuracy. The output voltage Vout which is proportional to the current Iload is measured by the MSP430. The amount of Vout is:
Vout = I load Rshunt R2 R1 R2| | R3 R1

(open switch, low current)

Vout = I load Rshunt

(closed switch, high current)

The value ki [A/step], used for the calculation of the meter constant CZ (section 4.1.3.3) is:

131

Metering Application Report


ki = SVcc R1 14 2 Rshunt R2 SVcc R1 14 2 Rshunt R2| | R3

MSP430 Family

(open switch, low current. See 41.12)

ki =

(closed switch, high current)

Advantages:

- Resistive behavior - Simple - More than one range possible with switches - High losses with high currents - Very low output voltage with small currents (amplifier necessary) - Only usable with single phase meters
I load Live Load I sec Rshunt Neutral
+2.5V Wprim

Disadvantages:

I load Load
R2 R3

Live
Wsec

Neutral +
R1

Vout -2.5V

V out

R1

R2

Shunt
R3

Current Transformer

Figure 41.12: Current Measurement 4.1.4.5.2 Current Transformer The secondary current Isec of the current transformer, which is
Isec = w prim wsec Iload

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:
Vout = w prim w sec I load Rsec

Where:

Rsec = R2 Rsec = R2||R3

(switch open, low currents) (switch closed, high currents)

The value ki [A/step], used for the calculation of the meter constant CZ (section 4.1.3.3) is:
ki = w sec SVcc 14 2 Rsec w prim

(See figure 41.12)

Advantages:

- Isolation from the mains

132

MSP430 Family

Metering Application Report - High accuracy for the magnitude of the current (0.1% reachable) - More than one range possible with switched resistors

Disadvantages:

- Sensible to DC current: may lead to saturation - Costly

4.1.4.5.3 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 at all. The small output voltage Vfc of this coil is amplified, integrated and measured by the MSP430. The gain v of the pre-amplifier is used for the range switching. The ferrite core behaves as an inductivity L i.e. the output voltage Vfc is:
V fc = dI load L dt

This means, the voltage Vfc 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 mains 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 41.13. The value ki [A/step], used for the calculation of the meter constant CZ (section 4.1.3.3) is:
ki = SVcc C R1 2 14 vL

The formula is valid only if R2 >> R1 (normal case). Advantages: - Isolation from the mains - No saturation possible by DC parts of the load current due to the air-gap - Low output voltage due to loose coupling - Output voltage leads 90 compared to load current - Fast load current changes cause relatively high output voltages (di/dt) - Circular buffering or amplification and integration necessary

Disadvantages:

133

Metering Application Report

MSP430 Family

I load
Rsense

I load +
wsens

Ferrite Core
wsec

Vout

I sec

Air-Core Coil Ferrite Core


0V

V fc

Rsec Range 0V 0V +2.5V Range

+ Vout -2.5V C R2

0V

Compensated Ferrite Core

R1

v x Vfc

Ferrite Core

Figure 41.13: Current Measurement 4.1.4.5.4 Compensated Ferrite Core The load current Iload 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 wsec in a way that compensates the primary flux to (nearly) zero. This means that the driving of the resistor Rsec 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 all over the core (not as it is shown in figure 41.13 for simplicity). Additional current ranges are possible with switched resistors in parallel with Rsec. The output voltage Vout is:
Vout = Iload Rsec wsec w prim wsense Rsec + v Rsense

The term wsense Rsec/v Rsense is the remaining error of the compensated ferrite core. The value ki [A/step], used for the calculation of the meter constant CZ (section 4.1.3.3) is (the error term is not included due to its low value):
ki = SVcc 1 w sec 14 2 Rsec w prim

Advantages:

- Isolation from the mains - Nearly complete compensation of the ferrite cores hysteresis and nonlinearity errors - Amplifier necessary - Difficulties to stabilize feedback loop

Disadvantages:

134

MSP430 Family 4.1.4.6 Voltage Measurement

Metering Application Report

The problem of the current measurement, the large dynamic range, does not exist for the voltage measurement: the mains voltage always has a nearly constant value. Two measurement methods are used normally.
I load Live Vmains Neutral ADC Rc Vsec 0V Resistor Divider 0V Vsec ADC Rm Load Live
Wprim Wsec

Load

PR

Neutral

Voltage Transformer

Figure 41.14: Voltage Measurement 4.1.4.6.1 Resistor Divider The mains voltage Vmains is adapted to the range of the ADC by a simple resistor divider. All of the shown examples use this method. The amount of Vsec is:
Vsec = Rc Vmains Rm + Rc

The value ku [V/step], used for the calculation of the meter constant CZ (section 4.1.3.3) is:
ku = SVcc Rm + Rc 2 14 Rc

[V/step] (See figure 41.14)

4.1.4.6.2 Voltage Transformer A voltage transformer is used if the mains voltage is very high or if a 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 Vmains w prim

The value ku [V/step], used for the calculation of the meter constant CZ (section 4.1.3.3) is:
ku = SVcc w prim 214 wsec

[V/step] (See figure 41.14)

135

Metering Application Report 4.1.5 Single Phase Electricity Meters

MSP430 Family

The next two Electronic Electricity Meter proposals are made for the measurement of European mains. From the utility one phase and ground are led into the house. In this way a nominal voltage of 230V is available. The Reduced Scan Principle is applied exactly as described in chapter 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 41.2. The Analog-to-Digital-Converter (ADC) of the MSP430 measures the voltage between its AVss and SVcc connections with a resolution of 14 bits. To shift the signed voltages coming from the current transformer and voltage divider into the unsigned range of the ADC a split power supply with +2.5V and -2.5V is used: the common ground of these 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 41.15. The load current Iload flows through the shunt which has a resistance of approx. 1.0m. The voltage drop at the shunt is amplified and measured by the MSP430. The voltage V out 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 to keep the time information (provided by the Basic Timer) also during power-down periods. All current-consuming peripherals may be switched off therefore: the reference diode, the range switch and the amplifier by the SVcc-output, the EEPROM with a TPoutput. A pre-payment interface is connected to the MSP430. It allows to switch-on the mains only after the insertion of a valid pre-payment card.

136

MSP430 Family

Metering Application Report

Live I load Load Rshunt Neutral


SVcc

Vout
-2.5V

+
1k

4.7M 1k 176k

32kHz
Range Switch 6k

+2.5V AVcc SVcc TP.0 A1 A0 A5 A4

COM SEL
Error kW kWh

Voltage Current

TP.2 TP.1 P0.0 P0.2


TXD

33k

82k

0V

Clk Vcc EEPROM Data TSS721 MBUS

Reference

P0.1
RCV

LMx85 Uref -2.5V Power Relay

MSP430C32x P0.3 AVss TP.3 P0.4 I/Os DVss DVcc P0.5

IR-IF Key +2.5V

Pulse Ws -2.5V

Pre-Payment Interface -2.5V +2.5V

Backup Battery

Figure 41.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 41.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 used range switch algorithm uses a certain hysteresis to avoid too often occurring switching. If needed, additional current ranges can be implemented (three analog switches of the TLC4016 are not used). An AC Down-signal out of the power supply connected to the interrupt I/O-pin P0.6 allows the MSP430 to save the important values (like the energy consumption) in the EEPROM in case of a power-fail. See chapter Battery Check and Power Fail Detection The RF-readout module is connected to free outputs: this may be an unused segment line, a TPoutput or an I/O-pin of Port0. The timing for the RF-readout is made by the internal Basic Timer: it delivers the necessary interrupt frequencies. The necessary supply voltage for the RF-Interface is won with a step-up voltage supply: it transforms the available 5V to 6V or more.

137

Metering Application Report

MSP430 Family

Wprim

Live
Wsec R2 R3

+2.5V I sec I load Load -2.5V

Voltg. Conv.

+3.5V RF-Antenna RFINTERFACE Mod -2.5V

Neutral

Range Switch

Step-up Frequ.

4.3M

+2.5V AVcc SVcc TP.0 A1 A0 A5 A4 COM SEL


Error kW kWh

Voltage 33k 82k Current

TP.1 P0.0 P0.2


TXD

0V

Clk EEPROM Data TSS721 MBUS

Reference

P0.1
RCV

LMx85 Uref -2.5V AC Down

MSP430C32x P0.3 AVss P0.6 P0.4

IR-IF Key +2.5V

DVss DVcc P0.5

Pulse Ws

-2.5V +2.5V

Figure 41.16: Single Phase Electricity Meter with Current Transformer and RF-Readout 4.1.5.3 Calculations For four single phase versions the typical values are calculated: 1. Version with minimum current consumption (low CPU and ADC speed) 2. Compromise between current consumption and resolution (medium CPU speed, medium ADC speed). The Basic Timer is used for the time base. 3. Compromise like 2. but with the use of the Universal Timer/Port Module for the time base 4. Version with high resolution due to sampling speed. If necessary, the ADC Clock may be up to 1.5MHz.

138

MSP430 Family

Metering Application Report

Table 41.8: Typical Values for a Single Phase Meter Item Minimum Compr. 1 Compr. 2 Consumpt. Mains Frequency 50Hz 50Hz 50Hz Time Base for ARR ACLK/18 Basic Timer ACLK/9 2048Hz MCLK (CPU Clock) 0.754MHz 0.754MHz 1.048MHz ADC Clock (ADCLK) 0.754MHz 0.754MHz 1.048MHz N (MCLK/ACLK) 23 23 32 ADC Repetition Rate ARR 1820.4Hz 2048Hz 3640.9Hz Phase Repetition Rate (ARR/2) 910.22Hz 1024Hz 1820.4Hz Phase Repetition Time (2/ARR) 1098.63s 976.56s 549.32s Measurements per 360 (50Hz) 1) 36.4 41.0 72.8 9.88 4.94 Sample Phase Shift 8.79 Inherent Error 2) -1.5% -1.2% -0.37% ADC Conversion Time tc (14 bits) 175.1s 175.1s 125.89s Interrupt Overhead ti 22 MCLKs 4) 29.2s 29.2s 10.5s Time per Measurement tc + ti 204.3s 204.3s 136.4s Time between interrupts 1/ARR 549.3s 488.3s 274.7s ADC Loading (tc + ti) x ARR 37.2% 41.8% 49.7% CPU Loading by MPYs 3) 19.3% 21.8% 27.6% Approx. Icc (nominal) for 820A 820A 1035A MSP430C323
1)

High Resolution 50Hz ACLK/5 2.195MHz 1.097MHz 67 6553.6Hz 3276.8Hz 305.18s 131.1 2.75 -0.11% 120.25s 10.0s 130.3s 152.6s 85.4% 23.8% 1872A

ADC conversions per complete mains period (voltage and current samples) 2) The Inherent Error - a constant value - is compensated with the calibration values 3) One signed multiplication per Phase Repetition Time; 160 cycles for each one 4) Time from ADC interrupt acknowledge until next conversion is started (after 22 MCLKs)

4.1.6 Dual Phase Electricity Meters The measurement sequence for a dual phase electricity meter is shown in figure 41.17.

Vr Vs Ir Is Vr Vs Ir Is Vr

1/ARR Repetition Time

Time

Figure 41.17: Timing for the Reduced Scan Principle (Dual Phase Meters) Where: Repetition Time 1/ARR

1/Phase Repetition Rate. Length of a complete Measurement Cycle Repetition Rate of the Analog-to-Digital Converter Inherent Phase Shift of the Measurement Method 139

Metering Application Report Vx Ix Voltage sample Phase x Current sample Phase x

MSP430 Family

Two Electronic Electricity Meters are shown, designed for the measurement of US domestic mains. As power connections two phases and a neutral line are led into the house. This enables the use of two voltages: 120V and 240V. To measure the used electric energy 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 (120V) are measured as well as loads connected between the two phases (240V). 4.1.6.1 Current Measurement with Current Transformers and Virtual Ground IC A solution which uses two current transformers for the measurement of the load currents is shown in figure 41.18. 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 TLC4016I; for low currents this switch is opened to get a higher voltage and therefore a better resolution. The used range switch algorithm has a certain hysteresis to avoid too often occurring 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 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: two analog switches of the TLC4016 are not used. A backup battery allows to keep the time information (provided by the Basic Timer) also during power-down periods. All current-consuming peripherals may be switched off therefore: the reference diode, the range switches and the Virtual Ground IC by the SVcc-output, the EEPROM with a TP-output.

140

MSP430 Family

Metering Application Report

Live

Current Transformer

Range Switch Neutral

Load 120V Load 240V Load 120V

Current Tr. Live 32kHz


2 x 2.2M

TP.0 TP.1 +5V AVcc SVcc A0 A1 A2 A3 COM SEL


Error

kW

kWh

Currents

TP.3 TP.2 P0.0 Clk Vcc EEPROM Data


TXD

Voltages

2 x 33k

I O C TLE2426C

82k Virtual Ground

A5

P0.2

TSS721

MBUS

Reference

P0.1 A4 MSP430C32x P0.3 P0.4

RCV

IR-IF Key +2.5V

LMx85 Uref AVss 0V 0V +5V

DVss DVcc P0.5 0V

Pulse Ws

Backup Battery

Figure 41.18: Dual Phase Electricity Meter with Current Transformers and Virtual Ground 4.1.6.2 Current Measurement with Current Transformers and Software Offset The figure 41.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). To get the ADC value of the virtual midpoint of the ADC-range, the software offset method is used (see 4.1.4.4.3). This value is subtracted from each voltage and current sample to get signed, offset corrected results. No backup battery is provided, this means that in regular time intervals the actual amount of the energy consumption needs to be stored in the EEPROM. If the used power supply provides an AC Down , this storage is only necessary if this signal is activated. An AC Down-signal out of the power supply connected to the interrupt I/O-pin P0.6 allows the MSP430 to save the important values (like the energy consumption) in the EEPROM in case of a power-fail. See chapter Battery Check and Power Fail Detection.

141

Metering Application Report

MSP430 Family

Live

Current Transformer

Range Switch Neutral

Load 120V Load 240V Load 120V

Current Tr. Live 32kHz

2 x 1.9M

TP.0 TP.1 +5V AVcc SVcc A0 A1 TP.2 A3


Voltages

COM SEL
Error

kW

kWh

Currents 2 x 56k 82k

P0.0 P0.2
TXD

Clk EEPROM Data TSS721 MBUS

A2
Reference

2 x 56k

LMx85 Uref

P0.1 A4 MSP430C32x P0.3 P0.6 AVss P0.4

RCV

IR-IF Key +2.5V

DVss DVcc P0.5 0V AC Down 0V +5V

Pulse Ws

Figure 41.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: 1. Version with minimum current consumption 2. Compromise between current consumption and resolution 3. Version with high resolution due to sampling speed. If necessary the ADC Clock may be up to 1.5MHz

142

MSP430 Family

Metering Application Report

Table 41.9: Typical Values for a Dual Phase Meter Item Minimum Compromise Consumption Mains Frequency 60Hz 60Hz Time Base for ARR ACLK/9 ACLK/7 MCLK (CPU Clock) 0.754MHz 1.048MHz ADC Clock (ADCLK) 0.754MHz 1.048MHz N (MCLK/ACLK) 23 32 ADC Repetition Rate ARR 3640.9Hz 4681.1Hz Phase Repetition Rate (ARR/4) 910.22Hz 1170.3Hz Phase Repetition Time (4/ARR) 1098.63s 854.5s Measurements per 360 (60Hz) 1) 30.34 39.0 11.86 9.22 Sample Phase Shift Inherent Error 2) -2.10% -1.29% ADC Conversion Time tc (14 bits) 175.1s 125.9s Interrupt Overhead ti 4) 29.2s 21.0s Time per Measurement tc + ti 204.3s 146.9s Time between interrupts 1/ARR 274.7s 213.6s ADC Loading (tc + ti)xARR 74.4% 68.8% CPU Loading by MPYs 3) 38.6% 35.7% Approx. Icc (typical) for MSP430 820A 1035A
1) 2)

High Resolution 60Hz ACLK/5 2.195MHz 1.097MHz 67 6553.6Hz 1638.4Hz 610.35s 54.6 6.59 -0.66% 120.3s 10.0s 130.3s 152.6s 85.4% 23.8% 1872A

ADC conversions per complete mains period and phase (voltage and current samples) The Inherent Error - a constant value - is compensated with the calibration values 3) Two signed multiplications per Phase Repetition Time; 160 cycles for each one 4) Time from ADC interrupt acknowledge until next conversion is started (after 22 MCLKs)

4.1.7 Three Phase Electricity Meters Two Electronic Electricity Meters are shown, designed for the measurement of European domestic mains. As power connections three phases and a neutral connection are led into the house. This enables the use of two voltages: 230V (phase to neutral) and 400V (phase to phase). To measure the used electric energy 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 (230V) are measured as well as loads connected between the phases (400V). The measurement sequence is shown in figure 41.20.

143

Metering Application Report

MSP430 Family

Vr Vs Vt Ir Is It Vr Vs Vt

1/ARR Repetition Time

Time

Figure 41.20: Normal Timing for the Reduced Scan Principle (Three Phase Meters) Where: Repetition Time 1/ARR

1/Phase Repetition Rate. Length of a complete Measurement Cycle Repetition Rate of the Analog-to-Digital Converter Inherent Phase Shift of the Measurement Method

If a more evenly spaced sequence is wished, for example to distribute better the multiplications, then the following sequence may be used. Current and voltage sampling is made alternating.

Vr It Vs Ir Vt Is Vr It Vs

1/ARR Repetition Time

Time

Figure 41.21: Evenly Spaced Timing for the Reduced Scan Principle (Three Phase Meters) 4.1.7.1 Current Measurement with Ferrite Cores and Software Offset The figure 41.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 this voltage dividers are chosen to be smaller than the maximum source impedance of the ADC (see 4.1.4.2). To get the ADC value of the virtual middle of the ADC range, the software offset method is used (see 4.1.4.4.3). This value is subtracted from each voltage and current sample to get signed, offset corrected results. The range is selected by different amplifications of the coil pre-amplifier. The reference is provided by the stable +5V supply. If needed, with additional TLC4016 ICs additional current ranges can be implemented. A backup battery allows to keep the time information (provided by the Basic Timer) also during power-down periods. All current-consuming peripherals may be switched off therefore: the resistor dividers, the range switches and the amplifiers (integrators) by the SVcc-output, the EEPROM with a TP-output.

144

MSP430 Family

Metering Application Report

Ferrite Core Phase R


SVcc Coil Range Vout

Ferrite Core Interface

0V +5V

+ 0V

+2.5V To other I/Fs

Phase S
Coil Range Vout

Loads 400V

Coil
SVcc

+ Vout
0V Coil Range Vout

Phase T Loads 230V

Range
R1

C R2

Neutral
Range Switches

Ferrite Core Interface

TP.0..2
Currents 3 x 4.1M

Xin Xout XBUF COM SEL


Error kW kWh

A2 A1 A0 AVcc SVcc

32kHz

+5V

3 x 56k

TP.4 TP.3 A5
Voltages

P0.0 P0.2 P0.1


TXD

Clk Vcc EEPROM Data TSS721 MBUS

A4 A3

3 x 56k

MSP430C32x P0.3 P0.4 AVss DVss DVcc P0.5 0V 0V +5V

RCV

IR-IF Key +2.5V

Pulse Ws 0V

Backup Battery

Figure 41.22: Three Phase Electricity Meter with Ferrite Cores and Software Offset 4.1.7.2 Current Measurement with Current Transformers and Split Power Supplies The six analog inputs of the MSP430C32x allow only the measurement of the three currents and three voltages without external circuitry. If a reference diode is needed (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 necessary. See figure 41.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 used power supply provides an AC Down, this storage is only necessary if this signal is activated. The same circuitry may be used with a Virtual Ground IC. Only few modifications are necessary. See figure 41.18.

145

Metering Application Report

MSP430 Family

An AC Down-signal out of the power supply connected to the interrupt I/O-pin P0.6 allows the MSP430 to save the important values (like the energy consumption) in the EEPROM in case of a power-fail. See chapter Battery Check and Power Fail Detection.

Phase R

Range Switch

Phase S

Loads 400V

Current Transformer

Phase T Loads 230V Neutral

Current 3 x 4.3M

Range Switch

TP.1 A1 TP.0 A0 Xin A2 Xout TP.2 AVcc SVcc COM SEL XBUF

32kHz

+2.5V

Error
82k

kW

kWh

MSP430C32x A4 A3 P0.6 P0.0 P0.2 P0.6 A5 P0.3 P0.1


TXD

1A 2A 3A 3 x 33k 4A

1B 2B 3B 4B xC

Reference

Clk EEPROM Data TSS721 MBUS

Voltages

LM385

RCV

0V

TLC4016 3

IR-IF Key +2.5V

TP.3..5 P0.4 AVss DVss DVcc P0.5

Pulse Ws

-2.5V AC Down -2.5V +2.5V

Figure 41.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: 1. Version with minimum current consumption 2. Compromise between current consumption and resolution 3. Version with high resolution. This version may be used with an MCLK frequency of 3.3MHz if a maximum calculation performance is needed. 4. Version with the highest resolution due to the maximum sampling speed

146

MSP430 Family

Metering Application Report

Table 41.10: Typical Values for a Three Phase Meter Item Minimum Compromise High Supply Resolution Current Mains Frequency 50Hz 50Hz 50Hz Time Base for ARR Basic Timer ACLK/6 ACLK/5 4096Hz MCLK (CPU Clock) 1.048MHz 2.097MHz 2.195MHz ADC Clock (ADCLK) 1.048MHz 1.048MHz 1.097MHz N (MCLK/ACLK) 32 64 67 ADC Repetition Rate ARR 4096Hz 5461.3Hz 6553.6Hz Phase Repetition Rate (ARR/6) 682.67Hz 910.22Hz 1092.3Hz Phase Repetition Time (6/ARR) 1464.8s 1098.63s 915.53s Measurements per 360 (50Hz) 1) 27.3 36.4 43.7 13.19 9.88 8.24 Sample Phase Shift Inherent Error 2) -2.6% -1.5% -1.03% ADC Conversion Time tc (14 bits) 125.9s 125.9s 120.3s Interrupt Overhead ti 4) 21.0s 10.5s 10.0s Time per Measurement tc + ti 146.9s 136.4s 130.3s Time between interrupts 1/ARR 244.1s 183.1s 152.6s ADC Loading 60.2% 74.5% 85.4% CPU Loading by MPYs 3) 31.3% 20.8% 23.8% Approx. Icc (typical) for MSP430 1035A 1800A 1872A
1) 2)

Highest Resolution 50Hz Basic Timer 8192Hz 2.949MHz 1.475MHz 90 8192Hz 1365.33Hz 723.4s 54.6 6.59 -0.66% 89.5s 7.5s 97.0s 122.1s 73.3% 20.8% 2423A

ADC conversions per complete mains period and phase (voltage and current samples) The Inherent Error - a constant value - is compensated with the calibration values 3) Three signed multiplications per Phase Repetition Time; 160 cycles for each one 4) Time from ADC interrupt acknowledge until next conversion is started (after 22 MCLKs) 4.1.7.4 Timing and Software The timing in figure 41.24 is shown for the Compromise Solution in section 4.1.7.3 (figure 41.22). The interrupt of the Universal Timer/Port Module (UT/PM) reads out the actual ADCresult, prepares and starts the next measurement. The ADC interrupt is not used. The instruction timing is shown for CPU cycles (MCLK 2.097MHz). The ADC timing uses an ADCLK = 1.048MHz (MCLK/2). Register R5 is used exclusively by the interrupt handler (status word) to reduce the execution time of the interrupt handler. Figure 41.24 shows the timing without any latencies due to other interrupts. If these latencies are included the complete timing can increase by several cycles. This 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 start. Calculations showed that the interrupt latency time does not influence the measurements: the statistical distribution results in an error nearly zero. See 4.1.2.5.

147

Metering Application Report

MSP430 Family

UT/PM Intrpt
Start Conversion

UT/PM Intrpt 132 ADCLKS (tc)


Conv. compl. RETI Read ADC

12c
UT/PM Restart Read ADC

ti

22c

ti 39c 136.4us 183.1us 152.6us

ACLK = 32.768kHz MCLK = 2.0972MHz ADCLK = 1.0486MHz ACLK/6 ACLK/5

Figure 41.24: Timing for the Reduced Scan Principle The used interrupt software: (The register R5 is reserved for the interrupt handling to get the shortest possible time) ; Hardware Definitions ; ADAT .EQU 0118h ; ADC 14-bit result buffer ACTL .EQU 0114h ; ADC control word M2 .EQU 02000h ; ADC prescaling: ADCLK = MCLK/2 Rauto .EQU 0800h ; Automatic range selection CSoff .EQU 0100h ; Current Source off A5 .EQU 014h ; Analog input A5: Vt A4 .EQU 010h ; Analog input A4: Vs A3 .EQU 00Ch ; Analog input A3: Vr A2 .EQU 008h ; Analog input A2: It A1 .EQU 004h ; Analog input A1: Is A0 .EQU 000h ; Analog input A0: Ir CS .EQU 001h ; Conversion Start TPCTL .EQU 04Bh ; UT/PM control word RC1FG .EQU 002h ; UT/PM interrupt flag TPCNT1 .EQU 04Ch ; UT/PM counter ; ; RAM Definitions ; ADCTAB .WORD 0,0,0,0,0,0 ; Ir,Vt,Is,Vr,It,Vs storage; ; MCLK Cycles ; ; ; Interrupt Latency 6 UT_HNDLR MOV &ADAT,ADCTAB(R5) ; Store act. ADC result 6 MOV TAB(R5),PC ; Go to individual handler 3 TAB .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. ; Vt MOV #M2+Rauto+CSoff+A5+CS,&ACTL ; Select Vt 6 JMP UT_COM ; 2

148

MSP430 Family Is Vr It Vs Ir MOV JMP MOV JMP MOV JMP MOV JMP MOV MOV

Metering Application Report #M2+Rauto+CSoff+A1+CS,&ACTL ; Select Is UT_COM ; #M2+Rauto+CSoff+A3+CS,&ACTL ; Select Vr UT_COM ; #M2+Rauto+CSoff+A2+CS,&ACTL ; Select It UT_COM ; #M2+Rauto+CSoff+A4+CS,&ACTL ; Select Vs UT_COM ; #M2+Rauto+CSoff+A0+CS,&ACTL ; Select Ir #-2,R5 ; Restart sequence with Vt 6 2 6 2 6 2 6 2 6 2

; ; Common part: time base is subtracted from UT/P. UT/P Flag is ; reset. Next measurement is prepared ; UT_COM SUB.B #6,&TPCNT1 ; ACLK/6 is time base BIC.B #RC1FG,&TPCTL ; Reset UT INTRPT flag ADD #2,R5 ; To next measurement RETI ; Return from INTRPT

6 4 1 5

Nearly the same interrupt handler may be used with a sampling timing defined by the Basic Timer. The differences are: No resetting of the interrupt flag is necessary (it is reset automatically) No re-loading of the timer register is necessary, the timer runs continuously

This shortens the interrupt handler by 12 cycles. ; ; Interrupt Latency 6

UT_HNDLR MOV &ADAT,ADCTAB(R5) ; Store actual ADC result 6 ADD #2,R5 ; To next measurement 1 MOV TAB-2(R5),PC ; Go to individual handler 3 TAB .WORD Vt,Is,Vr,It,Vs,Ir ; Six measurement handlers ; ; Individual handler parts for each phase (current and voltage) ; The next sample is selected and the measurement started. ; Vt MOV #M2+Rauto+CSoff+A5+CS,&ACTL ; Select Vt 6 RETI ; Return from INTRPT 5 ; Is MOV #M2+Rauto+CSoff+A1+CS,&ACTL ; Select Is 6 RETI ; 5 ; Vr MOV #M2+Rauto+CSoff+A3+CS,&ACTL ; Select Vr 6 RETI ; 5
;

It ; Vs ; Ir

MOV RETI MOV

#M2+Rauto+CSoff+A2+CS,&ACTL ; Select It ; #M2+Rauto+CSoff+A4+CS,&ACTL ; Select Vs RETI ; #M2+Rauto+CSoff+A0+CS,&ACTL ; Select Ir 149

6 5 6 5 6

MOV

Metering Application Report CLR RETI R5 ; Restart sequence ;

MSP430 Family 1 5

The above interrupt handler may be adapted also to the electricity meter shown in figure 41.23. The input selection with the TP-outputs must be included into the parts serving the three mains voltages. The selected ADC-input 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 will probably use another algorithm than an electricity meter for active power doing the reactive power measurement as a background task only. This chapter shows simple methods that uses as far as possible the voltage and current samples measured for the active power calculation anyway. 4.1.8.1 Measurement of Voltage and Current The measurement of voltage and current is possible by summing-up the absolute values of the ADC-results during integer numbers of full periods. The result is an indication of the average value of the voltage Vavrg resp. of the current Iavrg. If corrected like shown, the current and voltage values can be used for other purposes too. The formula for a sinusoidal voltage is shown below, the one for the current is equivalent to it.
Vavrg = Vpeak Vavrg p Vpeak 2 ; Veff = Veff = 1.11 Vavrg p 2 2 2

4.1.8.2 Measurement of the Apparent Power The apparent power is defined by the formula Papp = U I. There is no exact definition for the apparent power if harmonics are included. A possible solution is to use the voltage and current samples (see 4.1.8.1) taken for the active power measurement. These samples are made absolute and summed-up for an integer number of mains 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 above 4.1.8.1. The apparent energy Wapp is:
Wapp = Vavrg Iavrg 1.112 t

4.1.8.3 Measurement of the Reactive Power Two simple methods exist for the measurement of the reactive power: 1. Delay of the voltage (or current) samples for the time representing 90 (/2) of the mains frequency 2. Calculation out of the apparent power and the active power 4.1.8.3.1 Delay of Samples With a carefully chosen sampling frequency the angle 90 (/2) can be made an integer multiple of the sampling interval. If each voltage sample is delayed with a RAM-based FIFO (first-in-first-out

150

MSP430 Family

Metering Application Report

buffer) by this integer number and multiplied then with the actual current sample, the result will be the reactive power. EXAMPLE: mains frequency 50Hz, 90 are 5ms, with a sampling frequency of 2000Hz the necessary FIFO buffer is 5ms x 2000Hz = 10 words. For every phase 20 bytes of RAM are needed for the FIFO. 4.1.8.3.2 Calculation out of the Apparent Power The apparent power is calculated like described in section 4.1.8.2. Then the reactive power is calculated with the values of the active power and the apparent power by the formula:
Wreact = Wapp 2 Wact 2

NOTE All the calculations described above may be made with the MSP430 Floating Point Package. It is available with two lengths of mantissa: 24 bits and 40 bits. See chapter The Floating Point Package. 4.1.9 Calculation of the System Current Consumption The base of the current consumption table below is derived from the following data sheet information: Table 41.11: Current Consumption of the System Components Icc fosc Vcc Temperature Device MSP430C32x (ADC on) 1) 1000A 1.0MHz 5.0V TA = -40...+85C TLC4016 n.a. 5.0V TA = 25C 20A TLE2426 5.0V TA = 25C n.a. 170A TSS721 2) 18mA max. n.a. 5.0V TA = -40...+85C EEPROM 24AA01 3) 5.5V TA = 0...+70C n.a. 100 max. OPAMP TLC1079 n.a. 5.0V TA = 25C 40A LM385-2.5 4) n.a. 5.0V 30A n.a. 5.0V LCD 20mm100mm 5) 26A Crystal 6) 32.768kHz n.a. 2A
1)

2)

3)

4) 5) 6)

The supply current of the MSP430 (excluding the analog-to-digital converter) depends on the MCLK in a linear manner. The supply current of the ADC depends mainly on the current flowing through the internal resistor divider and is treated as constant therefore. The power for the TSS721 is taken from the M-BUS, so the electricity meters supply is not charged. Standby current of the Microchip EEPROM. Read and write currents are 1mA and 3mA. The EEPROM may be switched off completely during the standby periods The reference diode may be switched-off when not used for the reference measurements. A typical current value of 13nA/mm2 is used. A typical driver power of 10W is assumed.

With the above data the system consumption is calculated under the following conditions:

151

Metering Application Report

MSP430 Family

The compromise solutions shown in sections 4.1.5, 4.1.6 and 4.1.7 are used for the six hardware proposals Nominal current consumption is assumed for all system components The mains voltage has its nominal value The mains load current is assumed to be zero: this is to eliminate the influence of different current interfaces. Table 41.12: System Current Consumption for six Proposals Dual Single Single Dual Three Phase Phase Phase Phase Phase Shunt Virtual Software Ferrite Current Offset Core Transf. Ground IC 820A 820A 1035A 1035A 1800A 20A 20A 20A 20A 20A 170A 100A 100A 100A 100A 100A 40A 40A 30A 30A 30A 30A 30A 28A 28A 28A 28A 28A 134A 134A 1038A 12mW 998A 12mW 1383A 13mW 1347A 15mW 2152A 44mW

Device

MSP430C32x TLC4016 TLE2426 TSS721 EEPROM OPAMPs LM385-2.5 LCD / Crystal Resistor Dividers System Current Voltage Path

Three Phase Current Transf. 1800A 40A 100A 30A 28A 1998A 37mW

The value given for the Voltage Path shows the power needed for the voltage dividers adapting the mains 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 parts following. The system components not described until now are explained below: 1. 2. 3. 4. 5. 6. 7. 8. 9. The microcomputer MSP430C32x with its 14-bit Analog-to-Digital Converter (ADC) The Liquid Crystal Display (LCD) with up to 10.5 digits (4MUX) The EEPROM with 128 bytes (256 bytes) The current interface and the current range switches The power supply including the ADC 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 may be omitted if not needed.

152

MSP430 Family 4.1.10.1 The Microcomputer MSP430 The MSP430 is described in chapter 1. See there for details. 4.1.10.2 The Liquid Crystal Display

Metering Application Report

Any customized LCD can be connected to the MSP430 as long as it meets the electrical specifications (max. capacitance per segment and common lines for example). Every segment of the LCD can be controlled independently of the other ones. This means 256 resp. 512 (3MUX) possible combinations. SL means number of segment lines. Number of digits dependent on the multiplexing scheme: 4MUX digits = SL/2 3MUX digits = SL/3 2MUX digits = SL/4 1MUX digits = SL/8 The unused segments H (decimal points) of the digits can be used for the display of complete words e.g. kWh, Ws, Low Tariff a.s.o. This is used within the figures showing the electricity meter proposals. 4.1.10.3 The EEPROM The EEPROM (electrically erasable programmable read-only memory) contains data which must not be lost during power down cycles: 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 (statistical data e.g.) Error characteristics: current transformer, ADC aso.

For the summed-up energy a kind of circular buffer may be used, that avoids to use the same cells for every update. No pointer can be used for this purpose, so a simple check for the lowest stored energy value determines the next storage location. This check is 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) may be used for the safety of the stored data. The tables containing the error characteristics of the current transformer and the ADC may be used for correction purposes if needed. Dependent on the amount of data to be stored an EEPROM with 128 bytes or with 256 bytes is needed. The EEPROM is driven with a software handler: clock and data lines are set and reset by software (see also chapters Storage of Calibration Constants and I2C Connections). The EEPROM may be switched off by an output if it is not in use to save current. 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

153

Metering Application Report

MSP430 Family

be overlapping and the decision-making should use a SCHMITT trigger characteristic for the change of the ranges. This is to avoid too often occurring changes. 4.1.10.5 Power Supplies The stability of the used power supply decides if a reference voltage (see section 4.1.10.8) is necessary or not. If the power supply is stable enough then it may be used as the reference too. This simplifies the system in two ways: 1. No reference measurements are necessary in regular time intervals (e.g. every second) that makes the omission of one sample necessary. 2. No correction calculations are needed to correct the summed-up energy values. 3. No reference diode and additional hardware is necessary. The analog input may be used for other purposes. The stability of the power supply should be better than factor 4 as the wished 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 chapter Power supplies for the MSP430. 4.1.10.6 The M-Bus Interface 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: 1. Calibration: connection to the calibration hardware 2. Automatic readout by a host: the actual consumption and other interesting values may be read out with a customer defined protocol. 3. Tariff switching: the host defines the actual tariff by sending the appropriate information 4. 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 may be used with the MSP430. 4.1.10.7 The Infrared Interface The Infrared Interface allows bi-directional data transfer for calibration, test and readout. One of the P0-ports may be used with its interrupt capability for bi-directional transfers. 4.1.10.8 The Voltage Reference To have a reference for the measurements a reference diode LM385-2.5 may 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 ADC measurements. To reduce the supply current the LM385 may be switched on only during the reference measurements. See figure 41.15. No reference diode is necessary if a +5V voltage regulator (or two 2.5V regulators) are used with the necessary accuracy and long term stability. See section 4.1.10.5. The stability of the reference should be better than factor 4 as the wished accuracy of the electricity meter.

154

MSP430 Family 4.1.10.9 Peripherals

Metering Application Report

Some options are shown how to interface the MSP430 to other devices: Pulse Output: this output changes its state when a certain energy amount is consumed. Usable during calibration or accuracy checks. Mechanical displays can use this pulse output too. Key Interface: keys can be interfaced very simply to the inputs of the MSP430. Interrupt is possible with all Port0 inputs. LEDs: currents up to 1.5mA @ 0.4V voltage drop can be driven without external buffers.. 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), ACLK/2 (16.384kHz), ACLK/4 (8.192kHz). 4.1.11 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. 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 analog-to-digital converter can be nearly eliminated. This allows to build electricity meters for the classes 2, 1 and 0.5 ranging from single phase meters to three phase meters. A customer developed a single phase electricity meter with the following properties: Class 0.5 meter for the range 0.5A to 130A Error within 0.2% from 300mA to 40A 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 25mA 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 may be the only phase or one phase of a poly-phase meter. The Error Simulator (ES) simulates nearly exact an MSP430C32x working as an electronic electricity meter: all influences due to the MSP430 hardware are taken into account. The error due to the characteristic of the analog-to-digital converter (ADC) The error due to the interrupt latency of the MSP430 interrupt system The error due to the range transition for samples at the boundaries of the four ADC ranges The error due to the used Reduced Scan Principle for the measurement 155

Metering Application Report

MSP430 Family

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): (Listing path name) The characteristic of the ADC: the ADC-errors (in steps) at the five range boundaries are defined. See figure 41.25 for explanation. The time interval between two appertaining voltage and current samples (sampling interval) The nominal mains frequency 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. The correct ADC value for the external reference voltage 0V The measurement time for each measurement

4.1.12.3 Calibration The next step is the calibration part for the simulated system: the input values of section 4.1.1 are used. Two calibrations are necessary for the complete current range (the ranges shown below may be changed if needed): 1. 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. 2. 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 point is summed-up for five seconds each. The conditions are:

Voltage = 100% Nominal mains voltage Cos = 1 Resistive load Frequency deviation = 0 Nominal mains frequency Third harmonic in current = 0 No distortion, pure sine Interrupt latency time = 5s No interrupt activity except from the Basic Timer Measurement time for each calibration point = 5s

The calculation for the calibration part is made exactly the same way as described in section 41.4 for the error calculations. The slope and the offset for the correction formulae are calculated with the errors calculated for these two calibration points when compared to the correct energy values. The correct energy W is calculated with the formulae:
W = U I t cos

4.1.12.4 Conditions for the Load Curve Next the ES asks for the special conditions used for a load curve: The start current, the delta current and the maximum current in per cent of the maximum current

156

MSP430 Family

Metering Application Report

The voltage value in per cent of the nominal voltage The phase angle between voltage and current in degrees The frequency deviation from the nominal mains frequency The per cent value of the 3rd harmonic overlaid to the current path The measurement time for each measurement

With the values input, the load curve is calculated and the results are written to the listing output 4.1.12.5 Energy Calculation The ES now calculates the error for the measurement points the same way the MSP430 hardware does it: The ES calculates the real ADC value for the given 0V reference and truncates it: this is the ADC value including the ADC error 4.1.12.5.1 Calculation of the Voltage Sample The voltage sample used by the ADC to define the actual ADC range (bits 13 and 12 of the ADC result) is taken: The sampling time for the next voltage sample is calculated with the defined value of the sampling interval: last voltage sample time + 2 sampling interval To this calculated voltage sampling time a random value ranging from zero up to the defined maximum interrupt latency time is added. This simulates the interrupt latency time of the MSP430s interrupt system. The correct value of the next voltage sample is calculated including the frequency deviation and the given voltage value. The result is a signed ADC value (steps, but with a fractional part) The 0V value defined during the Common Measurement Conditions is added to the voltage value: this shifts the signed voltage value into the unsigned ADC range This voltage value is modified with the ADC error defined by the ADC characteristic and truncated afterwards to get an integer value between 0000h to 3FFFh. Overflow and underflow leads to the results 3FFFH and 0000h respectively. This value is used for the range transition check. The real ADC value of the 0V reference (as seen by the ADC) is subtracted from the truncated voltage value: this is the signed integer voltage value used for the calculations.

The same procedure as shown above is made for a second voltage sample measured 36s later: this second sample is used by the ADC for the 12-bit conversion. If the two samples are located in different ADC ranges - due to the fast changing input voltage - then the saturated ADC result for the range of the 1st sample is used, exactly like the MSP430 hardware does it. This treatment simulates the range transition error of the ADC. If the two samples are located in the same ADC range, then the ADC value of the second sample is used for the energy calculation. 4.1.12.5.2 Calculation of the Current Samples Each voltage sample is multiplied with the sum of two current samples: the current sample one sampling interval before it and the current sample one sampling interval after it. Both are sampled the same way (in reality each current sample is used twice, only one measurement is made). 157

Metering Application Report The current sample used by the ADC to define the actual ADC range is taken:

MSP430 Family

The sampling time for the next current sample is calculated with the defined value of the sampling interval: actual voltage sample time + sampling interval To this calculated current sampling time a random value ranging from zero up to the defined maximum interrupt latency time is added. This simulates the interrupt latency time of the MSP430. The correct value of the next current sample is calculated including the percentage of the current, the frequency deviation, the phase angle and the percentage of the 3rd harmonic. The result is a signed ADC value (steps, but with fractional part) The 0V value defined during the Common Measurement Conditions is added to the current value: this shifts the current value into the ADC range The current value is modified with the ADC error defined by the ADC characteristic and truncated to get an integer value between 0000h and 3FFFh. Overflow and underflow leads to the results 3FFFH and 0000h respectively. This value is used for the range transition check. The real ADC value of the 0V reference (as seen by the ADC) is subtracted from the truncated current value: this is the signed integer current value used for the calculations.

The same procedure as shown above is made for a second current sample measured 36s later: this second sample is used by the ADC for the 12-bit conversion. The same steps are used as described above for the voltage samples. This second sample is used for the energy calculation. 4.1.12.5.3 Calculation of the Energy Value The two calculated current samples described in section 4.1.4.2 are added and are multiplied afterwards with the voltage sample located between them (see 4.1.4.1). The result is divided by two (two samples are added) and summed-up to the energy buffer containing Werror After the defined measurement time the energy buffer is multiplied by the slope and corrected with the offset (both from the calibration part) Then the error calculation is made with the normal error formulae:
e = Werror Wcorrect 100 Wcorrect

Where:

e Werror Wcorrect

Measurement error in per cent Summed-up energy during simulation Calculated energy with the formulae shown at chapter 2

4.1.12.6 Explanation Figures Figure 41.25 shows the placement of the current and voltage coming from the voltage and the current interfaces into the analog-to-digital converters range. All calculations are based on a use of 90% of the ADC range for nominal (100%) values of current and voltage. This means up to 111% of the magnitude of the nominal values are still measured correctly. This allocation may be changed if necessary.

158

MSP430 Family

Metering Application Report

Figure 41.26 shows the ADC characteristic that produces the worst case errors. The ADC characteristic is defined at the boundaries of the four ADC ranges. The values shown are As = 0, Ae = +10, Be = 0, Ce = -10 and De = 0.
ADC Value [steps] 3FFFh 100% SVcc 95% SVcc +10 ADC Error [steps] Ae

100% Current 0V Time 100% Voltage 5% SVcc 0000h AVss -10 Range A As

Range C Be
1FFFh

Range D De
3FFFh

ADC Value

Range B

Ce

Figure 41.25: Allocation of the ADC-Range 4.1.12.7 Conclusion

Figure 41.26: Explanation of the ADC Deviation

The description above shows that all steps made from the hardware of an MSP430 analog-to-digital converter are also included in the simulation of the ADCs performance.

159

Metering Application Report 4.2 Gas Meter

MSP430 Family

A gas meter is shown that contains all peripherals which modern gas meters may have. The volume interface is shown for a mechanical meter, and on the left hand side for an electronic solution: The mechanical interface uses contacts to give the volume information to the MSP430. The output Oz is used for scanning, reducing this way the current flow if one or more contacts are closed permanently. The electronic interface outputs electrical signals to the MSP430 as long as the enable input is high. The signals V1 and V2 are 90 out of phase to allow a reliable distinction of the gas flow direction.

The gas temperature is measured with the ADC of the MSP430: this allows a much better accuracy for the volume measurement, because the dependence of the gas volume to the temperature can be taken into account (laws of Boyle-Mariotte and Gay-Lussac). Any combination of the peripherals shown can be used for a given solution: it is not necessary to have all of them implemented. The MSP430 is normally in Low Power Mode 3 (I = 1.6A nom.), but all enabled interrupt sources will wake it up: 1. Every change of the volume interface if output Oz is high 2. Timing of the Basic Timer: this allows keeping the timing and the scanning if Oz is low due to closed contacts.. 3. Actuation of the key 4. M-BUS activity 5. Prepayment interface
LCD

32kHz

SVcc

COM SEL Ox P0.0 Clk

Error

m3

A0 Gas Temperature

EEPROM Data TSS721

AGND MSP430

TXD MBUS RCD

Gas Flow Enable

Gas Flow

P0.3 Oz P0.5 Volume Interface V1 V2 Volume Interface P0.6 P0.x Vcc V1 V2 Vss n A1 Oy

IR-IF Mode/LCD + Pulse liters PREPAYMENT INTERFACE

3V/1.6uA

Figure 42.1: Gas Meter with MSP430C32x

160

MSP430 Family

Metering Application Report

The gas meter can be built-up also with the MSP430C31x or MSP430C33x versions. The only difference is the connection of the temperature sensor to the MSP430. The next figure shows this configuration:

32kHz

0V Rref

CIN TPD.1

COM SEL Ox Clk

Error

m3

Gas Temperature Rsens

TPD.0 P0.0 TXD

EEPROM Data TSS721

MBUS

RCD Gas Flow Enable Gas Flow MSP430 P0.3 Oz P0.5 Volume Interface V1 V2 Volume Interface P0.6 P0.x Vcc V1 V2 Vss n A1 Oy IR-IF Mode/LCD + Pulse liters PREPAYMENT INTERFACE

3V/1.6uA

Figure 42.2: Gas Meter with MSP430C31x

161

Metering Application Report 4.3 Water Flow Meter

MSP430 Family

The water flow meter uses an electronic interface to the rotating part of the meter. These signals are 90 out of phase for reliable scanning of direction. The MSP430 is in Low Power Mode 3 normally, but every change coming from the volume interface wakes it up. The water flow meter can be built up also with the MSP430C31x version of the MSP430 family. The only difference is the connection of the sensor for the water temperature. See the above gas meter solution with the MSP430C31x version for details.

32kHz COM SEL

SVcc

Error

m3

A0 Water Temperature

Ox P0.0

Clk EEPROM Data TSS721

LCD

AGND

TXD MBUS

RCD MSP430 P0.3 Water Flow Enable P0.7 P0.5 P0.6 Vcc Vss 3V/1.6uA A1 Oy IR-IF Mode/LCD + Pulse liters

Volume Interface

Figure 43.1: Electronic Water Flow Meter

162

MSP430 Family 4.4 Heat Allocation Counter

Metering Application Report

A Heat Allocation Counter with the possibility of sending out the consumption information via RFfrequencies is shown below. The RAM information is scrambled by the DES standard and sent out using the bi-phase code with 19.2kBaud. The software routines used for the scrambling and the transmission are contained in the section "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 MSP430s 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 calculates out of these 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.

32kHz Rext Heater T. SVDD Ri A1 A2 P0.4


19.2kBaud Biphase Code

RFUnit

MSP430C32x Room T. + Keys MBUS+ 2 AGND P0.z P0.y COM0-3 SEL

Error

P0.x Vcc Vss 3V/1.6uA

LCD

Figure 44.1: Electronic Heat Allocation Meter with MSP430C32x The heat allocation meter can be built-up also with the MSP430C31x version. Figure 44.2 shows the schematic for this configuration.

163

Metering Application Report

MSP430 Family

32kHz 0V Reference Room T. Heater T. CIN TPD.0 TPD.1 TPD.2 MSP430C31x + Keys MBUS+ 2 P0.z P0.y COM0-3 SEL P0.4
19.2kBaud Biphase Code

RFUnit

Error

P0.x Vcc Vss 3V/1.6uA

LCD

Figure 44.2: Electronic Heat Allocation Meter with MSP430C31x

164

MSP430 Family 4.5 Heat Volume Counter

Metering Application Report

The Heat Volume Counter shown in Figure 45.1 is 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 normally runs in Low Power Mode 3 (CPU off, oscillator on) but any change at one of the inputs will wake-up the MSP430. Every platinum sensor from 100 to 1500 can be used with the MSP430: the Current Source is able to drive them.

32kHz

Rext Pt100/Pt500 Inlet C1 L1

SVcc

COM SEL
Error m3 T

Ri A0

Oy P0.x

Clk EEPROM Data TSS721

LCD

AGND Water Flow Outlet Pt100/Pt500


Enable

TXD MBUS RCD

C2 L2 Ox P0.l P0.m Vcc V1 V2

A1 MSP430 P0.y P0.z P0.k Vss IR-IF Mode/LCD + Pulse Ws

Volume Interface

V1 V2

3V/1.6uA

Figure 45.1: Heat Volume Counter MSP430C32x The Four-Wire circuitry can also be used here. It is possible to use only five analog inputs with the schematic below: the signals at A2 and A5 can share one input and one resistor connected to AVss.

165

Metering Application Report

MSP430 Family

32kHz

Rext Inlet Pt100/Pt500

SVcc

COM SEL Oy P0.x TXD TSS721 Clk

Error

m3

Ri A0 A1 A2 AGND

LCD

EEPROM Data

MBUS

Water Flow Outlet


Enable

Pt100/Pt500

A5 RCD A4 MSP430 A3 P0.y Ox A2 A3 Vcc P0.z P0.k Vss

IR-IF Mode/LCD + Pulse Ws

Volume Interface

V1 V2

V1 V2 3V/1.6uA

Figure 45.2: Heat Volume Counter with 4-Wire-Circuitry MSP430C32x Figure 45.3 shows the same heat volume counter as figure 45.2 but with an enlargement of the ADC-resolution to 16 bits. The principle is explained in section Enlargement to 16-Bits See there for details of operation.

32kHz

Rext R15 R14 Inlet Pt100/Pt500

TP.0 TP.1 SVcc COM SEL Oy P0.x TXD TSS721 MBUS Clk EEPROM Data
Error kWh T

Ri A0 A1 A2 AGND

LCD

Water Flow Outlet


Enable

Pt100/Pt500

A5 RCD A4 MSP430 A3 P0.y Ox A2 A3 Vcc P0.z P0.k Vss

IR-IF Mode/LCD + Pulse Ws

Volume Interface

V1 V2

V1 V2 3V/1.6uA

Figure 45.3: Heat Volume Counter with 16 Bits Resolution MSP430C32x

166

MSP430 Family 4.6 Battery Charge Meter

Metering Application Report

The battery charge meter shown in figure 46.1 monitors the charge of a battery by means of the measurement of all relevant parameters: 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. Battery current: the voltage across a shunt gives an exact indication of the current flowing. The low shunt voltage is shifted into the ADC 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. 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 applicable from camcorders to forklifts. The reference voltage for the system is delivered by the voltage regulator output; the voltage therefore needs to be sufficiently stable. Referencing by a reference diode (LMx85) is also possible. This reference diode may 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 below, with a battery symbol showing 20% steps. Other methods for indication are also possible e.g. LEDs 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 necessary due to 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 RS232 using the MSP430s UART) can be used for the transfer of data: charge, temperature, voltage, current and other 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 (max. current, nominal capacity, end of charge criteria aso.) The EEPROM also contains the actual capacity (dependent on age and charge cycles) and a safety copy of the actual charge register. See also chapter Battery Check and Power Fail Detection.

167

Metering Application Report

MSP430 Family

To Host Q1 LCD

32kHz SVcc R1 Ri Batteries


Temperature

FULL

RCD TXD COM SEL To Loader EEPROM P0.x P0.y +3V Vcc

Load

Data

A2 A1

Clock

Voltage

MSP430C32x Voltage Regulator


Current

R3

A0 R2 Shunt AGND

P0.z Vss

Figure 46.1: Battery Charge Meter MSP430C32x

168

MSP430 Family 4.7 Connection of Sensors

Metering Application Report

The MSP430 family allows the connection of nearly all kind of sensors. Some special connections are shown in the following chapter. 4.7.1 Sensor Connection and Linearization Figure 47.1 shows the connection of simple resistive sensors to the MSP430C32x. The Current Source resistor Rext needs to be calculated in a way that allows its use for both sensor circuits (Rsens2 and Rsens3). The ways of connection shown in figure 47.1 are described in detail in chapter The Analog-toDigital Converters.

SVcc Rv Vin Rext Ics Ri A2 A1 Rsens1 Rsens2 A0

SVcc A3 R1 A6 A4 Rsens4 A5 A7 Rsens3 R2

MSP430C32x Rlin AGND Vss AGND Vcc

0V

+3V (+5V)

Figure 47.1: Resistive Sensors connected to MSP430C32x 4.7.1.1 Voltage Supply The sensor Rsens1 in figure 47.1 is connected this way. Resistor Rv supplies the sensor and is used for the Linearization too. The optimum value of Rv in dependence of Rsens is: Rv = Where: Ru Ro Rm Sensor resistance at the lower temperature limit Tu Sensor resistance at the upper temperature limit To sensor resistance at the medium temperature (To + Tu)/2 Rm ( Ru + Ro ) 2 Ru Ro Ru + Ro 2 Rm

The ADC values measured are independent of the supply voltage Vcc because the measurements are made relative to Vcc. 4.7.1.2 Current Supply Sensor Rsens2 in figure 47.1 is connected this way. If a linearization of the sensor is wished the same formula used for the resistor Rv with voltage supply may be used for the resistor Rlin. See section 4.7.1.1

169

Metering Application Report

MSP430 Family

4.7.1.3 Use of Reference Resistors Two measurement methods with reference resistors are possible: the use of one reference resistor and the use of two reference resistors: 1. Measurement with one reference resistor: the reference resistor is chosen in a way that it equals the sensor resistance at the most important measurement point. Eventually sensor and reference resistor are selected as pairs. The offset error is eliminated completely this way, only the slope error needs to be corrected. 2. Measurement with two reference resistors: the two reference resistors represent the sensor resistances at the limits of the measurement range. This method corrects also the influence of the internal resistance (RDSon of the TP-outputs). If sensors 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 (Rref2 Rref1) + Rref1 Nref2 Nref1

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

As shown only known or measurable values are needed for the calculation of Rx from Nx. Slope and offset of the ADC are corrected automatically.

TP.0 TP.1 TP.2 TP.3 Rref1 CIN Rsens1 Rsens2 Rref2 C MSP430 AGND Vss 0V Vcc +3V (+5V)

Figure 47.2: Measurement with Reference Resistors 4.7.1.4 Connection of Bridge Assemblies This kind of sensors is best known for pressure measurement: the voltage difference of the bridge legs changes with the pressure to be measured.

170

MSP430 Family

Metering Application Report

Bridge Assembly 1

Bridge Assembly 2 SVcc Ri SVcc R1 R2 A2 A1 A0 A3 A4 A5


Reference

Rext

Vm Vp

Temp1

MSP430C32x AGND Vss AGND Vcc

Temp2

0V

+3V (+5V)

Figure 47.3: Connection of Bridge Assemblies Figure 47.3 shows in its left hand part a bridge assembly that creates a voltage difference that is big enough to be measured by the ADC of the MSP430. The measurement result is the difference of the two results of the analog inputs A2 and A1. Due to the temperature dependence of most bridge assemblies a compensation of this dependence is necessary. The sensor Temp1 is used therefore to measure the temperature of the bridge legs (it is integrated in some bridge assemblies). The used formula is: P = MWP ( Ye + ( T Tk ) Tke ) + Yo + ( T Tk ) Tko Where: P MWP Ye T Tke Yo Tko Tk Pressure to be measured Difference of the measured values at A2 and A1 Sensitivity of the pressure sensor Temperature of the sensor Temperature coefficient of the sensitivity Offset Temperature coefficient of the offset Temperature during Calibration (e.g. +25C)

The units depend on the used system (hP, kg/m2, kg/mm2 a.s.o.) If the difference of the two measurement results is too small to be used then an operational amplifier as shown in the right hand part of figure 47.3 may be used. 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 the input A3. The same formula as above can be used if MWP is calculated like shown below: MWP Difference of the measured values at A4 and A3: MWP = (A3 - A4)

The actual measured voltage difference V between the analog inputs A3 and A4 is:

V = VA3 -VA4 = v (Vp Vm) + Vp Vp = v (Vp Vm)


Where: V Voltage difference between analog inputs A3 and A4 171

Metering Application Report v Vp Vm

MSP430 Family

Amplification of the operational amplifier: v = R1/R2 Voltage at the bridge leg connected to the non-inverting input Voltage at the bridge leg connected to the inverting input

The use of the reference input A4 results in correct values for the measurements like shown above. If only the differences of two A3 measurements are used, then the result needs to be corrected due to the following behavior:

V = VA32 -VA31 = v (Vp2 Vp1 - (Vm2 -Vm1)) + Vp2 Vp1 V =

(v + 1)(Vp2 Vp1) v (Vm2 Vm1)

It is obvious that the voltage differences of the two bridge legs are amplified by different factors (v resp v+1). 4.7.1.5 Fixing of Bridge Assemblies into one ADC-Range Bridge assemblies normally output only small signals - which makes amplification necessary - and have a relatively high temperature dependency. Both effects together can shift the small amplifier output range over a large input range of the analog-to-digital converter. The four ranges A, B, C and D of the ADC are not necessarily conform (slope and offset). Figure 47.4 shows a simplified characteristic of the analog-to-digital converter of the MSP430. Two different output ranges of the operational amplifier are indicated. The simplest way to get highest accuracy is to fix the output range of the amplifier to only one ADC-range; the one where the calibration was made.
ADC Error [steps] +10 Range 1 Range 2

0FFFh

1FFFh

2FFFh

3FFFh

ADC Value

Range A

Range B

Range C

Range D

-10

Figure 47.4: Simplified ADC-Characteristic This fixing is made by two TP-outputs with the resistor values R and 3R (see figure 47.5). 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 for a scale) the amplifier output is within a certain range of the ADC. Due to the possible TP-port output states Vcc, Vss and HI-Z, nine different and nearly equally spaced correction currents Icorr are available. The correction is possible for the positive and for the negative direction. The correction current Icorr can also be fed into the bridge leg Vm. The equation to calculate the correction resistors R and 3R is:

Rb SVcc SVcc / 2 SVcc 4v 2 v R < Rb 2 R 3R + Rb / 2 4 3

172

MSP430 Family Where: Rb R v

Metering Application Report Resistance of a bridge leg Resistance of the correction resistor Amplification of the operational amplifier: v = R1/R2

Bridge Assembly SVcc R1 MSP430C32x R2 A3 A4 TP.0 TP.1 Vss AGND Vcc


Reference

Rb
Vm Vp

+ 3R R Icorr

Rb

0V

+3V (+5V)

Figure 47.5: Fixing of Bridge Assemblies into one ADC-Range 4.7.2 Connection of Special Sensors Not only analog sensors can be connected to members of the MSP430 family. Nearly all existing sensors can be connected to the MSP430 in a simple way. The examples following will proof this. 4.7.2.1 Gas Sensors The right hand part of figure 47.6 shows the connection of two gas sensors (CH4, hydrogen, alcohol, carbon monoxide, ozone etc.). The gas sensor at the right hand side (connected to A0) is supplied by the internal current source of the MSP430C32x, where the current flowing through the sensor is defined by the resistor Rext. The gas sensor shown at the left hand side (connected to A1) owns a load resistance RL where the output voltage can be measured with the ADC input A1. Both sensors are heated by a pulse-width modulated voltage. The medium current is 133mA, the power is 120mW. The measurement of the sensor resistances is made always during the period without current flow. The temperature dependence of the sensor is corrected by the measurement of the sensor temperature: this is made by sensor Temp2. Only the MSP430C32x may be used for this kind of sensors: they are not potential free so the Universal Timer/Port cannot be used.

173

Metering Application Report

MSP430 Family

+5V

32kHz +5V P0yx,Oz P0.x,Oy VH

IH = 63 - 80mA (SP-xx) IH = 200mA (ST-xx)

VH

SVcc I = 133mA MSP430C32x RL Rext 2 3

FIS SP-xx/ST-xx 3

RH 4 A3 Temp1

Ri A0 A1 A2

1 Temp2 AGND FIS SB-xx AGND AGND

0V A4

RL Vss AGND 0V 0V +5V Vdd

Figure 47.6: Gas Sensor Connection to the MSP430C32x The left hand part of figure 47.6 shows the connection of another gas sensor. The heating of the sensor is made here with 5V DC. The connection is possible only the way shown, therefore the current source cannot be used. Temperature compensation of the measurement result is necessary here too. Sensor Temp1 is used for this purpose. 4.7.2.2 Digital Sensors Figure 47.7 shows two digital thermometers. They are controlled by instructions via the data bus DQ. The signed measurement result (9 bits) and other internal registers are accessible too via the data bus DQ. The circuit shown left hand uses a clock line for the data transfer, the right one differs the signals by their length (short is 1, long is 0).

SVcc,Vcc

SVcc,Vcc

Vdd CLK DQ GND RST DS1620

P0.x,Oz P0.y P0.z,Oy MSP430 AGND Vss Vcc DS1820

Vdd DQ GND P0.y MSP430 AGND Vss To other DS1820 Vcc

0V

+5V

0V

+3V (+5V)

Figure 47.7: Connection of Digital Sensors (Thermometer) 4.7.2.3 Sensors with Frequency Output

174

MSP430 Family

Metering Application Report

The output signal of these sensors is a frequency that is proportional to the measured value. This output frequency can be connected to any of the eight inputs of Port0 and counted via interrupt with a simple software routine. The frequency is the number of interrupts occurring in a one second window defined by the Basic Timer. If the frequencies to be measured are above 30kHz then the Universal Timer/Port or the 8-bit Interval Timer/Counter may be used for counting. The left hand part of figure 47.8 shows the connection of the linear "Light-Frequency-Converter" TSL220 to the MSP430. The TSL220 outputs a frequency proportional to the incoming light intensity. The range of this output frequency is defined by the capacitor Cf. The Timer_A is ideally suited for these applications. See section The Timer_A.

SVcc,Vcc Light Vdd C1 Cf C2 GND TSL220 AGND Vss AGND Vcc Out P0.y P0.x, CIN TAx Data GND Sensor Vdd

MSP430

0V

+5V (+3V)

Figure 47.8: Connection of Sensors with Frequency Output resp. Time Output 4.7.2.4 Time Measurements If the information to be measured is represented by pulse distances or pulse widths then it is also easy to be measured with the MSP430. The right hand part of figure 47.8 shows how to do this. The signal to be measured is connected to one of the eight inputs of Port0. Each one of these I/Os allows interrupt on the trailing and on the leading edge. With the Basic Timer an appropriate timing is selected for the needed resolution and the measurement made. The Universal Timer/Port may be used for this purpose too: the pulse to be measured is connected to pin CIN and the time measured from edge to edge. Even better resolution is possible with the Timer_A. The input signal is connected to one of the TA-inputs and a Capture Register is used for the time measurements. See section The Timer_A. 4.7.2.5 Hall Sensors Digital hall sensors have an output signal that indicates if the magnetic flux flowing through them is larger or smaller than a certain value. They normally show a hysteresis. Figure 47.9 shows the connection of a revolution counter realized with the TL3101. Everytime one of the wings breaks the magnetic flux through the TL3101 a negative pulse is generated and output. These pulses are counted by the MSP430 with interrupt.

175

Metering Application Report

MSP430 Family

SVcc,Vcc

Vcc Output GND TL3101 AGND Vss Vcc P0.y MSP430

0V

+3V (+5V)

Figure 47.9: Revolution Counter with a Digital Hall Sensor Analog hall sensors output a signal that is proportional to the magnetic flux through them. For these applications only the MSP430C32x with its 14-bit ADC is usable. During the calibration the ADC value at a known magnetic flux is measured and used for the correction of the slope. The ADC value measured at the magnetic flux zero is subtracted from any measured value. The calculated correction values are stored in the RAM or in an external EEPROM. For the correction of the temperature coefficient of the hall sensor a temperature sensor may be used. Figure 47.10 shows the connection of an analog hall sensor to the MSP430C32x and the typical output voltage dependent on the magnetic flux.
Output Vcc Rext SVcc Ri 0.9 A1 0.8

Vcc Output GND A0 Magn. Flux Temp. MSP430C32x AGND Vss

Vcc

0.7

0V

+5V

-25

0.0

+25

Magn. Flux Density mT

Figure 47.10: Measurement of the magnetic Flux with an Analog Hall Sensor

176

MSP430 Family 4.8 RF Readout

Metering Application Report

The read-out of metering devices gets more and more important. The next proposals show Electricity Meters having the possibility to send their consumption information via an RFtransmitter to a host having an RF-receiver. For data security reasons the information sent is normally encrypted with the DES encryption algorithm (Data Encryption Standard). The normally used frequency for this purpose is 433MHz but any other frequency may be used too (if it is allowed). The modulation mainly used is Amplitude Modulation (but Bi-Phase Modulation is used too). See also section 4.8.4 4.8.1 MSP430 Electricity Meter Figure 48.1 shows an Electricity Meter with the MSP430C32x. This single chip microcomputer contains all necessary peripherals on-chip except the EEPROM. The measurement of voltage and current is made with the internal 14-bit Analog-to Digital Converter. The interface to the mains is shown only for the phase R. The other two phases S and T use the same interfaces. The RF-readout is connected to a free output: this may be an unused segment line or an output bit of Port0. The timing for the RF-readout is made by the internal Basic Timer: it delivers the necessary interrupt frequencies. The necessary supply voltage for the RF-Interface is won with a step-up voltage supply: it transforms the available 5 Volts to 6 Volts or more. The shown hardware proposal uses the "Reduced Scan Principle" a way of measurement that needs only one Analog-to-Digital Converter: Every measured current sample is used twice, once with the voltage sample measured before and once with the one measured after it. This reduces the number of necessary samples without loosing accuracy. A second advantage is the halving of the number of necessary multiplications. This advantage is especially important for microcomputers that do not have a hardware multiplier like most of the MSP430 family members. See also chapter Electricity Meters.

177

Metering Application Report

MSP430 Family

+2.5V

Voltg. Conv.

+3.5V RF-Antenna RFINTERFACE Mod

-2.5V Step-up Frequ.

Mains N R S T
Out Out UR US UT IR I S IT 0V Range Control Vss A6 A5 A4 A3 A2 A1

-2.5V 32kHz COM SEL Out P0.x TXD TSS721 MBUS Clk EEPROM Data

Error

kW

kWh

RCD MSP430C32x A0 P0.y P0.n P0.z Vcc P0.k

IR-IF Key + Pulse Ws -2.5V

-2.5V

+2.5V

Backup Battery

N R S T To Loads

Figure 48.1: MSP430C32x EE-Meter with RF-Readout 4.8.2 MSP430 Electricity Meter with Frontend Figure 48.2 shows an Electricity Meter with the MSP430C31x. This single chip microcomputer contains all necessary peripherals on-chip except the EEPROM and an ADC. The measurement of voltage and current is made with a front-end owned by the customer. This front-end does the scanning and multiplying and delivers pulses to the MSP430 with a defined value per pulse (Ws/pulse, kWs/pulse aso.). The MSP430 counts and accumulates these pulses. The interface to the mains is shown only for the phase R. The other two phases S and T use the same interfaces. The RF-readout is connected to a free output: this may be an unused segment line or an output port of Port0. The timing for the RF-readout is made by the internal Basic Timer, the Timer_A or by the Universal Timer/Port Module. All of them are able to create the necessary interrupt frequencies.

178

MSP430 Family

Metering Application Report

RF-Antenna +6V Vcc RFModule Modul. 0V

Mains N R S T
Out UR US UT IR I S IT 1-3 P0.m

32kHz

COM SEL Out P0.x TXD TSS721 RCD MSP430 P0.y P0.n P0.z Vss Vcc P0.k MBUS Clk EEPROM Data

Error

kW

kWh

FrontEnd

0V Range Control

IR-IF Key + Pulse Ws -2.5V

-2.5V

+2.5V

Backup Battery

N R S T To Loads

Figure 48.2: MSP430 EE-Meter with RF-Readout 4.8.3 MSP430 Ferraris Wheel Electricity Meter with RF-Readout If RF-readout is necessary for conventional Ferraris Meters an MSP430C31x may be used for this purpose too. An optical or magnetic pick-up counts the revolutions of the disk and outputs a signal to the MSP430. The MSP430 computes the used energy and displays it on the LCD. In regular intervals the measured energy is transmitted with the RF-module.

179

Metering Application Report

MSP430 Family

RF-Antenna +6V Vcc RFModule Modul. 0V

32kHz Out COM SEL Ferraris Wheel Out P0.m Pick-up P0.x TXD TSS721 RCD MSP430 P0.y P0.z Vss Vcc P0.k IR-IF Key + Pulse Ws -2.5V -2.5V +2.5V Backup Battery MBUS Clk EEPROM Data
Error kW kWh

Figure 48.3: MSP430 with a Ferraris Wheel Meter and RF-Readout 4.8.4 RF-Interface Module The RF-Interface Module is normally connected to a supply voltage coming from the power supply of the EE-Meter. If this voltage is not available, the step-up power supply shown in figure 48.4 may be used: an existing supply voltage (here +3V) is transformed by the step-up circuit to +8V and regulated down to the wished +6V. The step-up frequency is delivered by the microcomputer: this frequency starts at a relatively high value and is lowered then to get a good power efficiency. Complete RF-Interface modules are available from several sources.

+8V L +3V Voltage Step-up Frequ. GND Modulation C Regul.

+6V

Vcc RFModule GND Mod.

RF-Antenna

Figure 48.4: RF-Interface Module Used modulation modes are: 1. Amplitude Modulation: the 433MHz oscillator is switched on for a logical "1" and switched off for a logical "0" (100% modulation).

180

MSP430 Family

Metering Application Report

2. Bi-Phase-Modulation: 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. 3. Bi-Phase Space: a logical "1" (space) is represented by a constant signal during the complete bit time. A logical "0" (mark) changes the signal in the middle of the bit time. The signal is changed after each transmitted bit. A stationary transmitter off is also treated as a mark state. The last two modulation modes do not have a DC part. Figure 48.5 shows all three modulations modes.

"0"

"1"

"1"

"0"

"1"

"0"

"0"

"1"

Information

Amplitude Mod.

RF on

Bi-Phase Code

RF off

Bi-Phase Space

Figure 48.5: RF-Modulation Modes 4.8.5 Protocol The protocol to be used with the RF-readout is not defined yet. One way is to split the data to be sent into blocks of 64 bits and to transmit these 64-bit blocks (with or without encrypting them with the DES encryption algorithm). Another way is to use the M-BUS protocol as it is defined for the M-BUS hardware: If the "Long Frame" format is used, data blocks up to 252 bytes can be transmitted in one frame. If the DES algorithm is used, these data blocks should have a length of 8 bytes (64 bits) due to the definition of the DES algorithm. Figure 48.6 shows a Long Frame block for 8 bytes of data. This block may be adapted to the needs of the wireless readout, for example the use of a 16-bit checksum due to the higher error probability of this kind of transmission.

181

Metering Application Report

MSP430 Family

Start 68h L Field L Field Start 68h C Field A Field CI Field User Data 8 Bytes Checksum Stop 16h

Start Character Length of Data (8 Bytes) Length of Data (Repitition) Start Character (Repitition) Function Field Address Field Control Information Field Data Field Encrypted or non-encrypted Data Checksum of Data Field Stop Character

Figure 48.6: M-BUS Long Frame Format To allow the receiver hardware the adaptation to the signal strength a pre-header needs to be transmitted in front of the data. This pre-header has the same length as the data block and transmits customer owned information (e.g. a series of marks which results in an alternating sequence of transmitter on and off signals in bit length). Figure 48.7 shows the sequence of a data transfer.

Pre-Header

First Data Block

Second Data Block

Figure 48.7: Sequence of Data Transmission 4.8.6 RF-Readout with other Metering Applications The shown RF readout solutions may be used also for gas meters, water meters, heat allocation meters and other metering applications. The supply for the RF part needs to be adapted to the possibilities of the battery used: a battery with a high internal resistance needs a large capacitor in parallel to deliver the necessary current.

182

MSP430 Family 4.9 Ultra-Low-Power-Design with the MSP430-Family

Metering Application Report

To get all the "Low Power"-advantages the MSP430-family can provide, some rules need to be minded. This chapter gives an overview to these rules. 4.9.1 The Ultra-Low-Power-Concept of the MSP430 A lot of microcomputer applications need to be battery-driven. It is important for these applications to run as long as possible with a small battery. To reach a battery lifetime longer than 5 years, often the configuration shown in figure 49.1 (left hand side) is used: A low-frequency oscillator feeds a prescaler that outputs a pulse every second (or in longer intervals) which sets a flip-flop. This pulse delivers the needed time base with the accuracy of the crystal. The set flip-flop switches on the supply voltage of the microcomputer. The microcomputer measures the necessary system values with an external analog-to-digital converter (necessary if the needed accuracy exceeds 8-bit) and calculates the results afterwards. The results are summed-up in an external RAM and are displayed with an external LCDdriver. After the completion of all necessary activities the microcomputer resets the flip-flop and switches off itself this way. The current consumption of the system reduces to the value that is drawn by the oscillator, the RAM and the LCD-driver.

The shown system needs a relatively big battery due to the high number of external system components (>5Ah).
Vbatt 32 kHz SVbatt x MHz 32 kHz

0V >5Ah

Vcc

Vbatt

LCD LCD Select

Osc. :2 15 1Hz

Set Q FF Reset I/O

I/O

LCD-Driver
Error kW kWh

Common

Error

kW

kWh

I/O 8-bit Micro Vbatt RAM Address/ Data

Peripherals

MSP430

SVbatt

P0.x A0 A1 A2 Vss Vdd

Peripherals

ADC I/O Vss Sensors

Sensors

0V

0.5Ah

Figure 49.1: Two Solutions for battery-driven Systems The MSP430-family allows to realize the system described above as a one-chip solution: all external components shown are on-chip peripherals. Figure 49.1 (right hand side) shows this MSP430-solution. Constantly active are only the 32kHz oscillator, 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 if necessary. The advantages of this concept are obvious:

183

Metering Application Report Smaller board possible due to reduced chip count Lower assembly cost due to less components Simplicity of design Lower current consumption (smaller power supply or battery needed) Faster development

MSP430 Family

The following examples use the current characteristic shown in figure 49.2 (these values are not guaranteed values, only approximated ones).

Nominal characteristics of LPM3 and LPM4, no peripheral module active 5 4 ICC 3 uA 2 1 0 -40 1.44 0.055 -20 1.36 0.055 0 1.35 0.05 20 Temperature - C
o

4.3 LPM3 2.8 1.6 0.1 40 1.8 1.1 0.5 60 85 LPM4 2.6

Figure 49.2: Approximated Characteristics for the Low Power Supply Currents 4.9.2 Current Consumption and Battery Lifetime To reduce the current consumption of an MSP430 system as far as possible it is necessary to use the Low Power Mode 3 nearly all the time: Basic Timer, LCD and interrupt circuitry are switched on, the CPU is switched off and is woken-up only in programmed time intervals (e.g. every second). The current consumption characteristic of such a system, that is woken-up every second and that measures and calculates every minute only, looks like follows:

184

MSP430 Family

Metering Application Report

MSP430-Current Consumption

t proc IAMAD IAM 1mA t Tim 100uA t ADC

10uA ILPM3 t2 1uA t1

n+1

n+2

n+3

n+60

n+61

Time s

Figure 49.3: Current Consumption Characteristic

Where:

t1 t2 tTim tADC tproc tLPM3

Time interval between two measurements (here 60s) Time interval between two wake-ups (here 1s) Processing time after the wake-up. Typically 25s to 1ms. (e.g. incrementing of a second counter, check if t1, elapsed) Processing time with switched-on ADC (100 to 150s per measurement) Processing time with enabled CPU. Typically 1ms to 100ms. (e.g. calculations after measurements) Time, the system runs in Low Power Mode 3

The average current Icc taken out of the battery by the MSP430 is:
ICC = 1 t1 t1 tTim IAM + tproc IAM + tADC IAMAD + t1 tTim tADC tproc ILPM3 t2 t1 t2

This may be simplified, if tTim, tADC and tproc are much shorter than t1 (normal case):
ICC 1 1 tTim IAM + (tproc IAM + tADC IAMAD) + ILPM3 t2 t1

EXAMPLE: with TA = +20C, t1 = 60s, t2 = 1s, tTim = 0,5ms, tADC = 0,15ms and tproc = 10ms a medium current Icc results:
ICC 1 1 0,5ms 0,35mA + (10ms 0,35mA + 0,15ms 0,8mA) + 1,6 A = 1,83A 1s 60s

With the above example the current consumption increases by 15% only compared to the consumption of Low Power Mode 3 (1.6A).

185

Metering Application Report

MSP430 Family

4.9.3 Minimization of the System Consumption The overall current consumption of an MSP430-system is composed of three components: 1. The consumption of the MSP430 2. The self-discharge of the battery 3. The consumption of the other system components The minimization of the current consumption of each of these three parts will be 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 if necessary. The rules for the minimization of the current consumption are: 1. Leaving of the Low Power Mode 3 (wake-up) as rarely as possible, for example only every two seconds. 2. 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, immediate return to the Low Power Mode 3. 3. The time intervals between active periods (calculations) should be as long as possible e.g. 60 seconds and longer. 4. 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 it should be switched-off. This may be supported by the use of the ADC-interrupt: the interrupt service routine of the ADC switches off the ADC supply SVcc after the completion. 5. Use of the interrupt capability of Port0 to react to external changes. The possibility of these inputs to interrupt to the leading and to the trailing edge of an input signal ensures the detection of any changes at the inputs without current-wasting polling. 6. 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. 7. Subroutine CALLs should be avoided in frequently used software parts due to the overhead they have. Instead the code should be inserted two or three times (like a MACRO). More ROM space is necessary but the needed CPU-cycles are less. 8. Short loops should be avoided due to the overhead of the loop control. Instead the loop should be enrolled to a linear code sequence. 9. For longer software parts the working registers R4 to R15 should be used. This results in shorter execution times and in less ROM space. If the above mentioned recommendations are applied, then the current consumption of the Active Mode is of second order only: the exceptionally high calculation power of 660 million instructions per Watt-second (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 Battery This part of the current consumption allows only few influence. It is necessary to follow the recommendations of the battery manufacturer. It is recommended to place the battery at a relatively

186

MSP430 Family

Metering Application Report

cool location inside of the case. That means not directly 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 2A for a 0.5Ah battery. 4.9.3.3 Current Consumption of other System Components This current is composed of different parts. The most important ones are explained. Crystal Good quality and a low frequency (32768Hz) result in a necessary driver power ranging from 1W to 10W. With a supply voltage of 3V the current consumption ranges from 333nA to 3.33A (average 1A). This current is consumed always, because the 32kHz oscillator is used for the time base. Liquid Crystal Display Good quality and a low frequency (128Hz) result in a current consumption of approx. 13nA/mm2 segment area. For an LCD with 100mm2 this means a current near one microamp (1.3A). The MSP430 allow to optimize the adaptation to the given LCD by 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 to avoid the current flowing through the internal or external pull-down resistor. Figure 49.4 shows three examples: If a contact is closed longer than a defined time, then the external pull-down resistor or the contact is switched off. From now on a regular polling is necessary to control if the contact opened again. If this is the case, the normal mode is re-installed again.

Ox,P0.y,TP.z From System 0V MSP430 +3V From System Ox,P0.y,TP.z +3V No Pull-Down Resistor 0V External Pull-Down Resistor Internal Pull-Down Resistor

Figure 49.4: Connection of Keys to Inputs Inputs of the MSP430 always should have a defined potential, otherwise a current flows inside of the input circuitry. Figure 49.4 shows three possibilities to connect an input to a defined potential.

187

Metering Application Report


MSP430 Family

Input with an internal pull-down resistor: the key is switched-off with an output. This is made by switching the output to Vss (DVss) or to Hi-Z. Input with an external pull-down resistor: the resistor itself is switched to the potential given by the switch. This means if the switch is open Vss-potential, if it is closed Vccpotential. No pull-down resistor: the switch connects to defined potentials in both positions

External circuitry (e.g. sensors) should be turned-off if not in use. This can be established by the use of the SVcc-pin. (figure 49.5 left hand side). If the current is too high for the SVcc-pin (I >10mA), then a PNP-transistor may be used for this purpose (figure 49.5 right hand side). The SVcc-pin is used then as a reference input for the analog-to-digital converter While a 1k sensor sinks 3mA when connected always to a voltage Vcc = 3V, the same sensor sinks a very low average current if connected only every 60s during the conversion time of the ADC (135s @ ADCLK = 1MHz):
Isensor = 3V 135s = 6,75nA 1k 60s

The average current through the sensor is now only 6.75nA if it is consequently switched-on only during the conversion time.
32kHz +3V

P0.x,Oy SVcc I < 10mA MSP430C32x SVcc I > 10mA

External A3 Circuitry A0

External Circuitry

AVss

AVss

DVss

DVcc

Figure 49.5: Turn-off of external Circuitries With the consumption values found out until now, the lifetime of the battery can be calculated: tBatt = Where: tBatt QBatt Icc ISys QBatt ICC + ISys

Lifetime of the battery in hours Usable charge of the battery in Ah (70% of 0,5Ah for this example) Supply current of the MSP430 in A (1,83A for this example) Current through the external circuitry (crystal, LCD, peripherals) in A (2.3A for this example)

188

MSP430 Family

Metering Application Report

For an ambient temperature TA = +20C and the consumption values calculated before the lifetime of the battery is: 0,7 0,5Ah tBatt = = 84745h 1,83A + 2,3A This number of hours is equivalent to 9.6 years. For ambient temperatures deviating from +20C the typical values for ILPM3 may be seen in figure 49.2. The exact values for the self-discharge of a battery can be found in the device specification. 4.9.4 Correct Termination of unused Pins MSP430 pins not used need to be treated in a defined manner. The list below defines the correct termination for every pin not used in a given application. The shown termination assures lowest supply current.

189

Metering Application Report PIN


MSP430 Family Comment Necessary for EPROM programming too As above. See figure 21.16 May be used as a low impedance output Switched to analog inputs: AEN.x = 0

Potential DVcc DVss open open open Vcc open open Vss open open Vss Vss Vss open open open open DVcc resp. Vcc

AVcc: AVss: SVcc: Rext: A0 to A7: Xin: Xout: XBUF: CI: TP0.0 to TP0.5: P0.0 to P0.7: R03: R13: R23: R33: S0 to S1: S3 to S20: Com0 to Com3: RST/NMI:

May be used as a digital input TP.5 switched to output direction, others to HI-Z Unused ports switched to output direction Display off: LCDM0 = 0

Switched to output direction Pull-up resistor 100k

EPROM Types:

TDO: TDI: TMS: TCK:

Pull-down Pull-down open open

68k to Vss (AVss) 68k to Vss (AVss)

ROM Types:

TDO: TDI: TMS: TCK:

open open open open

190

MSP430 Family 4.10 Controller for a Heating Installation

Metering Application Report

A very big part of the energy consumed in Europe is used for the heating of rooms. An intelligent controller for the heating installation is a good investment therefore. The controller shown in figure 410.1 has the following possibilities for the optimum alignment: Opening and closing of the mixing valve (regulates the mix of hot boiler water with the warm reflux). Control of the burner (off/on). Control of the circulation pump (off/on resp. speed control with a TRIAC). If the outdoor temperature is above a programmable limit (e.g. 20C) then the circulation pump is off always. Supervision of the boiler temperature: measurement with a temperature sensor. Supervision of all temperature sensors (feasibility checks)

The criteria for all of these decisions come from the following inputs: The measured outdoor temperature is the most important value. It is measured with an outdoor temperature sensor. 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 of the 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. 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: Self calibration of the complete system is possible: learning phase and final optimization. Exact tuning of the optimum mixing temperature due to the involvement of all relevant data 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

191

Metering Application Report

MSP430 Family

32 kHz

MON
TP0.0 Boiler Temp. Select 0V TP0.1 Outdoor Temp. 0V TP0.2 Water Temp. 0V C 0V Rref TP0.3 CIN I/O I/O I/O I/O ULN200x Common

Open mixing valve Close mixing valve Burner on Circulation pump on (TRIAC control)

MSP430C31x Keyboard n I/O Vss I/O Vdd 2 EEPROM

0V

+5V

Figure 410.1: Intelligent Heating Installation Control with the MSP430 In a very similar manner like shown for the heating installation controller of figure 410.1 for a house with more than one flat, the MSP430 can be used too in a temperature controller for a home of ones own. Figure 410.2 illustrates this example. The boiler control is made by a second MSP430 or by the shown MSP430 too (with the RS232 driver shown dotted). The room temperature selection is made with a potentiometer or with a small keyboard. Both possibilities are shown in figure 410.2.

32 kHz Room Temp. Selection TP0.0 Room Temp. Sensor Select Common TP0.1 TXD

TUE

TXD to Boiler Controller Driver RCV from Boiler Controller

RCV TP0.2 Rref C 0V CIN TP.x MSP430C31x n Keyboard I/O Vss I/O Vdd 2 EEPROM TP.y ULN200x

Burner on Pump on

0V

+5V

Figure 410.2: Heating Installation Controller for a Home of Ones own

192

MSP430 Family 4.11 Digital Motor Control

Metering Application Report

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 Digital Motor Control has some advantages compared to conventional concepts for motor control: 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 (brushless 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 length. The high speed results from the RISC-mode it uses (mainly single cycle instructions) and the involved hardware multiplier. See also chapter 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 Timer_A allowing four independent 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.8MHz and single cycle instructions if the register/register addressing mode is used for the source and the destination - the normal addressing combination for real time applications - result 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. Actually the MSP430 family consists of three different sub-families. The hardware peripherals of the different sub-families are listed in table 411.1. The instruction set is the same for all members of the family.

193

Metering Application Report Table 411.1: Peripherals of the MSP430 sub-families Hardware Item MSP430x31x MSP430x32x LCD Segment lines 23 21 14-Bit ADC No Yes Universal Timer/Port Module Yes Yes I/Os with Interrupt 8 8 I/Os without Interrupt 0 0 16-Bit Timer_A No No USART (SCI or SPI) No No HW/SW UART Yes Yes Watchdog Timer Yes Yes No No 16 16 HW-Multiplier Basic Timer Yes Yes Oscillator FLL Yes Yes LPM3 (Sleep Mode) Yes Yes LPM4 (Off Mode) Yes Yes Package 56SSOP 64QFP 4.11.1.1.1 The Low Power Modes

MSP430 Family

MSP430x33x 30 No Yes 24 16 Yes Yes Yes Yes Yes Yes Yes Yes Yes 100QFP

The MSP430 family is designed for minimum power consumption; this feature - which allows full CPU activity with only 400A current consumption (730A for the MSP430C33x) for an MCLK frequency of 1MHz - reduces the size of the power supply to a minimum. Five different Low Power Modes are implemented. The nominal supply currents IAM are shown for the MSP430C33x. The supply voltage is +5V and the temperature range is from -40 to +85C. 1. Low Power Mode 0: the CPU is switched off, the 32kHz oscillator (ACLK) the main clock MCLK (with enabled loop control) and the peripherals are active. IAM = 120A. 2. Low Power Mode 1: the CPU is switched off, ACLK, peripherals and MCLK (with disabled loop control) are active. IAM = 120A. 3. Low Power Mode 2: the CPU and MCLK are switched off, ACLK and peripherals are active. IAM = 18A. 4. Low Power Mode 3: the CPU is switched off, ACLK is active, the Basic Timer, the Watchdog and the interrupt hardware can be active (if enabled). IAM = 5.2A. 5. Low Power Mode 4: all parts of the MSP430 are off, only the RAM and the interrupt hardware are powered. IAM = 0.4A. 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-Bit Timer_A The features of the MSP430 Timer_A are very important for the pulse width modulation necessary for the Digital Motor Control. See also chapter The Timer_A for explanations of the possibilities of this timer.

194

MSP430 Family 4.11.1.3 The Universal Timer/Port Module

Metering Application Report

MSP430 family members that do not contain the Timer_A, contain at least the Universal Timer Port/Module (UTPM), a combination of two 8-bit timers with a common control unit and inputs and outputs. The Universal Timer/Port Module is primarily thought as an analog-to-digital converter 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 RC1FG) is set and an interrupt is requested. This method allows precise timings for TRIAC-control or PWM-control in the range of 128Hz to 4000Hz (repetition rate). This frequency range allows to replace PWM-control arrangements realized by relays, a solution sometimes seen in automotive applications. The Universal Timer/Port Module can be used for: Low frequency pulse width modulation (see section Low Frequency PWM): up to two independent PWM-outputs are possible. Measurement of the MCLK frequency e.g. if used without crystal (see section Use without Crystal) TRIAC triggering: time measurement starting with the zero crossing of the mains voltage Other time measurements

TPSSEL1 TPSSEL0

CMP ACLK MCLK MCLK


Event Count ACLK MCLK MCLK 0 0 1 1 0 1 0 1

0 1 2 3

0 Clk 8-bit Counter TPCNT1 EN1 Vcc LSB Data

8 Clk 8-bit Counter TPCNT2 EN2

15

RC1

RC2

Carry: Set RC2FG-Flag

MSB Data

Figure 411.1: Block Diagram of the Universal Timer/Port Module (16-Bit Timer Mode) Figure 411.2 shows the generation of a low frequency PWM with the Universal Timer/Port Module 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 256Hz repetition rate are possible. The resolution for this case is 128 steps. The formula for the period t of the PWM-frequency is:

t = t1 + t2 =

n1 + n2 fCLK

The formulas for the pulse width t1 and the corresponding value n1 are (the negative value of n1 is loaded into TPCNTx):

t1 =

n1 n1 = fCLK t1 fCLK

n2 and t2 are calculated the same way as n1 and t1.

195

Metering Application Report

MSP430 Family

0FFh -n1 -n2 0h

t2
Output

t1 td

t2

t1

t2 = n2/ACLK t1 = n1/ACLK td: Interrupt Latency and SW execution time

RC2FG

RC2FG

RC2FG

RC2FG

Interrupts

Figure 411.2: Low Frequency PWM-Timing generated with the Universal Timer/Port Module Figure 411.3 shows a solution that is synchronized by the Basic Timer (only one PWM-timing is shown): its interrupt (here with 128Hz) 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 PWM Digital-to-Analog Converter with the Universal Timer/Port Module.

TPCNTx 0FFh -n1

t (1/256Hz)

f TCNTx = 32768 Hz 128 Steps Resolution 256 Hz Repetition Rate


0h

t1
Output

t1

t1 = n1/ACLK

t = 1/fBT

td td: Interrupt Latency and SW execution time Interrupts

Basic T.

RCxFG

Basic T.

RCxFG

Figure 411.3: Low Frequency PWM-Timing by Universal Timer/Port Module and Basic Timer 4.11.1.4 The Basic Timer Additional to the timers mentioned before 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.5Hz to 65536Hz) derived from the crystal (ACLK) or the System Clock Generator (MCLK). This way the Timer_A and the Universal Timer/Port Module 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 power-up and is active immediately therefore.

196

MSP430 Family

Metering Application Report

4.11.2 Digital Motor Control with Pulse Width Modulation (PWM) Two modes of the Timer_A - 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 chapter. 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 may be used. The direction of rotation of the motor is changed by a relay which switches over 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 shown examples can use the high frequency PWM (> 15kHz) or the low frequency PWM (100 Hz and higher). The formulas for the coming circuit proposals are:

Vm =
Where: Vm Vmotor nCCRx nCCR0

nCCRx Vm Vmotor nCCRx = nCCR0 nCCR0 Vmotor

Mean voltage at the motor [V] Voltage of the motor power supply [V] Content of Compare Register x Content of Compare Register 0 (Period Register)

4.11.2.1.1 Single Output Stage with a Bipolar Power Transistor Figure 411.4 shows a single output stage with an NPN power transistor. The PWM signal generated by Timer_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 411.4 shows such a driver stage at the lower right-hand corner. A simple configuration with only a PNP and an NPN transistor is possible too: this driver stage is shown in figure 411.4 at the upper right-hand corner. The EEPROM connected to the MSP430 contains the characteristic of the controlled motor.
+5V
0V

Vcc
Error rpm

Motor Temperature

Possible Pre-Drivers: +5V

CIN TP.1
Rsens1

30+4 2

COM SEL Ports

TP.0

Rref

+600V Field Winding

TA1

BU426

EEPROM

MSP430C33x
40 I/Os 3 USART HW/SW-UART 2 P0.1/2 Vss Port4 TA1 TP.2 Ports

0V

+5V BU426 6.2V Direction of Rotation 0V

TA1

BU426

Figure 411.4: Transistor Output Stage allowing both Directions of Rotation

197

Metering Application Report Applicable for: Advantages:

MSP430 Family

- DC motors, universal motors - Minimum component count for only one direction of rotation

4.11.2.1.2 Single Output Stage with a MOSFET Power Transistor Instead of NPN power transistors it is also possible to use power MOSFETs or IGBTs. Figure 411.5 shows a circuit with a dual MOSFET TPIC2202 and the appropriate MOSFET driver SN75372. An MSP430C33x controls two PWM outputs. If the necessary calculations for the control of the motors are not too complex then it is possible to control more than two motors with a single MSP430C33x (up to four). If a change of the direction of rotation is needed then a relay can be used like shown in figure 411.4. The temperature of the motors can be observed with a temperature sensor, e.g., an NTC-sensor. Figure 411.5 shows the circuitry needed for the connection of two temperature sensors to the ADC inputs of the MSP430C33x. The motor temperatures are measured in appropriate time intervals to be sure, that normal circumstances are present. In case of a too 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 shown circuitry 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 HI-Z state to get eight different thresholds (corresponding to eight different temperatures).
+5V Vcc 0V FAULT LED TP.3 32kHz
0V

Motor Temperature

Xin Xout

CIN TP.2 TP.1 TP.0


Rref +5V +15V Vcc2 Rsens2 Rsens1

+45V

+45V
Tachometer

M1

M2

EEPROM

2 Ports

Vcc1

MSP430C33x
23 I/Os 2 ADC (Sensors) 3 USART Port4 TP.x
InpB

Drain1 InpA +5V EnA OutA Gate1

Drain2

Ports w INTRPT

TA1

SN75372 TA2
EnB OutB Gate2 Source

TPIC2202

P0.7,NMI 5 I/Os Ports w/o INTRPT Vss P0.0 P3.1 P3.2 P3.3 +
Rshunt 0V Number of Revolutions R 2R 4R

0V
Current Comparison

Figure 411.5: Control for two MOSFET Output Stages Applicable for: Advantages: - DC motors, permanently excited DC motors - Control for two motors with minimum chip count

The MOSFETs shown in figure 411.5 allow up to 7.5A continuous current simultaneously for both transistors. The TPIC2202, having only one source pin, 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 pins. For motor currents up to 3A the 15V supply for the SN75372 is not necessary, a 5V supply is sufficient then for the switch-on of the MOSFETs.

198

MSP430 Family

Metering Application Report

4.11.2.2 H-Bridge Output Stages An H-bridge means the fourfold expense for power drivers compared to a single output stage. But if integrated drivers are used then 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. 4.11.2.2.1 H-Bridges for low Motor Voltages For voltages up to 36V Texas Instruments offers several solutions. Into this range belong the automotive sector and industrial control applications working with 24V supply voltage.
4.11.2.2.1.1 Output Stage with a MOSFET Bridge

Motor control applications working with relatively low voltages can use the Texas Instruments Hbridge TPIC5424. This device is able to switch currents up to 3A at a maximum voltage of 60V. The complete circuit diagram is shown in figure 411.6. 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 5V 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: 1. PWM-output TA3 is used with the full PWM frequency (e.g. 19.2kHz) 2. PWM-output TA0 is used with the divided PWM-frequency (e.g. 9.6kHz for 19.2kHz). This is due to the only possible output mode for the Period Register CCR0: Toggle/Toggle Mode. This way has the advantage that no other timer output is needed. Figure 411.6 illustrates this solution. 3. One of the available output frequencies of the XBUF output is used: ACLK, ACLK/2 or ACLK/4 corresponding to 32.768kHz, 16.384kHz or 8192Hz. The solutions 2 and 3 have the advantage of an always usable output voltage: they are independent of the PWM output driving the electric motor. NOTE The shown power inverter BT1 may be replaced by some paralleled - not used otherwise - output ports of the MSP430C33x. They are toggled by a software routine, driven by the interrupts of the Period Register CCR0. A possible driver circuit for a pull-down output is shown on the upper left-hand corner in figure 411.6: the additional NPN transistor lowers the output impedance for the positive supply voltage +12V. This way the supply voltage Vcc2 (+18V), 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 +5V signals. This is possible because the TPIC5424 is designed for logic drive signals (0 to +5V). As shown in figure 411.6 the TPIC5424 has integrated all necessary protection diodes on-chip; therefore no external components are needed. The signals at the MOSFET gates are shown in figure 411.6 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 H-bridge halves, then the comparator output switches off the 199

Metering Application Report

MSP430 Family

lower drivers T2 and T4 and the additionally requested P0.0 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 like shown in figure 411.5. The motor temperature can be measured the same way as shown in figure 411.5. Applicable for: Advantages: - Permanently excited DC motors - Few components necessary - Both directions of rotation possible
+12V

+12V 1N914 0V

Bootstrap-Gen.
+18V 10 1uF Vcc2

0V

Vmotor +12V
0V

32kHz
Xin Xout 29 TA0 Ports 30 Select TA1

0.1uF

BT1
fPWM/2
InpA EnA

+5V Vcc1

T1
OutA

T3

TPIC5424L

SYSTEM LCD RCV TXD


3

MSP430C33x
P0.1 P0.2 TA2 Port4 P1.x +5V Vcc P1.y

+5V
EnB InpB OutB

M
T2 SN75372 T4

USART

0V

EEPROM

Ports Vss

P0.0

+
Overcurrent Detection reverse +5V 0V 0V forward reverse halt Shunt

0V

T4 Gate T2 PWM-Signals T1 T3

Figure 411.6: PWM Motor Control with a MOSFET H-Bridge


4.11.2.2.1.2 H-Bridge for a Brushless DC Motor

Figure 411.7 shows the control circuitry for a brushless DC motor. Complementary power MOSFETs are used for the output stages. The advantage of this solution is that no gate voltage above the motor voltage Vmotor is necessary. The H-bridge is switched over in dependence of a position indicator working with the Hall effect: if the change of polarity is necessary for the motor voltage then the Hall sensor requests interrupt and the MSP430 switches over the H-bridge. The necessary delay times (ts in figure 411.7 below), which prevent a short circuit in the H-bridge halves, are generated by software. If this should happen although, then the over current detection will switch off the two lower MOSFET drivers T2 and T4. The simultaneously requested interrupt

200

MSP430 Family

Metering Application Report

at input P0.0 will force the software to switch-off all of the MOSFET drivers completely until the lost synchronism is built-up again. The direction of rotation may be reversed by the change of the current flow direction relatively to the location of the rotor. This is possible because the field is generated normally with a permanent magnet (see pulse diagram in figure 411.7 lower part). The shown circuitry does not need a tachometer because the signal of the Hall sensor is usable for the measurement of the number of revolutions per second too. The TLE2144 operational amplifiers are used as MOSFET drivers with their outputs and as AND gates with their inputs. The used circuitry with the eight equal resistors allows the two control outputs P0.4 and P0.5 to switch the PWM signal to the proper MOSFET transistors: the PWMoutput TA1 is able to switch off both operational amplifier drivers and to switch on the driver prepared by P0.4 or P0.5. This solution leaves three Compare/Capture Latches for other purposes. The applied kind of control (only one half of the bridge is switched by the PWM signal, the other half is switched on in a static manner) decreases the switching losses. Applicable for: Advantages: - Brushless DC motors - Both directions of rotation possible - Robust motors without brush wear usable - Control of the motor speed without expense (Hall sensor)

Position Indication Signal

32kHz
Xin Xout Motor Hall Signal 30 P0.3 Select P0.1 P0.2 3 P0.5 P0.4 TA1

0V

0V +5V

TLE2144 T1 + T3

Vmotor 24V

LCD RCV TXD USART


+5V

8 x 100k

+ MSP430C33x

0V T2

T4

Port4 P0.6 Vcc 27 Ports P0.7

0V

+5V

I/Os EEPROM

Overcurrent Switch-off +5V P0.0,NMI Vss

Ports

+ Overcurrent Detection 0V Shunt

0V
1 Revolution

0V

HALL-Signal
ts

T4 Gate T2 T1 PWM-Signals T3 Reverse Halt Forward

Figure 411.7: PWM Motor Control for Brushless DC Motor

201

Metering Application Report

MSP430 Family

The circuitry shown in figure 411.7 may be used for other kinds of motors too. The driving signals for the H-bridge need to be changed in this case e.g. according to figure 411.6 for a DC motor. The measurement of the motor temperature is possible the same way as shown in figure 411.5.
4.11.2.2.1.3 H-Bridge with integrated Output Stages

Figure 411.8 shows an integrated H-bridge motor controller made with an L293. Two H-bridges of this type are integrated in a single package. The direction of rotation of the motor is controlled with the static output P1.1. The pulse width of the PWM output TA1 defines the effective output voltage for the motor. If the direction of rotation is changed then the PWM-signal at output TA1 needs to be inverted: the output signal that represents the highest output voltage for the forward direction means the lowest voltage for the reverse direction (see diagram in figure 411.8). This inversion can be made by software (INV dst) or by the change of the drive mode of the Output Unit. See section The Output Unit.
+24V +5V
0V

Motor Temperature

1N4934

Vcc CIN TP.1 TP.0


Rref Rsens

M
+24V
Vcc2 1Y

0V
2Y

+5V
Vcc1

TA1

1A

2A

MSP430 P1.0 P1.1 P0.0,NMI P3.1 P3.2 Vss 0V


TA1 (PWM ) P1.1 (Direction)
Halt Slowly forward Fast forward Fast reverse Slowly reverse 1,2EN GND

1/2 L293
reverse forward

Current Comparison

+
R

Rshunt 0V 0V

2R

0V

Figure 411.8: Integrated PWM Motor Control with static Direction of Rotation The motor current is observed with a threshold detection circuit (analog comparator at input P0.0); the motor current can be compared to four analog thresholds. The resistor connected to output P1.0 ensures that the enable input of the L293 is switched off during the initialization of the MSP430: no current can flow through the motor during this time. Applicable for: - Permanently excited DC motors

202

MSP430 Family Advantages:

Metering Application Report - Change of direction of rotation is included - Minimum hardware, single chip only - Built-in overheating protection - Full PWM resolution for both directions of rotation - No generation of delay times necessary (included in the L293)

+5V +24V Vcc COM SEL


Error ON rpm

1N4934

M
0V
3Y 4Y

+24V MSP430
Vcc2

+5V
Vcc1

TA1

3A

4A

P1.0 P3.0
R

3,4EN

GND

1/2 L293

Current Comparison

Rshunt 0V 0V 0V

Vss

NMI,P0.1 P3.2 0V

0V
2R

TA1 (3A) TA1 (4A)


Halt Fast reverse Fast forward Slowly forward Slowly reverse Halt

Enable (3,4EN)

Figure 411.9: Integrated PWM Motor Control with dynamic Direction of Rotation Figure 411.9 shows the L293 used with a dynamic definition of the direction of rotation: input 4A is driven always with the inverted signal of input 3A. The inverter at input 4A can be omitted if the inverted signal at 4A is generated by a second PWM-output (e.g. TA2): the appertaining Capture/Compare Latch CCR2 is always loaded with the same value as CCR1, but the inverted Output Mode of the Output Unit 1 is used (e.g. set/reset instead of reset/set). Standstill of the motor is reachable in two ways (see diagrams in figure 411.9): - With a PWM impulse ratio equal to one (left-hand side of the diagram) - By switching low of the enable input of the L293 (here P1.0, right-hand side of diagram) With the same PWM output frequency the dynamic control allows only half of the resolution when compared to the static control shown in figure 411.8: one resolution bit is necessary for the sign of the direction of rotation.

203

Metering Application Report Applicable for: Advantages:

MSP430 Family

- Permanently excited DC motors - Change of direction of rotation is included - Minimum hardware, single chip only - Built-in overheating protection - Sliding transition possible for the change of the direction of rotation - No generation of delay times necessary (included in the L293)

The two circuits shown in figure 411.8 and 411.9 may be controlled together by a single MSP430C33x: both figures can be integrated into one schematic with only slight modifications. If a lower motor current is sufficient as the current the L293 is able to deliver then the L293D may be used. Both the L293 and the L293D feature a built-in overheating protection that switches off the IC in case of over temperature. 4.11.2.2.2 H-Bridge for high Motor Voltages Electric motors with voltages above 60V need completely different driver concepts: the motor drive is then made with IGTBs most often. The voltages and currents necessary for the driving of these semiconductors are delivered from special driver ICs. These ICs contain also the necessary safety circuits. An example for such a driver circuit is shown in figure 411.10. The MSP430 defines the direction of rotation with the PWM-outputs TA1 and TA2: only one of them is active, the other one switches on the lower transistor of the other half of the bridge (static). This way the circuitry shown in figure 411.10 is able to run the motor in both directions of rotation. As supply voltage for the motor the rectified mains voltage 230V is used. The Capture/Compare Register 4 works as a capture latch: it is used for the speed measurement of the motor (input TA4).

204

MSP430 Family

Metering Application Report

COM SEL TA4 +15V

Torque

r/m

Error

Position/Speed

M1

11DF4 Vcc +5V Vcc VB3 VB2 VB1 H01 H02 H03 10uF VS3 VS2 TA2 HIN2 LIN2 +5V TA3 P0.0 Vss +5V
Overcurrent Adjustment

+325V

M2

74HC00 TA1 MSP430C33x HIN1 LIN1

IR2130

HIN3 LIN3 Fault Vss

VS1 L03 30S10 L01 L02 Itrip VS


Shunt

5 x IRGBC20S

0V

+15V 5uF

0V

TA1

TA2
Halt Slowly forward Fast forward Slowly reverse Fast reverse

only one direction of rotation possible

TA3

Figure 411.10: PWM Motors Control for high Motor Voltages The MSP430 software does not need to take care, if both transistors of one bridge half are switched on together. Built-in delay times in the IR2130 prevent this state. In case of overcurrent the built-in overcurrent detection at the input Itrip switches off the IR2130 completely: the output Fault indicates this state as well as undervoltage at the pin Vcc of the IR2130 with a LO signal. The gate voltage of the two upper power transistors, which must be higher than the motor voltage, is generated by the IR2130 with the help of a bootstrap generator. The output signals VS2 and VS1 drive this internal generator. Externally only two diodes and two storage capacitors are needed. Static operation is not possible this way, the generation of the gate voltage makes dynamic operation necessary: at least VS1 or VS2 must be active also during the standstill of the motor (lower bridge transistors off). With the unused IR2130 output LO3 a second motor M2 can be driven with the PWM output TA3. For the change of the direction of rotation a relay is necessary, the circuitry for this is shown in 205

Metering Application Report

MSP430 Family

figure 411.4. Motor M2 is driven like described in section Single Output Stage with a Transistor. The motor M2 is completely independent from the motor M1. Applicable for: Advantages: - DC motors with direct main circuit connection, universal motors - Both directions of rotation possible due to H-bridge - Direct main circuit connection possible - Built-in delay times - Full PWM resolution for both directions of rotation - High motor power possible

4.11.2.3 Three Phase Motor Control The MSP430C33x is able to control also 3-phase electric motors. This is due to the following hardware features: Three synchronized PWM outputs (Timer_A) Table processing capabilities (indirect, indirect with autoincrement and indexed addressing modes) Hardware multiplier (1616 bit) with immediate 32-bit result Up to 3.8MHz CPU frequency: 263ns execution time for single cycle instructions (register/register mode)

These features together allow the generation of three PWM output signals that are phase shifted by 120 relative to the other ones. To be not audible the repetition rate can be up to 20kHz. With a PWM frequency of 16kHz nearly 8-bit resolution is possible. The system works as follows: The repetition rate of the PWM pulses is defined by the content of the Period Register CCR0; this value is always the same. The pulse width for the three PWM signals is defined by the registers CCR1 to CCR3: each CCR controls one phase. The nominal pulse widths for the generation of a sine curve are contained in a byte table (nominal 100% values). Dependent on the angle counter the actual values are read out individually for each phase by indexed addressing. The frequency of the motor voltage is defined by the modification frequency of the angle counter. The hardware multiplier is used here for the necessary calculations. The motor voltage is defined by the modified pulse width (table value multiplied by the percentage of the voltage). The hardware multiplier is used also for this task

The complete hardware is shown in figure 411.12. The interface to the motor is made by an IR2130 motor controller. This chip includes the necessary safety functions too: overcurrent detection and the generation of the necessary dead times for the output transistors. The formula for the timer value nCCRx is:

Vm nCCRx + 0.5 nCCR0 Vm = 0.5 Vmotor nCCRx = Vmotor nCCR0


Where: Vm Vmotor nCCRx Mean voltage at the motor phases (-Vmotor/2 to +Vmotor/2) [V] Voltage of the motor power supply [V] Content of Compare Register x

206

MSP430 Family nCCR0 Applicable for:

Metering Application Report Content of Compare Register 0 (Period Register) - Three phase motors like induction motors - Open loop control method - Voltage/frequency method

Figure 411.11 shows some PWM outputs for different phase voltages.
Phase Voltage
Vmotor

+Vmmax

120

120

-Vm max

Time

Figure 411.11: PWM Outputs for different Phase Voltages Note that zero volt for a motor phase is generated by a pulse width of 0.5 relative to the period.

207

Metering Application Report

MSP430 Family

COM SEL TA4 +15V

Torque

r/m

Error Position/Speed

0V

11DF4 Vcc +5V Vcc VB3 VB2 VB1 74HC00 TA1 MSP430C33x TA2 LIN1 HIN1 VS2 LIN2 HIN2 TA3 LIN3 HIN3 P0.x Vss +5V
Overcurrent Adjustment

Vmotor

+325V

IR2130

H01 H02 H03 10uF VS3

VS1 L03 30S10 L01 L02 Vss Itrip VS


Shunt

Fault

6 x IRGBC20S

0V

+15V 5uF

0V

Figure 411.12: PWM Motors Control for high Motor Voltages 4.11.2.4 Low Frequency Pulse Width Modulation The PWM examples demonstrated in the circuits of this chapter are primarily thought for high repetition rates (16kHz and more) but a lot of motor control applications do not need these high repetition rates. For these applications the same hardware proposals may be used with an output controlled by the Universal Timer/Port Module. If fed by the ACLK (32kHz) it allows for example the following combinations: 128Hz repetition rate with a resolution of 256 steps or 256Hz repetition rate with a resolution of 128 steps 512Hz repetition rate with a resolution of 64 steps

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 and 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 the section PWM-Digital-to-Analog Converter with the Universal Timer/Port Module

208

MSP430 Family Applicable for: - All motors controllable by TRIACs - DC motors

Metering Application Report

4.11.2.5 Bandwidth of the MSP430 Solutions for PWM Control Figure 411.13 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 pins or the SW/HW UART (RS232 link). It allows relatively slow PWM frequencies (1kHz). The maximum system with the MSP430C337 is shown at the right hand side. Its capabilities allow to take over the complete system control, not only the motor handling. The PWM control for a single phase motor normally does not load the MSP430 CPU by 100%, so that in many applications the function of the host computer can be taken over by the MSP430 too, e.g., when used in a tumbler or a dish washer controller. This is especially true for the MSP430 versions having large memories and much I/O lines.
+5V +5V 3 27+4 LCD/Outputs 6 I/Os 4 Sensors SW/HW-UART 2 ADC P0.1,P0.2 Vss Port0 Vcc Select/Common USART Port4 30+4 LCD/Outputs 6 Sensors Temperature TP.y TP.x XBUF Frequency Out 0V Current Comp. 33 I/Os Keys Display LEDs Lamps Relay Drivers Counter ADC Select/Common Vcc Speed TA4 Current

MSP430C312 Power Stage

MSP430C337
TA1 Ports CIN Vss TA2 TA3 XBUF Frequency Out

Power Stages

0V

Figure 411.13: Minimum System and Maximum System with the MSP430 Family In figure 411.13 all components not absolutely necessary for the understanding are omitted. The shown hardware proposals are not only usable for the motor type named in the text, but also for other motor types if the necessary changes are made with the hardware (e.g. the adding of a Hall sensor (position indication sensor) for a brushless DC motor). If necessary the shown hardware proposals may be completed with one or more of the following features: Temperature sensors for the measurement of the motor temperature(s) Temperature sensors for the driver IC Tachometer for the measurement of the motor speed or the rotor position Inputs for light sensors (safety, movement, flame observation a.s.o.) Analog inputs for the measurement of the motor voltage (improvement of control) Connections to a host via the USART (SPI or SCI), HW/SW-UART or ports Some of the possibilities shown in figure 411.13 (keys, LEDs, relays, LCD a.s.o.) Caused by the numerous peripherals of the MSP430 family, all of these functions above may be implemented easily and with few hardware expenses.

209

Metering Application Report 4.11.3 Digital Motor Control with TRIACs

MSP430 Family

With the help of a TRIAC (TRiode for AC) the following electric motor types may be controlled: Universal motors DC motors (connected via a bridge rectifier. See figure 411.14) Capacitor motors Single phase asynchronous motors Single phase synchronous motors

The timing for the TRIAC control is possible with the Universal Timer/Port Module and the Timer_A. Both can deliver the timing in the range from 0.5ms to 20ms with the necessary resolution. 4.11.3.1 Motor Connection and Control The electric motor to be controlled may be connected to the mains directly or via a bridge rectifier. Both possibilities are shown in figure 411.14: it is possible to control AC motors as well as DC motors with a TRIAC.
220V A.C. Mains

M
230V A.C. Mains
Zero Crossing

+5V

+5V

Zero Crossing

+5V

+5V

M
Vcc TP.x SVcc INT1 Vss Ri An C 3.5V R 0V Vcc A0

MSP430C32x
P0.0 3.5V

MSP430
Vss R 0V C

Figure 411.14: TRIAC Control for AC Motors and DC Motors

The RC-combination switched in parallel to the TRIAC (see figure 411.14) prevents the turn-on of the TRIAC in case of too fast voltage changes (too large du/dt): switching transients on the mains cannot cause errors therefore. Otherwise this RC-combination reduces the generation of switching noise (EMV) strongly. With the circuitry of the left hand side of figure 411.14, the current through the TRIAC can be measured in the positive and in the 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 reasons are responsible for this:

210

MSP430 Family

Metering Application Report

1. A normal microcomputer output cannot provide the necessary current for the TRIAC-gate. This gate current is near 100mA. 2. During the triggering of the TRIAC the TRIAC gate generates a voltage that may pull the microcomputer output above or below the supply voltages Vcc resp. Vss. This may lead to the destroying of the output, to latch-up or to a hang-up of the software. Both of the above mentioned disadvantages are omitted if a simple transistor stage is included between the microcomputer output and the TRIAC gate: The current amplification of the transistor allows to deliver the necessary gate current out of the limited output current of the microcomputer The voltage range of the transistor collector withstands even strong voltage peaks generated by the TRIAC gate. Depending on the use of negative or positive gate current, an NPN- or a PNP-transistor is used. Both possibilities are shown in figure 411.15. Which circuit arrangement is better depends on the gate characteristic of the used TRIAC. The necessary gate current is normally lower if a negative going gate trigger pulse is used.
230V A.C. Mains
Zero Crossing

230V A.C. Mains


Zero Crossing

+5V

+5V

-5V

-5V

M
Vcc TP.x +5V Vss TP.x

Amplifier

P0.3

MSP430
Vss P0.0
Overcurrent Detection

Comparator

P0.3 3.5V

MSP430
Vcc P0.0
Overcurrent Detection

3.5V

0V

0V

Figure 411.15: Positive and negative TRIAC Gate Control The TRIAC-gate may be controlled in a static or in a dynamic manner: 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. Dynamic Gate Control: a sequence of short pulses (duration approx. 10s) switches on the TRIAC. If the first pulse doesnt have energy enough, then one of the following pulses will switch on the TRIAC safely. This method needs only few energy and loads the power supply therefore less. One of the MSP430 timers may be used running in the PWM mode or a setting/resetting by software can do this job.

211

Metering Application Report

MSP430 Family

Zero Crossing
t delay t delay t delay

Dynamic Control

typically 5 to 8 Pulses

Static Control

Motor Voltage

Voltages
Conduction Angle

A.C. Mains

Figure 411.16: Static and dynamic TRIAC Gate Control

The time tdelay in figure 411.16 represents the time delay measured from the zero crossing of the mains voltage to the triggering of the TRIAC. This way the conduction angle is defined. The sequence of software steps is different for the Timer_A and the Universal Timer/Port Module. Universal Timer/Port Module: The time tdelay is calculated by the MSP430 software depending on the control algorithm The negated number of cycles (MCLK or ACLK) corresponding to the result tdelay is loaded into the Counter Registers TPCNT1 and TPCNT2 after the zero crossing of the mains voltage The timer requests interrupt after the elapsed time tdelay (TPCNT2 overflows). The called interrupt handler finally triggers the TRIAC which switches the mains voltage to the load. Timer_A (Continuous Mode): The time tdelay is calculated by the MSP430 software depending on the control algorithm 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 mains voltage The Output Unit x is programmed to the mode that outputs the wished trigger pulse The CCRx requests interrupt after the elapsed time tdelay (CCRx equals the Timer Register). The Output Unit x triggers the TRIAC which switches the mains voltage to the load. 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.

212

MSP430 Family 4.11.3.3 Control Algorithms

Metering Application Report

The value to be controlled (speed/velocity, current consumption, torque) is influenced with the conduction angle of the TRIAC. This conduction angle (see figure 411.16) is defined by tdelay, the time the triggering of the TRIAC is delayed with reference to the zero crossing of the mains voltage. For the control algorithms (that need to run in real time) two different methods are used: Normal calculation of the algorithm: for this method the MSP430c33x is suited very well due to its hardware multiplier on-chip. This allows a very high calculation speed. (10 to 20 times higher than possible with an 8-bit CPU. Use of tables (especially with very high control speeds): for this method the MSP430 is also suited very well, because its addressing modes indirect indirect autoincrement and indexed allow a very simple and fast access to table values. With TRIAC controls normally everything necessary for the controlling is calculated directly. For DC machines e.g. PID control is possible without the use of characteristics due to their linear behavior. Exception: With asynchronous machines most often a voltage/frequency or a current/frequency characteristic method is used that uses description tables. These are located in the ROM (normalized form) or in an external memory. 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. 4.11.3.4.1 Non-Regulated 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, so this part may be supplied directly from the charge capacitor Cch. Figure 411.17 illustrates this way; this solution has another advantage: the two supplies are separated completely, the power part influences the control part as few as possible. The NPN-transistor may be replaced by an unused driver on the board.
Non-regulated voltage 230V A.C. Mains VC Vreg +5V +5V

M
Vcc +5V

To the AC voltage

Cch

MSP430
Vss

TP.x

0V

Figure 411.17: Non-Regulated Voltage for the TRIAC Control

213

Metering Application Report 4.11.3.4.2 Use without Crystal

MSP430 Family

Despite the relatively low cost of the 32kHz crystal it may be an advantage if this component can be left out. The TRIAC-control makes it necessary anyway to measure the mains frequency: to know the exact time of the zero crossing of the mains voltage. If no crystal is used, then the DCO frequency can be controlled by the measurement of a full mains period with one of the MSP430 timers. The formula for the calculation of the MCLK frequency fMCLK out of the timer value n and the mains frequency fmains is:

fMCLK = n k fmains
Where: fMCLK fmains n k Output frequency of the DCO Mains frequency Measurement result in the timer register Pre-divider constant of the used timer (1, 2, 4, 8) [Hz] [Hz]

The measured DCO frequency fMCLK can be adjusted to the wished value by measurements in regular time intervals. The calculated value of fMCLK is used afterwards as a time base for the TRIAC triggering. No LCD is possible if this mode is used. More details are given in the section Use without Crystal. 4.11.3.5 Bandwidth of the MSP430 Solutions for TRIAC Control Figure 411.18 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 of the 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 may be controlled also 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.
+5V MCLK,ACLK +5V 230V A.C. Mains 5 Sensors 8 I/O Ports 23 LCD,Outputs HW/SW-UART 2 Sxx P0.1,P0.2 CIN Vss XBUF MCLK,ACLK 0V TP.x Vcc +5V USART 2 HW/SW-UART P0.1,P0.2 4 Sensors EEPROMs 34 I/O Ports Keyboard Display (LCD) LEDs Lamps Relais Driver Ext. Memories Gates Jumpers Counter Input TP.x Ports TP.y TP.z 3 Port4 Vcc XBUF +5V +5V 230V A.C. Mains

MSP430C312
Ports TP.y

M1

M2

MSP430C337
Tx,CIN Vss TAy 2 PWM

Counter Input

Figure 411.18: Minimum System and Maximum System with the MSP430 Family In figure 411.18 all circuitry not necessary for the understanding is omitted.

214

MSP430 Family 4.11.4 Motor Measurements

Metering Application Report

The shown methods for the measurement of the necessary values like temperature, speed/velocity a.s.o are valid for PWM control and TRIAC control. 4.11.4.1 Overcurrent Detection Many applications make it necessary to detect increased motor current and to start provisions if 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 steps against the overcurrent e.g. the switch-off of the motor by preventing further gate triggering or by switching-off the PWM-output. 4.11.4.1.1 Threshold Detection MSP430 family members that do not have an analog-to-digital converter on-chip must simplify the overcurrent detection to the detection of a passed-over threshold value. A simple operational amplifier is used in a way, that it compares the voltage generated by the motor current over a shunt with the calculated threshold. If this fixed threshold is reached an interrupt is requested. Figure 411.19 shows this kind of overcurrent detection in its left-hand part. 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 then 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 known better, then a variable threshold like shown in figure 411.19 at the right-hand side may be used. The MSP430 defines the wished threshold by the switching of the resistors 2R and 4R. If the outputs use the high, the low and the HI-Z states, then 9 different thresholds are possible with this circuit. The NMI-input (Non-Maskable Interrupt) may be used also for the overcurrent detection: no disabling is possible and fastest response is assured.
230V A.C. Mains
Zero Crossing

230V A.C. Mains +5V +5V

+5V

+5V

M
Vcc TP.x +5V Vcc TP.x

M
+5V R P0.0
Overcurrent Detection

P0.3

MSP430
Vss P0.0
Overcurrent Detection

Comparator

MSP430
Vss Outputs

Comparator

+ 2R 0V 4R

3.5V

0V

Figure 411.19: Overcurrent Detection with Single and Multiple Thresholds 4.11.4.1.2 Current Measurement MSP430 family members having an on-chip ADC (MSP430C32x), 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 it 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 A0 to A5. The resolution at these analog inputs 215

Metering Application Report

MSP430 Family

is 305V for a supply voltage of 5V. If this is not sufficient, a simple amplifier is used. The zero point can be measured during periods with zero current. Figure 411.20 shows the measurement of the motor current.
230V AC Mains
Voltage Measurement

230V AC Mains

+5V

+5V

M
Vcc A0
Zero Crossing

TP.x SVcc Ics Ri A1 Rv Vsh C

+3V

MSP430C32x
Vss

A1:

P0.0 3.5V

+2.5V +2V

+0.5V

Vsh: 0V

0V -0.5V

Current Measurement

Figure 411.20: Motor Voltage Measurement and Current Measurement 4.11.4.2 Voltage Measurement Figure 411.20 shows at the left-hand side how to measure the mains voltage (or another voltage) if this is needed. The diode prevents a negative voltage at the analog input A0; 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 may be used: the voltage drop of Ics at a 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 mains 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 411.21 shows a simple circuit for this purpose: via a resistor with a high resistance the mains is connected to an interrupt input of the MSP430. This interrupt input is protected by a Zener diode (3.5V) which protects against too high positive or negative voltages. The two edges of the square wave input signal give a very good indication for the positive and the negative zero crossing of the mains voltage. The time error of the zero crossing due to this circuit arrangement is approx. 60s.

216

MSP430 Family
+5V Vcc
Error kW rpm

Metering Application Report

32kHz
0V

Xin Xout

CIN COM SEL TP.2 TP.1 230V A.C. Mains TP.0


Rref Rsens2 Rsens1

230V A.C. Mains Tacho Generator +5V

MSP430
SCHMITT-Trigger

+5V

M
P0.0 TP.x SVcc +5V

T
+ 0V Comparator -

Zero Crossing

+
Zero Crossing

P0.3 P0.4 Vss


Revolutions

2.7V 0V

0V

3.5V

P0.5 A1
Overcurrent Detection MotorTemp.

0V

Figure 411.21: Support Functions for the TRIAC Control A second possibility for the detection of the zero crossing is shown at the left-hand side of figure 411.21. In case of a heavy disturbed mains voltage the operational amplifier used as a Schmitttrigger will give an undisturbed zero crossing signal. 4.11.4.4 Measurement of the Motor Speed If the control of an electric motors speed is wished then a tachometer or something similar is necessary at the motors 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 if the output signal is too low. The second method is shown in figure 411.21. With the capture latches the Timer_A provides, very precise time measurements are possible. 4.11.4.5 Supervision of the Motor Temperature To avoid the overheating of the motor a temperature sensor (e.g. an NTC sensor) can be connected to the MSP430 family members which have an analog-to-digital converter on-chip. In figure 411.21 this possibility is shown for the analog input A1. Other MSP430 members can use the Universal Timer/Port Module as an analog-to-digital converter (see figure 411.21). The software has to take steps if a too high temperature is detected e.g. turn-off of the motor, turn-on of an error indication and other things more. 4.11.4.6 Change of the Direction of Rotation In figure 411.22 it is shown how the direction of rotation may be changed for a universal motor (single phase series commutator motor): the field winding is changed over with a relay having two change over contacts. The same way the motor winding may be changed over.

217

Metering Application Report

MSP430 Family

230V A.C. Mains +5V 6 I/O Ports 23 LCD,Outputs 2 SW/HW-UART P0.1,P0.2 Vss TP.1 6.8V Direction of Rotation P0 Vcc TP.0 +5V Feld Winding

MSP430C312
Sxxx

+5V

Figure 411.22: Change of the Direction of Rotation for a Universal Motor

4.11.5 Conclusion The shown application examples 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 on-chip hardware modules like analog-to-digital converter, I/O ports and other helpful peripherals ease the task additionally. The total software compatibility of the MSP430 family members allows to use the developed software also with other family members. Table 411.4 gives an overview over the capabilities of the MSP430 sub-families: Table 411.4: Capabilities of the MSP430 sub-families MSP430x31x MSP430x32x Capability 20kHz PWM Control No No Slow PWM Control (< 1kHz) Yes Yes TRIAC Control Yes Yes Single Phase PWM Motor Control Yes Yes Three Phase PWM Motor Control No No Voltage/Current Measurement No Yes Voltage/Current Comparison Yes Yes Temperature Measurement Yes Yes Speed Measurement Yes Yes

MSP430x33x Yes Yes Yes Yes Yes No Yes Yes Yes

218

MSP430 Family

Metering Application Report

Third Part of the Metering Application Report UG430.DOC V3.0.1 13.4.97 Final Version __ 219 5 SOFTWARE APPLICATIONS ________________________________________________ 224
5.1 Integer Calculation Subroutines ___________________________________________________ 224
5.1.1 Unsigned Multiplication 16 x 16-bits ______________________________________________________ 5.1.1.1 Run Time optimized unsigned Multiplication 16 x 16-bits__________________________________ 5.1.2 Signed Multiplication 16 x 16 ___________________________________________________________ 5.1.3 Unsigned Multiplication 8 x 8-bits ________________________________________________________ 5.1.4 Signed Multiplication 8 x 8-bits __________________________________________________________ 5.1.5 Unsigned Division 32/16-bits ____________________________________________________________ 5.1.6 Shift Routines ________________________________________________________________________ 5.1.7 Square Root _________________________________________________________________________ 5.1.8 Signed and unsigned 32-bit Compares _____________________________________________________ 5.1.9 Random Number Generation ____________________________________________________________ 5.1.10 Rules for the Integer Subroutines ________________________________________________________ 224 226 227 229 230 232 233 234 235 236 238

5.2 Table Processing ________________________________________________________________ 241


5.2.1 Two dimensional Tables________________________________________________________________ 243 5.2.2 Three dimensional Tables_______________________________________________________________ 248

5.3 Signal Averaging and Noise Cancellation ____________________________________________ 251


5.3.1 5.3.2 5.3.3 5.3.4 5.3.5 5.3.6 5.4.1 5.4.2 5.4.3 5.4.4 Oversampling ________________________________________________________________________ Continuous Averaging _________________________________________________________________ Weighted Summation __________________________________________________________________ Wave Digital Filtering _________________________________________________________________ Rejection of Extremes__________________________________________________________________ Synchronization of the Measurement to Hum________________________________________________ Active Mode _________________________________________________________________________ Normal Mode is Low Power Mode 3 ______________________________________________________ Normal Mode is Low Power Mode 4 ______________________________________________________ Recommendations for Real Time Applications ______________________________________________ 251 252 253 253 254 255 258 258 258 258 260 261 261 262 263 264 264 266 267 269 269 273 275 275 277 279 280 281 282 282 283 284 286

5.4 Real Time Applications___________________________________________________________ 258

5.5 General Purpose Subroutines______________________________________________________ 260


5.5.1 Initialization _________________________________________________________________________ 5.5.2 RAM clearing Routine _________________________________________________________________ 5.5.3 Binary to BCD Conversion______________________________________________________________ 5.5.4 BCD to Binary _______________________________________________________________________ 5.5.5 Keyboard Scan _______________________________________________________________________ 5.5.6 Temperature Calculations for Sensors _____________________________________________________ 5.5.6.1 Table Processing for Sensor Calculations_______________________________________________ 5.5.6.2 Algorithms for Sensor Calculations ___________________________________________________ 5.5.6.3 Coefficient Calculation for the Equations _______________________________________________ 5.5.7 Data Security Applications ______________________________________________________________ 5.5.7.1 Data Encryption Standard (DES) Routines______________________________________________ 5.5.7.2 Output Sequence for 19.2kHz Bi-Phase Space Code ______________________________________ 5.5.8 Status/Input Matrix ____________________________________________________________________ 5.5.8.1 Matrix with few valid Combinations___________________________________________________ 5.5.8.2 Matrix with valid Combinations only __________________________________________________ 5.6.1 General _____________________________________________________________________________ 5.6.2 Common Conventions _________________________________________________________________ 5.6.3 The Basic Arithmetic Operations _________________________________________________________ 5.6.3.1 Addition ________________________________________________________________________ 5.6.3.2 Subtraction ______________________________________________________________________ 5.6.3.3 Multiplication ____________________________________________________________________ 5.6.3.4 Division_________________________________________________________________________ 5.6.3.5 Error Handling ___________________________________________________________________

5.6 The Floating Point Package _______________________________________________________ 279

219

Metering Application Report

MSP430 Family
286 287 288 288 288 289 290 290 291 291 291 292 292 295 296 297 297 298 298 299 299 300 300 301 301 302 302 304 307 307 307 308 308 309 310 310 312 316 320 324 327 330 330 331 332 333 334 336 338 338 342 345 347

5.6.3.6 Stack Allocation __________________________________________________________________ 5.6.3.7 Number Range and Resolution _______________________________________________________ 5.6.3.7.1 .FLOAT Format ______________________________________________________________ 5.6.3.7.2 .DOUBLE Format_____________________________________________________________ 5.6.4 Calling Conventions for the Comparison ___________________________________________________ 5.6.5 Internal Data Representation ____________________________________________________________ 5.6.5.1 Computation of the Mantissa M ______________________________________________________ 5.6.5.2 Computation of the Exponent E ______________________________________________________ 5.6.6 Execution Cycles _____________________________________________________________________ 5.6.7 Conversion Routines___________________________________________________________________ 5.6.7.1 General _________________________________________________________________________ 5.6.7.2 Conversions _____________________________________________________________________ 5.6.7.2.1 Binary to Floating Point Conversions ______________________________________________ 5.6.7.2.2 Binary Coded Decimal to Floating Point Conversion __________________________________ 5.6.7.2.3 Floating Point to Binary Conversion_______________________________________________ 5.6.7.2.4 Floating Point to Binary Coded Decimal Conversion __________________________________ 5.6.7.3 Handling of non-integer Numbers_____________________________________________________ 5.6.7.3.1 Binary to Floating Point Conversion_______________________________________________ 5.6.7.3.2 Binary Coded Decimal to Floating Point Conversion __________________________________ 5.6.7.3.3 Floating Point to Binary Conversion_______________________________________________ 5.6.7.3.4 Floating Point to Binary Coded Decimal Conversion __________________________________ 5.6.7.4 Rounding and Truncation ___________________________________________________________ 5.6.7.5 Execution Cycles _________________________________________________________________ 5.6.8 Memory Requirements of the Floating Point Package _________________________________________ 5.6.9 Inclusion of the Floating Point Package into the Customer Software ______________________________ 5.6.10 Software Examples ___________________________________________________________________ 5.6.10.1 Square Root Subroutines___________________________________________________________ 5.6.10.2 Cubic Root Subroutines ___________________________________________________________ 5.6.10.3 Fourth Root Subroutine____________________________________________________________ 5.6.10.4 Other Root Subroutines____________________________________________________________ 5.6.10.5 Calculations with Intermediate Results ________________________________________________ 5.6.10.6 Absolute Value of a Number _______________________________________________________ 5.6.10.7 Change of the Sign of a Number_____________________________________________________ 5.6.10.8 Integer Value of a Number _________________________________________________________ 5.6.10.9 Fractional Part of a Number ________________________________________________________ 5.6.10.10 Approximation of Integrals________________________________________________________ 5.6.10.11 Statistical Calculations ___________________________________________________________ 5.6.10.12 Complex Calculations ____________________________________________________________ 5.6.10.13 Trigonometric and Hyperbolic Functions _____________________________________________ 5.6.10.14 Other Trigonometric and Hyperbolic Functions ________________________________________ 5.6.10.15 Faster Approximations for Trigonometric Functions ____________________________________ 5.7.1 Battery Check ________________________________________________________________________ 5.7.1.1 Battery Check with the 14-Bit Analog-to-Digital Converter_________________________________ 5.7.1.1.1 Battery Check with a Reference Measurement _______________________________________ 5.7.1.1.2 Battery Check with the Calculation of the Voltage ____________________________________ 5.7.1.1.3 Battery Check with a fixed Value for Comparison ____________________________________ 5.7.1.2 Battery Check with an external Comparator _____________________________________________ 5.7.1.3 Battery Check with the Universal Timer/Port Module _____________________________________ 5.7.2 Power Fail Detection __________________________________________________________________ 5.7.2.1 Power Fail Detection by Observation of the Charge Capacitor ______________________________ 5.7.2.2 Power Fail Detection with the Watchdog _______________________________________________ 5.7.2.3 Power Fail Detection with a Supply Voltage Supervisor ___________________________________ 5.7.3 Conclusion __________________________________________________________________________

5.7 Battery Check and Power Fail Detection ____________________________________________ 330

6 ON-CHIP PERIPHERALS ___________________________________________________ 349


6.1 The Basic Timer_________________________________________________________________ 349

220

MSP430 Family
6.1.1 6.1.2 6.1.3 6.1.4

Metering Application Report


350 351 353 355

Change of the Basic Timer Frequency _____________________________________________________ Elimination of the Crystal Tolerance ______________________________________________________ Clock Subroutines_____________________________________________________________________ The Basic Timer used as a 16-Bit Timer ___________________________________________________

6.2 The Watchdog Timer ____________________________________________________________ 357


6.2.1 Supervision of one Task with the Watchdog ________________________________________________ 357 6.2.2 Supervision of multiple Tasks with the Watchdog ____________________________________________ 357

6.3 The 16-Bit Timer_A _____________________________________________________________ 361


6.3.1 The Timer Register TAR _______________________________________________________________ 6.3.2 The Period Register CCR0 ______________________________________________________________ 6.3.3 The Capture/Compare Registers CCR1 to CCR4 _____________________________________________ 6.3.4 The Timer Vector Register TAIV_________________________________________________________ 6.3.5 Control Registers _____________________________________________________________________ 6.3.6 The Output Units _____________________________________________________________________ 6.3.7 The Timer_A Modes __________________________________________________________________ 6.3.7.1 The Continuous Mode _____________________________________________________________ 6.3.7.2 The Up-Mode ____________________________________________________________________ 6.3.7.3 The Up-Down Mode_______________________________________________________________ 6.3.7.4 The Stop Mode ___________________________________________________________________ 6.3.7.5 Use of the Modes _________________________________________________________________ 361 362 362 362 363 363 364 364 366 367 368 368

6.4 The Hardware Multiplier _________________________________________________________ 370


6.4.1 Hints for the Hardware Multiplier ________________________________________________________ 370 6.4.2 The Sum Extension Register_____________________________________________________________ 370

6.5 The System Clock Generator ______________________________________________________ 372


6.5.1 Initialization _________________________________________________________________________ 6.5.1.1 First Setting of the DCO Taps during Initialization _______________________________________ 6.5.2 Entering of Low Power Mode 3 __________________________________________________________ 6.5.3 Wake-up from Interrupts in Low Power Mode 3 _____________________________________________ 6.5.4 Adaptation of the DCO Tap during Calculations _____________________________________________ 6.5.5 Wake-up from Interrupts in Low Power Mode 4 _____________________________________________ 6.5.6 Change of the System Frequency _________________________________________________________ 6.5.7 The Modulation Bit M _________________________________________________________________ 6.5.8 Use without Crystal ___________________________________________________________________ 6.5.9 High System Frequencies together with the 14-bit ADC _______________________________________ 6.5.10 Dependencies of the System Clock Generator ______________________________________________ 6.5.11 Short Time Accuracy of the System Clock Generator ________________________________________ 6.6.1 Description of the MSP430 RESET-Function _______________________________________________ 6.6.1.1 The Power-On Reset Signal _________________________________________________________ 6.6.1.2 The Power-Up Clear Signal _________________________________________________________ 6.6.1.3 Common Operations for Power-Up and Power-On Reset___________________________________ 6.6.1.4 Differences between Power-Up and Power-On Reset______________________________________ 6.6.1.4.1 Special to the Power-On Reset Signal______________________________________________ 6.6.1.4.2 Special to the Power-Up Clear Signal______________________________________________ 6.6.1.5 The RST/NMI-Pin Hardware ________________________________________________________ 6.6.2 RESET with the internal Hardware including the Watchdog ____________________________________ 6.6.2.1 Restrictions ______________________________________________________________________ 6.6.2.2 Start-up of the Crystal ______________________________________________________________ 6.6.3 Secure RESET with slowly coming-up Power Supplies ________________________________________ 6.6.3.1 RESET with a Key ________________________________________________________________ 6.6.3.2 PNP-Transistor with Zener Diode_____________________________________________________ 6.6.3.3 Operational Amplifier with Reference Diode ____________________________________________ 6.6.3.4 Supply Voltage Supervisors _________________________________________________________ 6.6.3.4.1 TL7701 Supply Voltage Supervisor _______________________________________________ 6.6.3.4.2 TP3750 Supply Voltage Supervisor and Regulator____________________________________ 372 372 372 373 373 373 374 374 375 375 375 376 380 380 381 381 381 382 382 382 383 383 383 384 384 384 385 387 388 389

6.6 The RESET-Function ____________________________________________________________ 380

221

Metering Application Report

MSP430 Family

6.6.4 Conclusion __________________________________________________________________________ 390

6.7 The Universal Timer/Port Module __________________________________________________ 391


6.7.1 Universal Timer/Port used as an Analog-to-Digital Converter___________________________________ 6.7.2 Universal Timer/Port used as a Timer _____________________________________________________ 6.7.2.1 Continuous Mode _________________________________________________________________ 6.7.2.2 Pulse Width Modulation Mode_______________________________________________________ 391 391 391 392

7 HINTS AND RECOMMENDATIONS __________________________________________ 393


7.1 Design Checklist_________________________________________________________________ 398 7.2 Most often occurring Software Errors ______________________________________________ 399 7.3 Most often occurring Hardware Errors _____________________________________________ 402 7.4 Checklist for Problems ___________________________________________________________ 403
7.4.1 Hardware related Problems______________________________________________________________ 403 7.4.2 Software related Problems ______________________________________________________________ 403

7.5 Run Time Estimation ____________________________________________________________ 404

8 ARCHITECTURE AND INSTRUCTION SET ___________________________________ 405


8.1 Introduction ____________________________________________________________________ 405 8.2 Reasons for the Popularity of the MSP430 ___________________________________________ 405
8.2.1 Orthogonality ________________________________________________________________________ 8.2.2 Addressing Modes ____________________________________________________________________ 8.2.2.1 Register Addressing _______________________________________________________________ 8.2.2.2 Indirect Register Addressing_________________________________________________________ 8.2.2.3 Indirect Register Addressing with Autoincrement ________________________________________ 8.2.2.4 Indexed Addressing _______________________________________________________________ 8.2.2.5 Immediate Addressing ______________________________________________________________ 8.2.2.6 Symbolic Addressing ______________________________________________________________ 8.2.2.7 Absolute Addressing_______________________________________________________________ 8.2.3 RISC Architecture without RISC Disadvantages _____________________________________________ 8.2.4 Constant Generator ____________________________________________________________________ 8.2.5 Status Bits___________________________________________________________________________ 8.2.6 Stack Processing ______________________________________________________________________ 8.2.7 Usability of the Jumps _________________________________________________________________ 8.2.8 Byte and Word Processor _______________________________________________________________ 8.2.9 High Register Count ___________________________________________________________________ 8.2.10 Emulation of non-implemented Instructions________________________________________________ 8.2.11 No Paging __________________________________________________________________________ 8.3.1 8.3.2 8.3.3 8.3.4 8.3.5 Less Program Space ___________________________________________________________________ Shorter Programs _____________________________________________________________________ Reduced Development Time ____________________________________________________________ Effective Code without Compressing ______________________________________________________ Optimum C Code _____________________________________________________________________ 405 406 407 407 407 408 408 408 409 409 409 410 410 410 411 411 412 412 413 413 413 413 413 414 414 415 415 416

8.3 Effects and Advantages of the MSP430 Architecture __________________________________ 413

8.4 The MSP430 Instruction Set_______________________________________________________ 414


8.4.1 Implemented Instructions _______________________________________________________________ 8.4.1.1 Two Operand Instructions___________________________________________________________ 8.4.1.2 Single Operand Instructions _________________________________________________________ 8.4.1.3 Conditional Jumps ________________________________________________________________ 8.4.2 Emulated Instructions __________________________________________________________________

8.5 Benefits ________________________________________________________________________ 417


8.5.1 High Processing Speed _________________________________________________________________ 417 8.5.2 Small CPU area ______________________________________________________________________ 417

222

MSP430 Family
8.5.3 8.5.4 8.5.5 8.5.6 8.5.7

Metering Application Report


418 418 418 418 418

High ROM Efficiency__________________________________________________________________ Easy Software Development_____________________________________________________________ Usability in the Future _________________________________________________________________ Flexibility of the Architecture____________________________________________________________ Usable for modern Programming Techniques _______________________________________________

8.6 Conclusion _____________________________________________________________________ 418

APPENDIX __________________________________________________________________ 419 A1 CPU REGISTERS _________________________________________________________ 419


A1.1 The Program Counter R0 _______________________________________________________ 419 A1.2 Stack Processing _______________________________________________________________ 419
A1.2.1 Usage of the System Stack Pointer R1____________________________________________________ 419 A1.2.2 Software Stacks _____________________________________________________________________ 420

A1.3 Byte and Word Handling ________________________________________________________ 420 A1.4 Constant Generator ____________________________________________________________ 421 A1.5 Addressing ____________________________________________________________________ 422 A1.6 Program Flow Control __________________________________________________________ 423
A1.6.1 A1.6.2 A1.6.3 A1.6.4 Computed Branches and Calls __________________________________________________________ Nesting of Subroutines________________________________________________________________ Nesting of Interrupts _________________________________________________________________ Jumps _____________________________________________________________________________ 423 424 424 424

A2 SPECIAL CODING TECHNIQUES __________________________________________ 426


A2.1 Conditional Assembly___________________________________________________________ 426 A2.2 Position Independent Code ______________________________________________________ 427
A2.2.1 Referencing of Code inside Position Independent Code ______________________________________ 427 A2.2.2 Referencing of Code outside of PIC (Absolute) ____________________________________________ 428

A2.3 Reentrant Code ________________________________________________________________ 429 A2.4 Recursive Code ________________________________________________________________ 430 A2.5 Flag Replacement by Status Usage ________________________________________________ 430 A2.6 Argument Transfer with Subroutine Calls _________________________________________ 432
A2.6.1 Arguments on the Stack _______________________________________________________________ 432 A2.6.2 Arguments following the Subroutine Call _________________________________________________ 434 A2.6.3 Arguments in Registers _______________________________________________________________ 434

A2.7 Interrupt Vectors in RAM _______________________________________________________ 435

223

Metering Application Report

MSP430 Family

5 SOFTWARE APPLICATIONS
5.1 Integer Calculation Subroutines Integer routines have important advantages compared to all other calculation subroutines: 1. Speed: 2. ROM space: 3. Adaptability: Highest speed is possible especially if no loops are used Least ROM space is needed for these subroutines 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 may be changed if necessary. ; Integer Subroutines Definitions: Software Multiply ; IRBT .EQU R9 ; Bit test register MPY IROP1 .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 ; ; Hardware Multiplier ; ResLo .EQU 013Ah ; HW_MPYer: Result reg. LSBs ResHi .EQU 013Ch ; Result register MSBs SumExt .EQU 013Eh ; Sum Ext. Register All multiplication subroutines shown below permit two different modes: 1. The normal multiplication: the result of the multiplication is placed into the result registers 2. The "Multiplication and Accumulation" function (MAC): the result of the multiplication is added to the previous content of the result registers. 5.1.1 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 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 below:

224

MSP430 Family
15 R9 IRBT 0

Metering Application Report

Bit Test Register

R4 IROP1

Multiplicand

R6 IROP2M

R5 IROP2L

Multiplier

R8 IRACM

R7 IRACL

Accumulated Result

Figure 51.1: 16 x 16 Bit Multiplication : Register Use ; EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES @ 1MHZ): ; TASK MACU MPYU EXAMPLE ;------------------------------------------------------------; MINIMUM 132 134 00000h x 00000h = 000000000h ; MEDIUM 148 150 0A5A5h x 05A5Ah = 03A763E02h ; MAXIMUM 164 166 0FFFFh x 0FFFFh = 0FFFE0001h ; UNSIGNED MULTIPLY SUBROUTINE: ; ; USED REGISTERS IROP1, IROP2L, ; MPYU CLR IRACL CLR IRACM IROP1 x IROP2L -> IRACM/IRACL IROP2M, IRACL, IRACM, IRBT ; 0 -> LSBs RESULT ; 0 -> MSBs RESULT

; UNSIGNED MULTIPLY AND ACCUMULATE SUBROUTINE: ; (IROP1 x IROP2L) + IRACM|IRACL -> IRACM|IRACL ; MACU CLR IROP2M ; MSBs MULTIPLIER MOV #1,IRBT ; BIT TEST REGISTER L$002 BIT IRBT,IROP1 ; TEST ACTUAL BIT JZ L$01 ; IF 0: DO NOTHING ADD IROP2L,IRACL ; IF 1: ADD MULTIPLIER TO RESULT ADDC IROP2M,IRACM L$01 RLA IROP2L ; MULTIPLIER x 2 RLC IROP2M ; ; RLA IRBT ; NEXT BIT TO TEST JNC L$002 ; IF BIT IN CARRY: FINISHED RET If the hardware multiplier is implemented then the above 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 of the multiplication. The SumExt 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 ; 225

Metering Application Report MPYU .MACRO MOV MOV .ENDM arg1,arg2 arg1,&0130h arg2,&0138h ; Unsigned MPY 16x16

MSP430 Family

; Result in ResHi|ResLo

; ; 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 contents located in a table, R6 points to ; MOV #ResLo,R5 ; Pointer to LSBs of result MPYU @R6+,@R6 ; CALL the MPYU macro NOP ; NOP: allow completion of MPYU MOV @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 ; MACU .MACRO arg1,arg2 ; Unsigned MAC 16x16 MOV arg1,&0134h ; Carry in SumExt MOV arg2,&0138h .ENDM ; Result in SumExt|ResHi|ResLo ; ; Multiply and accumulate the contents of two registers ; MPYU R5,R6 ; Initialize SumExt|ResHi|ResLo MACU IROP1,IROP2L ; Add IROP1 x IROP2 to result ADC &SumExt,RAM ; Add carry to RAM extension ; 5.1.1.1 Run Time optimized unsigned Multiplication 16 x 16-bits If the operands of the multiplication subroutine are normally shorter than 16 bits then the multiplication subroutine MPYU shown before can be run time optimized: The multiplication stops immediately after the operand IROP1 gets zero; this means that the operand with leading zeroes should be in IROP1. This run time optimized subroutine may be used everywhere instead of the normal subroutine. (The subroutine was developed by Leslie Mable/UK). ; ; EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES @ 1MHZ): ; TASK MACU MPYU IROP1 IROP2 ;------------------------------------------------------------; MINIMUM 18 20 00000h x 00000h = 000000000h ; MEDIUM 90 92 000FFh x 0FFFFh = 000FEFF01h ; MAXIMUM 170 172 0FFFFh x 0FFFFh = 0FFFE0001h ; UNSIGNED MULTIPLY SUBROUTINE (Run time optimized): ; IROP1 x IROP2L -> IRACM|IRACL ;

226

MSP430 Family

Metering Application Report

; USED REGISTERS IROP1, IROP2L, IROP2M, IRACL, IRACM ; MPYU CLR IRACL ; 0 -> LSBs RESULT CLR IRACM ; 0 -> MSBs RESULT ; UNSIGNED MULTIPLY AND ACCUMULATE SUBROUTINE: ; (IROP1 x IROP2L) + IRACM|IRACL -> IRACM|IRACL ; MACU CLR IROP2M ; MSBs MULTIPLIER L$002 BIT #1,IROP1 ; TEST ACTUAL BIT (LSB) JZ L$01 ; IF 0: DO NOTHING ADD IROP2L,IRACL ; IF 1: ADD MULTIPLIER TO RESULT ADDC IROP2M,IRACM L$01 RLA IROP2L ; Double MULTIPLIER IROP2 RLC IROP2M ; ; RRC IROP1 ; Next bit of IROP1 to LSB JNZ L$002 ; If IROP1 = 0: finished RET 5.1.2 Signed Multiplication 16 x 16 The following subroutine performs a signed 16 x 16-bit multiplication (label MPYS) or "Multiplication and Accumulation" (label 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 use is the same as with the unsigned multiplication; Figure 51.1 is therefore also valid. ; EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES @ 1MHZ): ; TASK MACS MPYS EXAMPLE ;------------------------------------------------------------; MINIMUM 138 140 00000h x 00000h = 000000000h ; MEDIUM 155 157 0A5A5h x 05A5Ah = 0E01C3E02h ; MAXIMUM 172 174 0FFFFh x 0FFFFh = 000000001h ; SIGNED MULTIPLY SUBROUTINE: IROP1 x IROP2L -> IRACM|IRACL ; ; USED REGISTERS IROP1, IROP2L, IROP2M, IRACL, IRACM, IRBT MPYS CLR CLR IRACL IRACM ; 0 -> LSBs RESULT ; 0 -> MSBs RESULT

; SIGNED MULTIPLY AND ACCUMULATE SUBROUTINE: ; (IROP1 x IROP2L) + IRACM|IRACL -> IRACM|IRACL ; MACS TST IROP1 ; MULTIPLICAND NEGATIVE ? JGE L$001 SUB IROP2L,IRACM ; YES, CORRECT RESULT REGISTER L$001 TST IROP2L ; MULTIPLIER NEGATIVE ? JGE MACU SUB IROP1,IRACM ; YES, CORRECT RESULT REGISTER ; THE REMAINING PART IS EQUAL TO THE UNSIGNED MULTIPLICATION

227

Metering Application Report

MSP430 Family

MACU L$002

L$01 ;

CLR MOV BIT JZ ADD ADDC RLA RLC RLA JNC RET

IROP2M #1,IRBT IRBT,IROP1 L$01 IROP2L,IRACL IROP2M,IRACM IROP2L IROP2M IRBT L$002

; ; ; ; ;

MSBs MULTIPLIER BIT TEST REGISTER TEST ACTUAL BIT IF 0: DO NOTHING IF 1: ADD MULTIPLIER TO RESULT

; MULTIPLIER x 2 ; ; NEXT BIT TO TEST ; IF BIT IN CARRY: FINISHED

If the hardware multiplier is implemented then the above 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 of the multiplication. The SumExt Register contains the sign of the result in ResHi and ResLo: 0000h (positive result) or 0FFFFh (negative result). ; Macro Definition for the signed multiplication 16 x 16 bits ; MPYS .MACRO arg1,arg2 ; Signed MPY 16x16 MOV arg1,&0132h MOV arg2,&0138h .ENDM ; Result in SumExt|ResHi|ResLo ; ; Multiply the contents of two registers ; MPYS IROP1,IROP2 ; CALL the MPYS macro MOV &ResLo,R6 ; Fetch LSBs of result MOV &ResHi,R7 ; Fetch MSBs of result MOV &SumExt,R8 ; Fetch Sign of result ; ; Multiply the contents located in a table, R6 points to ; MOV #ResLo,R5 ; Pointer to LSBs of result MPYS @R6+,@R6 ; CALL the MPYS macro NOP ; NOP: allow completion of MPYS MOV @R5+,R7 ; Fetch LSBs of result MOV @R5+,R8 ; Fetch MSBs of result MOV @R5,R9 ; Fetch sign of result ; ; 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 arg1,arg2 ; Signed MAC 16x16

228

MSP430 Family MOV MOV ADD ADDC ADDC .ENDM arg1,&0132h arg2,&0138h &ResLo,MAClo &ResHi,MACmid &SumExt,MAChi

Metering Application Report ; Signed MPY is used ; Add LSBs to result ; Add MSBs to result ; Add SumExt to MSBs ;

; ; Multiply and accumulate signed the contents of two tables ; MACS 2(R6),@R5+ ; CALL the MACS macro .... ; Accumulation is yet made ; 5.1.3 Unsigned Multiplication 8 x 8-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 of the multiplication to the contents of the result register. The upper bytes of IROP1 and IROP2L must be zero when the subroutine is called; the MOV.B instruction used for the loading ensures this. The register use is shown below:
15 00 R9 R4 0 Bit Test Register IRBT

00

Multiplicand

IROP1

00 R7

R5

Multiplier

IROP2L

Accumulated Result IRACL

Figure 51.2: 8 x 8 Bit Multiplication : Register use ; EXECUTION TIMES FOR REGISTERS CONTENTS (CYCLES @ 1MHZ): ; TASK MACU8 MPYU8 EXAMPLE ;------------------------------------------------------------; MINIMUM 58 59 000h x 000h = 00000h ; MEDIUM 62 63 0A5h x 05Ah = 03A02h ; MAXIMUM 66 67 0FFh x 0FFh = 0FE01h ; UNSIGNED BYTE MULTIPLY SUBROUTINE: IROP1 x IROP2L -> IRACL ; ; USED REGISTERS IROP1, IROP2L, IRACL, IRBT ; MPYU8 CLR IRACL ; 0 -> RESULT ; ; UNSIGNED BYTE MULTIPLY AND ACCUMULATE SUBROUTINE: ; (IROP1 x IROP2L) +IRACL -> IRACL ; MACU8 MOV #1,IRBT ; BIT TEST REGISTER 229

Metering Application Report L$002 L$01 BIT JZ ADD RLA RLA.B JNC RET IRBT,IROP1 L$01 IROP2L,IRACL IROP2L IRBT L$002 ; ; ; ; ; ;

MSP430 Family TEST ACTUAL BIT IF 0: DO NOTHING IF 1: ADD MULTIPLIER TO RESULT MULTIPLIER x 2 NEXT BIT TO TEST IF BIT IN CARRY: FINISHED

If the hardware multiplier is implemented then the above 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 of the multiplication. If byte instructions are used for the load of the multiplier registers, then the high byte is cleared like a CPU register. ; Macro Definition for the unsigned multiplication 8 x 8 bits ; MPYU8 .MACRO arg1,arg2 ; Unsigned MPY 8x8 MOV.B arg1,&0130h ; 00xx to 0130h MOV.B arg2,&0138h ; 00yy to 0138h .ENDM ; 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 ; 00xx MOV.B arg2,&0138h ; 00yy .ENDM ; Result in SumExt|ResHi|ResLo ; ; Multiply and accumulate the low bytes of two registers ; MACU8 IROP1,IROP2 ; CALL the MACU8 macro 5.1.4 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 subroutine adds the result of the multiplication to the contents of the result register. The register usage is the same as with the unsigned 8 x 8 multiplication; Figure 51.2 is therefore also valid. The part starting with label MACU8 is the same as used with the unsigned multiplication. ; EXECUTION TIMES FOR REGISTER CONTENTS (CYCLES @ 1MHZ): ; TASK MACS8 MPYS8 EXAMPLE

230

MSP430 Family

Metering Application Report

;------------------------------------------------------------; MINIMUM 64 65 000h x 000h = 00000h ; MEDIUM 75 76 0A5h x 05Ah = 0E002h ; MAXIMUM 86 87 0FFh x 0FFh = 00001h ; SIGNED BYTE MULTIPLY SUBROUTINE: IROP1 x IROP2L -> IRACL ; ; USED REGISTERS IROP1, IROP2L, IRACL, IRBT ; MPYS8 CLR IRACL ; 0 -> RESULT ; ; SIGNED BYTE MULTIPLY AND ACCUMULATE SUBROUTINE: ; (IROP1 x IROP2L) +IRACL -> IRACL ; MACS8 TST.B IROP1 ; MULTIPLICAND NEGATIVE ? JGE L$101 ; NO SWPB IROP2L ; YES, CORRECT RESULT SUB IROP2L,IRACL SWPB IROP2L ; RESTORE MULTIPLICATOR ; L$101 TST.B IROP2L ; MULTIPLICATOR NEGATIVE ? JGE MACU8 SWPB IROP1 ; YES, CORRECT RESULT SUB IROP1,IRACL SWPB IROP1 ; ; THE REMAINING PART IS THE UNSIGNED MULTIPLICATION ; MACU8 MOV #1,IRBT ; BIT TEST REGISTER L$002 BIT IRBT,IROP1 ; TEST ACTUAL BIT JZ L$01 ; IF 0: DO NOTHING ADD IROP2L,IRACL ; IF 1: ADD MULTIPLIER TO RESULT L$01 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 then the above 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 of the multiplication. If byte instructions are used for the load of the multiplier resgisters, then the high byte is cleared like a CPU register. ; Macro Definition for the signed multiplication 8 x 8 bits ; MPYS8 .MACRO arg1,arg2 ; Signed MPY 8x8 MOV.B arg1,&0132h ; 00xx SXT &0132h ; Extend sign: 00xx or FFxx MOV.B arg2,&0138h ; 00yy SXT &0138h ; Extend sign: 00yy or FFyy .ENDM ; Result in SumExt|ResHi|ResLo ; ; Multiply the contents of two registers signed (low bytes) 231

Metering Application Report ; MPYS8 MOV MOV IROP1,IROP2 &ResLo,R6 &ResHi,R7

MSP430 Family

; CALL the MPYS8 macro ; Fetch result (16 bits) ; Only sign: 0000 or FFFF

; ; 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 arg1,&0132h ; MPYS is used SXT &0132h ; Extend sign: 00xx or FFxx MOV.B arg2,&0138h ; 00yy SXT &0138h ; Extend sign ADD &ResLo,MAClo ; Accumulate LSBs 16 bits ADDC &ResHi,MACmid ADDC &SumExt,MAChi ; Add SumExt to MSBs .ENDM ; ; ; Multiply and accumulate signed the contents of two byte tables ; MACS8 2(R6),@R5+ ; CALL the MACS8 macro .... ; Accumulation is yet made 5.1.5 Unsigned Division 32/16-bits The subroutine performs an unsigned 32-bit by 16-bit division. If the result does not fit into 16-bit, then the carry is set after return. If a valid result is obtained, then the carry is reset after return. The register usage is shown in the next figure:

IROP2M Remainder 15

IROP2L 0 IROP1

Dividend

Divisor

IRACL

Result

IRBT

Counter

Figure 51.3: Unsigned Division: Register Use ; DIVISION SUBROUTINE 32-BIT BY 16-BIT ; IROP2M|IROP2L : IROP1 -> IRACL REMAINDER IN IROP2M ; RETURN: CARRY = 0: OK CARRY = 1: QUOTIENT > 16 BITS ; DIVIDE CLR IRACL ; CLEAR RESULT

232

MSP430 Family MOV CMP JLO SUB RLC JC DEC JZ RLA RLC JNC SUB SETC JMP RET #17,IRBT IROP1,IROP2M DIV2 IROP1,IROP2M IRACL DIV4 IRBT DIV4 IROP2L IROP2M DIV1 IROP1,IROP2M DIV2

Metering Application Report ; INITIALIZE LOOP COUNTER ;

DIV1 DIV2

; Decrement loop counter

DIV4

5.1.6 Shift Routines The results of the above subroutines (MPY, DIV) accumulated in IRACM/IRACL have to be adapted to different numbers of bits after the decimal point, or because they are getting too large to fit into 32 bits. The following subroutines can do these jobs. If other numbers of shifting are necessary they may 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, bit0 -> carry RRC IRACL ; Shift LSBs, carry -> bit15 SHFTRS2 RRA IRACM RRC IRACL SHFTRS1 RRA IRACM RRC IRACL RET ; ; Unsigned shift right subroutine for IRACM/IRACL ; SHFTRU6 CALL #SHFTRU3 ; Shift 6 bits right unsigned SHFTRU3 CLRC ; Clear carry RRC IRACM ; Shift MSBs, bit0 -> carry, 0 -> bit15 RRC IRACL ; Shift LSBs, carry -> bit15 SHFTRU2 CLRC RRC IRACM RRC IRACL SHFTRU1 CLRC RRC IRACM RRC IRACL RET ; ; Signed/unsigned shift left subroutine for IRACM/IRACL ; SHFTL6 CALL #SHFTL3 ; Shift 6 bits left 233

Metering Application Report SHFTL3 SHFTL2 SHFTL1 RLA RLC RLA RLC RLA RLC RET IRACL IRACM IRACL IRACM IRACL IRACM

MSP430 Family ; Shift LSBs, bit0 -> carry ; Shift MSBs, carry -> bit15

5.1.7 Square Root The square root is often needed in computations. The following subroutine uses the NEWTONIAN approximation for this problem. The number of iterations depends on the length of the operand. The general formula is:
m

A=X 1 A (m 1) Xn + m 1 m Xn
A=X Xn + 1 = 1 A Xn + 2 Xn

Xn + 1 = For m = 2 (square root):

X0 = A2
To calculate A/Xn a division is necessary, which is done with the subroutine XDIV. The result of this division has the same integer format as the divisor Xn. This makes an easy operation possible. Ah Al XNh XNl .EQU .EQU .EQU .EQU R8 R9 R10 R11 ;High word of A ;Low word of A ;High word of result ;Low word of result

; Square Root ; The valid range for the operand is from 0000.0002h to ; 7FFF.ffffh ; EXAMPLE: SQR(2)=1.6a09h ; SQR(7fff.ffffh) = B5.04f3h ; SQR(0000.0002h) = 0.016ah ; SQR .EQU $ MOV Ah,XNh ; set X0 to A/2 for the first MOV Al,XNl ; approximation RRA XNh ; X0=A/2 RRC XNl SQR_1 CALL #XDIV ; R12xR13=A/Xn ADD R13,XNl ; Xn+1=Xn+A/Xn ADDC R12,XNh RRA XNh ; Xn+1=1/2(Xn+A/Xn) RRC XNl

234

MSP430 Family CMP JNE CMP JNE RET XNh,R12 SQR_1 XNl,R13 SQR_1 ; ; ; ; ;

Metering Application Report is high word of Xn+1 = Xn no, another approximation yes, is low word of Xn+1 = Xn no, another approximation yes, result is XNh.XNl remainder is in R14|R15 Save operands onto the stack

SQR_3 ; ; Extended unsigned division ; R8|R9 / R10|R11 = R12|R13, ; XDIV .EQU $ PUSH R8 ; PUSH R9 PUSH R10 PUSH R11 MOV #48,R7 ; CLR R15 ; CLR R14 CLR R12 ; CLR R13 L$361 RLA R9 ; RLC R8 RLC R15 RLC R14 CMP R10,R14 ; JLO L$364 ; JNE L$363 ; CMP R11,R15 ; JLO L$364 ; L$363 SUB R11,R15 ; SUBC R10,R14 L$364 RLC R13 ; RLC R12 DEC R7 ; JNZ L$361 ; POP R11 ; POP R10 POP R9 POP R8 RET

Counter=48 Clear remainder Clear result Shift one bit of R8|R9 to R14|R15

Is subtraction necessary? No Yes R11=R15 No Yes, subtract Shift result to R12|R13 Are 48 loops over ? No Yes, restore operands

5.1.8 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 (48 bit, 64 bit etc.). ; Comparison for unsigned 32-bit numbers: R11|R12 with R13|R14 ; CMP R11,R13 ; Compare MSBs JNE L$1 ; MSBs are not equal CMP R12,R14 ; Equality: Compare LSBs too L$1 JLO LO ; Jumps are used for MSBs and LSBs JEQ EQUAL ; ... ; R13|R14 > R11|R12 LO ... ; R13|R14 < R11|R12 235

Metering Application Report EQUAL ... ; R13|R14 = R11|R12

MSP430 Family

The shown approach can be adapted to any number length; only additional comparisons have to be added: ; Comparison for unsigned 48-bit numbers: R10|R11|R12 with ; R13|R14|R15 ; CMP R10,R13 ; Compare MSBs JNE L$1 ; MSBs are not equal CMP R11,R14 ; Equality: Compare MSBs-1 too JNE L$1 ; MSBs-1 are not equal CMP R12,R15 ; Equality: Compare LSBs too L$1 JLO LO ; Jumps are used for all words JEQ EQUAL ; ... ; R13|R14|R15 > R10|R11|R12 LO ... ; R13|R14|R15 < R10|R11|R12 EQUAL ... ; R13|R14|R15 = R10|R11|R12 ; Comparison for signed 32-bit numbers: R11|R12 with R13|R14 ; CMP R11,R13 ; Compare MSBs signed JLT LO ; R13 < R11 JNE HI ; Not LO, not EQUAL: only HI rests CMP R12,R14 ; Equality: Compare LSBs too L$1 JLO LO ; LSBs use unsigned jumps! JEQ EQUAL ; Not LO, not EQUAL: only HI rests HI ... ; R13|R14 > R11|R12 LO ... ; R13|R14 < R11|R12 EQUAL ... ; R13|R14 = R11|R12 ; Comparison for signed 48-bit numbers: R10|R11|R12 with ; R13|R14|R15 ; CMP R10,R13 ; Compare MSBs signed JLT LO JNE HI ; Not LO, not EQUAL: only HI rests CMP R11,R14 ; Equality: Compare MSBs-1 too JNE L$1 ; MSBs-1 are not equal CMP R12,R15 ; Equality: Compare LSBs too L$1 JLO LO ; Used for MSBs-1 and LSBs JEQ EQUAL ; Not LO, not EQUAL: only HI rests HI ... ; R13|R14|R15 > R10|R11|R12 LO ... ; R13|R14|R15 < R10|R11|R12 EQUAL ... ; R13|R14|R15 = R10|R11|R12 5.1.9 Random Number Generation The linear congruential method is used (introduced by D. Lehmer in 1951). The advantages of this method are speed, simplicity to code, and ease of use. However, if care is not taken in choosing the multiplier and increment values, the results can quickly become 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 a repeatable pattern every 16 calls.

236

MSP430 Family

Metering Application Report

The linear congruential method has the following form: Rndnumn = Rndnumn 1 MULT + INC(modM) With: Rndnumn Rndnumn-1 MULT INC M Current random number Previous random number Multiplier (unique constant) Increment (unique constant) Modulus (word width of MSP430 = 16 bits = 64K)

Much research has been done to identify the optimal choices for the constants MULT and 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. Following is a more detailed look at the algorithm and the numbers used: M M is the modulus value and is typically defined by the word width of the processor. The linear congruential algorithm will return a random number between 0 and 65,536 and is NOT internally bounded. If the user requires a min/max 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. 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, but the first two results of the generator will be 0 and 1. This is OK if the code is allowed 3 calls to warm up before the numbers are taken seriously. The number 21,845 was used in this implementation because it is 1/3 of the modulus (65,536). 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. Caution: the generator is extremely sensitive to the choice of this constant! 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:
1 1 INC = 3 M 2 6

SEED

MULT

INC

(Using M=65,536 leeds 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 the initialization routine INIRndnum must be called. Then you can call the subroutine Rndum16 calculating the random numbers as often you want. The necessary code and the description of the subroutine MPYU can be found in section 5.1.1. ; ; INITIALIZE CONSTANTS FOR RANDOM NUMBER GENERATION ; 237

Metering Application Report SEED MULT .set .set 21845 31821 ; ; ; ;

MSP430 Family Arbitrary seed value (65536/3) Multiplier value (last 3 Digits are even-2-1) 1 and 13849 have been tested

INC .set 13849 ; ; 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 $ ; Uses Rndnum16 MOV #SEED,Rndnum ; Initialize generator ; ; SUBROUTINE: GENERATES NEXT RANDOM NUMBER ; Rndnum16 .equ $ MOV Rndnum,IROP2L ; Prepare multiplication MOV #MULT,IROP1 ; Prepare multiplication CALL #MPYU ; Call unsigned MPY (5.1.1) ADD #INC,IRACL ; Add INC to low word of product ; ; Overwrite old random number with low word of new product ; MOV IRACL,Rndnum ; Result to Rndnum and IRACL RET EXAMPLE: Use of the Random Generator (1st call and succeeding calls). ; ; First call: produce the 1st random number ; CALL INIRndnum ; 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 Designers Notebook Number 43 Random Number Generation on a TMS320C5x". 7/94 5.1.10 Rules for the Integer Subroutines Despite the fact that the subroutines shown above can only handle integer numbers it is possible to use numbers with fractional parts. It is only necessary 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 therefore a good programming style to indicate in the comment part of

238

MSP430 Family

Metering Application Report

the software listing where the decimal point is currently located. The indication can have the following form: N.M with: N M Worst case bit count of integer part (allows additional assessments) Number of bits after the virtual decimal point

The rules for determining the location of the decimal point are easy: 1. Addition and subtraction: Positions after the decimal point have to be equal. The position is the same for the result. 2. Multiplication: Positions after the decimal point may be different. The two positions are added to get the results position after the decimal point. 3. Division: Positions after the decimal point may be different. The two positions are subtracted to get the results position. (Dividend - divisor) EXAMPLES: Table 51.1: Examples for the Virtual Decimal Point First Operand Operation Second Operand Result NNN.MMM + NNNN.MMM NNNN.MMM NNN.M NN.MMM NNNNN.MMMM NNN.MM NN.MM NNN.MM NNNN.MMMM : NN.MMM NN.M NNN.M + NNNN.M NNNN.M NNN.MM NN.MMM NNNNN.MMMMM NNN.M NN.M NNN.M NNNN.MMMMM : NN.M NN.MMMM If two numbers have to be divided and the result should have n digits after the decimal 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 may be used if a smaller number is to be divided by a larger one. EXAMPLES for the division: Table 51.2: Rules for the Virtual Decimal Point First Operand Operation Second Operand (shifted) NNNN.000 : NN NNNN.000 : NN.M NNNN.000 : N.MM 0.MMM000 : NN.M EXAMPLE for a source using the number indication: MOV MOV CALL CALL ADD #01234h,IROP2L R15,IROP1 #MPYS #SHFTRS3 #00678h,IRACL ; ; ; ; ; 239 Constant 12.34h loaded 8.8 Operand fetched 2.3 Signed MPY 10.11 Remove 3 fraction bits 10.8 Add Constant 6.78h 10.8

Result NN.MMM NN.MM NNN.M 0.MMMMM

Metering Application Report ADC IRACM ; Add carry

MSP430 Family 10.8

240

MSP430 Family 5.2 Table Processing

Metering Application Report

One of the development targets of the MSP430 was the capability to process tables. This is due to the fact that software can be written more readably and functionally 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: Good visibility Simple changes: Enlargements and deletions are made easily Low software overhead: Short programs High speed: Fastest way to access data Data is arranged in blocks, each block containing the complete information of one item Data is arranged in several tables, each table containing one or two kinds of information for all items.

Generally, two ways exist of arranging data in tables:

Max. Pressure MPY EEPROM Block 0

Max. Pressure

Item 0

Offset Max. Pressure

Max. Pressure

Item n

MPY MPY EEPROM Block 1

EEPROM

Item 0

Offset MPY EEPROM Item n

Max. Pressure Offset MPY EEPROM Block n Item 0

Offset Offset Block Arrangement of Data Data in several Tables Item n

Figure 52.1: Data Arrangement in Tables EXAMPLE: A table arranged in blocks is shown. Some examples for random access are given. The addressed tables refer to figure 52.1 ;Block Arrangement of data ; TABLE .WORD 2095 TEEPR .BYTE 16 TMPY .BYTE 3 TOFFS .WORD 01456h

; ; ; ; 241

Maximum pressure item 0 EEPROM start address Multiply constant Offset correction value

Metering Application Report ; TABN

MSP430 Family

.WORD ... .WORD .BYTE .BYTE .WORD

3084 2010 37 3 00456h

; Maximum pressure item 1 ; ; ; ; Maximum pressure item N EEPROM start address Multiply constant Offset correction value

; ; Access examples for the above block arrangement: ; R5 points to the 1st word of a block (max. pressure) ; Examples how to access the other values are given: ; MOV @R5,R6 ; Copy max. pressure to R6 MOV.B TEEPR-TABLE(R5),R7 ; EEPROM start to R7 CMP.B TMPY-TABLE(R5),R8 ; Same constant as in R8? MOV &ADAT,R9 ; ADC result to R9 ADD TOFFS-TABLE(R5),R9 ; Correct ADC result ADD #TABN-TABLE,R5 ; Address next items block ; ; Copying of block arranged data to registers ; MOV @R5+,R6 ; Copy max. pressure to R6 MOV.B @R5+,R7 ; EEPROM start to R7 MOV.B @R5+,R8 ; MPY constant to R8 MOV @R5+,R9 ; Offset to R9 ; ; R5 points to next items block now EXAMPLE: A table arranged in several tables is shown. Some examples for random access are given. The addressed tables refer to figure 52.1 ; Arrangement of data in several tables ; TMAXPR .WORD 2095 ; Maximum pressure item 0 .WORD 3084 ; Maximum pressure item 1 ... .WORD 2010 ; Maximum pressure item N ; TEEMPY .BYTE 16,3 ; EEPROM start, MPY constant .BYTE 37,3 ; item 1 ... .BYTE 37,114 ; item N ; TOFFS .WORD 01456h ; Offset correction value ... .WORD 00456h ; item N ; ; Access examples for the above arrangement: ; R5 contains the item number x 2: (word offset) ; Examples with identical functions as for the block arrangement ; shown in the example before ; MOV TMAXPR(R5),R6 ; Copy max. pressure to R6

242

MSP430 Family MOV.B CMP.B MOV ADD INCD TEEMPY(R5),R7 TMPY+1(R5),R8 &ADAT,R9 TOFFS(R5),R9 R5 ; ; ; ; ;

Metering Application Report EEPROM start to R7 Same constant as in R8? ADC result to R9 Correct ADC result Address next item

5.2.1 Two dimensional Tables Often the output value of a function 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: 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. The ignition angle of an Otto-motor depends on the throttle opening and the motor revolutions per minute.

Figure 52.2 shows a function such as described. The output value T depends on the input values X and Y.
T

Ym

Xm

Figure 52.2: Two-dimensional Function A table contains the output values T for all crossing points of X and Y that have distances of X and Y respectively. For every point in between these table points, the output value can be calculated.

243

Metering Application Report

MSP430 Family

T01

f(X,Yb+1) T11

f(X,Y) Yb+1 T00 Y Y Yb f(X,Yb)

T10

Xa X

Xa+1

Figure 52.3: Algorithm for two-dimensional Tables The calculation formulas are:
f(X,Yb) = X Xa X Xa (T10 T00) + T00 = (T10 T00) + T00 Xa + 1 Xa X f(X,Yb + 1) = X Xa (T11 T01) + T01 X

f(X,Y) =

Y Yb ( f(X,Yb + 1) (f(X,Yb)) + f(X,Yb) Y

These formulas need division. There are two possible ways to avoid the division: To choose the values for X and Y in such a way that simple shifts can do the divisions (X = 0.25, 0.5, 1, 2, 4 etc.) To use adapted output values T within the table T xy = This adaptation leads to:
f(X,Yb) = (X Xa) (T 10 T 00) + T 00 Y

Txy X Y

244

MSP430 Family

Metering Application Report


f(X,Yb + 1) = (X Xa) (T 11 T 01) + T 01 Y f(X,Yb + 1) f(X,Yb) f(X,Yb) f(X,Y) = (Y Yb) Y + Y Y Y

The output value f(X,Y) is calculable now with multiplications only. EXAMPLE: A 2-dimensional table is given. X and Y are 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 X and Y values are used then the adaptation parts and masks have to be changed. Item Delta Input value format Starting value End value Input value (RAM, reg) X 2 8.2 0 42 XIN Y 4 7.1 0 56 YIN Comment X and Y Bits before/after dec.point X0 resp. Y0 XM resp. YN 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 ; Mask 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: ; T00 .EQU TABLE ; (XA,YB) TABLE(XAYB) T01 .EQU TABLE+2 ; (XA,YB+1) TABLE+2(XAYB) T10 .EQU TABLE+(YN*2) ; (XA+1,YB) TABLE+(YN*2)(XAYB) T11 .EQU TABLE+(YN*2)+2 ; (XA+1,YB+1) TABLE+(YM*2)+2(XAYB) ; ; Table for two dimensional processing. Contents are signed ; numbers. ; TABLE .WORD 01015h,...073A7h ; (X0,Y0) (X0,Y1)...(X0,YN) .WORD 02222h,...08E21h ; (X1,Y0) (X1,Y1)...(X1,YN) ... .WORD 0A730h,...068D1h ; (XM,Y0) (XM,Y1)...(XM,YN) ; ; Table calculation software 2-dimensional. Approx. 700 cycles ; 245

Metering Application Report

MSP430 Family

; Input value X in XIN, Input value Y in YIN ; Result T in IRACL, same format as TABLE contents ; ; Calculation of YB out of YIN. One less adaption due to ; word table. Relative address of (X0,YB) to IRACL ; TABCAL2 CLR IRACM ; 0 -> Hi result register MOV YIN,IRACL ; Y -> Lo result register 7.1 RRA IRACL ; Shift out fraction part 7.0 RRA IRACL ; Adapt to dY = 4 6.0 BIC #1,IRACL ; Word address needed ; ; Calculation of XA out of XIN. One less adaption due to ; word table. Relative address of (XA,YB) to IRACL (T00) ; MOV XIN,IROP1 ; X -> Multiplicand 8.2 RRA IROP1 ; Shift out fraction part 8.1 RRA IROP1 ; Adapt to dX = 2 8.0 BIC #1,IROP1 ; Word address needed MOV #YN,IROP2L ; Max. Y (YN) to multipl. 5.0 CALL #MACS ; Rel 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 ; Rel. address of ZC ; ; Calculation of f(X,YB) = (XIN-XA)/dX x (T10-T00) + T00 ; MOV XIN,IROP1 ; build (XIN - XA) 8.2 AND #XCL,IROP1 ; Fraction and dX rests 1.2 MOV T10(XAYB),IROP2L ; T10 -> IROP2L 16.0 SUB T00(XAYB),IROP2L ; T10 - T00 16.0 CALL #MPYS ; (XIN - XA)(T10 - T00) 17.2 CALL #SHFTRS3 ; :dX, to integer 15.0 ADD T00(XAYB),IRACL ; (XIN-XA)(T10-T00)+T00 15.0 PUSH IRACL ; Result on stack ; ; Calculation of f(X,YB+1) = (XIN-XA)/dX x (T11-T01) + T01 ; (XIN-XA) still in IROP1 ; MOV T11(XAYB),IROP2L ; T11 -> IROP2L 16.0 SUB T01(XAYB),IROP2L ; T11 - T01 16.0 CALL #MPYS ; (XIN - XA)(T11 - T01) 17.2 CALL #SHFTRS3 ; :dX, to integer 15.0 ADD T01(XAYB),IRACL ; (XIN-XA)(T11-T01)+T01 15.0 ; ; Calculation of f(X,Y) = (YIN-YB)/dY x (f(X,YB)-f(X,YB+1) + ; f(X,YB) ; MOV YIN,IROP1 ; build (YIN - XB 7.1 AND #YCL,IROP1 ; Fraction and dX rests 2.1 SUB @SP,IRACL ; f(X,YB+1)-f(X,YB) 16.0

246

MSP430 Family MOV CALL CALL ADD RET IRACL,IROP2L #MPYS #SHFTRS3 @SP+,IRACL ; ; ; ; ;

Metering Application Report Result to multiplier (YIN-YB)(f..-f..) :dY, to integer (YIN-YB)(f..-f..)+f.. Result T in IRACL

18.1 16.0 15.0 16.0

The table used with the example before uses unsigned values for X and Y (the upper left hand table of figure 52.4 shows this). If X or Y or both are signed values then the structure of the table and its entry point have to be changed. The following examples in figure 52.4 show how to do that.

Y0

YN X0

Y-N-1

Y0

YN X0

XM X unsigned Y unsigned X unsigned Y signed Location of Address TABLE

XM

Y0

YN X-M-1

Y-N-1

Y0

YN X-M-1

X0

X0

XM X signed Y unsigned X signed Y signed

XM

Figure 52.4: Table Configuration for signed X and Y The above tables are shown in assembler code: ; X unsigned, Y unsigned ; TABLE .WORD 01015h,...073A7h .WORD 02222h,...08E21h ... .WORD 0A73h,...068D1h ; ; X unsigned, Y signed ; .WORD 03017h,...093A2h TABLE .WORD 02233h,...08721h .WORD 03017h,...093A2h ... .WORD 00173h,...07851h ; 247

; (X0,Y0)...(X0,YN) ; (X1,Y0)...(X1,YN) ; (XM,Y0)...(XM,YN)

; (X0,Y-N-1)...(X0,Y-1) ; (X0,Y0)...(X0,YN) ; (X1,Y-N-1)...(X1,YN) ; (XM,Y-N-1)...(XM,YN)

Metering Application Report ; X signed, Y unsigned ; .WORD 03017h,...093A2h .WORD 08012h,...0B3C1h ... .WORD 04019h,...0D3A3h TABLE .WORD 02233h,...08721h .WORD 03017h,...093A2h ... .WORD 00173h,...07851h ; ; X signed, Y signed ; .WORD 03017h,...093A2h .WORD 08012h,...0B3C1h ... .WORD 04019h,...0D3A3h .WORD 02233h,...08721h TABLE .WORD 02233h,...08721h .WORD 03017h,...093A2h ... .WORD 00173h,...07851h

MSP430 Family

; (X-M-1,Y0)...(X-M-1,YN) ; (X-M,Y0).....(X-M,YN) ; (X-1,Y0)...(X-1,YN) ; (X0,Y0)....(X0,YN) ; (X1,Y0)....(X1,YN) ; (XM,Y0)....(XM,YN)

; (X-M-1,Y-N-1)(X-M-1,YN) ; (X-M,Y-N-1) ...(X-M,YN) ; ; ; ; (X-1,Y-N-1)...(X-1,YN) (X0,Y-N-1)....(X0,Y-1) (X0,Y0).......(X0,YN) (X1,Y-N-1)....(X1,YN)

; (XM,Y-N-1)....(XM,YN)

The entry label TABLE always points to the word or byte with the coordinates (X0,Y0). 5.2.2 Three dimensional Tables If the output value T depends on three input variables X, Y and Z, then a three dimensional table is necessary for the crossing points. Eight values T000 to T111 are used for the calculation of the output value T. The simplest way for the calculation is to calculate the output values for two two-dimensional tables f(X,Y,Zc) and f(X,Y,Zc+1) with the subroutine TABCAL2 used for the two-dimensional tables. The two results are used for the final calculation:
f(X,Y, Z) = Z Zc ( f(X,Y, Zc + 1) (f(X,Y, Zc)) + f(X,Y, Zc) Zc + 1 Zc

The next figure shows this method: the output values T are calculated for Zc and for Zc+1. Out of these two output values the final value f(X,Y,Z) is calculated.

248

MSP430 Family
T010

Metering Application Report

f(X,Yb+1,Zc) T110 T011

f(X,Yb+1,Zc+1) T111

f(X,Y,Zc) Yb+1 T000 Y f(X,Yb,Zc) T100 Yb Y Yb+1

f(X,Y,Zc+1)

T001 f(X,Yb,Zc+1)

T101

Yb

Xa

Xa+1 f(X,Y,Z)

Xa

Xa+1

f(X,Y,Zc)

f(X,Y,Zc+1)

Zc

Zc+1

Figure 52.5: Algorithm for a three-dimensional Table EXAMPLE: A 3-dimensional table is given. X and Y and Z are chosen as multiples of 2. The integer subroutines are used for calculations. Item X Y Z Comment Delta 2 4 256 X, Y, Z Input value format 8.2 7.1 0 Bits after dec.point Starting value 0 0 0 X0, Y0, Z0 End value 42 56 214-1 XM, YN, ZP Input value (RAM, reg) XIN YIN ZIN Assembler mnemonic ; XIN .EQU R15 ; unsigned X value, register or RAM YIN .EQU R14 ; unsigned Y value, register or RAM ZIN .EQU R13 ; unsigned Z value, register or RAM XM .EQU 42 ; 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 ZCL .EQU 0FFh ; Mask for deltaZ XAYB .EQU R12 ; Rel. address of (XA,YB), register ZCFLG .EQU 1 ; Flag: 0: 2-dim. 1: 3-dim. Table OFFZC .EQU R11 ; Relative offset to actual (X0,Y0,ZC) ; ; Three dimensional table ; TABL3D .WORD 01015h,...073A7h ; (X0,Y0,Z0)...(X0,YN,Z0) ... .WORD 02222h,...08E21h ; (XM,Y0,Z0)...(XM,YN,Z0) ; .WORD 0A730h,...068D1h ; (X0,Y0,Z1)...(X0,YN,Z1) ... .WORD 010A5h,...09BA7h ; (XM,Y0,Z1)...(XM,YN,Z1) ;

249

Metering Application Report .WORD ... .WORD

MSP430 Family

02BC2h,...08E41h ; (X0,Y0,ZP)...(X0,YN,ZP) 0A980h,...023D1h ; (XM,Y0,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 adaption due to ; word table. ; TABCAL3 MOV ZIN,IROP1 ; Z -> Operand register 14.0 SWPB IROP1 ; Use only upper byte (dZ =256) MOV.B IROP1,IROP1 ; Adapt to dZ = 256 6.0 ; ; Calculation of relative address of (X0,Y0,ZC) to IRACL ; Corrected for word table ; MOV #YN*2*XM,IROP2L ; Table length for dZ CALL #MPYU ; Rel address (X0,Y0,ZC) 13.0 MOV IRACL,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) -> IRACL 16.0 PUSH IRACL ; Save f(X,Y,ZC) ; Calculation of f(X,Y,ZC+1): The ; ADD #YN*2*XM,OFFZC ; CALL #TABCAL2 ; ; ; Calculation of f(X,Y,Z) ; MOV ZIN,IROP1 ; AND #ZCL,IROP1 ; SUB @SP,IRACL ; MOV IRACL,IROP2L ; CALL #MPYS ; CALL #SHFTRS6 ; CALL #SHFTRS2 ; ADD @SP+,IRACL ; RET ; table block for ZC+1 is used Rel. adress (X0,Y0,ZC+1) f(X,Y,ZC+1) -> IRACL 16.0

build (YIN - XB Fraction and dZ rests f(X,Y,ZC+1)-f(X,Y,ZC) Result to multiplier (ZIN-ZC)(f..-f..) :dZ, to integer (ZIN-ZC)(f..-f..)+f.. Result in IRACL

6.8 0.8 16.0 16.8 16.2 16.0 15.0

250

MSP430 Family 5.3 Signal Averaging and Noise Cancellation

Metering Application Report

If the measured signals contain noise, spikes and other not wanted signal components then it is 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 that need only small calculation power are used for the signal conditioning. 5. Rejection of Extremes: the largest and the smallest sample are rejected from the measured values and the remaining ones added-up and averaged. 6. Synchronization of the measurements to hum The advantages and disadvantages of the different methods are shown in the appertaining sections. 5.3.1 Oversampling Oversampling is the most simple 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 next algorithm steps. It is only necessary to remember that the added-up value is N-times too large. For example the formula below used for a single measurement needs to be modified if N samples are summed-up as shown: V normal = Slope ADC + Offset V oversample = ( Slope ADC + Offset ) N

EXAMPLE: N measurements have to be summed-up in SUM and SUM+2. The number N is defined in R6 SUMLO SUMHI ; .EQU .EQU CLR CLR MOV CALL ADD ADC DEC JNZ ... R4 R5 SUMLO SUMHI #16,R6 #MEASURE &ADAT,SUMLO SUMHI R6 OVSLOP ; LSBs of sum ; MSBs of sum ; Init of registers ; ; ; ; ; Sum-up 16 samples of the ADC Result in ADAT LSD of accumulated sum MSD Decr. N counter: 0 reached?

OVSLOP

; Yes, 16 samples in SUMHI|SUMLO - High current consumption due to number of ADC conversions - Low suppression of spikes etc. (by N) - Simple programming

Disadvantages: Advantages:

251

Metering Application Report

MSP430 Family

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 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 as with oversampling. 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 next figure:

0.0625 -10

0.125

0.25

0.5

Input Frequ. Scan Frequ.

-20

-30

-40

Attenuation dB

Figure 53.1: Frequency Response of the Continuous Averaging Filter Disadvantages: Advantages: - RAM allocation: N words are needed for the circular buffer - Low current consumption due to one measurement only - Fast update of buffer - Good suppression of certain frequencies (multiples of scan frequency) - Low pass filter characteristic

EXAMPLE: An interrupt driven routine (e.g. from the ADC which is started by the Basic Timer) is shown that updates a circular buffer with N items. 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 .EQU .BSS .BSS .BSS PUSH MOV 16 CFSTRT,N*2 CFSUM,4 CFPOI,2 R5 CFPOI,R5 ; ; ; ; Circular buffer with N items Address of 1st item Accumulated sum 32 bits Points to next (= oldest) item

; CFHND

; Save R5 ; Actual address to R5

252

MSP430 Family CMP JLO MOV

Metering Application Report #CFSTRT+(N*2),R5 ; Outside circ. buffer? L$300 ; No #CFSTRT,R5 ; Yes, reset pointer from the sum. The newest item is added to the sum ; Subtract oldest item from CFSUM ; Move actual item to buffer ; Add latest ADC result to CFSUM ; Update pointer ; Restore R5

; ; The oldest item is subtracted ; overwrites the oldest one and ; L$300 SUB @R5,CFSUM SBC CFSUM+2 MOV &ADAT,0(R5) ADD @R5+,CFSUM ADC CFSUM+2 MOV R5,CFPOI POP R5 RETI 5.3.3 Weighted Summation

The weighted sum of the measurements before and the actual measurement result are added and then divided by two. This gives every measurement result a certain weight: Table 53.1: Sample Weight Measurement Time Weight t0 0.5 0.25 t0 - t 0.125 t0 - 2t 0.0625 t0 - 3t 0.03125 t0 - 4t 2-(n+1) t0 - nt Disadvantages: Advantages:

Comment Actual measurement Last measurement

- Suppression of spikes not sufficient (factor 2 only for actual sample) - Low current consumption due to one measurement only - Low pass filter characteristic - Very short code - Only one RAM word needed

EXAMPLE: The update of the actual sum WSSUM is shown. .BSS ; WSHND ADD RRA ... WSSUM,2 &ADAT,WSSUM WSSUM ; Accumulated weighted sum ; Add actual measurement to sum ; New sum divided by 2 ; Continue with value in WSSUM

5.3.4 Wave Digital Filtering Wave Digital Filters (WDFs) have notable advantages: Excellent stability properties even under nonlinear operating conditions resulting from overflow and roundoff effects Low coefficient word length requirements 253

Metering Application Report Inherently good dynamic range Stability under looped conditions

MSP430 Family

Compared with the often used averaging of measured sensor data, the digital filtering has advantages: Lowpass filtering with sharp cut-off region, notch filtering of noise, ... For the design of Wave Digital Filter algorithms specialized CAD programs have been designed in order to speed-up the top-down design from filter specification to the machine program for the processor: LWDF_DESIGN allows the design of Lattice-WDFs LWDF_COMP transforms a Lattice-WDF structure into an assembler program for the MSP430 DSP430 allows fast transient simulations of the filter algorithms on a model of the MSP430, analysis of frequency response, check of accuracy and stability proof.

The programs enable the users of the MSP430 to solve special measurement problems by means of robust digital filter algorithms. A complete description of the WDF algorithms and development tools is given in the "TEXAS INSTRUMENTS Technical Journal" November/December 1994. Disadvantages: Advantages: - Complex algorithm. Support software needed for finding algorithm - Low current consumption due to one measurement only per time slice - Good attenuation inside stopband - Good dynamic stability

5.3.5 Rejection of Extremes This averaging method measures (N+2) ADC-samples and rejects the largest and the smallest values. The remaining N samples are added-up and the accumulated sum is divided by N afterwards or is used as it is with the next algorithm steps. It is only necessary to remember that the added-up value is N-times too large. Disadvantages: Advantages: - Current consumption due to (N+2) ADC conversions - Simple programming - Very good suppression of spikes (extremes are rejected) - Low RAM needs (4 words)

The software example below adds six ADC samples, subtracts the two extremes and returns with the sum of the four medium samples. The constant N may be changed to any number, but the summing-up buffer SESUM needs two words if N exceeds two. It is an advantage to use powers of two for N due to the simple division if needed (right shifts only). Register use is possible too for SESUM, SEHI and SELO. N .EQU .IF .BSS .ELSE .BSS 4 N>2 SESUM,4 SESUM,2 ; Sample count used -2 ; Summing-up buffer ; ; N<=2

254

MSP430 Family .ENDIF .BSS .BSS .BSS ; SEHND CLR .IF CLR .ENDIF MOV.B MOV CLR

Metering Application Report

SEHI,2 SELO,2 SECNT,1 SESUM N>2 SESUM+2 #N+2,SECNT #0FFFFh,SELO SEHI

; Largest ADC result ; Smallest ADC result ; Counter for N+2 ; Initialize buffers

; Sample count +2 to counter ; ADCmax -> SELO ; ADCmin -> 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 ; Use 2nd sum buffer if N>2 ADC SESUM+2 .ENDIF CMP R5,SEHI ; Result > SEHI? JHS L$1 ; No MOV R5,SEHI ; Yes, actualize SEHI L$1 CMP R5,SELO ; Result < SELO? JLO L$2 ; No MOV R5,SELO L$2 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 .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 mains frequency may help to overcome this problem. Fig. 53.2 shows the influence of the mains voltage during the measurement of a single sensor. The necessary number of measurements (here 10) is split into two equal parts, the second part is measured after exactly one half of the period Tmain of the mains frequency. The hum introduced to the two parts is equal but has different signs. Therefore the accumulated influence (the sum) is nearly zero.

255

Metering Application Report

MSP430 Family

Mains Voltage n/2 Meas. V1

Tmain/2 -V1 n/2 Meas.

Time

Figure 53.2: Reduction of Hum by Synchronizing to the Power Frequency. Single Measurement If the Basic Timer is used for the timing then the following numbers of Basic Timer interrupts can be used: Table 53.2: Basic Timer Frequencies for Hum Suppression Timer Number of BT Time Error et Residual Error er Mains Frequency Basic fmain Frequency fBT Interrupts k max. max. 50Hz 60Hz 4096Hz 2048Hz 41 17 0.097% -0.39% 0.61% -2.45%

The formulas to get the above errors are:


TBT et = 2k 1 100 TMAIN TBT er = sin 2k 2 100 TMAIN

where:

et er TBT Tmain k

Maximum time error due to fixed Basic Timer frequency in per cent Maximum remaining influence of the hum in per cent compared to a measurement without hum cancellation Period of Basic Timer frequency (1/fBT) Period of mains (1/fmain) Number of Basic Timer interrupts to reach Tmain/2 resp. Tmain

If difference measurements are used, the two measurements to be subtracted should be made with a delay of exactly one mains 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.

256

MSP430 Family

Metering Application Report

Mains Voltage n/2 Meas. V1 n/2 Meas.

Tmain

Time

Figure 53.3: Reduction of Hum by Synchronizing to the Mains Frequency. Differential Measurement If the Basic Timer is used for the timing then the following numbers of Basic Timer interrupts can be used: Table 53.3: Basic Timer Frequencies for Hum Suppression Mains Frequency Basic Timer Number of Time Error et Residual Error er fmain Frequency fBT Interrupts k max. max. 50Hz 60Hz 2048Hz 1024Hz 41 17 0.097% -0.39% 0.61% -2.45%

The formulas to get the above results are:


TBT et = k 1 100 TMAIN

TBT er = sin k 2 100 TMAIN

The software needed for the modification of the Basic Timer frequency without the loss of the exact time base is shown in chapter "Change of Basic Timer Frequency"

257

Metering Application Report 5.4 Real Time Applications Real Time Applications for microprocessors are defined often as follows:

MSP430 Family

The controlling processor is able also 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 nominal frequency - but by the multiplication of the frequency of the 32kHz 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 if the speed of the MSP430 is the critical factor of an application. 5.4.2 Normal Mode is Low Power Mode 3 This mode is used for battery driven systems where the power consumption plays an overwhelming role: battery lifetimes over ten years are only possible if 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 six MCLK cycles; the system clock oscillator is working at the correct frequency then. This means true real time capability, no delay due to the slow coming-up of the main oscillator crystal (up to 400ms) is slowing down the system behavior. See section Use of the System Clock Generator for the details of the programming. 5.4.3 Normal Mode is Low Power Mode 4 The Low Power Mode 4 is used if relatively long time elapses between two interrupt events. The power consumption goes below 0.1A if this mode is used: all oscillators are switched off, only the RAM and the interrupt hardware are powered. Despite this inactivity the MSP430 CPU is at the start of the interrupt handler within six cycles of the programmed DCO tap. See section Use of the System Clock Generator for the details of the speed-up of the CPU. 5.4.4 Recommendations for Real Time Applications 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 at the start of the interrupt handler. This allows nested interrupts and avoids the blocking of other interrupts. Interrupt handlers (foreground) should be as short as possible. All calculations should be made in the background part of the program. The communication between the two software parts is made by status bytes. See section Flag Replacement by Status Usage. Use status bytes and calculated branches. See the appendix for examples. The interrupt capability of the I/O-ports makes input polling superfluous: any change of an input is seen immediately. Use of the ports this way is recommended.

258

MSP430 Family

Metering Application Report

Disabling and enabling of the peripheral interrupts during the software run is not recommended. Additional interrupt requests may 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.

259

Metering Application Report 5.5 General Purpose Subroutines

MSP430 Family

The following, tested software examples may be of help during the software development phase. The examples may not fit into any application, but they can be modified easily to the users 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 Cold Start and Warm Start. The reason is the possibility of initializations caused by electromagnetic interference (EMI). 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 made by comparing RAM bytes with known content to their nominal value. These RAM bytes could be identification codes or extra written test patterns (e.g. A5h, F0h). If the tested RAM locations contain the right 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 loss of power) 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 chapters "Use of the System Clock Generator" and The RESET Function. ; Initialization part: Check if Cold Start or Warm Start: ; RAM location 0200h decides kind of initialization: ; Cold Start: content differs from 0A5F0h ; Warm Start: content is 0A5F0h ; INIT CMP #0A5F0h,&0200h ; Test content of &200h JEQ EMIINI ; Correct content: No reset ; ; Control RAM content differs from 0A5F0: RAM needs to be ; cleared, peripherals needs to be initialized ; MOV #0300h,SP ; Init. Stack Pointer CALL #RAMCLR ; Clear complete RAM MOV #0A5F0h,&0200h ; Insert test word ; ; System frequency MCLK is set to 2.048MHz ; MOV.B #64-1,&SCFQCTL ; 64 x 32kHz = 2.048MHz MOV.B #FN_2,&SCFI0 ; DCO current for 2MHz ; ; Waiting loop for the DCO of the FLL to settle: 130ms ; CLR R5 ; 3 x 65536us = 186ms L$1 INC R5 JNZ L$1 ... ; ; EMI caused initialization: Periphery needs to be initialized: ; Interrupts need to be enabled again ; EMINI ...

260

MSP430 Family

Metering Application Report

5.5.2 RAM clearing Routine The RAM is cleared starting at label RAMSTRT up to label RAMEND (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 RCL CLR CLR.B INC CMP JLO RET R5 ; Prepare index register RAMSTRT(R5) ; 1st RAM address R5 ; Next address #RAMEND-RAMSTRT+1,R5 ; RAM cleared? RCL ; No, once more ; Yes, return

; 5.5.3 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 DADD instruction reduces this to a loop with five instructions. ; THE BINARY NUMBER IN R12 IS CONVERTED TO A 5-DIGIT BCD ; NUMBER CONTAINED IN R14 AND R13: R14|R13 ; BINDEC MOV #16,R15 ; LOOP COUNTER CLR R14 ; 0 -> RESULT MSD CLR R13 ; 0 -> RESULT LSD L$1 RLA R12 ; Binary MSB to carry DADD R13,R13 ; RESULT x2 LSD DADD R14,R14 ; MSD DEC R15 ; THROUGH? JNZ L$1 RET ; YES, RESULT IN R14|R13 The above subroutine may be enlarged to any length of the binary part simply by the adding of registers for the storage of the BCD number (a binary number with n bits needs approx. 1.2 x n bits for BCD format). If numbers containing fractions have to be converted to BCD the following algorithm may 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 BINDEC. The BCD result is a number with the same number of fractional digits as the binary number has fractional bits. EXAMPLE: The hex number 0A8Bh has the binary format MMM.NNN. The decimal value is therefore 337.375. The steps to get the BCD number are: 1. 0A8Bh is to be multiplied by 53 or 12510 due to its 3 fractional bits. 0A8Bh x 12510 =0525DFh 261

Metering Application Report

MSP430 Family

2. 0525DFh has the decimal equivalent 337375: the correct BCD number with 3 fractional digits To convert the above example the basic subroutine BINDEC needs to be enlarged: two binary registers are necessary to hold the input number. ; THE BINARY NUMBER IN R12|R11 IS CONVERTED TO AN 8-DIGIT BCD ; NUMBER CONTAINED IN R14 AND R13: R14|R13 ; Max. hex number in R12|R11: 05F5E0FFh (999999999) ; BINDEC MOV #32,R15 ; LOOP COUNTER CLR R14 ; 0 -> RESULT MSD CLR R13 ; 0 -> RESULT LSD L$1 RLA R11 ; MSB of LSBs to carry RLC R12 ; Binary MSB to carry DADD R13,R13 ; RESULT x2 LSD DADD R14,R14 ; MSD DEC R15 ; THROUGH? JNZ L$1 RET ; YES, RESULT IN R14|R13 5.5.4 BCD to Binary This subroutine converts a packed 16 bit BCD word to a 16 bit binary word by multiplying each digit with its valency. To reduce code length, the HORNER scheme is used as follows:
R5 = X0 + 10(X1 + 10(X2 + 10X3)

; The packed BCD number contained in R4 is converted to a binary ; number contained in R5 ; BCDBIN MOV #4,R8 ; LOOP COUNTER ( 4 DIGITS ) CLR R5 CLR R6 SHFT4 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 ; XN+10XN+1 CLR R6 DEC R8 ; THROUGH ? JZ END ; YES MPY10 RLA R5 ; NO, MULTIPLICATION WITH 10 MOV R5,R7 ; DOUBLED VALUE RLA R5 RLA R5 ADD R7,R5 ; VALUE X 8 JMP SHFT4 ; NEXT DIGIT END RET ; RESULT IS IN R5

262

MSP430 Family 5.5.5 Keyboard Scan

Metering Application Report

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, then 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 then 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 interesting signal edges. If one of the interesting input signal changes occurs, interrupt is given and wake-up takes place. Figure 55.1 shows a keyboard with 16 keys.
32kHz

LCD

COM SEL
Error kW kWh

MSP430 Ox/P0.a Oy/P0.b Oz/P0.c Ok/P0.d An/P0.w Am/P0.x Ao/P0.y Ap/P0.z * * * * * * * * * * * * * * * *

*=

Figure 55.1: Keyboard Connection The following figure 55.2 shows some possibilities for connecting external signals to the MSP430: The first row contains keys. The decoupling diode in the row selection line prevents that pressed keys are shortening other signals. If more than one key can be activated simultaneously then any key needs to have a decoupling diode. The second row contains diodes. This is a simple way to tell a system which version is used. The third row selects digital signals coming from peripherals with outputs that can be switched to HI-Z mode. The fourth row uses an analog switch to connect digital signals to the MSP430. Shown is the output of a CMOS gate and the output of a comparator.

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 to 100ms, and the information read then 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.

263

Metering Application Report

MSP430 Family

32kHz

LCD

COM SEL MSP430 Ox/P0.a Oy/P0.b Oz/P0.c Ok/P0.d An/P0.w Am/P0.x Ao/P0.y Ap/P0.z * * * * x x x x # # # # xC 1B 1A 2B 2A 3B 3A 4B 4A 4016 *= x= #= Digital Signals + Error kW kWh

Vin

Figure 55.2: Connection of different Input Signals 5.5.6 Temperature Calculations for Sensors Several sensors can be connected to the MSP430. The chapter The Analog-to-Digital 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)

with:

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.1. Two methods are described of how to represent the function f(N): 1. Table processing 2. Algorithms (linear, quadratic, cubic or hyperbolic equations) 5.5.6.1 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. The next figure shows such a non-linear sensor characteristic.

264

MSP430 Family

Metering Application Report

Xm ADC value

Figure 55.3: Nonlinear Function Steps for the development of a sensor table: 1. Definition of the external circuitry used at the ADC inputs (See section "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 () ADC values n 4. Calculation of the sensor resistances for the above 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 = 128 starting at value N0 = 256. The output value K is content of this table. The ADC result is corrected with offset and slope coming from the calibration procedure. ; .BSS OFFSET,2 ; Offset from calibration 10.0 .BSS SLOPE,2 ; Slope from calibration 1.10 DN .EQU 128 ; Delta N ; ; Table contains signed values. The decimal point may be anywhere ; TABLE .WORD 02345h, ...,00F3h ; N0, N1, ...NM ; TABCAL1 MOV &ADAT,IROP1 ; ADC result to IROP1 14.0 ADD OFFSET,IROP1 ; Correct offset 10.0 MOV SLOPE,IROP2L ; Slope 1.10 CALL #MPYS ; (ADC+OFFSET)xSLOPE 15.10 ; ; Corrected ADC value in IRACM|IRACL. ; CALL #SHFTLS6 ; Result to IRACM 15.0 MOV IRACM,XIN ; Copy it ; ; Calculation of NA address. One less adaptation due to ; word table (2 bytes/item). ; MOV XIN,IROP1 ; N -> Multiplicand 15.0 SWPB IROP1 ; Adapt to deltaN = 128 14.0 BIC.B #1,IROP1 ; Even word address needed 8.0 265

Metering Application Report SUB MOV MOV

MSP430 Family

#2,IROP1 ; Adapt to N0 = 256 (2 x deltaN) TABLE(IROP1),R15 ; NA from table TABLE+2(IROP1),R14 ; NA+1 from table

; ; K = XIN-NA/(deltaN) x (NA+1 - NA) + NA ; SUB R15,XIN ; XIN - NA MOV R14,IROP2L ; NA+1 SUB R15,IROP2L ; NA+1 - NA) MOV XIN,IROP1 ; XIN - NA CALL #MPYS ; (XIN - NA) x (NA+1 - NA) CALL #SHFTRS6 ; /deltaN CALL #SHFTRS1 ; deltaN = 2^7 ADD R15,IRACL ; + NA, result in IRACL RET 5.5.6.2 Algorithms for Sensor Calculations If the sensor characteristic can be described by a function K = f(N) of the category Linear Equation

K = a1 N + a0
or Quadratic Equation

K = a2 N 2 + a1 N + a0
or Cubic Equation

K = a3 N 3 + a2 N 2 + a1 N + a0
or Root Equation

K = a0 b1 N +b0
or Hyperbolic Equation
K = b1 + a0 N + b0

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. MATHCAD), with formulas by hand or by the MSP430 itself. Steps for the development of a sensor algorithm: 1. Definition of the hardware circuitry used at the ADC inputs (See section "The Analog-toDigital Converters" 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 above chosen value of K

266

MSP430 Family

Metering Application Report

5. Calculation of the voltage at the analog input Ax for this sensor resistance (See section "The Analog-to-Digital Converters" 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 Coefficient Calculation for the Equations. EXAMPLE: A quadratic behavior is given for a sensor characteristic:

K = a2 N 2 + a1 N + a0
with N representing the ADC result. The corrected ADC result (see above) is stored in XIN; the three terms are stored in the ROM locations A2, A1 and A0. ; A2 .WORD 07FE3h ; Quadratic term +-0.14 A1 .WORD 00346h ; Linear term +-0.14 A0 .WORD 01234h ; Constant term +-15.0 ; QUADR MOV XIN,IROP1 ; Corrected ADC result 14.0 MOV A2,IROP2L ; Factor A2 +-0.14 CALL #MPY ; XIN x A2 14.14 ADD A1,IRACL ; (XIN x A2) + A1 +-0.14 ADC IRACM ; Carry to HI reg CALL #SHFTL3 ; To IRACM 14.1 MOV IRACM,IROP2L ; (XIN x A2) + A1 -> IROP2L 14.1 CALL #MPYS ; (XIN x A2) + A1) x XIN 28.1 CALL #SHFTL2 ; Result to IRACM 15.0 ADD A0,IRACM ; Add A0 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, A0 may 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 chapter 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) resp. four pairs (cubic equations) of Kn and Nn the coefficients an and bn can be calculated. The formulas are shown below. where: Kn Nn an bn Calculation result for the ADC result Nn (e.g. temperature, pressure) Input value for the calculation e.g. ADC result Coefficient for the Nn value of the polynoms Coefficients for the hyperbolic and root equations 267

Metering Application Report

MSP430 Family

Linear equation:

K = a1 N + a0 a1 = K2 K1 N2 N 1 a0 = K 1 N 2 K2 N 1 N 2 N1

Quadratic Equation: a2 =

K = a2 N 2 + a1 N + a0

(K 2 K 1 ) a1 (N 2 N1 )
2 N 2 N 12

a0 = K1 a2 N 12 a1 N1

a1 =

(K2 K1 ) (N 32 N 22 ) (K3 K2 ) (N 22 N12 ) ( N 2 N1 ) (N 32 N 22 ) ( N 3 N 2 ) (N 22 N12 )


K = a3 N 3 + a2 N 2 + a1 N + a0

Cubic Equation:

The equations for the four coefficients an are too complex. Shift the calculation task to the calibration PC and use MATHCAD or something similar to it. Root Equation:
a0 =

K = a0 b1 N +b0

(N 2 N 1 ) (K 32 K 12 ) (N 3 N 1 ) (K 22 K 12 ) 0.5 (N 2 N 1 ) ( K 3 K 1 ) ( N 3 N 1 ) ( K 2 K 1 )
2 2

b1 =

(K

K 12 ) 2a0 (K 2 K 1 ) N 2 N1
K =

b0 = ( K1 - a0) b1 N1
2

Hyperbolic Equation:

b1 + a0 N + b0

b0 =

(N 3 K3 N1 K1 ) ( N 2 N 1 ) (N 2 K 2 N1 K1 ) ( N 3 N1 ) (N 3 N 1 ) ( K 2 K 1 ) ( N 2 N 1 ) ( K 3 K 1 )
b1 = ( K1 - a0) ( N1 + b0)

a0 =

(N 3 K3 N1 K1 ) + b0 ( K 3 K1 )
N 3 N1

EXAMPLE: the used sensor has a quadratic characteristic R = d2K2 + d1K + d0. This means, the value K is described best by the root equation (inverse to the quadratic characteristic of the sensor):

268

MSP430 Family

Metering Application Report

K = a0 b1 N +b0
where the sensor resistance R is replaced by the analog-to-digital converter result N. During the calibration with the values for Kn 0, 200 and 400, the following ADC Results Nn were measured: Calc.Value Kn (C, hP, V) K1 0 K2 200 K3 400 ADC Value Nn N1 N2 N3

4196 4430 4652

With the above numbers the coefficients a0 b0 and b1 can be calculated:

( 4430 4196 ) (400 2 0 2 ) (4652 4196 ) (200 2 0 2 ) a0 = 0.5 = 4000 (4430 4196 ) ( 400 0) (4652 4196 ) (200 0)
b1 =

(200

0 2 2 4000 ( 200 0) 4430 4196


2

= 6666.6667

b0 = (0 - 4000) ( 6666.6667) 4196 = 43.97371E6

With the above calculated coefficients, the negative root value is to be used:
K = a0 b1 N + b0

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 too. The next two 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 totally scrambled 64 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 permutations (the tables mentioned refer to the booklet "Data Encryption Algorithm" of the ANSI): 1. 2. 3. 4. 5. 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

269

Metering Application Report

MSP430 Family

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:
7 Rep. Bit EOT 5 Byte Index 3 2 Bit Position 0

Where: Rep. Bit 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 The byte address 0 to 7 inside the output block The bit address 0 to 7 inside the output byte

EOT Byte Index Bit Position

The following figure shows the permutation of bit i. The description table contains at address i the information: Repetition Bit = 0: EOT = 0 Byte Index = 3: Bit Position = 5: The bit i is to be inserted into the output table only once Bit i is not the last bit in the description table The relative byte address inside the output table is 3 (PTOUT+3) The bit position inside the output byte is 5 (020h)
Bit Position Bit Address 1 1 7 5 0 0

i 0 0 3 5 i 64 Description Table 64 i

7 Byte Index Input Table Output Table

Figure 55.4: 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 above described permutations follow. The subroutines PERMUT and PERM_BIT are used for all necessary permutations (see above). The subroutines shown have the following needs: 1. The initialization of the subroutine PERMUT decides which permutation takes place. The address of the actual description table is written to pointer register PTPOI. 2. Permutations are always made from table PTIN (input table) to table PTOUT (output table).

270

MSP430 Family

Metering Application Report

3. Only "Ones" are processed during the permutation. This saves 50% of processing time. The output buffer is therefore cleared initially by the PERMUT subroutine. 4. 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 64 bits are ; permuted to other tables. ; ; Definitions for the permutation software ; PTPOI .EQU R6 ; Pointer to description table PTBYTP .EQU R7 ; Byte index input table PTBITC .EQU R8 ; Bit counter inside input byte .BSS PTIN,8 ; Input table 64 bits .BSS PTOUT,8 ; Output table 64 bits EOT .EQU 040h ; End of table indication bit REP .EQU 080h ; Repetition bit ; ; 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 #PERMUT ; Process Initial Permutation ; ... ; ; Permutation subroutine. Table PTIN is permuted to table PTOUT ; PERMUT CLR PTBYTP ; Clear byte index input table CLR PTOUT ; Clear output table 8 bytes CLR PTOUT+2 CLR PTOUT+4 CLR PTOUT+6 PERML CLR PTBITC ; Bit counter (bits inside byte) L$502 RRA.B PTIN(PTBYTP) ; Next input bit to Carry JNC L$500 ; If bit = 0: No activity nec. L$501 CALL #PERM_BIT ; Bit = 1: Insert bit to output L$500 INC PTPOI ; Incr. description table pointer TST.B -1(PTPOI) ; REP bit set for last bit? JN L$501 ; Yes, process 2nd output bit ; ; 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,-1(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) 271

Metering Application Report

MSP430 Family

; 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 RET ; PTBIT .BYTE 1,2,4,8,10h,20h,40h,80h ; Bit table ; ; Description Table for the Initial Permutation. 64 bits of ; the input table are permuted to 64 bits in the output table ; (IP-1 table contains these numbers) ; IP .BYTE 40-1 ; Bit 1 -> position 40 .BYTE 8-1 ; Bit 2 -> position 8 ; ... .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 permutations multiplied with the number of cycles per bit gives an estimation of the needed processing time. 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 16 48 16 32 16 32 64 56 16 48 2744 58996 cycles 117992 cycles 32 ones in block 64 ones in block

Number of cycles typically (2744 43 x 0.5) maximum (2744 43)

272

MSP430 Family

Metering Application Report

For a block with 64 bits approximately 59ms are needed with an MCLK of 1MHz. ROM space: The needed ROM space can be divided into the following parts: 1. Main program (approx.) 2. Subroutines 3. Tables for permutations Sum of bytes 400 bytes 100 bytes 570 bytes 1070 bytes

The complete DES encryption software fits into 1K of bytes. 5.5.7.2 Output Sequence for 19.2kHz Bi-Phase Space Code The encrypted information is output normally with a Bi-Phase Code: Figure 55.5 shows such a modulation. At the beginning of a bit a level change occurs. A zero bit "0" has an additional level change in the middle of the bit, a one bit "1" has the same information during the whole bit.

"0"

"1"

"1"

"0"

"1"

"0"

"0"

"1"

Information Bi-Phase Space

RF off

RF on

Figure 55.5: Bi-Phase Space Code The output sequence is written for P0.4 (as shown in section Heat Allocation Meters). This means that no constant of the Constant Generator can be used. If P0.0, P0.1, P0.2 or P0.3 are used, the instructions which address the ports are one cycle shorter and the delay subroutines have to be adapted. The output sequence below is written with counted instructions per bit due to the normal use of batteries (Vcc = 3V) for these applications: this means the maximum MCLK is 1MHz. If the supply voltage is 5V then MCLK frequencies up to 3.3MHz 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 chapter RF Readout. ; ; ; ; ; OUT192 OUTPUTS THE RAM STARTING AT "RAMSTART" BITWISE IN BI-PHASE-CODE. EVERY 040h ADDRESSES A SCAN IS MADE TO READ P0.1 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.

273

Metering Application Report

MSP430 Family

; All interrupts must be disabled during this output subroutine! ; CALL #NOPx MEANS x CYCLES OF DELAY. MCLK = 1MHz ; OUTPUT .EQU 010h ; P0.4: PORT .EQU 011h ; PORT0 RAMSTART .EQU 0200h ; Start of output info 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 MOV MOV #16,Rz @Ry,Rx ; BIT COUNTER ; FETCH WORD CYCLES 2 5

; OUTPUT NEXT BIT: Change output state BITLOP XOR.B #OUTPUT,&PORT ; CHANGE OUTPUT PORT 5 ; ; CHECK IF NEXT SCAN OF WATER FLOW IS NECESSARY: Ry >= Rw ; CMP Rw,Ry ; 1 JHS SCAN ; YES 2 NOP ; NO 5 NOP NOP NOP NOP JMP BITT ; 2 SCAN ADD #SCAND,Rw ; NEXT SCAN ADDRESS 2 PUSH &PORT ; PUSH INFO OF PORT 5 ; BITT RRC Rx ; NEXT BIT TO CARRY 1 JNC OUT0 ; BIT = 0 2 ; ; BIT = 1: OUTPUT PORT IS CHANGED IN THE MIDDLE OF BIT ; CALL #NOP9 ; 9 XOR.B #OUTPUT,&PORT ; CHANGE OUTPUT PORT 5 JMP CHECK ; 2 ; ; BIT = 0: OUTPUT PORT STAYS DURING COMPLETE BIT ; OUT0 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

274

MSP430 Family JMP BITLOP ; ; ; COMPLETE WORD OUTPUT: ADDRESS NEXT WORD L$1 ADD CMP JEQ NOP NOP JMP #2,Ry #RAMEND,Ry COMPLET ; YES WORDLP

Metering Application Report 2

; POINTER TO NEXT WORD ; RAM OUTPUT? ; ; NO, NEXT WORD ; ; 4 SCANS ON STACK

2 2 2 2 2

; COMPLET ....

; 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 ; CALL #NOPxx needs 5 cycles NOP15 NOP NOP14 NOP NOP13 NOP NOP12 NOP NOP11 NOP NOP10 NOP NOP9 NOP NOP8 RET ; RET needs 3 cycles ; 5.5.8 Status/Input Matrix A few subroutines are described that handle the inputs coming from keys, signals aso. They check if the inputs are valid for the given status of the 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 yes, which response is necessary. This solution is recommended if only few valid combinations exist out of a large possible number. See figure 55.6

15

AKT02

STATUS 2 1 0 0 INPUT 1 2 3 4
AKT01 AKT03 AKT00 AKT00 AKT00

10

11

12

13

14

15

Figure 55.6: Matrix for few valid Combinations Call: Input number in R5 275

Metering Application Report Status in R4 R4 = 0: Input not valid (not included in the table) R4 # 0: task number in R4 MOV MOV CALL ... MOV.B ADD CMP.B JEQ INC TST.B JNE CLR RET STATUS,R4 INPUT,R5 #STIMTRX STTAB(R4),R4 #STTAB,R4 @R4+,R5 L$2 R4 0(R4) L$3 R4 ; ; ; ; ; ; ; ; ; ; ; ; ; Program status to R4 New input to R5 Check validity R4 contains info

MSP430 Family

Return

CALL

; STIMTRX L$3

Start of table for status Table address to R4 New input included in table? Yes, output it No, skip response byte End of status table? (0) No, try next input Yes, end of table reached Input invalid, return with R4 = 0

L$2

MOV.B @R4,R4 RET

; Input valid, return with task ; number in R4

; ; Table with relative start addresses for the status tables ; STTAB .BYTE ST0-STTAB,ST1-STTAB,ST2-STTAB,...ST15-STTAB ; ; Status tables: valid inputs,response,..,0 (up to 15 inputs) ; ST0 .BYTE IN5,AKT00,0 ; Status 0 table ST1 .BYTE IN1,AKT01,IN4,AKT03,0 ; Status 1 table ST2 .BYTE IN15,AKT00,IN6,AKT06,0 ; Status 2 table .... ; Status 3 to 14 ST15 .BYTE IN5,AKT02,0 ; Status 15 table With a small change, the task to do is also executed within the subroutine: CALL MOV MOV CALL ... MOV.B ADD CMP.B JEQ INC TST.B JNE CLR RET STATUS,R4 INPUT,R5 #STIMTRX STTAB(R4),R4 #STTAB,R4 @R4+,R5 L$2 R4 0(R4) L$3 R4 ; ; ; ; ; ; ; ; ; ; ; ; ; Program status to R4 New input to R5 Check validity and execute task R4 = 0: invalid input Start of table for status to R4 New input included? Yes, proceed No, skip task address End of status table? (0) No, try next input End of table reached Input invalid, return with R4 = 0

; STIMTRX L$3

L$2

MOV.B @R4,R4 ADD R4,PC

; Input valid, go to task ; offset to AKT00 in R4

276

MSP430 Family AKT00 AKT01 AKT06 AKT03 ... RET ... RET ... RET ... RET ; Task 00 ; Task 01 ; Task 06 ; Task 03

Metering Application Report

; ; Table with relative start addresses for the status tables ; STTAB .BYTE ST1-STTAB,ST2-STTAB,...ST15-STTAB ; ; Status tables: valid inputs,task-table_start,0 ; ST1 .BYTE IN5,AKT00-AKT00,0 ; Status 1 table ST2 .BYTE IN1,AKT01-AKT00,IN4, AKT03-AKT00,0 ST3 .BYTE IN15,AKT00-AKT00,IN6,AKT06-AKT00,0 .... ; Status 4 to 14 ST15 .BYTE IN5,AKT02-AKT00,0 ; 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. Call: Return CALL ; STIMTRX CALL MOV.B MOV.B RLA RLA ADD MOV.B ADD .BYTE .BYTE .BYTE ... .BYTE Input number in RAM byte INPUT (four possibilities 0 to 3) Program status in RAM byte STATUS (four possibilities 0 to 3) No information returned #STIMTRX ; Execute task for input

STTAB

STATUS,R4 ; Program status 00xx INPUT,R5 ; Input (key, Intrpt,) 0yy R4 ; STATUS x 4: 00xx -> 0xx0 R4 ; 0xx0 -> 0xx00 R5,R4 ; Build table offset: 0xxyy STTAB(R4),R4 ; Offset of Start of table R4,PC ; Handler start to PC AKT00-STTAB ; Action STATUS = 0, INPUT = 0 AKT01-STTAB ; Action STATUS = 0, INPUT = 1 AKT02-STTAB,AKT03-STTAB,AKT04-STTAB,AKT05-STTAB

AKT12-STTAB,AKT13-STTAB,AKT14-STTAB,AKT15-STTAB ; ; Action handlers for the 16 STATUS/INPUT xy combinations ; AKT00 ... ; Handler for task 0,0 RET AKT01 ... ; Handler for task 0,1 RET 277

Metering Application Report ... ... RET ... RET ; Tasks 02 to 31 ; Handler for task 3,2 ; Handler for task 3,3

MSP430 Family

AKT32 AKT33

The next subroutine also executes the tasks belonging to the 16 possible STATUS/INPUT combinations. Here the handler start addresses can be located in the complete 64K address space. The number of STATUS/INPUT combinations can be enlarged to any value. Call: Return CALL ; STIMTRX CALL MOV MOV RLA RLA ADD RLA MOV Input number in RAM byte INPUT (five possibilities 0 to 3) Program status in RAM byte STATUS (four possibilities 0 to 3) No information returned #STIMTRX STATUS,R4 INPUT,R5 R4 R4 R5,R4 R4 STTAB(R4),PC ; Execute task for input ; ; ; ; ; ; ; ; ; ; ; Program status 00xx Input (key, Intrpt) 0yy 00xx -> 0xx0 0xx0 -> 0xx00 0xxyy table offset To word addresses Offset of Start of table Action Action Action Action STATUS = STATUS = handlers STATUS = 0, INPUT 0, INPUT AKT02 to 3, INPUT = 0 = 1 AKT32 = 3

; STTAB

.WORD AKT00 .WORD AKT01 ... .WORD AKT33

278

MSP430 Family 5.6 The Floating Point Package

Metering Application Report

Floating point arithmetic is necessary if the range of the used numbers 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 24bit and 40bit 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 binary-coded-decimal (BCD) numbers. Examples are given for a lot of subroutines and applications like the square root are included in a software example chapter. The Floating Point Package makes use of the RISC architecture of the MSP430 family: during the initialization of the subroutines the arguments are copied into the registers (R4 to R15) and the complete calculations take place there. After the completion of the calculation the result is placed on the top of the stack. 5.6.1 General This Floating Point Package (FPP) consists of 3 files supporting the .FLOAT format (32 bits) and the .DOUBLE format (48 bits): 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 may 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 appertaining sections. FPP4 is upward compatible to FPP3. The assembly time variable DOUBLE defines which format is to be used: DOUBLE = 0: 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: SW_UFLOW = 1: Software underflow (result is zero) is not treated as an error 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 16 bit hardware multiplier is used

279

Metering Application Report

MSP430 Family

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 in RAM. Before the call for an operation the two pointers RPARG and RPRES are loaded with the address(es) of the most significant word MSW of the argument(s). After the return from the call both pointers and also the stack pointer SP point to the result (on the stack) for an easy continuation of arithmetical expressions. NOTES 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 @SP or 0(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 may be used freely: the result of the last operation is stored on the stack. See note above. If at an intermediate stage of the Basic Arithmetic Operations renormalization shift of one or more bit positions to the left is required - to compensate for loss of leading bits - then valid bits are available for the shift into the low-order 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 which hold the pointers are called: RPRES RPARG Pointer to Argument 1 and Result Pointer to Argument 2 and Result

The following possibilities to address the two operands exist:

280

MSP430 Family

Metering Application Report


1. RESULTNEW = @(RPRES) < operator > @(RPARG) 2. RESULTNEW = @(RPRES) < operator > RESULTOLD 3. RESULTNEW = RESULTOLD < operator > @(RPARG)

To 1. RPRES and RPARG both point to the arguments for the next operation. This is the common form that is always valid independent where the two pointers point to (new arguments or result). The result of the operation is written to the address the stack pointer SP points to. 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). To 3. RPARG points to the 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). NOTE The formulas 2 and 3 are not equal, they allow to use the result on the TOS in two ways with the division and the subtraction. No time and ROMconsuming 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 was used as an operand. 3. The result is located on the top of the stack (TOS), the stack pointer SP, 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", "De-normalized Number" or "Infinity" do exist. This way the MSP430 FPP has a larger range than other FPPs have and allows a higher speed with smallest memory usage. This is due to the unnecessary checks for invalid numbers. 5. Every floating point operation outputs a valid floating point number that can be used immediately by the other operations. 6. If a result is too large (exceeds the number range) then the signed, maximum number is output. An error indication is given in this case (see Error Indication Table). 7. The CPU registers used are modified within the FPP subroutines, but do not contain necessary information after the return from the subroutine. This means they may 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 the ideal fit for this target. A common save and recall routine for the registers used at the beginning and the end of an arithmetical expression is an additional optimization. The subroutines FLT_SAV and FLT_REC should be applied as shown in the examples below.

281

Metering Application Report 5.6.3.1 Addition FLT_ADD

MSP430 Family

The floating point number pointed to by the register RPARG is added to the floating point number pointed to by the register RPRES. The 25th bit (41st 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)


Errors: Output: Normal error handling. See chapter Error Handling for a detailed description. The floating point sum of the two arguments is placed on the top of the stack. The stack pointer SP points to the same location as it did before the subroutine call. The stack pointer SP, RPRES and RPARG point to the MSBs of the floating point sum. If an error occurred (N = 1 after return) then the result is the number that represents the correct result best: 0 resp. 3.4 1038.

EXAMPLE: The floating point number (.FLOAT format) contained in the ROM locations starting at address NUMBER is added to the RAM locations pointed to by R5. The result is written to the RAM addresses RES, and RES+2 (LSBs). DOUBLE .EQU MOV MOV CALL JN MOV MOV ... 0 R5,RPRES #NUMBER,RPARG #FLT_ADD ERR_HND @RPRES+,RES @RPRES+,RES+2 ; ; ; ; ; ; ; Address of Argument 1 in R5 Address of Argument 2 Call add subroutine Error occurred, check reason Store FPP result (MSBs) LSBs Continue with program

5.6.3.2 Subtraction FLT_SUB The floating point number pointed to by the register RPARG is subtracted from the floating point number pointed to by the register RPRES. By proper loading of the two input pointers it is possible to calculate (Argument1 - Argument2) and (Argument2 - Argument1). The 25th bit (41st bit in case of DOUBLE format) of the calculated mantissa is used for rounding: it is subtracted from the result.

RESULT on TOS = @(RPRES) - @(RPARG)


Errors: Output: Normal error handling. See chapter Error Handling for a detailed description. The floating point difference of the two arguments is placed on the top of the stack. The stack pointer SP points to the same location as it did before the subroutine call. The stack pointer SP, RPRES and RPARG point to the MSBs of the floating point difference. If an error occurred (N = 1 after return) then the result is the number that represents the correct result best: 0 resp. 3.4 1038.

282

MSP430 Family

Metering Application Report

EXAMPLE: The floating point number (.DOUBLE format) contained in the ROM locations starting at address NUMBER is subtracted from the RAM locations pointed to by R5. The result is written to the RAM addresses pointed to by R5. DOUBLE .EQU MOV MOV CALL JN MOV MOV MOV ... 1 R5,RPRES #NUMBER,RPARG #FLT_SUB ERR_HND @RPRES+,0(R5) @RPRES+,2(R5) @RPRES,4(R5) ; ; ; ; ; Address of Argument1 in R5 Address of Argument2 ((R5)) - (NUMBER) -> TOS Error occurred, check reason Store FPP result (MSBs)

; LSBs ; Continue with program

5.6.3.3 Multiplication 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 (41st and 42nd bit in case of DOUBLE format) of the calculated mantissa are used for rounding: If a shift is necessary to get the MSB of the mantissa set then the LSB-1 is shifted into the mantissa and the LSB-2 is added to the result. If the MSB of the mantissa is yet set then only the LSB-1 is added to the result. The multiplication subroutine returns the same result independent if the hardware multiplier is used (HW_MPY = 1) or not (HW_MPY = 0).

RESULT on TOS = @(RPRES) @(RPARG)


Errors: Output: Normal error handling. See chapter Error Handling for a detailed description. The floating point product of the two arguments is placed on the top of the stack. The stack pointer SP points to the same location as it did before the subroutine call. The stack pointer SP, RPRES and RPARG point to the MSBs of the floating point product. If an error occurred (N = 1 after return) then the result is the number that represents the correct result best: 0 resp. 3.4 1038. 00=0 0X=0 X0=0

Special Cases:

EXAMPLE: The result of the last operation, a floating point number (.FLOAT format) on the top of the stack, is multiplied by the constant . DOUBLE .EQU MOV CALL JN ... .FLOAT 0 #PI,RPARG #FLT_MUL ERR_HND 3.1415926535 ; ; ; ; ; Address of constant PI ((RPRES)) x (PI) -> TOS Error occurred, check reason Continue with program Constant PI

PI

283

Metering Application Report 5.6.3.4 Division FLT_DIV

MSP430 Family

The floating point number pointed to by the register RPRES is divided by the floating point number pointed to by the register RPARG. By proper loading of the two input pointers it is possible to calculate (Argument1 / Argument2) and (Argument2 / Argument1). The 25th bit (41st 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)

Errors:

Normal error handling. See chapter Error Handling for a detailed description. Division by zero is indicated too. The floating point quotient of the two arguments is placed on the top of the stack. The stack pointer SP points to the same location as it did before the subroutine call. The stack pointer SP, RPRES and RPARG point to the MSBs of the floating point quotient. If an error occurred (N = 1 after return) then the result is the number that represents the correct result best for example the largest number that can be represented if a division by zero was made. 0/0 = 0 0/X = 0 -X/0 = max. neg. number +X/0 = max. pos. number

Output:

Special Cases:

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. DOUBLE .EQU MOV MOV CALL JN MOV MOV MOV ... 1 R5,RPARG #NUMBER,RPRES #FLT_DIV ERR_HND @RPRES+,0(R5) @RPRES+,2(R5) @RPRES,4(R5) ; ; ; ; ; Address of dividend Address of divisor (NUMBER) / ((R5)) -> TOS Error occurred, check reason Store FPP result (MSBs)

; LSBs ; Continue with program

Examples for the Basic Arithmetic Operations The example below shows the following program steps for the .FLOAT format: 1. 2. 3. The used registers R5 to R12 are saved on the stack. Four bytes are allocated on the stack to hold the results of the operations. The pointer to a 12-digit BCD-buffer is loaded into pointer RPARG and the BCD-tofloating point conversion is called. The resulting floating point number is written to the result space allocated before. The resulting floating point number is multiplied with a number residing in the memory address VAL3. RPARG points to this address. To the last result a floating point number contained in the memory address VAL4 is added

4. 5.

284

MSP430 Family 6. 7.

Metering Application Report

8.

The final result is converted back to BCD format (6 bytes) that can be displayed in the LCD. The final result is copied to the RAM addresses BCDMSD, BCDMID and BCDLSB. The three necessary POP instructions correct the stack pointer SP to the value after the "Save Register" subroutine. The used registers R5 to R12 are restored from the stack. The system environment is exactly the same now as before the floating point calculations. .EQU ...... CALL SUB MOV CALL 0 #FLT_SAV #4,SP #BCDB,RPARG #CNV_BCD_FP ; Use .FLOAT format ; ; ; ; ; Normal program Save registers R5 to R12 Allocate stack for result Load address of BCD-buffer Convert BCD number to FP

DOUBLE ;

; ; 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 JN CNVERR ; Result too big for BCD buffer POP BCDMSD ; BCD number MSDs and sign POP BCDMID ; BCD digits MSD-4 to LSD+4 POP BCDLSD ; BCD digits LSD+3 to LSD ; Stack is corrected by POPs CALL #FLT_REC ; Restore registers R5 to R12 ; Continue with program VAL3 .FLOAT -1.2345 ; Slope VAL4 .FLOAT 14.4567 ; Offset CNVERR ... ; Start error handler The next example shows the following program steps for the .DOUBLE format: 1. 2. 3. The used registers R5 to R15 are saved on the stack. Six bytes are allocated on the stack to hold the results of the operations. 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 allocated before. The resulting floating point number is multiplied with a number located at the memory address VAL3. RPARG points to this address. To the last result a floating point number contained in the memory address VAL4 is added. The final result is converted back to binary format (6 bytes) that can be used for integer calculations. The resulting binary number is copied to the RAM addresses BINMSD, BINMID and BINLSB. The three necessary POP instructions correct the stack pointer SP to the value after the "Save Register" subroutine.

4. 5. 6. 7.

285

Metering Application Report 8.

MSP430 Family

The used registers R5 to R15 are restored from the stack. The system environment is now exactly the same as it was before the floating point calculations. .EQU ...... CALL SUB MOV CALL 1 #FLT_SAV #6,SP #ADAT,RPARG #CNV_BIN16U ; Use .DOUBLE format ; ; ; ; ; Normal program Save registers R5 to R15 Allocate stack for result Load address of ADC data buffer Convert unsigned result to FP

DOUBLE ;

; ; Calculate (ADC-Result 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_BIN ; Convert final FP result to binary POP BINMSD ; Store MSBs of result and sign 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 SR is reset to zero, no error occurred. If the N-bit is set to one, an error occurred. The kind of error can be seen in the Error Indication Table below. The columns .FLOAT and .DOUBLE show the returned results for each error. Table 56.1: Error Indication Table Error No error Overflow positive Overflow negative Underflow Divide by zero Dividend positive Dividend negative Status N=0 N=1, C=1, Z=1 N=1, C=1, Z=0 N=1, C=0, Z=0 N=1, C=0, Z=1 .FLOAT xxxx,xxxx FF7F,FFFF FFFF,FFFF 0000,0000 FF7F,FFFF or FFFF,FFFF .DOUBLE xxxx,xxxx,xxxx FF7F,FFFF,FFFF FFFF,FFFF,FFFF 0000,0000,0000 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

286

MSP430 Family

Metering Application Report

subroutine level during the calculations for the common initialization subroutine. The allocation in figure 56.1 is shown for the use of FLT_SAV.

Address n R12 Address n-4 R11 R5 Address n-8 R6 R7 Address n-12 R8 R9 Address n-16 R10 Return FLT_SAV Address n-20 Result LSBs Result MSBs Address n-24 Return FLT-xxx

SP during MAIN

Address n R15 Address n-4 R14 R5 Address n-8 R6 R7 Address n-12 R8 R9 Address n-16 R10 R11 Address n-20 R12 R13 Address n-24 Return FLT_SAV Result LSBs Address n-28 Result MIDs Result MSBs Address n-32 Return FLT-xxx

SP during MAIN

SP after return SP during FLT_xxx

SP after return SP during FLT_xxx

Figure 56.1: Stack Allocation for .FLOAT and .DOUBLE Formats The FPP-subroutines work only correctly if the above allocation is provided. This means the stack pointer SP points to the return address on the stack. If the FPP-subroutines are called inside of a subroutine then 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 example below shows the correct procedure: SUBR SUB MOV MOV .if MOV .endif MOV MOV CALL ... MOV MOV .if MOV .endif RET #(ML/8)+1,SP @RPARG+,0(SP) @RPARG+,2(SP) DOUBLE=1 @RPARG,4(SP) SP,RPARG #xx,RPRES #FLT_xxx @SP+,result @SP+,result+2 DOUBLE=1 @SP+,result+4 ; Allocate new result area ; Fetch argument 2 to new ; result area

; ; ; ; ; ;

Point again to argument 2 Point to argument 1 Use new result area for calc. Continue with calculations Free allocated stack Store result, correct SP

Note that it is strongly recommended to provide conscientious housekeeping for the stack pointer SP to avoid stack overflow. 5.6.3.7 Number Range and Resolution E = exponent of the floating point number. See chapter 5.6.5 for explanation.

287

Metering Application Report

MSP430 Family

5.6.3.7.1 .FLOAT Format Most positive number Least positive number Zero Least negative number Most negative number Resolution 5.6.3.7.2 .DOUBLE Format Most positive number Least positive number Zero Least negative number Most negative number Resolution FF7F,FFFF,FFFF 0000,0000,0001 0000,0000,0000 0080,0000,0000 FFFF,FFFF,FFFF 2127 x (2 - 2-39) 2-128 x (1 + 2-39) 0 -2-128 -2127 x (2 - 2-39) 2-39 x 2E = 3.402824 x 1038 = 2.938736 x 10-39 = 0.0 = -2.938736 x 10-39 = -3.402824 x 1038 = 1.818989 x 10-12 x 2E FF7F,FFFF 0000,0001 0000,0000 0080,0000 FFFF,FFFF 2127 x (2 - 2-23) 2-128 x (1 + 2-23) 0 -2-128 -2127 x (2 - 2-23) 2-23 x 2E = 3.402823 x 1038 = 2.938736 x 10-39 = 0.0 = -2.938736 x 10-39 = -3.402823 x 1038 = 119.2093 x 10-9 2E

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. Only if the signs of the two operands are equal, then the mantissas are compared. After the comparison the status bits of the status register (SR) 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 56.2 Comparison Results Relations Argument 1 > Argument 2 Argument 1 < Argument 2 Argument 1 = Argument 2 Status C=1, Z=0 C=0, Z=0 C=1, Z=1

The calling and the use of the returned status bits is shown in the next example: ... MOV #ARG1,RPRES MOV #ARG2,RPARG CALL #FLT_CMP JEQ EQUAL JHS ARG1_GT_ARG2 ...... EQUAL ...... ARG1_GT_ARG2 .. ; ; Other possibilities after the ; CALL #FLT_CMP JHS ARG1_GE_ARG2 ; ; ; ; ; ; ; ; Point to Argument 1 MSBs Point to Argument 2 MSBs Comparison: result to SR Condition for program flow ARG1 is greater than ARG2 ARG1 is less than ARG2 ARG1 and ARG2 are equal ARG1 is greater than ARG2

return ; Comparison: result to SR ; ARG1 is greater/equal ARG2

288

MSP430 Family ...... ; CALL JNE ...... ; CALL JLO ...... #FLT_CMP ARG1_LT_ARG2 #FLT_CMP ARG1_NE_ARG2

Metering Application Report ; ARG1 is less than ARG2 ; Comparison: result to SR ; @RPRES not equal to @RPARG ; ARG1 is equal to ARG2 ; Comparison: result to SR ; ARG1 is less than ARG2 ; ARG1 is greater/equal ARG2

5.6.5 Internal Data Representation The description explains both the FLOAT and the DOUBLE formats. The two floating point formats consist of a floating point number whose 8 most significant bits represent the exponent and the 24 resp. 40 least significant bits hold the sign and the mantissa.

31 Exponent e7 47 Exponent e7 e0 Sm m38 e0 Sm m22

16 15 Mantissa

0 .FLOAT m0

32 31 Mantissa

16 15

0 .DOUBLE m0

Figure 56.2: 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

N = ( 1) Sm M 2 E
NOTE The only exception to the above equation is the floating zero: it is represented by all zeroes (32 resp. 48 zeroes). No negative zero exists, the corresponding number (0080,0000) is a valid non-zero number: the smallest negative number. An often 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 used often in a real time environment where calculations need to be completed before the next input data are present.

289

Metering Application Report

MSP430 Family

2. Battery supplied applications make short calculations necessary to reach battery lifes longer than for example 10 years. These two main reasons make a run-time optimized floating point package necessary. The format of the floating point number plays an important role to reach this target: With the MSP430-format every floating point number represents a valid value. No invalid combinations like "Not a Number", "De-normalized Number" or "Infinity" exist. This way the MSP430 FPP has a larger range than other FPPs have and allows a higher speed with smallest memory usage. This is due to the unnecessary checks for invalid numbers. The exponent of the IEEE-format is located in two bytes due to 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 use therefore the advantages of the byte-oriented architecture of the MSP430: no shifts and no bit handling are necessary to manipulate the exponent.

5.6.5.1 Computation of the Mantissa M

M = 1 +

(m
i=0

22

2 i 23 )

. FLOAT Format

M = 1 +

(m
i=0

38

2 i 39 )

. DOUBLE Format

The result of the above calculation is always: 2 > M 1 For the MSB 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 therefore called Hidden Bit. The sign bit is located at this place instead: Sm = 0: Sm = 1: positive Mantissa negative Mantissa

NOTE Note that the mantissa of a negative floating point number is NOT represented as a twos-complement number, only the sign bit Sm decides if the floating-point number is positive or negative. 5.6.5.2 Computation of the Exponent E

E =

(e
i=0

2 i ) 128

The MSB of the exponent indicates whether the exponent is positive or negative. MSB of exponent = 0: The exponent is negative MSB of exponent = 1: The exponent is positive

290

MSP430 Family

Metering Application Report

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 Y .float .float 3.1416 3.1416*100 ; Resp. .double 3.1416 ; 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 MOV CALL .... #X,RPRES #Y,RPARG #FLT_xxx ; ; ; ; Address 1st operand Address 2nd operand X <op> Y Result on TOS

The following table shows the necessary number of cycles needed for the above shown calculations: Table 56.3: CPU Cycles needed for Calculations .FLOAT .DOUBLE Comment Operation 184 207 Addition X+Y 177 199 Subtraction X-Y 395 692 Software Loop Multiplication X Y 153 213 Hardware MPYer Multiplication X Y 405 756 Division X/Y 37 41 Comparison X - Y 5.6.7 Conversion Routines 5.6.7.1 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_BINxxx Convert 16-bit, 32-bit or 40-bit signed and unsigned integer binary numbers to the floating point format. See 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

CNV_BCD_FP CNV_FP_BIN CNV_FP_BCD

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 it is the result of the previous operation on the TOS 3. The result is located on the top of the stack (TOS), the stack pointer SP, RPARG and RPRES point to the most significant word of the result 291

Metering Application Report

MSP430 Family

4. Only integers are converted. See section 5.6.7.3 for the handling of non-integer numbers 5. The result is calculated using truncation normally, except rounding is specified. The assembly time variable SW_RND defines which mode is to be used: SW_RND = 0: SW_RND = 1: Truncation is used, the trailing bits are cut off Rounding is used, the first unused bit is added to the number

See section Rounding and Truncation for details. 6. The subroutines may 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: DOUBLE = 1: 7. Two word format .FLOAT Three word format .DOUBLE

All conversion subroutines need two resp. 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: .equ .equ SUB SUB SUB SUB 24 ; For .FLOAT. ML = 40 for .DOUBLE (ML/8)+1 ; Length of one FP number #4,SP ; .FLOAT format allocation #6,SP ; .DOUBLE format allocation #(ML/8)+1,SP ; For both formats #FPL,SP ; For both formats

ML FPL or or

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 formats, error handling and number range are given for each conversion. 5.6.7.2.1 Binary to Floating Point Conversions Binary numbers, 16-bit, 32-bit and 40-bit in length, are converted to floating point numbers. The used subroutine call defines if the binary number is treated as a signed or an unsigned number. No errors are possible, the N-bit of the Status Register 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 56.3 Range: -32768 to + 32767 (08000h to 07FFFh)

292

MSP430 Family

Metering Application Report

15 Address n Sign

0 RPARG

Figure 56.3: Signed Binary Input Buffer Format 16 Bits CNV_BIN16U The 16-bit number, RPARG points to, is treated as a 16-bit unsigned number. See figure 56.4 Range: 0 to + 65535 (00000h to 0FFFFh)
15 Address n 0 RPARG

Figure 56.4: 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 56.5 Range: -231 to +231 - 1 (08000,0000h to 07FFF,FFFFh)
15 Address n+2 Address n Sign RPARG 0

Figure 56.5: 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 56.6 Range: 0 to 232 - 1 (00000,0000h to 0FFFF,FFFFh)
15 Address n+2 Address n MSB 0 LSB RPARG

Figure 56.6: Unsigned Binary Input Buffer Format 32 Bits CNV_BIN40 The 48-bit number, RPARG points to, is treated as a 40-bit signed resp. unsigned number. See figure 56.7 Range signed: Range unsigned: -240 +1 to +240 - 1 (0FF00,0000,0001h to 000FF,FFFF,FFFFh) 0 to +240 - 1 (00000,0000,0000h to 000FF,FFFF,FFFFh) 293

Metering Application Report

MSP430 Family

15 Address n+4 Address n+2 Address n Sign Byte MSBs LSBs

RPARG

Figure 56.7: Binary Number Format 48 Bit The above 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 used call (signed or unsigned) 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 56.8 Range signed: Range unsigned: -240 +1 to +240 - 1 (0FF00,0000,0001h to 000FF,FFFF,FFFFh) 0 to +240 - 1 (00000,0000,0000h to 000FF,FFFF,FFFFh)
0 LSBs

15 BIN_LSB BIN_MID BIN_MSB Sign Byte MSBs

Figure 56.8: Binary Number Format 48 Bit NOTE Input values outside of the 40-bit range shown above do not generate error messages. The leading bits are truncated and only the trailing 40-bits are converted to the floating point format. Errors: Output: .FLOAT .DOUBLE No error is possible, the N-bit of the Status Register is always cleared on return. The output depends on the chosen floating point format, selected with the assembly time variable DOUBLE. 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. The three-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.

EXAMPLE: The 32-bit signed binary number contained in the 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).

294

MSP430 Family

Metering Application Report

DOUBLE

.EQU MOV CALL MOV MOV MOV ...

1 #BINHI,RPARG #CNV_BIN32 @RPRES+,RES @RPRES+,RES+2 @RPRES,RES+4

; ; ; ; ; ;

Define .DOUBLE format Address of binary MSBs Call conversion subroutine Store MSBs of result Store LSBs of result

5.6.7.2.2 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 Address n+4 Address n+2 Address n Sign MSD MSD-1 RPARG LSD+1 LSD 0

Figure 56.9: BCD Buffer Format CNV_BCD_FP The 12-digit number (contained in 3 words, see figure 56.9), RPARG points to, is converted to a floating point number. Range: -8 x 1011 +1 to +8 x 1011 -1

Errors:

Output: .FLOAT .DOUBLE

No error is possible, the N-bit 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. A floating point number on the top of the stack: 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. The three-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.

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_BCD_FP @RPRES+,RES @RPRES,RES+2 ; ; ; ; ; ; 295 Define .FLOAT format Address of BCD MSDs Call conversion subroutine Store FP result (MSBs) LSBs Continue with program

Metering Application Report

MSP430 Family

5.6.7.2.3 Floating Point to Binary Conversion The floating point number pointed to by the register RPARG is converted to a 40-bit signed binary number located on the top of the stack after conversion. See figure 56.10.

15 Address n+4 Address n+2 Address n Sign Byte (0 or FF) MSBs LSBs

SP, RPARG

Figure 56.10: Binary Number Format CNV_FP_BIN The floating point number, RPARG points to, is converted to a 40-bit signed binary number. Range signed: -240 +1 to + 240 - 1 (0FF00,0000,0001h to 000FF,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 on top of the stack is the largest signed binary number (saturation mode). A 40-bit signed, binary number at the top of the stack.. The sign uses a full byte. The stack pointer 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 reading of the result. The stack pointer SP, RPRES and RPARG point to the MSBs of the three word binary result.

Output: .FLOAT

.DOUBLE

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, and RES+2 and RES+4 (LSBs). DOUBLE .EQU MOV CALL JN MOV MOV MOV ... 1 #FPHI,RPARG #CNV_FP_BIN ERR_HND @RPRES+,RES @RPRES+,RES+2 @RPRES,RES+4 ; ; ; ; ; ; ; Address of FP MSBs Call conversion subroutine |FP number| is too big Store binary result (MSBs) LSBs Continue with program

296

MSP430 Family

Metering Application Report

5.6.7.2.4 Floating Point to Binary Coded Decimal Conversion The floating point number pointed to by the register RPARG is converted to a signed 12-digit BCD number located on the top of the stack after conversion. See figure 56.9. The MSD of the result has a maximum value of 7 due to the sign bit that uses the MSB position. CNV_FP_BCD The floating point number, RPARG points to, is converted to a 12-digit signed BCD number. Range: Errors: -8 x 1011 +1 to +8 x 1011 -1

Three errors at different stages of the conversion are possible that will set the N-bit in the status register: 1. The exponent value of the floating point number is greater than 39 which represents an absolute value greater than 1.0995 x 1012 2. The absolute value of the floating point number is greater than 8 x 1011 -1 3. The absolute value is greater than 1 x 10 12 Otherwise the N bit is cleared. The result on top of the stack is the largest signed BCD number in case of an error. A 12-digit signed BCD number at the top of the stack.. See figure 56.9. The stack pointer 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. The stack pointer SP, RPRES and RPARG point to the MSDs of the three word BCD result.

Output: .FLOAT

.DOUBLE

EXAMPLE: The floating point number (.FLOAT format) contained in the RAM locations starting at label FPHI (MSBs) is converted to a 12-digit BCD number. The result is written to the RAM addresses RES, and RES+2 and RES+4 (LSDs). DOUBLE .EQU MOV CALL JN MOV MOV MOV ... ... 0 #FPHI,RPARG #CNV_FP_BCD ERR_HND @SP+,RES @SP,RES+2 2(SP),RES+4 ; ; ; ; ; ; ; ; Address of FP MSBs Call conversion subroutine |FP number| is too big Store BCD result (MSDs) SP is corrected LSDs Continue with program Correct error here

ERR_HND

5.6.7.3 Handling of non-integer Numbers The conversion subroutines allow only the handling of integer numbers when converting to or from floating point numbers. The reasons for this restriction are: 1. 2. 3. 4. The stack grows if non-integer handling is included The necessary program code of the conversion software grows strongly The integration of non-integer numbers is easier outside of the conversion subroutines The execution time grows strongly due to the necessary successive divisions multiplications by 10. This cannot be tolerated in real time environments. 297

or

Metering Application Report

MSP430 Family

5.6.7.3.1 Binary to Floating Point Conversion If the location of the decimal point in the binary or hexadecimal number is known, then the correction of the result is as follows: The resulting floating point number is divided by the constant 2n for binary numbers resp. 16m for hexadecimal numbers (with m = 0.25n). This is made simply by subtracting of 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 buffer contains 1011000 (8810) but the real number is 10.11000 (2.7510: 88 / 32 = 2.75) MOV #BINHI,RPARG CALL #CNV_BIN32 SUB.B #5,1(SP) ... ; ; ; ; Address of binary buffer MSBs Call conversion subroutine Correct results exp. by 2^5 Continue with corrected number

5.6.7.3.2 Binary Coded Decimal to Floating Point Conversion If the location of the decimal point in the BCD number is known, then the correction of the result is as follows: The resulting floating point number is divided by the constant 10n after the conversion. Overflow or underflow is not possible due to the restricted range of the 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, containing 123456 represents the number 123.456 DOUBLE .EQU MOV CALL MOV CALL ... .FLOAT 0 #BCDHI,RPARG ; Address of BCD buffer MSDs #CNV_BCD_FP ; Call conversion subroutine #FLT1000,RPARG ; Address of constant 1000 #FLT_DIV ; Correct result by 1000 ; Continue with corrected input 1000 ; Correction constant 1000

FLT1000

If the location of the decimal point relative to the numbers end is contained in a byte DPL (content > 0) the following code may be used: DOUBLE LOOP .EQU MOV CALL MOV CALL 1 #BCDHI,RPARG #CNV_BCD_FP #DBL10,RPARG #FLT_DIV ; ; ; ; Address of BCD buffer MSDs Call conversion subroutine Divide result by 10 as often as DPL defines

298

MSP430 Family DEC.B DPL JNZ LOOP ... .DOUBLE 10 ; ; ; ;

Metering Application Report DPL - 1 Repeat as often as necessary Continue with corrected input Correction constant 10

DBL10

5.6.7.3.3 Floating Point to Binary Conversion If the binary result should contain n binary digits after the decimal point then the following procedure may be used: The floating point number is multiplied by the constant 2n before the conversion call. This is made simply by adding of n to the exponent of the floating point number. Overflow may occur if the floating point number is very large and cannot be converted to binary format anyway. 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 result (this means the result needs to be 16-times larger). For example: The floating point number is 12.125, the resulting binary number is 110000102 (C216) not only 11002 (C16) . DOUBLE .EQU MOV MOV ADD.B MOV CALL ... 0 FPHI,0(SP) FPHI+2,2(SP) #4,1(SP) SP,RPARG #CNV_FP_BIN ; ; ; ; ; ; MSBs of FP number to TOS LSBs to TOS+2 Correct exponent by 2^4 Act. pointer (if not yet done) Call conversion subroutine Result includes 4 add. bits

If the floating point number to be converted may be modified then a simplified code may be used: MOV ADD.B CALL ... #FPHI,RPARG #4,1(RPARG) #CNV_FP_BIN ; ; ; ; Address of FP number MSBs Correct exponent by 2^4 Call conversion subroutine Result includes 4 add. bits

5.6.7.3.4 Floating Point to Binary Coded Decimal Conversion If the BCD result of this conversion should contain n digits after the decimal point then the following procedure may be used: The floating point number is multiplied by the constant 10n before the conversion call. Overflow may occur if the floating point number is very large and cannot be converted to BCD format anyway due to the buffer length (12 digits max.). 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 MOV MOV 1 #FPHI,RPARG ; Address of FP number (MSBs) #DBL100,RPRES ; Address of constant 100

299

Metering Application Report CALL #FLT_MUL CALL #CNV_FP_BIN ... .DOUBLE 100 ; ; ; ;

MSP430 Family FP number x 100 -> TOS Call conversion subroutine Result includes 2 add. digits Constant 100

DBL100 ; 5.6.7.4 Rounding and Truncation

Two different modes for the 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) then the intermediate result is incremented, otherwise the result is not affected. If a carry occurs during the incrementing, then the exponent is corrected too. Rounding is used if SW_RND = 1 is selected during assembly. Rounding is applied (if chosen by 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 like with the binary to floating point conversion the 2-1 bit (the bit representing 0.5) of the floating point number is added to the binary integer result 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.

BCD to Floating Point: Floating Point to Binary: Floating Point to BCD:

If rounding is specified during assembly (SW_RND = 1), then 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 give an impression how long data conversion will take, the needed 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. Rounding is used. The cycle count for each conversion includes the loading of the pointer RPARG, the subroutine call and the conversion itself.

300

MSP430 Family

Metering Application Report Table 56.4: Execution Cycles of the Conversion Routines

Conversion CNV_BIN40 CNV_BCD_FP CNV_FP_BIN CNV_FP_BCD

.FLOAT 1 418 1223 535 1174

.FLOAT max 67 890 67 706

.DOUBLE 1 422 1227 531 1170

.DOUBLE max 71 894 63 701

5.6.8 Memory Requirements of the Floating Point Package The memory requirements of an implemented Floating Point Package are depending 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 56.5: Memory Requirements without Hardware Multiplier Package Basic Arithmetic Operations Conversion Subroutines Complete FPP .FLOAT 604 342 946 .DOUBLE 696 338 1034

Table 56.6: Memory Requirements with Hardware Multiplier Package Basic Arithmetic Operations Conversion Subroutines Complete FPP .FLOAT 638 342 980 .DOUBLE 786 338 1124

5.6.9 Inclusion of the Floating Point Package into the Customer Software This chapter shows how to insert the Floating Point Package into the users software. The symbolic definition of the working registers makes it necessary to include the FPP-definition file (FPPDEF4.ASM) before the customers 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 will fail. The two files FPP04.ASM and CNV04.ASM need to be located together as shown in the examples below. This is due to the common parts that are connected with jumps. The constant DOUBLE decides which FPP version will be generated. ; .text 08000h ; ROM/EPROM start address STACK .equ 0300h ; Initial value for SP ; DOUBLE .equ 1 ; Use .DOUBLE format FPP SW_UFLOW .equ 0 ; Underflow is no error SW_RND .equ 1 ; Use rounding for conversions HW_MPY .equ 1 ; Use the hardware multiplier ; .copy c:\fpp\fppdef4.asm ; FPP Definitions .copy c:\fpp\fpp04.asm ; FPP file 301

Metering Application Report .copy c:\fpp\cnv04.asm ; ; Customer software starts here ; START MOV #STACK,SP ..... ; Power-up start address: ; .sect "RstVect",0FFFEh .word START

MSP430 Family ; FPP Conversions

; Allocate stack ; Users SW starts here

; Reset vector

A second possibility is shown below: the FPP is located after the users software: ; .text 0E000h ; ROM start address STACK .equ 0300h ; Initial value for SP ; DOUBLE .equ 0 ; Insert .FLOAT format FPP SW_UFLOW .equ 1 ; Underflow is an error SW_RND .equ 0 ; No rounding for conversions HW_MPY .equ 0 ; No hardware multiplier ; .copy c:\fpp\fppdef4.asm ; FPP Definitions ; ; Customer software starts here ; START MOV #STACK,SP ; Allocate stack ..... ; ..... ; End of user's software .copy c:\fpp\fpp04.asm ; Copy FPP file .copy c:\fpp\cnv04.asm ; Copy conversions ; ; Power-up start address: ; .sect "RstVect",0FFFEh .word START ; Reset vector 5.6.10 Software Examples 5.6.10.1 Square Root Subroutines The following two subroutines show the use of the Floating Point Package for the calculation of the square root of a number. The NEWTONIAN approach is used: xn + 1 = 0.5 xn +

A xn

The subroutines use the same approach as the FPP subroutines: the input and the result are located on the top of the stack. A stack location is used for the counting of the approximation loops. The used algorithm for the 1st estimation (exponent/2) leads to worst case errors of +41% and 29%. The table below shows the maximum errors for each approximation step:

302

MSP430 Family

Metering Application Report

Table 56.7: Square Root Approximation Errors Step Max. pos. Error Max. neg. Error 1st estimation x0 +41% -29% 1st approximation x1 +6% +6% 2nd approximation x2 +0.17% +0.17% 3rd approximation x3 +1.5ppm +1.5ppm 4th approximation x4 <210-12 <210-12 5th approximation x5 <210-24 <210-24 ; Square Root Subroutine for .FLOAT format ; Calculate the square root out of A. A is located on TOS, where ; otherwise the results are located. The square root overwrites A ; For input RPARG and RPRES are not relevant ; SP, RPARG and RPRES point to a correct result on TOS ; RPARG and RPRES are not defined if the input is negative (N = 1) ; FLT_SQRT TST.B 2(SP) ; Argument negative? JN SQRET ; Yes, return with N = 1 PUSH #4 ; Loop count PUSH 8(SP) ; A lsbs PUSH 8(SP) ; A msbs to xn ; ; The 1st estimation x0 with halved exponent creates an error of ; max. 41% (1.414): ; this means 5 loops are sufficient for max. accuracy ; XOR.B #080h,1(SP) ; RRA.B 1(SP) ; Exponent/2 XOR.B #080h,1(SP) ; Back to exponent format SQLOOP MOV SP,RPARG ; Pointer to xn MOV SP,RPRES ADD #8,RPRES ; Pointer to A SUB #4,SP ; Allocate stack for result CALL #FLT_DIV ; A/xn ADD #4,RPARG ; Point to xn CALL #FLT_ADD ; A/xn + xn DEC.B 1(RPRES) ; 0.5 x (A/xn + xn) = xn+1 MOV @SP+,2(SP) ; xn+1 -> xn MOV @SP+,2(SP) DEC 4(SP) ; Decr. loop count JNZ SQLOOP MOV @SP+,6(SP) ; N = 0 MOV @SP+,6(SP) ; Root to result space ADD #2,SP ; Skip loop count MOV SP,RPARG ; Set RPARG and RPRES to result ADD #2,RPARG MOV RPARG,RPRES SQRET RET ; ; Square Root Subroutine for .DOUBLE format ; Calculate the square root out of A. A is located on TOS, where ; otherwise the results are located. The square root overwrites A 303

Metering Application Report

MSP430 Family

; For input RPARG and RPRES are not relevant ; SP, RPARG and RPRES point to a correct result on TOS ; RPARG and RPRES are not defined if the input is negative (N = 1) DBL_SQRT TST.B JN PUSH PUSH PUSH PUSH 2(SP) SQRET #5 10(SP) 10(SP) 10(SP) ; ; ; ; ; ; Argument negative? Yes, return with N = 1 Loop count A lsbs A mids A msbs for 1st estimation xn

; ; The 1st estimation x0 with halved exponent creates an error of ; max. 41% (1.414): ; this means 5 loops are sufficient for max. accuracy ; XOR.B #080h,1(SP) ; RRA.B 1(SP) ; Exponent/2 XOR.B #080h,1(SP) ; Back to exponent format SQLOOP MOV SP,RPARG ; Pointer to xn MOV SP,RPRES ADD #10,RPRES ; Pointer to A SUB #6,SP ; Allocate stack for result CALL #FLT_DIV ; A/xn ADD #6,RPARG ; Point to xn CALL #FLT_ADD ; A/xn + xn DEC.B 1(RPRES) ; 0.5 x (A/xn + xn) = xn+1 MOV @SP+,4(SP) ; xn+1 -> xn MOV @SP+,4(SP) MOV @SP+,4(SP) DEC 6(SP) ; Decr. loop counter JNZ SQLOOP MOV @SP+,8(SP) ; N = 0 MOV @SP+,8(SP) ; Root to result space MOV @SP+,8(SP) ADD #2,SP ; Skip loop count MOV SP,RPARG ; Set RPARG and RPRES to result ADD #2,RPARG ; Correct for return address MOV RPARG,RPRES SQRET RET 5.6.10.2 Cubic Root Subroutines The same way as shown for the square root the cubic root of a number may be calculated using the NEWTONIAN approach. The formula for the cubic root of A is:

xn + 1 =

1 A 2xn + 2 3 xn

The used algorithm for the 1st estimation of the cubic root (exponent/3) leads to worst case errors of +58% and -37%. The table below shows the maximum errors for each approximation step:

304

MSP430 Family

Metering Application Report

Table 56.8: Cubic Root Approximation Errors Step Max. pos. Error Max. neg. Error 1st estimation x0 +58% -37% 1st approximation x1 +19% +25% 2nd approximation x2 +3% +4.7% 3rd approximation x3 +0.08% +0.2% 4th approximation x4 +0.7ppm 4.6ppm 5th approximation x5 <1.4x10-13 2x10-11 ; The cubic root is calculated for the .FLOAT number on the top ; of the stack. The result is written there too. ; For input RPARG and RPRES are not relevant ; SP, RPARG and RPRES point to the result on TOS ; FLT_CUB .EQU $ PUSH #5 ; Loop count PUSH 8(SP) ; A LSBs PUSH 8(SP) ; A MSBs ; ; The 1st estimation x0 needs to be calculated very close to the ; final result: the exponent is divided by 3. ; MOV.B 1(SP),RPARG ; Exponent of A 00xx MOV.B #080h,1(SP) ; Set exponent of A to 2^0 TST.B RPARG ; Exponents sign? JN DCL$2 ; positive DCL$1 DEC.B 1(SP) ; Neg. exp.: exponent - 1 ADD.B #3,RPARG ; Add 3 until 080h is reached JN CBLOOP ; 080h is reached, JMP DCL$1 ; Continue DCL$3 INC.B 1(SP) ; Pos. exp.: exponent + 1 DCL$2 SUB.B #3,RPARG ; Subtr. 3 until 080h is reached JN DCL$3 ; Continue ; CBLOOP MOV SP,RPARG ; Point to xn MOV SP,RPRES SUB #4,SP ; Allocate stack for result CALL #FLT_MUL ; xn^2 ADD #12,RPRES ; Point to A CALL #FLT_DIV ; A/xn^2 INC.B 5(SP) ; xn x 2 ADD #4,RPARG ; Point to 2xn CALL #FLT_ADD ; A/xn^2 + 2xn MOV #FLT3,RPARG ; 1/3 x (A/xn^2 + 2xn) = xn+1 CALL #FLT_DIV MOV @SP+,2(SP) ; xn+1 -> xn MOV @SP+,2(SP) DEC 4(SP) ; Decr. loop count JNZ CBLOOP MOV @SP+,6(SP) ; N = 0 MOV @SP+,6(SP) ; Root to result space ADD #2,SP ; Skip loop count 305

Metering Application Report MOV ADD MOV RET .FLOAT SP,RPARG #2,RPARG RPARG,RPRES 3.0

MSP430 Family ; Set RPARG and RPRES to result ; Skip return address ; Constant for cubic root

FLT3

; The cubic root is calculated for the .DOUBLE number on the top ; of the stack. The result is written there too. ; For input RPARG and RPRES are not relevant ; SP, RPARG and RPRES point to the result on TOS ; DBL_CUB .EQU $ PUSH #5 ; Loop count PUSH 10(SP) ; A LSBs -> xn PUSH 10(SP) PUSH 10(SP) ; A MSBs ; ; The 1st estimation x0 needs to be calculated very close to the ; final result: the exponent is divided by 3. ; MOV.B 1(SP),RPARG ; Exponent of A 00xx MOV.B #080h,1(SP) ; Set exponent of A to 2^0 TST.B RPARG ; Exponents sign? JN DCL$2 ; positive DCL$1 DEC.B 1(SP) ; Neg. exp.: exponent - 1 ADD.B #3,RPARG ; Add 3 until 080h is reached JN CBLOOP ; 080h is reached, JMP DCL$1 ; Continue DCL$3 INC.B 1(SP) ; Pos. exp.: exponent + 1 DCL$2 SUB.B #3,RPARG ; Subtr. 3 until 080h is reached JN DCL$3 ; Continue ; CBLOOP MOV SP,RPARG ; Point to xn MOV SP,RPRES SUB #6,SP ; Allocate stack for result CALL #FLT_MUL ; xn^2 ADD #16,RPRES ; Point to A CALL #FLT_DIV ; A/xn^2 INC.B 7(SP) ; xn x 2 ADD #6,RPARG ; Point to 2xn CALL #FLT_ADD ; A/xn^2 + 2xn MOV #3,RPARG ; 1/3 x (A/xn^2 + 2xn) = xn+1 CALL #FLT_DIV MOV @SP+,4(SP) ; xn+1 -> xn MOV @SP+,4(SP) MOV @SP+,4(SP) DEC 6(SP) ; Decr. loop count JNZ CBLOOP MOV @SP+,8(SP) ; MOV @SP+,8(SP) ; Cubic root to result space MOV @SP+,8(SP) ADD #2,SP ; Skip loop count MOV SP,RPARG ; Set RPARG and RPRES to result

306

MSP430 Family ADD #2,RPARG MOV RPARG,RPRES RET .DOUBLE 3.0

Metering Application Report ; Skip return address ; Constant for cubic root

DBL3

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. .if PUSH .endif PUSH PUSH CALL JN CALL MOV MOV .if MOV .endif DOUBLE=1 NUMBER+4 NUMBER+2 NUMBER #FLT_SQRT ERROR #FLT_SQRT @SP+,RESULT @SP+,RESULT+2 DOUBLE=1 @SP+,RESULT+4 ; LSBs for DOUBLE ; ; ; ; ; ; ; LSBs of NUMBER to new space MSBs of NUMBER Square root on TOS Negative input Fourth root on TOS 4th root MSBs Correct SP to previous result

; LSBs for DOUBLE

5.6.10.4 Other Root Subroutines With the same way as shown above also higher roots may be calculated using the NEWTONIAN approach. The generic formula for the mth root out of A is:

xn + 1

1 A (m 1) xn + = m 1 m xn

5.6.10.5 Calculations with Intermediate Results If a calculation cannot be executed straight forward but has intermediate results then simply a new result space is used. This is done by subtracting 4 (.FLOAT) resp. 6 (.DOUBLE) from the stack pointer SP. EXAMPLE: The function for e shown below is to be calculated. The example is valid for both formats:

e = ab
FPL ; .equ SUB MOV MOV (ML/8)+1 #FPL,SP #a,RPRES #b,RPARG

c d ; Length of a FPP number


; Allocate result space 0 (RS0) ; Address argument 1 ; Address argument 2

307

Metering Application Report CALL SUB MOV MOV CALL ADD CALL MOV MOV .if MOV .endif #FLT_MUL #FPL,SP #c,RPRES #d,RPARG #FLT_DIV #FPL,RPRES #FLT_SUB @SP+,FPL-2(SP) @SP+,FPL-2(SP) DOUBLE=1 @SP+,FPL-2(SP) ; ; ; ; ; ; ; ; ;

MSP430 Family a x b -> RS0 Allocate result space 1 (RS1) Address c Address d c/d -> RS1 Address (a x b) in RS0 e = (a x b) - c/d -> RS1 Result e to RS0 Overwrite (a x b) with e

; LSBs for DOUBLE

; ; Housekeeping is made, SP points to RS0 again, but not ; RPARG and RPRES EXAMPLE: The multiply-and-add (MAC) function for e shown below is calculated. The example is written for both formats:

en + 1 = a b + en
SUB MOV MOV CALL MOV CALL MOV MOV .if MOV .endif #ML/8+1,SP #a,RPRES #b,RPARG #FLT_MUL #e,RPARG #FLT_ADD @RPARG+,e @RPARG+,e+2 DOUBLE=1 @RPARG+,e+4 ; ; ; ; ; ; ; ; Allocate result space Address argument 1 Address argument 2 a x b Address e (a x b)+ e Actualize e with result MIDs or LSBs

; LSBs

; ; 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 simply done by resetting of the sign bit of this number. EXAMPLE: the absolute value of the result on the top of the stack is needed. BIC #080h,0(SP) ; |result| on TOS

5.6.10.7 Change of the Sign of a Number If a sign change is necessary (multiplication by -1), this is simply done by inverting of the sign bit of this number. EXAMPLE: the sign of the result on the top of the stack is changed. XOR #080h,0(SP) ; Negate result on TOS

308

MSP430 Family

Metering Application Report

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 below. 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. 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 ; Address to RPARG ; CALL #FLT_INTG ; Call subroutine ; ... ; Result on TOS ; FLT_INTG MOV.B 1(RPARG),COUNTER ; Exponent to COUNTER MOV @RPARG+,2(SP) ; MSBs and Exponent MOV @RPARG+,4(SP) ; LSBs .FLOAT .if DOUBLE=1 MOV @RPARG,6(SP) ; LSBs .DOUBLE .endif MOV #0FFFFh,ARG2_MSB ; Mask for fractional part .if DOUBLE=1 MOV #0FFFFh,ARG2_MID .endif MOV #0FFFFh,ARG2_LSB JMP L$30 ; INTGLP CLRC ; Shift 0 in always RRC.B ARG2_MSB ; Shift mask to next lower bit .if DOUBLE=1 RRC ARG2_MID .endif RRC ARG2_LSB DEC COUNTER ; Shift as often as: L$30 CMP #080h,COUNTER ; SHIFT COUNT = EXPONENT - 07Fh JHS INTGLP BIC ARG2_MSB,2(SP) ; Mask out fract. part .if DOUBLE=1 BIC ARG2_MID,4(SP) ; For .DOUBLE format BIC ARG2_LSB,6(SP) .else BIC ARG2_LSB,4(SP) ; For .FLOAT format .endif MOV SP,RPARG ; Both pointer to results MSBs ADD #2,RPARG MOV RPARG,RPRES RET ; Return with Integer on TOS EXAMPLE: the integer value of the floating point number residing at address VOL1 is placed on TOS. MOV CALL #VOL1,RPARG #FLT_INTG ; Load pointer with address ; Calculate integer of VOL1

309

Metering Application Report .... 5.6.10.9 Fractional Part of a Number ; Integer on TOS

MSP430 Family

The fractional part of a floating point number can be calculated with the subroutine FLT_FRCT below. 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 above. Integer values or very large numbers return a zero value due to the missing resolution: .DOUBLE format: .FLOAT format: numbers > 1.099512 x 1012 numbers > 1.6777216 x107) (>240) (>224)

; Calculate the fractional part of the number RPARG points to. ; Result: on top of the stack. RPARG, RPRES and SP point to it ; Subroutine FLT_INTG is used ; Call MOV #number,RPARG ; Address to RPARG ; CALL #FLT_FRCT ; Call subroutine ; ... ; Result on TOS ; FLT_FRCT PUSH RPARG ; Copy operands address .if DOUBLE=1 PUSH 4(RPARG) ; Copy operand to allow the use .endif ; of the value on TOS PUSH 2(RPARG) PUSH @RPARG CALL #FLT_INTG ; Integer part of operand to TOS MOV ML/8+1(SP),RPRES ; Operand address to RPRES CALL #FLT_SUB ; Operand - Integer part to TOS .if DOUBLE=1 ; Housekeeping: MOV @SP+,ML/8+3(SP) ; Fractional part back .endif MOV @SP+,ML/8+3(SP) ; MOV @SP+,ML/8+3(SP) ; ADD #2,SP ; Skip saved operand address CLR HELP ; No error BR #FLT_END ; Use FPP termination ; EXAMPLE: the fractional part of the floating point number R5 points to is placed on TOS. MOV CALL .... R5,RPARG #FLT_FRCT ; Load pointer with address ; Calculate fractional part ; Fractional part on TOS

5.6.10.10 Approximation of Integrals Simpsons Rule states that the area A limited by the function f(x), the x-axis, x0 and xN is approximately: xN 1 A = f ( x) h [(y0 + yN ) + 2(y2 + y4. . . . yN 2) + 4(y1 + y3. . . . yN 1)] 3 x0

310

MSP430 Family

Metering Application Report

yN h

f(x)

y0 A

x0

x1 x2

xN-2 xN-1 xN

Figure 56.11: Function f(x) The subroutine SIMPSON below 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 may 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 ; y0 to yN are processed and stored in location A. ; Nmax = 254 (if larger, a word has to be used for INDEXn) ; ; Call: CLR.B INDEXn ; Before 1st call: n = 0 ; LOOP MOV #sample,RPARG ; Address of yn ; CALL #SIMPSON ; Process sample yn ; CMP.B #N+1,INDEXn ; YN processed? ; JLO LOOP ; No, proceed ; ... ; Yes, integral in A ; N .equ 8 ; Max. index (must be even) .if DOUBLE=0 A .equ 0200h ; summed up value (integral) INDXn .equ 0204H ; Index n (0 to N) FLT3 .float 3.0 h .float 0.32 ; Difference h: yn+1 - yn .else A .equ 0200h ; Summed up value (integral) INDXn .equ 0206H ; Index n (0 to N) FLT3 .double 3.0 h .double 0.32 ; Difference h: yn+1 - yn .endif SIMPSON SUB #(ML/8)+1,SP MOV @RPARG+,0(SP) MOV @RPARG+,2(SP) .if DOUBLE=1 MOV @RPARG,4(SP) ; Allocate new workspace ; Fetch yn

311

Metering Application Report .endif CMP.B JEQ CMP.B JEQ BIT JZ INC.B INC.B MOV MOV CALL JMP MOV MOV CALL MOV CALL MOV CALL MOV MOV .if MOV .endif INC.B RET

MSP430 Family

YEVEN

#0,INDXn Y0 #N,INDXn YN #1,INDXn YEVEN 1(SP) 1(SP) #A,RPARG SP,RPRES #FLT_ADD Y0 #A,RPARG SP,RPRES #FLT_ADD #FLT3,RPARG #FLT_DIV #h,RPARG #FLT_MUL @SP+,A @SP+,A+2 DOUBLE=1 @SP+,A+4 INDXn

; 1st value y0? ; Last value yN? ; Odd or even n? ; ; ; ; ; ; ; ; ; ; ; ; Odd: value x 4 Even: value x 2 Fetch summed-up value A New sample yn on TOS Add it to A Store added result in A Last value yN: calculate New sample yn on TOS Add last result to A To constant 3.0 Divide summed-up value by 3.0 Multiply with distance h

; YN

; Y0

; Store result to A ; and correct stack

; Next n ; Return with integral in A

EXAMPLE: The function f(x) described by the calculated results on top of the stack is integrated using Simpsons rule.. INTLOP CLR.B ... CALL CMP.B JLO ... INDXn #SIMPSON #N+1,INDXn INTLOP ; ; ; ; ; ; Initialization: INDXn = 0 Calculation, result on TOS Process samples y0 to yN Last sample yN processed? No, continue Yes, result in A

5.6.10.11 Statistical Calculations The Mean Value, the Standard Deviation and the Variance of measured samples can be calculated with the following subroutines. STAT_INIT clears the RAM-locations used for data gathering. STAT_PREP adds the input sample itself to the RAM location SUMYi, the squared input sample to SUM2Yi and increments the sample counter N. STAT_CALC calculates mean, standard deviation and variance from these three values and writes them back to the RAM-locations used for data recording.

312

MSP430 Family

Metering Application Report

MeanValue =
i= N i =1

y
i =1

i= N

N
i= N

Variance =

yi i =1
i= N

N N

i =1

yi

MeanValue yi
i =1

i= N

StandardDeviation =

y
i=1

i= N

i = N yi 2 i=1 N = Variance N N1

N 1

; 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-locations are used for the three results: ; MEANV .equ N ; Mean Value after return STDDEV .equ SUMYi ; Standard Deviation after return VARIANCE .equ SUM2Yi ; Variance after return ; .if DOUBLE=1 FLT1 .DOUBLE 1.0 ; Floating 1.0 .else FLT1 .FLOAT 1.0 .endif ; ; 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=1 CLR SUM2Yi+4 .endif CLR SUMYi ; Clear sum of input samples CLR SUMYi+2 .if DOUBLE=1 CLR SUMYi+4 .endif RET ; STAT_PREP sums-up the sample pointed to by RPARG in SUMYi ; (summed-up yi) and in SUM2Yi (summed-up squared yi).

313

Metering Application Report

MSP430 Family

; The binary sample counter N is incremented ; STAT_PREP PUSH RPARG ; Save address of input sample SUB #(ML/8)+1,SP ; Allocate stack space MOV RPARG,RPRES ; Copy input sample address CALL #FLT_MUL ; (yi)^2 MOV #SUM2Yi,RPRES ; Add (yi)^2 to SUM2Yi CALL #FLT_ADD ; (yi)^2 + SUM2Yi MOV @SP,SUM2Yi ; Sum back to SUM2Yi MOV 2(SP),SUM2Yi+2 .if DOUBLE=1 MOV 4(SP),SUM2Yi+4 .endif MOV (ML/8)+1(SP),RPARG ; Fetch sample address MOV #SUMYi,RPRES ; Add yi to SUMYi CALL #FLT_ADD MOV @SP+,SUMYi ; Summed-up yi MOV @SP+,SUMYi+2 ; House keeping .if DOUBLE=1 MOV @SP+,SUM2Yi+4 .endif 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: SUMYi ; STAT_CALC SUB #(ML/8)+1,SP ; Allocate stack space MOV #N,RPARG ; Convert N to FP-format 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 MOV @SP,MEANV ; Store Mean Value MOV 2(SP),MEANV+2 .if DOUBLE=1 MOV 4(SP),MEANV+4 .endif ; ; The Mean Value on TOS is used for the calculation ; of the Variance: ; Variance = (Sum(yi^2) - Mean Value x Sum(yi)/N)/N ; MOV #SUMYi,RPARG ; Mean Value x Sum(yi) CALL #FLT_MUL ; MOV #SUM2Yi,RPRES ; To Sum(yi^2) CALL #FLT_SUB ; Sum(yi^2) - MV x Sum(yi)

314

MSP430 Family ADD CALL MOV MOV .if MOV .endif

Metering Application Report #(ML/8)+1,RPARG ; Point to N #FLT_DIV ; Variance on TOS @SP,VARIANCE ; Store Variance 2(SP),VARIANCE+2 DOUBLE=1 4(SP),VARIANCE+4

; ; The Variance on TOS is used for the calculation of the ; Standard Deviation: Std Dev. = SQUROOT(Variance x N/(N-1) ; ADD #(ML/8)+1,RPARG ; Point to N CALL #FLT_MUL ; Variance x N MOV @SP+,STDDEV ; Store value for later use MOV @SP+,STDDEV+2 .if DOUBLE=1 MOV @SP+,STDDEV+4 .endif MOV #FLT1,RPARG ; Build N-1 MOV SP,RPRES ; point to N CALL #FLT_SUB ; N-1 on TOS MOV #STDDEV,RPRES ; point to (Variance x N) CALL #FLT_DIV ; Variance x N/(N-1) .if DOUBLE=1 CALL #DBL_SQRT ; StdDev = SQROOT(Var x N/(N-1)) .else CALL #FLT_SQRT .endif MOV @SP+,STDDEV ; Store Standard Deviation MOV @SP+,STDDEV+2 .if DOUBLE=1 MOV @SP+,STDDEV+4 .endif RET ; EXAMPLE: The normal calling sequence for the statistical calculations is shown. The input samples are contained in the ADC-result register ADAT. STATLOP CALL MOV CALL CALL .... CMP.B JLO #STAT_INIT #ADAT,RPARG #CNV_BIN16U #STAT_PREP #xx,N STATLOP ; ; ; ; ; ; ; Initialization: clear used RAM Set pointer to ADC-result Convert ADC-result to FP on TOS Process samples y1 to yN Continue yN processed? No, next sample

; ; N samples are pre-processed: Calculate Mean Value, Variance, ; and Standard Deviation out of SUMYi, SUM2Y1 and N ; CALL #STAT_CALC ; Call calculation subroutine .... ; Results in sample locations

315

Metering Application Report 5.6.10.12 Complex Calculations

MSP430 Family

Complex numbers of the form (a + jb) may be used in calculations too. The four basic arithmetic operations are shown for complex numbers. The 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 they point 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 56.12 (shown for .FLOAT format). Stack Usage: the subroutines need up to 36 bytes (.DOUBLE) resp. 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 used numbers stay within the range of the floating point package.
RAM/ROM Configuration SP during MAIN Address n+6 Address n+4 Address n-4 Imaginary Part MSBs Address n+2 SP after return SP during CMPLX_xxx Address n Real Part MSBs SP, RPARG, RPRES Imaginary Part MSBs

Stack Configuration Address n

Address n-8

Real Part

MSBs

Return CMPLX-xxx Address n-12 Additional Result Space Address n-x

Figure 56.12: Complex Number on TOS and in Memory (.FLOAT Format) FPL .equ (ML/8)+1 ; Length of an FP-number (bytes) ; ; Complex calculation is made with the complex numbers RPARG ; and RPRES point to. ; ; Call: MOV #arg1,RPRES ; Address argument1 ; MOV #arg2,RPARG ; Address argument2 ; CALL #CMPLX_xxx ; 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) 12 bytes (.FLOAT) ; CMPLX_SUB MOV #0FFFFh,HELP ; Define subtraction JMP 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=1 PUSH 10(RPARG) ; LSBs imaginary part d PUSH 8(RPARG) ; MIDS imaginary part d

316

MSP430 Family .endif PUSH PUSH PUSH PUSH TST JZ

Metering Application Report

6(RPARG) 4(RPARG) 2(RPARG) @RPARG HELP CA

; ; ; ; ;

The coming words depend on DOUBLE LSBs real part c MSBs real part c Addition or subtraction?

; ; Subtraction: the complex number (c + jd) is negated ; XOR #080h,0(SP) ; Negate real part c XOR #080h,FPL(SP) ; Negate imaginary part d CA MOV SP,RPARG ; Point to c CALL #FLT_ADD ; Add real parts (a + c) MOV @SP+,2*FPL+2(SP) ; To real storage MOV @SP+,2*FPL+2(SP) ; Housekeeping .if DOUBLE=1 MOV @SP+,2*FPL+2(SP) .endif MOV SP,RPARG ; Point to d MOV FPL(SP),RPRES ; Restore RPRES ADD #FPL,RPRES ; To imaginary part b CALL #FLT_ADD ; Add imaginary parts (b + d) MOV @SP+,2*FPL+2(SP) ; To imaginary storage MOV @SP+,2*FPL+2(SP) ; Housekeeping .if DOUBLE=1 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 1/(c + jd) ; with: 1/(c + jd) = (c - jd)/(c^2 + d^2) ;; Stack Usage: 36 bytes (.DOUBLE) 28 bytes (.FLOAT) ; CMPLX_DIV PUSH RPRES ; 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 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 #FLT_MUL ; d^2 ADD #FPL,RPARG ; to c^2 CALL #FLT_ADD ; c^2 + d^2 PUSH FPL(SP) ; Copy c^2 + d^2 PUSH FPL(SP) 317

Metering Application Report .if PUSH .endif MOV MOV ADD CALL XOR MOV MOV .if MOV .endif MOV MOV CALL DOUBLE=1 FPL(SP) SP,RPARG ; 3*FPL(SP),RPRES #FPL,RPRES ; #FLT_DIV ; #080h,0(SP) ; @SP+,2*FPL-2(SP) @SP+,2*FPL-2(SP) DOUBLE=1 @SP+,2*FPL-2(SP)

MSP430 Family

To (c2 +d2) ; Pointer to (c + jd) Address d d/(c^2 + d^2) imag. part -d/(c^2 + d2) ; Store imaginary part ; to final location

SP,RPARG ; To copy of c^2 + d^2 2*FPL(SP),RPRES ; To (c + jd) #FLT_DIV ; c/(c^2 + d2)

; ; Prepare the interface to the multiplication and call it: ; RPARG points to 1/(c + jd) yet made by FLT_DIV ; RPRES points to (a + jb) ; MOV 2*FPL+2(SP),RPRES ; address of (a + jb) CALL #CMPLX_MUL ; (a +jb) x 1/(c +jd) MOV #FPL,HELP ; Result to final location CDIVLMOV @SP+,2*FPL+4(SP) DEC HELP JNZ CDIVL ; JMP CMPLX_RET ; 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) 18 bytes (.FLOAT) ; CMPLX_MUL PUSH RPRES ; Save pointer to (a + jb) PUSH RPARG ; Save pointer to (c + jd) ; ; real Part ac - bd ; SUB #FPL,SP ; Allocate result space for a x c CALL #FLT_MUL ; 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 #FLT_MUL ; jb x jd = -bd 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=1 MOV 4(SP),FPL+4(SP)

318

MSP430 Family

Metering Application Report

.endif ; ; Imaginary Part j(ad + bc) ; MOV 2*FPL(SP),RPARG ; To c + jd MOV 2*FPL+2(SP),RPRES ; To a + jb ADD #FPL,RPARG ; To jd CALL #FLT_MUL ; a x d SUB #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 #FLT_MUL ; b x c ADD #FPL,RPARG ; To a x d CALL #FLT_ADD ; ad + bc MOV @SP+,4*FPL+4(SP) ; To imaginary result MOV @SP+,4*FPL+4(SP) .if DOUBLE=1 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 DOUBLE=1 MOV @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 ; Skip pointers CMPLX_RT MOV SP,RPARG ADD #2,RPARG MOV RPARG,RPRES 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 CN1 MOV #CN2,RPARG ; Address of CN2 CALL #CMPLX_DIV ; 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=1 MOV @RPARG+,CST3+8 MOV @RPARG+,CST3+10 319

Metering Application Report .endif ... ADD ...

MSP430 Family

#2*FPL,SP

; Continue with complex calc. ; Terminate complex calc.

5.6.10.13 Trigonometric and Hyperbolic Functions Four subroutines are shown for the calculation of the sine, the cosine the hyperbolic sine and the hyperbolic cosine. All four subroutines use the same kernel, only the initialization part is different for each one of them. Expansion in series is used for the calculation. The formulas are (X is expressed in radians): The sine function:
sin X = X 2n 1 n +1 (2n 1)! (1) 1
n n

The cosine function:

X 2n n cos X = (1) 0 (2n )! X 2n 1 sinh X = 1 (2n 1)!


n

The hyperbolic sine function:

The hyperbolic cosine function:

cosh X =

X 2n (2n)! 0
n

The number range for X is 2 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 also for numbers outside of this range, two possibilities exist: Addition or Subtraction of 2 until the number X is back in the range 2. The subroutine FLT_RNG may be used for this purpose. Increase of the software variable Nmax (normally 30.0, see software below) that defines the number of iterations. If this variable is changed to 120.0 (60 iterations) then deviations in the range 10-12 (.DOUBLE format) resp. 10-6 (.FLOAT format) 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 first help if needed. The calculation errors for the trigonometric functions are shown in the next table. They indicate absolute errors: the difference to the correct values. These errors are equal for positive and negative values of X, so only the errors for positive X are shown.

320

MSP430 Family

Metering Application Report

Angle 0 /2 2

Table 56.9: Errors of the Trigonometric Functions .FLOAT .DOUBLE Sine Cosine Sine -9 0 0 -2010 -9 -9 0 -2110 -6410 -9 -9 0 3.810 -22510 0 -1.310-6 210-6

Cosine 0 0 0 -8010-12

The errors of the hyperbolic functions are shown in the next table. They indicate relative errors; the differences to the correct values are related to the correct values. These errors are equal for positive and negative values of X, so only the errors for positive X are shown. Table 56.10: Errors of the Hyperbolic Functions .FLOAT .DOUBLE Hyperbolic Sine Hyperbolic Hyperbolic Sine Cosine 0 0 0 8510-9 16010-9 -12610-12 5510-9 10010-9 -24210-12 -9 -9 3410 21810 -15310-12

Angle 0 /2 2

Hyperbolic Cosine 0 25510-12 -47410-12 -30910-12

Calculation times (Nmax = 30.0: 15 iterations). The number of cycles is the same one for all four functions: .FLOAT with hardware multiplier: .FLOAT without hardware multiplier: .DOUBLE with hardware multiplier: .DOUBLE without hardware multiplier: ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; 18000 cycles 26000 cycles 28000 cycles 42000 cycles

Sine, Cosine, Hyperbolic Sine, Hyperbolic Cosine of X (radians) Call: MOV CALL ... #addressX,RPARG ; RPARG points to address of X #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 +--------------+-------+-------+--------+--------+ | INIT | sin X | cos X | sinh X | cosh X | +--------------+-------+-------+--------+--------+ | Sign Mask | 080h | 080h | 000h | 000h | | n | 1.0 | 0.0 | 1.0 | 0.0 | | Series Term | X | 1.0 | X | 1.0 | | Result Area | X | 1.0 | X | 1.0 | +--------------+-------+-------+--------+--------+ 321

Metering Application Report

MSP430 Family

; FPL .equ (ML/8)+1 ; Length of FPP numbers (bytes) ; ; Floating Point Sine Function: Result on TOS = SIN(@RPARG) ; Prepare the stack with the initial constants ; FLT_SIN PUSH #80h ; Sign mask (toggle) JMP SINc ; ; Hyperbolic Sine Function: Result on TOS = SINH(@RPARG) ; FLT_SINH PUSH #00h ; Sign mask (always pos.) SINc PUSH #0 ; n: 1 .if DOUBLE=1 PUSH #0 .endif PUSH #08000h ; .FLOAT 1.0 ; .if DOUBLE=1 PUSH 4(RPARG) ; Series term: X .endif PUSH 2(RPARG) PUSH @RPARG JMP TRIGCOM ; To common part ; ; Floating Point Cosine Function: Result on TOS = COS(@RPARG) ; Prepare the stack with the initial constants ; FLT_COS PUSH #80h ; Sign mask (toggle) JMP COSc ; ; Hyperbolic Cosine Function: Result on TOS = COSH(@RPARG) ; FLT_COSH PUSH #00h ; Sign mask (always pos.) COSc PUSH #0 ; n: 0 .if DOUBLE=1 PUSH #0 .endif PUSH #00h ; .FLOAT 0.0 ; .if DOUBLE=1 PUSH #0 ; Series term: 1.0 .endif PUSH #0 PUSH #08000h ; .FLOAT 1.0 ; ; Common part for sin X, cos X, sinh X and cosh X ; The functions are realized by expansions in series ; TRIGCOM .equ $ .if DOUBLE=1 PUSH 4(RPARG) ; Push X onto stack (gets X^2) .endif

322

MSP430 Family PUSH PUSH MOV CALL ; 2(RPARG) @RPARG RPARG,RPRES #FLT_MUL

Metering Application Report ; X^2 is calculated once ; Both pointers to X ; X^2 to actual stack

ADD #FPL,RPARG ; Copy series term to result space MOV @RPARG+,3*FPL+4(SP) ; is X or 1.0 MOV @RPARG+,3*FPL+6(SP) .if DOUBLE=1 MOV @RPARG+,3*FPL+8(SP) .endif SUB #FPL,SP ; Result space for calculations MOV SP,RPRES ; ; The actual series term is multiplied by X^2/(n+1)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=1 MOV @RPARG+,3*FPL+4(SP) .endif ; ; Build (n+1)x(n+2) for next term. (n+2)^2 - (n+2) = (n-1)x(n+2) ; MOV RPRES,RPARG ; Both point to (n+2) CALL #FLT_MUL ; (n+2)^2 ADD #3*FPL,RPARG ; Point to old n CALL #FLT_SUB ; (n+2)^2 -(n+2) = (n+1)x(n+2) ; ; The series term is divided by (n+1)x(n+2) ; ADD #2*FPL,RPRES ; Point to series term CALL #FLT_DIV ; Series term/(n+1)x(n+2) ADD #FPL,RPARG ; Point to x^2 CALL #FLT_MUL ; ST x X^2/(n+1)x(n+2) JN 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),0(SP) ; Modify sign with sign mask MOV @RPARG+,2*FPL(SP) ; Save new series term MOV @RPARG+,2*FPL+2(SP) .if DOUBLE=1 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) ; Result to result area 323

Metering Application Report MOV @RPARG+,4*FPL+6(SP) .if DOUBLE=1 MOV @RPARG+,4*FPL+8(SP) .endif

MSP430 Family

; ; 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 ; .if DOUBLE=1 FLT2 .DOUBLE 2.0 ; Constant 2.0 .else FLT2 .FLOAT 2.0 .endif Nmax .FLOAT 30.0 ; Iterations x 2 (MSBs used only) 5.6.10.14 Other Trigonometric and Hyperbolic Functions With the above four functions five other important functions can be calculated: the tangent, the cotangent, the hyperbolic tangent, the hyperbolic cotangent and the exponential function.
tan X = sin X cos X cot X = cos X sin X tanh X = sinh X cosh X coth X = cosh X sinh X

eX =

Xn n! = sinh X + cosh X

To calculate one of the above five functions the two functions it consists of are calculated and combined. The errors of the five functions can be calculated with the errors of the used two functions shown in tables 56.9 and 56.10: tan X, cot X, tanh X and coth X: the resulting error is the difference of the two errors 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: .FLOAT without hardware multiplier: .DOUBLE with hardware multiplier: .DOUBLE without hardware multiplier: 36000 cycles 52000 cycles 56000 cycles 84000 cycles

324

MSP430 Family

Metering Application Report

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 2. For larger numbers a relatively fast loss of accuracy occurs. ; Tangent ; ; Call: ; ; ; FLT_TAN of X (radians) MOV CALL ... CLR JMP #addressX,RPARG ; RPARG points to address of X #FLT_TAN ; Call the tangent function ; RPARG, RPRES, SP point to result R4 TRI_COM1 ; Offset for tan X ; Go to common handler

; ; Cotangent of X (radians) ; ; Call: MOV #addressX,RPARG ; RPARG points to address of X ; CALL #FLT_COT ; Call the cotangent function ; ... ; RPARG, RPRES, SP point to result ; FLT_COT MOV #2,R4 ; Offset for cot X JMP TRI_COM1 ; Go to common handler ; ; Hyperbolic Tangent of X (radians) ; ; Call: MOV #addressX,RPARG ; RPARG points to address of X ; CALL #FLT_TANH ; Call the hyperbolic tangent ; ... ; RPARG, RPRES, SP point to result ; FLT_TANH MOV #4,R4 ; Offset for tanh X JMP TRI_COM1 ; Go to common handler ; ; Hyperbolic Cotangent of X (radians) ; ; Call: MOV #addressX,RPARG ; RPARG points to address of X ; CALL #FLT_COTH ; Call the hyperbolic cotangent ; ... ; RPARG, RPRES, SP point to result ; FLT_COTH MOV #6,R4 ; Offset for coth X JMP TRI_COM1 ; Go to common handler ; ; Exponential function of X (ex) ; ; Call: MOV #addressX,RPARG ; RPARG points to address of X ; CALL #FLT_EXP ; Call the exponential function ; ... ; RPARG, RPRES, SP point to result ; FLT_EXP MOV #8,R4 ; Offset 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 $ 325

Metering Application Report MOV MOV .if MOV .endif SUB SUB CALL JN SUB ADD CALL ADD CALL MOV MOV .if MOV .endif ADD BR .word .word .word .word .word .word .word .word .word .word .word .word .word .word .word @RPARG+,2(SP) @RPARG+,4(SP) DOUBLE=1 @RPARG,6(SP) #FPL,SP #4,RPARG FT1(R4) TERR2 #FPL,SP #FPL+2,RPARG FT2(R4) #FPL,RPRES FT3(R4) @SP+,2*FPL(SP) @SP+,2*FPL(SP) DOUBLE=1 @SP+,2*FPL(SP) #FPL,SP #FLT_END FLT_SIN FLT_COS FLT_SINH FLT_COSH FLT_COSH FLT_COS FLT_SIN FLT_COSH FLT_SINH FLT_SINH FLT_DIV FLT_DIV FLT_DIV FLT_DIV FLT_ADD

MSP430 Family ; Copy X to result space

; ; ; ; ; ; ; ; ; ;

Allocate new result space Point to X again Calculate 1st function Error: error code in HELP Allocate cosine result space Point to X Calculate 2nd function Point to result of 1st function 1st result .OP. 2nd result Final result to result area

TERR2 ; FT1

; Skip 1st result ; Error code in HELP ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; tan = sin/cos 1st function cot = cos/sin tanh = sinh/cosh coth = cosh/sinh exp = cosh + sinh tan = sin/cos 2nd function cot = cos/sin tanh = sinh/cosh coth = cosh/sinh exp = cosh + sinh tan = sin/cos 3rd function cot = cos/sin tanh = sinh/cosh coth = cosh/sinh exp = cosh + sinh

; FT2

; FT3

If the argument X for trigonometric functions is outside of the range 2 then the subroutine FLT_RNG may be used. The subroutine moves the angle X into the range . ; Subroutine FLT_RNG moves angle X into the range -Pi < X < +Pi ; ; Call: MOV #addressX,RPARG ; RPARG points to address of X ; CALL #FLT_RNG ; Call the function ; ... ; RPARG, RPRES, SP point to result ; ; Range: -100xPI < X < +100xPI loss of accuracy increases with X ; FLT_RNG PUSH @RPARG ; Save sign of X on stack AND #080h,0(SP) ; Only sign remains

326

MSP430 Family

Metering Application Report

FR1

SUB #FPL,SP ; Reserve space for 2^n x Pi .if DOUBLE=1 PUSH 4(RPARG) ; X on stack .endif PUSH 2(RPARG) PUSH @RPARG BIC #080h,0(SP) ; |X| remains MOV FLT2PI,FPL(SP) ; 2xPi to stack MOV FLT2PI+2,FPL+2(SP) .if DOUBLE=1 MOV FLT2PI+4,FPL+4(SP) .endif CMP @SP,FLTPI ; Pi - |X| JHS FR2 ; Pi > |X|: range process done

; ; Successive approximation by subtracting 2^n x2Pi ; FR3 INC.B FPL+1(SP) ; 2Pi x 2 CMP @SP,FPL(SP) ; 2^n x 2Pi - |X| JLO FR3 ; 2^n x 2Pi < |X| DEC.B FPL+1(SP) ; 2^n x 2Pi > |X| divide by 2 MOV SP,RPRES ; Address |X| MOV SP,RPARG ADD #FPL,RPARG ; Address 2^n x 2Pi CALL #FLT_SUB ; |X| - 2^n x 2Pi JMP FR1 ; Check if in range now ; ; Move X (now between -Pi and +Pi) to old result space ; FR2 XOR 2*FPL(SP),0(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 ; To return address of FLT_RNG BR #FLT_END ; .if DOUBLE=1 FLTPI .DOUBLE 3.141592653589793 ; Pi FLT2PI .DOUBLE 3.141592653589793*2 ; 2xPi .else FLTPI .FLOAT 3.141592653589793 ; Pi FLT2PI .FLOAT 3.141592653589793*2 ; 2xPi .endif 5.6.10.15 Faster Approximations for Trigonometric Functions If the calculation times of the above iterations are too long and the high accuracy is not needed (e.g. for the calculation of pulse widths for PWM) then tables or cubic equations may be used. The table method is described in the MSP430 Software Users Guide.

327

Metering Application Report

MSP430 Family

With the following four definition points a cubic approximation to the sine curve is made. The range is 0 to /2. All other angles must be adapted to this range. X1:= X2:= X3:= X4:= 0.0000000000 0.3490658504 1.2217304760 1.5707963270 SIN SIN SIN SIN X1:= X2:= X3:= X4:= 0.0000000000 0.3420201433 0.9396926208 1.0000000000 ( 0) (20) (70) (90)

The resulting multiplication factors are: SIN X = -0.11316874 X3-0.063641170 X^2 +1.01581976 X The following results and errors are obtained with the above factors: X = X = X = X:= X:= X:= X:= 0 , /12 /6 /4 /3 5/12 /2 SIN SIN SIN SIN SIN SIN SIN X X X X X X X = = = = = = = 0.000000000 0.259548457 0.498189297 0.703738695 0.864012827 0.966827870 1.000000000 0.00% +0.28% -0.36% -0.47% -0.23% +0.09% 0.00% ( 0) (15) (30) (45) (60) (75) (90)

The error of the above approximation is within 0.5% from 0 to 2. Calculation times: .FLOAT with hardware multiplier: .FLOAT without hardware multiplier: .DOUBLE with hardware multiplier: .DOUBLE without hardware multiplier: 880 cycles 1600 cycles 1150 cycles 2550 cycles

; Sine Approximation: Sin X = A3xX^3 + A2xX^2 + A1xX + A0 ; 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 ... ; Use approximated value Sin X HORNER .equ .if PUSH .endif PUSH PUSH SUB MOV CALL ADD MOV CALL $ DOUBLE=1 4(RPARG) 2(RPARG) @RPARG #FPL,SP R4,RPRES #FLT_MUL #FPL,R4 R4,RPRES #FLT_ADD ; R4 points to cubic term ; Store X on stack ; for later use

; ; ; ; ; ;

Locate new result space Address cubic term A3 XxA3 Address quadratic term A2 XxA3 + A2

328

MSP430 Family ADD CALL ADD MOV CALL ADD CALL ADD MOV CALL MOV .if MOV .endif MOV ADD BR #FPL,RPARG #FLT_MUL #FPL,R4 R4,RPRES #FLT_ADD #FPL,RPARG #FLT_MUL #FPL,R4 R4,RPRES #FLT_ADD @SP+,2*FPL(SP) DOUBLE=1 @SP+,2*FPL(SP)

Metering Application Report ; to X ; X^2xA3 + XxA2 ; Address linear term A1 ; ; ; ; X^2xA3 + XxA2 + A1 to X X^3xA3 + X^2xA2 + XxA1 Address constant term A0

; X^3xA3 + X^2xA2 + XxA1 + A0 ; Copy to result area

@SP+,2*FPL(SP) #FPL,SP ; SP to return address #FLT_END ; Use standard FPP return

; ; Multiplication factors for the Sine generation (0 to Pi/2) ; SIN X = -0.11316874 X3-0.063641170 X^2 +1.01581976 X A3 A2 A1 A0 A3 A2 A1 A0 .if .DOUBLE .DOUBLE .DOUBLE .DOUBLE .else .FLOAT .FLOAT .FLOAT .FLOAT .endif DOUBLE=1 -0.11316874 -0.063641170 1.01581976 0.0 -0.11316874 -0.063641170 1.01581976 0.0 ; cubic term ; quadratic term ; linear term ; constant term ; cubic term ; quadratic term ; linear term ; constant term

NOTE The above used HORNER algorithm may be used for several other purposes too. It is only necessary to load the register R4 with the starting address of the appropriate block containing the factors (address A3 with the above example).

329

Metering Application Report 5.7 Battery Check and Power Fail Detection

MSP430 Family

The detection of the near loss of the supply voltage is shown for battery driven and for main powered MSP430 systems. Several methods are described how to check if the voltage of a battery or an accumulator is above the minimum supply voltage of the MSP430-system or not. Possibilities are shown for the family members having the 14-bit analog-to-digital converter on-chip and also for the members without it. Three ways with different hardware effort are described how to detect power fail situations for mains driven systems. For all explained applications, schematics, diagrams and proven software examples are added for a better understanding. 5.7.1 Battery Check In microcomputer systems driven by a battery or an accumulator it is necessary to detect the reaching of the lowest usable supply voltage. A battery check executed in regular time intervals ensures that the supply voltage is still sufficient. If the lowest acceptable voltage is reached, normally with an added security value, then a warning can be given with the LCD. The used decision algorithms may be very different: Simple checks if the low threshold is reached or not Sophisticated methods using the speed of the voltage reduction (V/t) dependent on the discharge behavior of the actual battery or accumulator type. For even better estimations the temperature of the battery may be taken into account also. 5.7.1.1 Battery Check with the 14-Bit Analog-to-Digital Converter Due to the ratiometric measurement principle of the 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 57.1 shows the connecting of the voltage reference for all three explained variants. Using the Auto-Mode of the A/D-Converter, the digital result value N for an analog input voltage Vin is:
N = INT Vin 2 14 VSVcc

With a reference voltage Vref (Vin) of 1.2V the supply voltage Vcc (exactly VSVcc) can be measured in steps of approximately 0.3mV near the voltage Vccmin = 2.5V. NOTE If the other analog parts connected to the SVcc-pin cause a voltage drop that cannot be neglected, then it is advised to connect the reference diode to an unused TP-output or an O-output. Otherwise the voltage drop falsifies the result: the calculated value for Vcc is too small.

330

MSP430 Family

Metering Application Report

32kHz

SVcc,TP.x To other analog parts R=82k MSP430C32x A3 LMx85-1.2 Vref=1.235V AVss DVss DVcc

0V

+3V

Figure 57.1: Connection of the Voltage Reference 5.7.1.1.1 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 the RAM. If the battery should be tested, another measurement is made and the result is compared to the stored value measured with Vcc = Vccmin. The result of the comparison determines the status of the battery: If the actually measured value exceeds the stored one, then Vcc < Vccmin and a Battery Low indication can be given by software. If the actually measured value is lower than the stored one, then Vcc > Vccmin EXAMPLE: The battery check with a reference measurement is shown for the analog input A3 (see figure 57.1). During the calibration a reference measurement is made with the lowest tolerable Vcc (Vccmin). Then the battery check is made in regular time intervals (here every hour). ; RAM storage for the ADC value measured for Vref with Vccmin ; ADVref .EQU 0202h ; ADC value for Vref at Vccmin ; ; Vccmin (+ security value) is adjusted. A certain code ; at Port0 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 ; Vref connected to A3 CMP ADVref,&ADAT ; (ADAT) - (ADVref) JLO VCCok ; Vcc > Vccmin ; ; The actual Vcc is lower than Vccmin. Indicate Battery ; Low in the LCD. 331

Metering Application Report ;

MSP430 Family

CALL #BATT_LOW ; Output warning with LCD VCCok ... ; Continue program ; ; Measurement subroutine for analog input A3. Result in ADAT ; MEAS_A3 BIC.B #ADIFG,&IFG2 ; Reset ADC flag ADIFG MOV #ADCLK2+RNGAUTO+CSOFF+A3+VREF+CS,&ACTL L$101 BIT.B #ADIFG,&IFG2 ; CONVERSION COMPLETED? JZ L$101 ; IF Z=1: NO RET ; Yes, return. Result in ADAT ; Advantages: - Very precise definition of one voltage - Short software - Different reference elements possible without software modifications Disadvantages: - Calibration necessary - Relation to only one supply voltage value is known (calibration voltage)

5.7.1.1.2 Battery Check with the Calculation of the Voltage If no reference measurement during a calibration phase is possible, the value of the supply voltage Vcc can be determined by calculation. The formula is: With: N Vref
Vcc = 2 14 Vref N

ADC result of the measurement of Vref Voltage of the reference diode [V]

EXAMPLE: The actual supply voltage Vcc needs to be checked. The formula above 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. Figure 57.1 shows the hardware. FPL .equ (ML/8)+1 ...... ; Length of FPP number ; Normal program sequence

; ; One hour elapsed: check if Vcc is above Vccmin or not. ; CALL #FLT_SAV ; Save FPP registers on stack SUB #FPL,SP ; Allocate stack for result CALL #MEAS_A3 ; Measure ref. diode at A3 (N) MOV #ADAT,RPARG ; Address of ADC result CALL #CNV_BIN16U ; Convert ADC result N to FP ; ; Calculate Vcc = 2^14 x Vref/(ADC-Result) ; MOV #Vref,RPRES ; Load address of Vref voltage CALL #FLT_DIV ; Calculate Vref/N (N on TOS) ADD.B #14,1(RPRES) ; Vcc = 2^14 x Vref/N (exp+14) MOV #VCCmin,RPARG ; Compare Vcc to VCCmin CALL #FLT_CMP ; Vcc - VCCmin

332

MSP430 Family JHS CALL ADD CALL ... .if .FLOAT .FLOAT BATT_ok #BATT_LOW #FPL,SP #FLT_REC DOUBLE=0 1.235 2.5 ; ; ; ; ;

Metering Application Report Vcc > VCCmin: ok Give Battery Low Indication Correct SP (result area) Restore FP registers Continue with program

BATT_ok

Vref VCCmin Advantages:

; Voltage of ref. diode 1.235V ; Vccmin MSP430: 2.5V

- Battery voltage is known (trend calculation possible) - Error of the reference element is not eliminated - Calculation takes time

Disadvantages:

5.7.1.1.3 Battery Check with a fixed Value for Comparison This method uses a fixed, ROM-based 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.235V with a maximum deviation of 0.012V. Therefore the fixed comparison value Nref for the minimum supply voltage Vccmin can be calculated:
N ref = INT Vref 2 14 Vcc m in

With Vccmin = 2.5V and Vref = 1.235 0,012V:


N ref = INT (1.235 0,012 V) 2 14 = 8093 78 2.5 V

To ensure that the voltage of the battery is above Vccmin, the reference value should be set to: 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, then a Battery Low warning should be given. EXAMPLE: The battery check with a fixed value for comparison is executed. Figure 57.1 shows the hardware. The comparison value is stored in the ROM at address VCCmin. ; One hour elapsed: check if Vcc is above Vccmin or not. ; CALL #MEAS_A3 ; Vref connected to A3 CMP VCCmin,&ADAT ; (ADAT) - (VCCmin) JLO VCCok ; Vcc > Vccmin ; ; The actual Vcc is lower than Vccmin. Output Battery ; Low to the LCD. ; CALL #BATT_LOW ; Output warning to the LCD VCCok ... ; Continue program ; 333

Metering Application Report

MSP430 Family

; ROM storage for the calculated ADC value: Vref at Vccmin. ; (worst case value). ; VCCmin .WORD 8015 ; ADC value 1.235V at 2.5V Advantages: Disadvantages: - Short software - Error of the reference element is not eliminated - Fixed reference element - Relation to only one supply voltage value is known

5.7.1.2 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 not having the 14-bit ADC. Figure 57.2 shows two possibilities: 1. At the left hand a simple Go/No_go solution. The voltage at P0.7 is high if Vcc is above Vcc min and low if Vcc is below this voltage. The threshold voltage Vccmin is:
R1 Vcc m in = Vref + 1 R2

2. At the right hand a circuit that allows to compare the battery voltage Vcc to three different voltage levels; two of them can be determined, the third one results from the calculated resistor values for R1, R2 and R3. This allows to distinguish four ranges of the supply voltage Vcc: Vcc < Vthmin Vthmin < Vcc < Vthmid Vthmid < Vcc < Vthmax Vthmax < Vcc The supply voltage is below the lowest threshold The supply voltage is between Vthmin and Vthmid The supply voltage is between Vthmid and Vthmax The supply voltage is above the maximum threshold

TP.0 R1 62k 56k + R2 56k Vref=1.2V Vss Vcc P0.7 MSP430 R2 56k Vref=1.2V R3 680k R1 62k 56k -

TP.1 TP.0

P0.7 + MSP430 Vss Vcc

0V

+3V

0V

+3V

Figure 57.2: Battery Check with an external Comparator The three different threshold levels are: Resistor R3 is switched off (TP.1 is switched to Hi-Z):

334

MSP430 Family
R1 Vth m id = Vref + 1 R2

Metering Application Report

R3 is switched to Vcc by TP.1:


R1| |R3 Vth m in = Vref + 1 R2

R3 is switched to Vss by TP.1: R1 Vth m ax = Vref + 1 R2| |R3 If the comparators output Vout is high, Vcc is above the selected threshold voltage, if Vout is low, then Vcc is below this voltage. The calculation of the resistors R1 to R3 starts with the wished threshold voltage Vthmid: R1 and R2 result from it. Then the low threshold voltage Vthmin defines the value of R3. The 3rd threshold Vthmax results from the other two threshold voltages. The resistor values shown in figure 57.2 define the following threshold values: Vthmin = 2.52V Vthmid = 2.66V Vthmax = 2.78V (calculated with second step) (calculated first) (results from the other two thresholds)

EXAMPLE: With the hardware shown in figure 57.2 (right hand circuit) the actual battery voltage Vcc is compared to three different thresholds. This allows to differentiate four different ranges for Vcc. For anyone of the four supply levels different actions are started at the appropriate label (not shown). Dependent on the speed of the MSP430 and the comparator used, there may be NOPs 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 #TP0+TP1,&TPD ; TP.0 and TP1 active high BIS.B #TP0+TP1,&TPE ; Comparison with Vthmin BIT.B #P07,P0IN ; Comparator output JZ BATTlo ; Vcc < Vthmin BIC.B #TP1,&TPE ; TP.1 to HI-Z BIT.B #P07,P0IN ; Comparator output JZ BATTmid ; Vthmin < Vcc < Vthmid BIC.B #TP1,&TPD ; TP.1 active to Vss BIS.B #TP1,&TPE ; Check Vthmax BIT.B #P07,P0IN ; Comparator output JNZ BATThi ; Vcc > Vthmax ... ; Vthmid < Vcc < Vthmax ; Advantages: - Four ranges defined (more ranges are possible if wished) - Very fast software - Different reference elements are possible without software change Disadvantages: - Hardware effort (except if an unused operational amplifier of a quad-pack can be used)

335

Metering Application Report 5.7.1.3 Battery Check with the Universal Timer/Port Module

MSP430 Family

(Idea from H. Diewald TID). The Universal Timer/Port Module allows a relatively accurate measurement of the battery voltage Vcc. The principle (figures 57.3 and 57.4) is as follows: the capacitor C, used also for the other measurements, is charged-up to the voltage Vref of the reference diode. Then C is discharged with Rref and the time tref until VC reaches the lower threshold VT of the input CIN is measured. Afterwards C is charged-up fully to the supply voltage Vcc and the discharge time tVcc is measured also. The supply voltage Vcc is then:
tVcc tref

Vcc = Vref e

With:

Vcc Vref tref tVcc VT-

Actual supply voltage of the MSP430 [V] Voltage of the reference diode [V] Time to discharge C from Vref to VT- [s] Time to discharge C from Vcc to VT- [s] Time constant for discharge: = Rref C [s] Lower threshold voltage of input CIN [V]

Vc 2 Vcc VT+ Vref 3 4 5 6 7 Conversion States

VT0 td tref tcharge tVcc Time

Figure 57.3: Discharge Curves for the Battery Check with the Universal Timer/Port Module Two hardware possibilities are shown in figure 57.4: The left hand side uses the existing ADC hardware for the battery check too. The right hand side uses an additional battery check hardware. This avoids any influence from the battery check to a precise ADC measurement hardware.

336

MSP430 Family

Metering Application Report

32kHz TP.1 TP.2 Rref Rsens MSP430 TP.0

Rref

CIN Vref C Rd Vss TP.3 Vss

TP.5 Vss TP.4 Vcc C Vref Rd Battery Check separated from Measurement Part

Battery Check combined with Measurement Part

0V

+3V

Figure 57.4: Battery Check with the Universal Timer/Port Module The conditions to be met for the reference voltage Vref are: Vref > VT Vref < Vccmin The reference voltage Vref must be higher than the lower threshold voltage VT of the input CIN at Vccmax Only voltages above the reference voltage Vref can be measured

The above conditions mean for an MSP430 system supplied with 3V: Vref = 1.5V ... 2.5V. The measurement sequence like shown in figure 57.3 is described for the left hand circuitry of figure 57.4 (the sequence numbers below refer to the Conversion States of figure 57.3): 1. Switch outputs TP.1 to TP.3 to HI-Z 2. Charge capacitor C with resistor Rref until input CIN gets HI (or simpler up to Vcc), 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 Rd C. Set TP.3 to HI-Z. 4. Discharge capacitor C from Vref to VT with Rref (TP.1 set to LO). Measure discharge time tref 5. Charge capacitor C with Rref to Vcc (tcharge > 5 Rref C) 6. Discharge capacitor C from Vcc to VT with Rref (TP.1 set to LO). Measure discharge time tVcc 7. Calculate Vcc with the formulae shown above For the interesting supply voltage range of a 3V-system (Vcc = 2.5V ... 3.5V) and a reference voltage Vref = 2.3V the exponential part of the equation can be replaced by a linear function:
tVcc tref Vcc = Vref 1.29 + 0.97

If the Universal Timer/Port 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/Os like shown in figure 57.4 at the right hand side. This way the measurement of the sensors cannot be influenced by the battery check circuitry. The software shown in chapter The Universal Timer/Port used as an ADC can be used for the battery check also, only a few modifications are necessary.

337

Metering Application Report Advantages: Disadvantages: - Minimum hardware effort if measurement part exists anyway - Supply voltage is known after the measurement - Slow measurement

MSP430 Family

5.7.2 Power Fail Detection Mains 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 or days. Therefore another methods are used. Three of them are described below: 1. The non-regulated side of the power supply is observed and if the voltage VC of the charge capacitor falls below a certain level VCmin, interrupt is requested. 2. The voltage at the secondary side of the mains transformer is observed; a sufficient level change there resets the watchdog. If the secondary voltage is too low or ceases, then the internal watchdog is not reset anymore and requests an interrupt therefore. 3. 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. The interrupt requested by the above three solutions is used to start the necessary emergency actions: Switching-off of all loads to lengthen the available time for the emergency actions Reduction of the system clock MCLK to 1MHz to be able to use Vcc down to Vccmin Storage of all important values into an external EEPROM Use of LPM3 finally to bridge the power fail eventually

The three shown 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 AC-Low signal. 5.7.2.1 Power Fail 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 then interrupt is requested. With the circuit shown in figure 57.5 this voltage level VCmin is:
R3 + 1 R4 VC m in = Vcc R1 + 1 R2

R1, R2, R3 and R4 are chosen in a way that delivers the wished threshold voltage VC min. The regulated supply voltage Vcc is used as a reference. The NMI (Non-Maskable Interrupt) may be used to get the fastest possible response. The remaining time trem for actions after a power fail interrupt is approximately: trem = (VC m in Vcc m in Vr ) Where: trem C ch I AM

Approximate time from interrupt to the reaching of Vccmin [s]

338

MSP430 Family Cch IAM VCmin Vccmin Vr

Metering Application Report

Capacity of the charge capacitor [F] Supply current of the MSP430 system (medium value) [A] Voltage at the charge capacitor that causes AC-low interrupt [V] Lowest supply voltage for the MSP430 [V] Dropout voltage (voltage difference between output and input) of the voltage regulator for function [V]

IAM 5V R1 VC + R3 Mains Vz Cch R2 -

+5V

Vcc

P0.0,NMI MSP430

R4 Vss 0V

Figure 57.5: Power Fail Detection by Observation of the Charge Capacitor With the following component values for the hardware shown in figure 57.5 the time trem remaining for emergency tasks can be calculated: Cch = 50F, Vccmin = 2.5V, Vr = 1V, IAM = 2mA, Vz = 10V, VCmin = 7V
trem = (7V 2.5V 1V ) 50 F = 87.5m s 2m A

This remaining time trem = 87.5ms 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 57.5 is used only to demonstrate this hardware possibility too. A normal transformer supply like shown with the other hardware examples can be used also.

339

Metering Application Report

MSP430 Family

Vz

Powerfail

MCLK=2...3MHz VC VCmin Vcc min trem INTRPT MCLK=1MHz

Figure 57.6: Voltages for the Power Fail Detection by Observation of the Charge Capacitor The equations shown above are only valid if the dropout voltage Vr of the used voltage regulator (Vr = VC - Vcc) is relatively low. The dropout voltage Vr must be:
Vr < VC 0 Vreg VC 0 VC min

Where: VC0 Vreg

Lowest voltage at Cch that must output low voltage to the MSP430 input [V] Nominal output voltage of the voltage regulator [V]

If this condition for Vr is not possible, then another approach is necessary. Figure 57.7 shows a circuitry that is independent of the above restriction.

5V R1 VC R2 + Mains Vz Cch Vref

+5V

Vcc

P0.0,NMI MSP430

R3 Vss

Figure 57.7: Power Fail Detection by Observation of the Charge Capacitor The threshold voltage level VCmin for the interrupt is :
R2 VCmin = Vref + 1 R3

The time trem remaining for emergency tasks can be calculated: trem = (VC m in Vcc m in Vr ) C ch I AM

340

MSP430 Family

Metering Application Report

If Brown out is a serious problem, then the hardware proposal of figure 57.7 can be used with the RESET/NMI-pin like described in section 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. EXAMPLE: The interrupt handler and its initialization is shown for the power fail 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 Low Power Mode 3 is entered to bridge eventually the power fail. The Basic Timer checks with its interrupt handler in regular intervals if the voltage is above VCmin again. The hardware shown in figure 57.5 is used. ; SYSTAT contains the current system status: calibration, ; normal run, power fail aso. ; SYSTAT .EQU 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) ; PF_INIT MOV #0300h,SP ; Restart after power fail ... ; Special initialization ; ; Initialization: Prepare P0.0 for power fail detection. ; BIS.B #P0IFG0,&IE1 ; Enable P0.0 interrupt BIS.B #P00,&P0IES ; Intrpt for trailing edge BIC.B #P0IFG0,&IFG1 ; Reset flag (safety) ... ; Continue with initialization EINT ; Enable GIE MAINLOOP MOV.B #NORMAL,SYSTAT ; Start normal program ... ; ; ; P0.0 Interrupt Handler: the voltage VC at Cch fell below a ; minimum voltage VCmin. Switch off all loads and interrupts ; except Basic Timer interrupt. ; P00_HNDLR BIS #PD,&ACTL ; ADC to Power down MOV.B #32-1,&SCFQCTL ; MCLK back to 1MHz BIC.B #01Ch,&SCFI0 ; DCO current source to 1MHz CLR.B &TPD ; Reset all TP-ports ... ; Store values to EEPROM ; ; All tasks are done, return to PF_INIT if Vcc is above Vccmin ; otherwise go to LPM3 to bridge eventually the power fail time ; BIT.B #P00,&P0IN ; Vcc above Vcmin again? JNZ PF_INIT ; Yes, restart program MOV.B #PF,SYSTAT ; System state is Power Fail BIS #CPUoff+GIE+SCG1+SCG0,SR ; Set LPM3 JMP PF_INIT ; Continue here from BT 341

Metering Application Report

MSP430 Family

; ; 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 #PF,SYSTAT ; System in Power Fail state? JNE BT$1 ; No, normal system states BIT.B #P00,&P0IN ; Yes: Vcc above VCmin again? JZ BT_RTI ; No, return to LPM3 BIC #CPUoff+SCG1+SCG0,0(SP) ; Yes, leave LPM3 BT_RTI RETI BT$1 ... ; Normal Basic Timer handler ; .SECT "INT_VEC0",0FFE2h .WORD BT_HNDLR ; Basic Timer Vector .SECT "INT_VEC1",0FFFAh .WORD P00_HNDLR ; P0.0 Inrtpt Vector .WORD 0 ; NMI not used .WORD INIT ; Reset Vector Advantages: Disadvantages: - Precise due to the use of the +5V regulator voltage for reference purposes - Fast response to charge losses - Hardware effort (except an unused operational amplifier of a multiple pack can be used)

5.7.2.2 Power Fail Detection with the Watchdog The AC-Low detection can be made also with the internal watchdog: the watchdog is reset twice by one half-wave of the AC-voltage Vtr and if this does not occur, due to a power fail, then 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 mains voltage is still active but too low for an error-free run. If brownout can be excluded or is impossible due to a hardware design taking care of this possibility, the watchdog solution is a very cheap and reliable possibility for an AC-Low detection. If the restricted interval possibilities (only eight discrete time intervals) of the Watchdog Timer cannot satisfy the needs, then the Watchdog Timer can be used as a normal timer and the needed interval built by summing-up of shorter intervals by software.

342

MSP430 Family

Metering Application Report

5V Vtr Mains VC 300k 1M

+5V

Vcc

VP0.0

P0.0, NMI MSP430

Cch

250k Vss

Figure 57.8: Power Fail Detection with the Watchdog With the component values shown in figure 57.8 a square wave out of the mains voltage Vtr is reached (the MSP430 inputs have Schmitt-trigger characteristic). The voltages Vtr+ and Vtr at the transformer output Vtr that switch the input voltage at the NMI (or P0.x ) input are +7V and +2V respectively. If these two voltage thresholds are carefully adapted to the actual environment, then also brown-out conditions can be handled very safely. The equation for the remaining time trem is:

C ch trem Vtr + Vcc m in Vr Vd tWD I AM


With: Vtr+ Vd tWD Transformer voltage that switches the P0.0 input to HI [V] Voltage drop of one rectifier diode [V] Watchdog interval [s]

All other definitions are equal to those explained in section 5.7.2.1

Vtr Vtr+ VtrVd Powerfail

Watchdog reset VP0.0

Watchdog reset

Watchdog reset

Watchdog not reset

Watchdog Interval twd

MCLK=2...3MHz Watchdog INTRPT VC


Vcc min

MCLK=1MHz

trem

Figure 57.9: Voltages for the Power Fail Detection with the Watchdog

343

Metering Application Report

MSP430 Family

EXAMPLE: An MSP430 system running with MCLK = 2MHz uses the watchdog for power fail detection. The watchdog uses the tap with (tMCLK 215) = 16ms (value after reset). After the completion of the emergency tasks, the software checks in a loop if the mains voltage is back again: this is made by a check if P0.0 gets HI. If this is the case the initialization part is entered. The circuit shown in figure 57.8 is used. ; Power-up and watchdog reset start at label INIT. The reason ; for the reset needs to be known (power-up or watchdog) ; INIT BIT.B #WDTIFG,&IFG1 ; Reset by watchdog? JNZ WD_RESET ; Yes; power fail ; ; Normal reset caused by RESET pin or power-up: Init. system ; BIS.B #4,&SCFI0 ; Switch DCO to 2MHz drive MOV.B #64-1,&SCFQCTL ; FLL to 2MHz MOV #05A00h+CNTCL,&WDTCTL ; Reset watchdog BIS.B #P0IE0,&IE1 ; Enable P0.0 intrpt ... ; Continue initialization EINT ; Finally set GIE MAINLOOP ... ; Start main program ; ; Reset caused by watchdog: missing main means power fail ; Supply current is minimized to enlarge active time. All ; interrupts except P0.0 interrupt are switched off ; WD_RESET BIC.B #03Fh,&TPD ; Switch off all TP-outputs ... ; Switch off other loads BIS #PD,&ACTL ; Power down ADC MOV.B #32-1,&SCFQCTL ; MCLK back to 1MHz BIC.B #01Ch,&SCFI0 ; DCO drive to 1MHz ... ; Store values to EEPROM ; ; All tasks are done: check if mains is back (P0.0 gets HI). ; Llow BIT.B #P00,&P0IN ; Actual state of P0.0 pin JZ Llow ; Still low BR #INIT ; P0.0 is HI, initialize ; ; The P00_HNDLR is called twice each full wave of the mains ; voltage. The watchdog is reset to indicate normal run, ; the edge selection bit of P0.0 is inverted. ; P00_HNDLR MOV #05A00h+CNTCL,&WDTCTL ; Reset watchdog XOR.B #P00,&P0IES ; Invert edge select for P0.0 RETI ; ; .SECT "INT_VEC1",0FFFAh .WORD P00_HNDLR ; P0.0 Inrtpt Vector .WORD 0 ; NMI not used .WORD INIT ; Reset Vector Advantages: - Minimum hardware effort - Minimum software effort - Very fast

344

MSP430 Family

Metering Application Report

- Brown out conditions can be handled by a precise hardware definition Disadvantages: - Remaining time trem can be calculated only worst case

5.7.2.3 Power Fail Detection with a Supply Voltage Supervisor For extremely safe MSP430 applications a TLC7701 Supply Voltage Supervisor can be used. The voltage VC of the charge capacitor Cch is observed: the output signal inverted RESET indicates if the voltage VC is higher or lower than the threshold voltage Vth. Figure 57.10 shows the schematic for this application. The output signal inverted-RESET of the TLC7701 is used in two different ways, depending on the actual state of the application: During power-up the TLC7701 output is used as a reset-signal. The MSP430 is held in the reset state until VC reaches a certain voltage Vth (e.g. supply voltage + regulator voltage drop). See figure 57.11. During run mode the RESET/NMI pin of the MSP430 is switched to NMI-mode (NonMaskable Interrupt) by software. If the voltage VC falls below the voltage Vth, an NMI is requested: the interrupt handler can start all necessary emergency tasks. See the introduction of this section for the description of these tasks. NOTES This method is quite different from the normal use of the TLC7701: if used the normal way, then the device outputs a reset signal in case of a too low supply voltage Vcc; this reset signal stops the CPU of the connected microcomputer and gives no possibility to save important values to an EEPROM. With the described method the output of the voltage regulator may be observed also. This allows to use a TLC7705. The remaining time trem is shorter then due to the lower threshold voltage used at the output side. For this application, the TPS7350, which includes the voltage regulator and the supply voltage supervisor, is suited ideally.

+5V 5V VDD Resin TLC7701 Sense Reset GND CTRL Ct Cch R2 Ct Vss Vcc

Mains

VC

R1

Vout

RESET/NMI MSP430

Figure 57.10: Power Fail Detection with a Supply Voltage Supervisor Figure 57.11 shows the different system states of the Voltage Supervisor solution. The voltage VC is drawn simplified for a better understanding of the system function. The different System States (shown below in figure 57.11) are: 1. The TLC7701 output is low until the voltage Vth is reached. The RESET/NMI input of the MSP430 is a reset input after the power-up, so the MSP430-CPU is inactive. 345

Metering Application Report

MSP430 Family

2. After the reaching of the voltage Vth (and the expiration of the delay trc) the MSP430 starts working and switches the RESET/NMI input to NMI-mode (interrupt input). 3. If the voltage VC goes below Vth due to a power fail then interrupt is requested and the necessary tasks (EEPROM saving aso.) are started. Finally the RESET/NMI pin is switched to the RESET function. 4. If like shown in figure 57.11 the power fail is only of short duration (Vout is high again) then the software continues at label INIT (after the elapse of trc). 5. If a real power fail occurs, the emergency tasks are completed and the reset mode for the RESET/NMI pin is switched on again. 6. This means stop for all MSP430 activities until the return of the mains power rises VC above Vth again. Then the MSP430 will restart with a normal power-up sequence like shown with system state 1.
NMI-Intrpt VC MCLK=1MHz
Vth

Powerfail

NMI-Intrpt CPU stops

MCLK=2..3MHz
Vccmin

trc Vout

trc

trem

undefined

Reset 1

NMI 2 Reset 3 4

NMI 5

Reset 6 System States

Figure 57.11: Voltages for the Power Fail Detection with a Supply Supervisor The formula for the remaining time trem is (the time available for emergency tasks):

trem =
Where: trem Vth Vccmin Vr Cch IAM

(Vth Vcc m in

Vr )

C ch I AM

Approximate time from power fail interrupt to the reaching of Vccmin [s] Threshold voltage for VC. Below this value Vout is low [V] Lowest supply voltage for the MSP430 [V] Dropout voltage of the voltage regulator [V] Capacity of the charge capacitor Cch [F] Supply current of the MSP430 system (medium value) [A]

The threshold voltage Vth of the TLC7701 can be calculated by:


R1 Vth = Vref + 1 R2

Where: Vref R2

Voltage of the internal reference diode of the TLC7701: +1.1V Resistor from SENSE input to 0V. Nominal value 100...200k

346

MSP430 Family

Metering Application Report

The delay trc after the return of VC is defined by the capacitor Ct shown in figure 57.10; if this delay is not wished, the capacitor Ct is omitted. The formula for the delay time trc is: trc = 21k Ct EXAMPLE: The MSP430 system shown in figure 57.10 with its initialization and run-time software. ; Initialization: prepare RESET/NMI as an NMI interrupt input. ; INIT MOV #05A00h+NMI+NMIES+CNTCL,&WDTCTL ; 1->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 ... ; Switch off other loads BIS #PD,&ACTL ; ADC Power down MOV.B #32-1,&SCFQCTL ; MCLK back to 1MHz BIC.B #01Ch,&SCFI0 ; DCO drive to 1MHz ... ; 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 #05A00h+CNTCL,&WDTCTL ; PC is set to INIT BR #INIT ; Short power fail: Vcc high ; .SECT "INT_VEC1",0FFFCh .WORD NMI_HNDLR ; NMI Vector .WORD INIT ; Reset Vector ; Advantages: - Extremely safe: can handle any environment with the appropriate software and hardware combination Disadvantages: - Hardware effort (TLC7701 needed)

5.7.3 Conclusion The shown concepts for battery check and power fail detection are possible only due to the MSP430s hardware features: Battery driven systems can be realized only with microcomputers that need only a very low supply current In mains driven systems the available security of MSP430 systems is due to three unique MSP430 features:

347

Metering Application Report

MSP430 Family

1. The low current consumption allows to use the remaining charge of the (relatively small) charge capacitor 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 Vccmin 3. The wide supply voltage range (+5.5V down to +2.5V) enlarges additionally the remaining time for these tasks. These three features together allow relatively simple hardware solutions for MSP430-systems, especially the use of small charge capacitors.

348

MSP430 Family

Metering Application Report

6 ON-CHIP PERIPHERALS
The following chapters do not give a complete description of the MSP430 peripherals. They are thought as a help when using them. 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. The following table shows all possible Basic Timer interrupt frequencies in dependence of the control bits in byte BTCTL (address 040h). The values are shown for MCLK = 1.048 MHz: Table 61.1: Basic Timer Interrupt Frequencies SSEL = 0 SSEL = 1 DIV = 0 DIV = 1 DIV = 0 DIV = 1 16348 Hz 8192 Hz 4096 Hz 2048 Hz 1024 Hz 512 Hz 256 Hz 128 Hz 64 Hz 32 Hz 16 Hz 8 Hz 4 Hz 2 Hz 1 Hz 0.5 Hz (524288 Hz) (262144 Hz) (131072 Hz) 65536 Hz) 32768 Hz 16348 Hz 8192 Hz 4096 Hz 64 Hz 32 Hz 16 Hz 8 Hz 4 Hz 2 Hz 1 Hz 0.5 Hz

IP2 0 0 0 0 1 1 1 1

IP1 0 0 1 1 0 0 1 1

IP0 0 1 0 1 0 1 0 1

The interrupt frequencies in brackets cannot be used by interrupt routines: the frequencies are too high. ; ; DEFINITION PART FOR THE BASIC TIMER ; BTCNT2 .EQU 047h ; Basic Timer Counter2 (0.5s) BTCTL .EQU 040h ; BASIC TIMER CONTROL BYTE: SSEL .EQU 080h ; 0: ACLK 1: MCLK RESET .EQU 040h ; 0: RUN 1: RESET BT DIV .EQU 020h ; 0: fBT1=fBT 1: fBT1=128Hz FRFQ .EQU 008h ; LCD FREQUENCY DIVIDER IP .EQU 001h ; BT FREQUENCY Selection bits ; IE2 .EQU 001h ; INTERRUPT ENABLE BYTE 2: BTIE .EQU 080h ; BT INTERRUPT ENABLE BIT ; .BSS TIMER,4 ; 0.5s COUNTER .BSS BTDTOL,1 ; LAST READ BT VALUE ; ; 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 = 128Hz: FRFQ = 3 ; ; Initialization part ; HLD .EQU 040h ; 1: Disable BT 349

Metering Application Report ; MOV.B BIS.B ...

MSP430 Family

#(DIV+(6*IP)+(3*FRFQ)),&BTCTL ; 1s interval #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 SUB.B @SP+,R5 ; ACTUAL - LAST VALUE -> R5 ADD R5,TIMER ; 16-BIT DIFFERENCE TO COUNTER ADC TIMER+2 ; Carry to high word POP R5 ; Restore R5 RETI ; .SECT "Int_Vect",0FFE2h .WORD BTHAN ; Basic Timer Interrupt Vector 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 do something if the frequency is changed during the normal run. 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. Afterwards all bits of the software timer register which represent the higher Basic Timer frequencies should be reset to zero. This is the correct time for the lower frequency. EXAMPLE: A Basic Timer interrupt handler is shown that works with two frequencies, 1Hz and 8Hz. All necessary status routines are shown. The handler may be used for all other possible frequency combinations too. The background software changes the status according to the needs. HIF LOF LOBIT ; BT_INT BTTAB .EQU .EQU .EQU .BSS .BSS PUSH MOV.B BR .WORD .WORD 8 1 HIF/LOF TIMER,2 BTSTAT,1 R5 BTSTAT,R5 BTTAB(R5) BT1HZ BT8HZ ; ; ; ; ; ; ; ; ; ; Hi frequency Lo frequency LSB position 16-bit timer Status byte is 8Hz is 1Hz of low frequency register

Save R5 R5 contains status (0, 2, 4, 6) Got to appropr. routine ST0: 1Hz interrupt ST2: 8Hz interrupt

350

MSP430 Family .WORD .WORD ; CHGT8 BT1HZ ; BT8HZ ; CHGT1 MOV.B BIC.B BIS.B ADD POP RETI INC POP RETI INC BIC MOV.B BIC.B BIS.B POP RETI .SECT .WORD CHGT8 CHGT1

Metering Application Report ; ST4: Change to 8Hz interrupt ; ST6: Change to 1Hz interrupt

#2,BTSTAT ; Change to 8Hz interrupt #IP2+IP1+IP0,&BTCTL ; Clear frequ. bits #IP1+IP0,&BTCTL ; Set 8Hz, use BT1HZ for INCR. #LOBIT,TIMER ; Incr. bit 3 of the 125ms timer R5 ; No change of status TIMER R5 ; Incr. bit 0 of the 125ms timer ; No change of status TIMER ; Incr. bit 0 (evtl. carry) #LOBIT-1,TIMER ; Reset 8Hz bits to zero #0,BTSTAT ; New status: 1Hz interrupt #IP2+IP1+IP0,&BTCTL ; Clear frequ. bits #DIV+IP2+IP1,&BTCTL ; Set 1Hz R5 "Int_Vect",0FFE2h BT_INT ; Basic Timer Interrupt Vector

6.1.2 Elimination of the Crystal Tolerance For normal measurement purposes the accuracy of 32768Hz 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 of the crystal used (together with the oscillator) from the exact frequency. An example for such an application is an electricity meter which has to switch 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 (1Hz and 10ppm) are shown in the table below. It indicates how long it takes to have a certain time error: Accuracy 32768Hz 1Hz 32768Hz 10ppm Table 61.2: Crystal Accuracy Deviation 1s Deviation 1m 9.10 hours 27.77 hours 22.75 days 69.44 days Deviation 1h 3.74 years 11.40 years

If these time deviations are not tolerable 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 32768Hz. The deviation measured is added at appropriate time intervals (32768s x10 or 32768s x 16) to the timer register which counts the seconds. 351

Metering Application Report

MSP430 Family

32kHz +-nHz LCD SVcc COM SEL


Error C T0

A0 Temperature

Ox MSP430 P0.y

Clk EEPROM Data

Calibration Unit 10s

AGND P0.x Vcc

Vss

3V/1.6uA

Figure 61.1: Calibration of the Crystal If necessary the temperature behavior of the crystal can also be taken into account. The next figure shows the typical dependence of a crystal in relation to its temperature. The nominal frequency is present at one temperature To (turning point); above and below this temperature the frequency is always lower (negative temperature coefficient). Beside the turning point the frequency deviation increases with the square of the temperature deviation (-0.035ppm/C2 for the example).

To-10 0 -3.5 -7

To

To+10

Crystal Temp. C

Frequency Deviation ppm

Figure 61.2: Crystal Frequency Deviation with Temperature The quadratic equation that describes this temperature behavior is approximately (To = +19C):

f = 0.035 (T 19) 2
with: f T Frequency deviation in ppm Crystal temperature in C

To use the above equation simply every hour the crystal temperature (PC board temperature) is measured and the frequency deviation computed. These deviations are added-up until an accumulated deviation of one second is reached: the counter for seconds is then incremented by one

352

MSP430 Family

Metering Application Report

and one second is subtracted from the accumulated deviation, leaving the remainder in the accumulation register. EXAMPLE: Quadratic crystal deviation correction. The crystal temperature is measured each hour (3600s) and computed. The result in ppm/1024 is added-up in RAM location PPMS. If PPMS reaches 1024 one second is added to the seconds counter SECONDS and PPMS is reduced by 1024. The numbers at the right margin show the digits before and after the assumed decimal point. ; Quadratic temperature compensation after each hour: ; tcorr = -|(T-19)^2 x -0.035ppm| x t ; Tmax = To+40C, Tmin = To-40C ; To .SET 19 ; Turning point of temperature PPM .SET 35 ; -0.035ppm/(T-To)^2 .BSS PPMS,2 ; RAM word for adding-up deviation .BSS SECOND,2 ; RAM word for seconds counting ; TIMCORR CALL #MEASTEMP ;Meas. crystal temperature 6.4h POP IROP2L ; Result to IROP2L 6.4h SUB #(To*10h),IROP2L ; T - To 6.4h MOV IROP2L,IROP1 ; Copy result CALL #MPYS ; |T-To|^2 (always pos.) 12.8 CALL #SHFTRS6 ; Adapt |T-To|^2 12.2 ADC IRACL ; Rounding MOV IRACL,IROP2L ; |T-To|^2 -> IROP2L 12.2 ; ; tcorr = 3600 x -0.035 x 1E-6 x (T-19)^2 s/h ; L$006 MOV #(36*PPM),IROP1 ; 36 x PPM/1E4 ms/h CALL #MPYS ; Signed multiplication ; ; IRAC contains: 36s x PPM x 4 (To-T)^2 x 1E-7 s/h ; = 36s x PPM x 4 (To-T)^2 x 1E-4 ms/h ms/h ; CALL #SHFTLS6 ; to IRACM ; ; IRACM contains: tcorr = 4 x dT x 36 x PPM/1024 ; Correction: 0.25 x 1E-7 x 1024 = 1/39062.5 ; ADD IRACM,PPMS ; Add-up deviation CMP #39062,PPMS ; One second deviation reached? JLO L$200 INC SECONDS ; Yes, add one second SUB #39062,PPMS ; and adjust deviation counter L$200 RET 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. ; 353

Metering Application Report

MSP430 Family

SEC .EQU 0200H ; Byte for counting of seconds MIN .EQU 0201H ; Byte for counting of minutes HOURS .EQU 0202H ; Byte for counting of hours ; ; Subroutine provides a decimal clock: 00.00.00 to 23.59.59 ; RTCLKD SETC ; Entry every second DADC.B SEC ; Increment seconds CMP.B #060H,SEC ; One minute elapsed? JLO RTRETD ; No, return (C = 0) CLR.B SEC ; Yes, clear seconds (C = 1) 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 RTRETD CLR.B HOURS ; 00.00.00 Return to caller RTRETD RET ; C = 1: one day elapsed ; ; Subroutine provides a hex clock: 00.00.00 to 17.3B.3B ; RTCLK INC.B SEC ; Entry point every second CMP.B #60,SEC ; Increment seconds JLO RTRET ; One minute elapsed? CLR.B SEC ; No, return to caller INC.B MIN ; Yes, clear seconds CMP.B #60,MIN ; Increment minutes JLO RTRET CLR.B MIN INC.B HOURS CMP.B #24,HOURS JLO RTRET CLR.B HOURS ; 00.00.00 RTRET RET ; C = 1: one day elapsed The next subroutine increments the date with each call. The handling of leap-years is included. The data is stored in binary format. DAY MONTH YEAR ; DATE .EQU .EQU .EQU PUSH INC.B MOV.B MOV.B CMP.B JNE BIT JNZ 0203h 0204h 0206h R5 DAY MONTH,R5 MT-1(R5),R5 #2,MONTH NOFEB #3,YEAR NOFEB ; Day of month 1 - 31 (byte) ; Month 1 - 12 (byte) ; Year 1990 - 65535 (word) ; Save R5 ; To next day of month ; Look for length of month ; February now? ; Yes, Leap Year?

354

MSP430 Family INC CMP.B JLO MOV.B INC.B CMP.B JLO MOV.B INC POP RET R5 R5,DAY DATRET #1,DAY MONTH #13,MONTH DATRET #1,MONTH YEAR R5 ; ; ; ; ; ; ; ; ; ;

Metering Application Report Yes, 29 days for February One month elapsed? No Yes, start with 1st day of next month Year over? No Yes, start with 1st month of next year Restore R5

NOFEB

DATRET

; ; Table with the length of the 12 months ; MT .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 6.1.4 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 16bit timer counting the ACLK. This 16-bit value can be used for time measurements: the difference of two readings is used. The problem is that the two registers cannot be read-out with one instruction; so BTCNT1 can overflow between the two readings and deliver this way a false result. The following software corrects this possible error: if the LSBs change during the read-out, then a second reading is made. This second read-out is correct, due to the relatively long time interval (30.5s). If interrupts between the readings can occur, then the interrupt can be disabled with the DINT instruction. BTCTL DIV BTCNT1 BTCNT2 ; L$1 MOV.B ... MOV.B MOV.B CMP.B JNE SWPB ADD #DIV+xx,BTCTL &BTCNT1,R5 &BTCNT2,R6 &BTCNT1,R5 L$1 R6 R5,R6 ; Define BT as a 16-bit counter ; ; ; ; ; ; Read LSBs of Basic Timer1 00yy Read MSBs 00xx LSBs still the same? No, read once more, 30.5us time Yes, prepare 16-bit result xx00 Correct result in R6 now: xxyy .equ .equ .equ .equ 040h 020h 046h 047h ; ; ; ; Basic Timer1 Control Register Clock for BTCNT2 is ACLK/256 LSBs of Basic Timer1 MSBs of Basic Timer1

If the result of the first reading is important, then the following subroutine may be used. The 16 bit value is read out and corrected if an overflow to zero may have happened between the reading of the low and high bytes. ; Read-out of the Basic Timer running as a 16-bit timer ; MOV.B &BTCNT1,R5 ; Read LSBs 00yy MOV.B &BTCNT2,R6 ; Read MSBs 00xx CMP.B R5,&BTCNT1 ; BTCNT1 still >= R5? 355

Metering Application Report

MSP430 Family

JHS L$1 ; Yes, no overflow ; ; Transition from 0FFh to 0 occurred with LSBs, read actual ; MSB, it now has the value + 1. ; MOV.B &BTCNT2,R6 ; Read actual MSBs 00xx DEC.B R6 ; MSB - 1 is correct L$1 SWPB R6 ; MSBs to high byte xx00 ADD R5,R6 ; 16-bit value to R6: xxyy

356

MSP430 Family 6.2 The Watchdog Timer

Metering Application Report

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, if there are difficulties after the start-up of the MSP430, the watchdog will reset the system as often as it is needed to start successfully. Within this chapter only the watchdog mode is explained.

6.2.1 Supervision of one Task with the Watchdog In section Power Fail Detection with the Watchdog an example is given how to use the watchdog for the supervision of a power fail task only. This example shows the necessary hardware and the software part needed to detect a coming power fail. As long as the mains voltage is active, interrupt is given for each polarity change of the mains. These interrupts reset the watchdog. If the mains voltage falls below a certain level or fails completely, these interrupts disappear, the watchdog is not reset and therefore will initialize the MSP430 system.

6.2.2 Supervision of multiple Tasks with the Watchdog The watchdog can only supervise one task normally: if this task does not reset the watchdog, the MSP430 is initialized by the watchdog. In complicated 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 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: A system running with MCLK = 3MHz uses the watchdog for the supervision of three functions: 1. Power fail by the checking of the 60Hz mains (see section Battery Check and Power Fail Detection for details) 2. Function 1: a check is made if the software reaches this background part regularly 3. Function 3: a check is made if this interrupt handler is called regularly Each supervised function sets a dedicated bit in the RAM-byte WDB in intervals less than 10.66ms (power-up value of the watchdog with MCLK = 3MHz) if everything is all right. The mainloop checks this byte WDB and resets the watchdog if all three bits are set (07h). If one of the functions fail the watchdog is not reset and will therefore reset the system. ; HARDWARE DEFINITIONS ACTL .EQU 0114h PD .EQU 1000h IFG2 .EQU 003h ; P00 .EQU 001h ; IE1 .EQU 000h P0IE0 .EQU 004h ; ADC CONTROL REGISTER: ; 1: ADC POWERED DOWN ; INTERRUPT FLAG REGISTER 2 ; P0.0 Bit Address ; Intrpt Enable Reg. 1 Addr. ; P0.0 Intrpt Enable Bit 357

Metering Application Report IFG1 P0IFG0 P0IES SCFQCTL SCFI0 ; WDTCTL WDTIFG CNTCL WDB ; .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU .EQU 002h 004h 014h 052h 050h 0120h 01h 008h 0202h ; ; ; ; ; ; ; ; ;

MSP430 Family Intrpt Enable Reg. 1 Addr. P0.0 Flag Bit Intrpt Edge Sel. Reg. Addr. Sys Clk Frequ. Control Reg. Sys Clk Frequ. Integr. Reg. Watchdog Watchdog Watchdog RAM byte Timer Control Reg. flag Clear Bit for functional bits

.TEXT 0E000h ; 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,&IFG1 ; Reset by watchdog? JNZ WD_RESET ; Yes; check reason ; ; Normal reset caused by RESET pin or power-up: Init. system ; INIT1 BIS.B #8,&SCFI0 ; Switch DCO to 3MHz drive MOV.B #96-1,&SCFQCTL ; FLL to 3MHz MCLK MOV #05A00h+CNTCL,&WDTCTL ; Define watchdog ; BIS.B #P0IE0,&IE1 ; Enable P0.0 interrupt BIS.B #P00,&P0IES ; To trailing edge BIC.B #P0IFG0,&IFG1 ; Reset flag (safety) ... ; Continue initialization CLR.B WDB ; Clear Functional Bits EINT ; Enable GIE BR #MAINLOOP ; Go to MAINLOOP ; ; Reset is caused by watchdog: check reason and handle ; individually ; WD_RESET MOV.B WDB,R5 ; Build handler address MOV.B TAB(R5),R5 SXT R5 ; Offsets may be negative! ADD R5,PC TAB .BYTE INIT1-TAB ; All functions failed: hang-up .BYTE PF-TAB ; power fail and function 3 .BYTE F1F3-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 F1-TAB ; Function 1 failed .BYTE INIT1-TAB ; All bits set: hang-up ; ; Missing mains voltage means power fail. ; Supply current is minimized to enlarge active time ; PF BIC.B #03Fh,&TPD ; Switch off all TP-outputs

358

MSP430 Family ... BIS MOV.B BIC.B ...

Metering Application Report ; Switch off other loads #PD,&ACTL ; Power down ADC #32-1,&SCFQCTL ; MCLK back to 1MHz #01Ch,&SCFI0 ; DCO drive to 1MHz ; Store values to EEPROM

; ; All tasks are done: LPM3 to bridge eventually the power fail ; BIS #CPUoff+GIE+SCG1+SCG0,SR JMP INIT1 ; Continue here eventually ; ; The handlers for all failures except power fail. ; Every failure can be handled individually ; F1 ... ; Function 1 failed F3 ... ; Function 3 failed F1F3 ... ; Function 1 and 3 failed ; ; Background: Main Loop. If RAM-byte WDB contains 07h then the ; watchdog is reset: all 3 supervised functions are OK. ; MAINLOOP CMP.B #07h,WDB ; Test WDB JNE L$1 ; WDB does not contain 7: continue MOV #05A00h+CNTCL,&WDTCTL ; All OK: reset watchdog CLR.B WDB ; Clear WDB L$1 ... ; Continue Mainloop ; ; Function 1: if the software reaches this address, the ; supervision bit 1 is set in WDB. This indicates normal run ; BIS.B #1,WDB ; Set supervision bit 1 ... ; ; Function 3: if the software reaches this interrupt handler, the ; supervision bit 3 is set in WDB. This indicates normal run ; INT_HNDLR ... BIS.B #4,WDB ; Set supervision bit 3 RETI ; ; The P00_HNDLR is called each the mains changes polarity. ; The bit 2 in WDB is set to indicate: No Power Fail. ; P00_HNDLR BIS.B #2h,WDB ; Set mains control bit XOR.B #P00,&P0IES ; Invert edge select for P0.0 RETI ; ; .SECT "INT_VEC1",0FFFAh .WORD P00_HNDLR ; P0.0 Inrtpt Vector .WORD 0 ; NMI not used .WORD INIT ; Reset Vector

359

Metering Application Report

MSP430 Family

The interrupt handler for the watchdog handling can be simplified if a strict priority exists for the processing. 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 this way: ; Reset is caused by watchdog: check reason and handle with ; priority from power fail to function 1. ; WD_RESET BIT.B #2,WDB ; Power fail? JZ PF ; Yes, prepare for it BIT.B #4,WDB ; Function 3 failed? JZ F3 ; Yes, handle it BIT.B #1,WDB ; Function 1 failed? JZ F1 ; Yes, handle it JMP INIT1 ; Hang-up occurred (WDB = 7)

360

MSP430 Family 6.3 The 16-Bit Timer_A

Metering Application Report

The 16-Bit Timer_A is a relatively complex timer consisting of the 16-bit Timer Register and five Capture/Compare Registers. Four of these registers are identical (CCR1 to CCR4) and one of them (CCR0) has additional features. The Timer_A, whose block diagram is shown in figure 63.1, has several registers available for different tasks. These registers are shortly described in the next section.
SSEL1 SSEL0

DC to MCLK Timer Clock 15 Input Divider

Data 0 Mode Control

16-bit Timer

TACLK ACLK MCLK INCLK

0 1 2 3

Timer Register TAR Clk RC Carry/Zero

ID1

ID0

POR/CLR Timer Bus

MC1

MC0

Equ0 Capture/Compare Reg. CCR0

Set_TAIFG

CCIS01 CCI0A CCI0B GND VCC

CCIS00 0 1 2 3 CCI0 Capture Mode CCM01

15 Capture 15 Comparator 0 CCM00 Capture/Compare Register CCR0

OM02

OM01

OM00 Out0

Output Unit0 EQU0

TA0

CCIS11 CCI1A CCI1B GND VCC

CCIS10 0 1 2 3 CCI1 Capture Mode CCM11 CCM10 Capture

Capture/Compare Reg. CCR1 15 Capture/Compare Register CCR1 15 Comparator 1 EQU1 Capture/Compare Reg. CCR2 15 Capture Mode CCI2 CCM21 CCM20 Capture 15 Comparator 2 EQU2 Capture/Compare Reg. CCR3 15 Capture Mode CCI3 CCM31 CCM30 Capture 15 Comparator 3 EQU3 Capture/Compare Reg. CCR4 15 Capture Mode CCI4 CCM41 CCM40 Capture 15 Comparator 4 EQU4 Capture/Compare Register CCR4 0 0 OM42 OM41 OM40 Out4 Output Unit3 TA4 Capture/Compare Register CCR3 0 0 OM32 OM31 OM30 Out3 Output Unit3 TA3 Capture/Compare Register CCR2 0 0 OM22 OM21 OM20 Out2 Output Unit2 TA2 0 0 OM12 OM11 OM10 Out1 Output Unit1 TA1

CCIS21 CCI2A CCI2B GND VCC

CCIS20 0 1 2 3

CCIS31 CCI3A CCI3B GND VCC

CCIS30 0 1 2 3

CCIS41 CCI4A CCI4B GND VCC

CCIS40 0 1 2 3

Figure 63.1: The Hardware of the 16-Bit Timer_A 6.3.1 The Timer Register TAR The timer input frequency - selectable from four different sources - is pre-scaled 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 Timer Bus. With all three timer modes this register contains the counted information. Figure 63.2 shows a simplified block diagram of the Timer Register. The maximum resolution for the Timer_A is 1/MCLK. This relates to a maximum input frequency for the Timer Register of MCLK (currently 3.8MHz, 263ns resolution for the MSP430C33x). 361

Metering Application Report

MSP430 Family

DC to MCLK Timer Clock SSEL1 SSEL0 0 1 2 3 Input 15

Data 0 Mode RC Carry/Zero Control Equ0

TACLK ACLK MCLK INCLK

Clk Timer Register TAR Divider

ID1 ID0 0 0 1 1 0 1 0 1

POR/CLR Pass 1/2 1/4 1/8 Timer Bus TIMOV Set_TAIFG

MC1 MC0 0 0 1 1 0 1 0 1 Stop Mode Up Mode Continuous Mode Up/Down Mode

Figure 63.2: Block Diagram of the 16-Bit Timer Register 6.3.2 The Period Register CCR0 The purpose of register CCR0 changes with the used timer mode. Continuous Mode: if this mode is used, CCR0 is a Capture/Compare Register exactly like the other four registers CCR1 to CCR4. Up-Mode or Up/Down Mode: with one of these modes selected, the register CCR0 works as the Period Register for the Timer_A: this register defines the length of the period. The content of the Period Register CCR0 is not modified normally: the time period is a constant value e.g. 50s for a repetition rate of 20kHz. But this value may be modified too if necessary.

6.3.3 The Capture/Compare Registers CCR1 to CCR4 These four identical registers may be used individually as compare registers or as capture registers. 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 n - corresponding to the time interval t - is added to CCRx. See example in section The Continuous Mode. The Output Units may be used to generate output changes at the output pins TAx with an exactly defined timing independent of interrupt latency times. Compare Mode with Up Mode or Up/Down Mode: the register CCRx contains the pulse width of the output signal at TAx. The registers CCRx are modified depending on the result of the control calculations. If no modification is necessary the timing continues without CPU intervention. Capture Mode: a register CCRx used with the Capture Mode, copies the Timer Register at the exact time the programmed input conditions are satisfied. This allows very accurate measurements of timings independent of the interrupt latency time. 6.3.4 The Timer Vector Register TAIV This 16-bit register contains an even numbered vector ranging from 0 (no interrupt pending) via 2 (CCR1 interrupt) to 10 (timer overflow interrupt TIMOV). If more than one interrupt is pending,

362

MSP430 Family

Metering Application Report

then the vector with the highest priority is placed into TAIV. The Timer Vector Register allows a very fast response to the different timer interrupts: its content is added to the Program Counter PC, using a JMP table located after the ADD instruction: ADD RETI JMP JMP JMP JMP ... &TAIV,PC HCCR1 HCCR2 HCCR3 HCCR4 ; ; ; ; ; ; ; INTRPT with highest priority 0: No INTRPT pending 2: CCR1 caused INTRPT 4: CCR2 caused INTRPT 6: CCR3 caused INTRPT 8: CCR4 caused INTRPT 10: Timer overflow is reason

HTIMOV

If the corresponding interrupt handlers are out of the reach of JMPs, then a word table containing the handler start addresses may be used: MOV MOV .WORD .WORD .WORD .WORD .WORD .WORD &TAIV,R5 TTAB(R5),PC PRET HCCR1 HCCR2 HCCR3 HCCR4 HTIMOV ; ; ; ; ; ; ; ; TAIV contains vector 0 - 12 Write table address to PC 0: No INTRPT pending, RET 2: CCR1 caused INTRPT 4: CCR2 caused INTRPT 6: CCR3 caused INTRPT 8: CCR4 caused INTRPT 10: Timer overflow is reason

TTAB

The Capture/Compare Register 0 is not included in the TAIV register: it owns a separate interrupt vector located at address 0FFF0h. The vector for the other Timer_A interrupts is located at address 0FFF2h. 6.3.5 Control Registers Several registers control the work of the Timer_A. Every Capture/Compare Register CCRx has its own control register CCTLx and the Timer Register TAR is also controlled by an own control register TACTL. 6.3.6 The Output Units Each Capture/Compare Register CCRx is connected to an Output Unit that controls the appertaining pulse output TAx. Eight output modes exist, they are selected by three bits in the output control register CCTLx: Table 63.1: Output Modes of the Output Units Action for EQUx Action for EQU0 Output TAx is set according to bit OUTx located in CCTLx Sets output No action Toggles output Resets output Sets output Resets output Toggles output No action Resets output No action Toggles output Sets output Resets output Sets output

Output Mode 0 1 2 3 4 5 6 7

363

Metering Application Report

MSP430 Family

NOTE If one of the toggle modes is used for EQUx, then it is recommended to use the corresponding set or reset mode of the action for EQU0 too. This assures a correction of the pulse sequence if the synchronization gets lost due to an error. This means for example to use Output Mode 6 or 2 instead of mode 4. The counting of the Timer Register and the switching of the Output Units continues after the initialization of the timer control registers without any necessary CPU intervention; only if the contents of the Capture/Compare Registers CCR1 to CCR4 (they define the output duty cycle and with this the DC level) need to be changed then some software effort is necessary. The software can therefore concentrate fully on calculations and other tasks between the modifications of the pulse width registers CCRx. 6.3.7 The Timer_A Modes The Timer_A provides four different modes to work with: Continuous Mode: Up Mode: Up/Down Mode: Stop Mode: the normal mode, except fast PWM generation is necessary used for fast, asymmetric PWM generation used for fast, symmetric PWM generation the Timer_A is halted, all control bits retain their status

The equations shown in the next sections use the following abbreviations: t t n n k fCLK Time interval between two interrupts [s] Time e.g. period of a PWM signal [s] Cycle value added to a CCRx register Number e.g. content of the period register CCR0 Pre-divider constant of Timer_A (1, 2, 4, 8). Input Divider Input frequency at the Input Divider of Timer_A [Hz]

NOTE If the interrupt latency time plays a role, then the values written to the Capture/Compare Registers CCRx need to be corrected. Normally only the initialization value written to this registers needs a correction with a mean latency time value. 6.3.7.1 The Continuous Mode This mode allows up to five completely independent timings. Figure 63.3 shows two independent timings generated by the Capture/Compare Registers CCR0 and CCR1. The content of the Capture/Compare Registers CCRx is updated during each interrupt sequence with a calculated cycle value n. The value n represents a time interval t. The formulas for a given time interval t respective the cycle value n are:

t =

n k t fCLK n = fCLK k

364

MSP430 Family

Metering Application Report

0FFFFh CCR1c CCR0c CCR0b CCR1a CCR0a 0h CCR1b CCR1d CCR1e CCR0d CCR1h CCR0e CCR1f CCR0g CCR0f CCR1g

Interrupt Events: Example EQU0

t0

t0

t0

t0

t0

t0

Example EQU1

t1

t1

t1

t1

t1

t1

t1

t1

Figure 63.3: Two different Timings controlled by the Continuous Mode EXAMPLE: the software example shows the use of the Vector Word TAIV and the overhead of the handling. It refers to the figure 63.3: the time interval t0 is 22000 cycles, the time interval t1 is 17500 cycles. The numbers at the right margin show the necessary cycles for every instruction. The example is written for Continuous Mode: the time difference to the next interrupt is added to the corresponding compare register CCRx. The handlers for the other Capture/Compare Modules (that allow three additional timings) are shown too. ; Software example for the interrupt part of the 16-bit Timer ; Cycles ; Interrupt latency 6 ; ; Interrupt handler for Capture/Compare Module 0. ; The interrupt flag CINT0 is reset automatically. The ; used time distance delta t0 is 22000 cycles ; TIMMOD0 .EQU $ ; Start of handler 6 ADD #22000,&CCR0 ; Prepare next INTRPT 5 ... ; Task0 starts here RETI 5 ; ; Interrupt handlers for Capture/Compare Modules 1 to 4. ; The interrupt flags CCIFGx are reset by the reading ; of the Timer Vector TAIV ; TIM_HND .EQU $ ; Interrupt latency 6 ADD &TAIV,PC ; Add Jump table offset 3 RETI ; Vector 0: No interrupt 5 JMP TIMMOD1 ; Vector 2: Module 1 2 JMP TIMMOD2 ; Vector 4: Module 2 2 JMP TIMMOD3 ; Vector 6: Module 3 2 JMP TIMMOD4 ; Vector 8: Module 4 2 ; ; Module 5. Timer Overflow Handler: the Timer Register is ; expanded into the RAM location TIMEXT (MSBs) ; TIMOVH .EQU $ ; Vector 10: TIMOV Flag INC TIMEXT ; Handle Timer Overflow 4

365

Metering Application Report RETI ; TIMMOD2 .EQU ADD ... RETI $ #NN,&CCR2 ; ; ; ; Vector 4: Module 2 Add time difference Task2 starts here Back to main program

MSP430 Family 5 6 5

5 ; ; Module 1 uses a repetition rate defined to 15000 cycles ; TIMMOD1 .EQU $ ; Vector 2: Module 1 ADD #15000,&CCR1 ; Add time difference 5 ... ; Task1 starts here RETI ; Back to main program 5 ; ; The Module 3 handler shows a way how to look if another ; Timer_A interrupt is pending: 5 cycles have to be spent, ; but 9 cycles may be saved if another interrupt is pending ; TIMMOD3 .EQU $ ; Vector 6: Module 3 ADD #PP,&CCR3 ; Add time difference 5 ... ; Task3 starts here JMP TIM_HND ; Look for pending intrpts 2 ; ; Module 4 uses a repetition rate defined to 1111 cycles ; TIMMOD4 .EQU $ ; Vector 8: Module 4 ADD #1111,&CCR4 ; Add time difference 5 ... ; Task4 starts here RETI ; Back to main program 5 ; .SECT "VECTORS",0FFF0h ; Interrupt Vectors ... .WORD TIMMOD0 ; Vector for Timer Module 0 .WORD TIM_HND ; Vector for all other Mod. 6.3.7.2 The Up-Mode The Up Mode is mainly used for the generation of asymmetric PWM-signals. The period of the PWM-frequency is loaded into the Period Register CCR0 and the pulse width for each one of the outputs TA1 to TA4 is loaded into the Capture/Compare Registers CCR1 to CCR4. The formulas for a given time t (period of the PMW-frequency or pulse width) respective the cycle value n are:

t =

nk t fCLK n = fCLK k

366

MSP430 Family

Metering Application Report

0FFFFh CCR0

CCR1

CCR2 0h CCR1: TA1 Output Output Mode 2: PWM Toggle/Reset or Output Mode 3: PWM Set/Reset CCR2: TA2 Output Output Mode 6: PWM Toggle/Set or Output Mode 7: PWM Reset/Set CCR0: TA0 Output Output Mode 4: PWM Toggle EQU2 EQU0 EQU1 EQU0 EQU2 EQU1 EQU0 EQU2 Interrupts generated

Figure 63.4: Three different asymmetric PWM-Timings generated with the Up-Mode If the Timer Register reaches the content of one of the four Capture/Compare Registers CCRx and the appertaining module is switched to the compare mode, then the Output Unit x is modified (toggled, set, reset or not affected) depending on the output mode defined in the Control Register CCTLx. If the interrupt for the module is enabled, an interrupt is generated too. If the Timer Register reaches the content of the Period Register CCR0, then the Timer Register TAR is reset to zero and the Output Units are modified (toggled, set, reset or not affected) depending on the appertaining Control Register CCTLx. The Timer Register continues with the counting starting at zero. If the interrupt for the reaching of CCR0 is enabled, then an interrupt is requested too. See figure 63.4. 6.3.7.3 The Up-Down Mode The Up-Down Mode is a symmetric PWM Mode. The advantage of this PWM-mode is the minimum of generated harmonics. The half period of the PWM-frequency is loaded into the Capture/Compare Register CCR0 and a calculated number for the pulse width for each one of the used outputs TA1 to TA4 is loaded into the Capture/Compare Registers CCR1 to CCR4. The formulas for a given time t (period of the PWM-frequency or pulse width) respective the cycle value n are (shown for positive pulses):
t = 2 (nCCR 0 n) k t fCLK n = nCCR 0 fCLK 2 k

see TA3 output in figure 63.5 see TA1 output in figure 63.5

t =

2nk t fCLK n = fCLK 2k

367

Metering Application Report

MSP430 Family

0FFFFh CCR0 CCR1

CCR3

0h CCR3: TA3 Output Output Mode 6: PWM Toggle/Set or Output Mode 4: Toggle CCR1: Output Mode 2: PWM Toggle/Reset or Output Mode 4: PWM Toggle TIMOV EQU3 EQU0 EQU3 EQU3 TIMOV EQU3 EQU0 EQU1 EQU1 EQU1 EQU1

TA1 Output

Interrupts generated

Figure 63.5: Two different symmetric PWM-Timings generated with the Up-Down Mode If the Timer Register reaches the content of one of the four Capture/Compare Registers CCRx and the appertaining module is switched to the compare mode, then the 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 module is enabled, then an interrupt is generated too. If the Timer Register reaches the content of the Period Register CCR0, then the Timer Register reverses its count direction and the 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 reaching of CCR0 is enabled, then an interrupt is requested too. If the Timer Register reaches the value zero again it starts immediately with the upward counting. If the interrupt for the reaching of zero (TIMOV) is enabled, then an interrupt is requested too. See figure 63.5. 6.3.7.4 The Stop Mode The Stop Mode halts the Timer Register without the change of any control register. This way the timer actions can continue exactly where they were stopped 6.3.7.5 Use of the Modes Table 63.2 gives an overview to the different applications of the Timer _A Modes together with the registers:

368

MSP430 Family

Metering Application Report Table 63.2: Combinations of Timer_A Modes Capture/Compare Register 0 Capture/Compare Regs 1 to 4 See CCR0 Interrupt timing Slow PWM generation TRIAC timing SW/HW UART (transmitter) See CCR0 Capturing of int. and ext. events SW/HW UART (receiver) Interrupt timing Asymmetrical PWMgeneration TRIAC timing SW/HW UART (transmitter) Capturing of int. or ext. events relative to the Period Register SW/HW UART (receiver) Symmetrical PWMgeneration (Capturing of int. and ext. events. not definite due to up/down counting)

Combinations Continuous Mode Compare Register

Capture Register

Up Mode Compare Register

Fixed to Period Register

Capture Register

Not possible

Up/Down Mode Compare Register Capture Register

Fixed to Period Register Not possible

The timer repetition frequency, which is chosen normally near to 20kHz to be not audible, may be used also as the time base for other tasks if defined appropriately: Serial Communication Interface (SCI): If for an MSP430, a second UART (RS232) is needed, then with a timer frequency of 19.2kHz (8 2.4kHz) 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 CCR0 for the synchronization of the UART software. Timing Intervals for Control: These important control values can be derived also from the timer frequency by an appropriate software pre-scaling.

369

Metering Application Report 6.4 The Hardware Multiplier

MSP430 Family

Examples for the use of the hardware multiplier are given in the section Integer Calculation Subroutines. For all of the multiplication subroutines written with software loops (16 16 bits, 8 8 bits, signed and unsigned, multiplication and multiply and accumulate) the appropriate MACROs for the hardware multiplier are given. 6.4.1 Hints for the Hardware Multiplier The Hardware Multiplier is a word module: the hardware registers can be addressed in byte mode - for the lower bytes only - or in word mode. The upper byte cannot be addressed. The operand registers of the Hardware Multiplier (addresses 0130h, 0132h, 0134h and 0138h) behave like the CPU working registers (R4 to R15) if modified in byte mode: the upper byte is cleared in this case. This allows 8 and 16-bit multiplications in any mixture without any overhead. See the examples in section Integer Calculation Subroutines. The Floating Point Package FPP version 4 uses the Hardware Multiplier if the variable HW_MPY is defined to one (HW_MPY .EQU 1). See chapter The Floating Point Package for details. 6.4.2 The Sum Extension Register The Sum Extension Register SumExt eases the use of arithmetic with results longer than 32 bits. It contains the information that is needed for the most significant parts of the result. Its content is different for the three multiplication modes: MPY Unsigned Multiply: SumExt contains always zero; no carry is possible, the maximum result is: 0FFFFh 0FFFFh = 0FFFE0001h. MPYS Signed Multiply: SumExt contains the extended sign of the 32-bit result (bit 31). This means if the result of the multiplication is negative (MSB = 1) then SumExt contains 0FFFFh; if the result is positive (MSB = 0) then SumExt contains 0000h. MAC Unsigned Multiply and Accumulate: SumExt contains the carry of the accumulate operation. SumExt contains 0 if no carry occured during the accumulation of the new product and 0001h if a carry occured.

The Sum Extension Register eases multiple word operations: no time and ROM-space wasting conditional jumps are necessary, straight forward adds are used instead. EXAMPLE: 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: ; MOV R15,&MPYS ; First operand MOV R14,&OP2 ; Start MPYS with operand 2 ADD ResLo,RESULT ; Lower 16 bits of result ADDC ResHi,RESULT+2 ; Upper 16 bits ADDC SumExt,RESULT+4 ; Result bits 32 to 47 ADDC SumExt,RESULT+6 ; Result bits 48 to 63 With the above way no checks are necessary, the result contains the signed accumulated sum automatically.

370

MSP430 Family

Metering Application Report

NOTE It is strongly recommended to use the MACROs defined in section Integer Calculation Subroutines instead of the way shown above: the way shown is much less descriptive than the MACROs using known abbreviations like MPY, MPYS and MAC.

371

Metering Application Report 6.5 The System Clock Generator

MSP430 Family

The System Clock Generator of the MSP430 family allows a lot of 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 Users Guide and Module Library": see chapter "Oscillator and System Clock Generator". The output frequency MCLK of the System Clock Generator is generated in the Digitally Controlled Oscillator (DCO), having 32 "taps". Each one of these taps represents an output frequency ranging from 500kHz to 4MHz typically. These tap frequencies depend on temperature and supply voltage and referencing to a crystal is necessary therefore. ; Software definitions for the programming examples ; SCG1 .equ 080h ; System Clock Generator Control Bit 1 SCG0 .equ 040h ; System Clock Generator Control Bit 0 OSCoff .equ 020h ; If 1: Oscillator off CPUoff .equ 010h ; If 1: CPU off GIE .equ 008h ; General Interrupt Enable Bit SCFI0 .equ 050h ; System Clock Frequency Integrator Reg. FN_2 .equ 004h ; DCO current switch for 2 x fnom SCFI1 .equ 051h ; DCO tap register 2^9 to 2^2 TAP .equ 008h ; 2^5 bit in SCFI1 SCFQCTL .equ 052h ; System Clock Frequency Control Register M .equ 080h ; Modulation Bit in SCFQCTL. M = 1: off 6.5.1 Initialization After the applying of the supply voltage Vcc the system clock frequency fsystem is initialized to 1.024MHz if a 32.768kHz 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 SCFI0 and SCFI1. If the CPU is always on afterwards and 1.024MHz is the wished frequency, nothing else is to do. 6.5.1.1 First Setting of the DCO Taps during Initialization The Digitally Controlled Oscillator of the MSP430 starts at the tap 0, which means at the lowest possible frequency ( 500kHz). To get from one tap to the next 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 DCO tap. The initialization routine should have a length of 32000 cycles therefore. If this is not the case a delay routine should be added to guarantee this length. An example is given below: INIT L$1 ... MOV DEC JNZ BR ; Loop Control is on (SCG1 = SCG0 = 0) #11000,R5 ; Init delay to allow DCO setting R5 ; 11000 x 3 cycles = 33000 cycles L$1 ; #MAINLOOP ; Start program

6.5.2 Entering of Low Power Mode 3 The Low Power Mode 3 (LPM3) (crystal on, DCO and loop control off) is the normal mode for battery driven systems. Enabled interrupts (e.g. the Basic Timer) wake-up the CPU. LPM3 is entered with the following source code:

372

MSP430 Family

Metering Application Report

BIS

#CPUoff+GIE+SCG1+SCG0,SR

; Enter LPM3

6.5.3 Wake-up from Interrupts in Low Power Mode 3 Wake-up from LPM3 clears only bit SCG1. Due to the set bit SCG0 the loop control of the DCO is off. Normal interrupt routines are too short to allow the loop control to adjust the DCO tap: 1024 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 DCO tap set during the last adaptation. A normal, short interrupt routine looks this way: BT_HAND INC RETI COUNTER ; Loop Control stays off: ; DCO is on for 15 cycles only

If woken-up from LPM3 the interrupt latency time (6 cycles) is increased by typ. 2s@1MHz resp. 1s@2MHz (if FN_2 = 1), this means 8 cycles are needed typically from the interrupt event to the start of the interrupt handler. The time the DCO needs to settle to the nominal frequency is 4 cycles typically; this means interrupt handlers are processed with the correct frequency. 6.5.4 Adaptation of the DCO Tap during Calculations The DCO 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 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 SCG0 bit in the Status Register after the wake-up: ; Calculations are necessary. Allow adaptation of the DCO tap ; BIC #SCG0,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 up to months until a stored module is woken-up for calibration. This means that the environment temperature may have changed seriously. If the LPM4 was entered at a high temperature, the used DCO tap 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,&SCFI1 ; Set DCO tap to 2 BIS #CPUoff+OSCoff+GIE+SCG1+SCG0,SR ; Enter LPM4 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 373

Metering Application Report

MSP430 Family

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.5.6 Change of the System Frequency The system clock frequency fsystem depends on two values:
fsystem = N fcrystal

with:

N fcrystal

Multiplication factor of the DCO loop Frequency of the crystal (normally 32.768kHz)

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 centered taps (13 to 18), which gives a security not to be at the frequency limits of the DCO, three switches FN_2 to FN_4 are implemented in the register SCFI0. These switches increase the internal current of the DCO and allow higher output frequencies if set. The switch nearest to the programmed DCO output frequency should be used. The switches FN_x settle typically 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 1MHz, then the new tap is one of the neighboring taps. This means, to settle at 2MHz needs maximum 1024 cycles (0.5ms) only. If FN_2 is not used, it would take up to 16 x 1024 cycles (8ms) because the misalignment could be up to 16 taps. ; ; ; ; ; Change system frequency to 2.048MHz (fcrystal = 32.768kHz) N = 64 : Multiply 32kHz by 64 to get 2.048MHz FN_2 = 1: Adjust DCO current to 2MHz output frequency M = 0 : Switch on modulation MOV.B MOV.B #64-1,&SCFQCTL #FN_2,&SCFI0 ; 64 x 32kHz = 2.048MHz, M = 0 ; Adjust DCO current to 2MHz

6.5.7 The Modulation Bit M The modulation bit M (SCFQCTL.7) switches off and on the influence of the 5 LSBs (NDCOmod) of the System Clock Frequency Integrator: M = 0: the modulation is on, this means all 10 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. M = 1: the modulation is off, this means only the 5 MSBs (NDCO) of the integrator influence the DCO. The used tap of the DCO is changed only after 1024 clock cycles (for fsystem = 1MHz) 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.

374

MSP430 Family

Metering Application Report

The modulation may be switched off if a series of MCLK cycles is needed with exactly the same length e.g. for measurements with the Universal Timer/Port Module. To get this the loop control needs to be switched off too. ; Ensure stable, non regulated output pulses with equal length: ; BIS.B #SCG0,SR ; Switch off loop control BIS.B #M,&SCFQCTL ; Switch off modulation ... ; Use non-regulated MCLK ; ; Return to a regulated MCLK with closed loop and modulation ; BIC.B #SCG0,SR ; Switch on loop control BIC.B #M,&SCFQCTL ; Switch on modulation 6.5.8 Use without Crystal If for an application no LCD and 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 500kHz. No special instructions are necessary to get this behavior. If this lowest DCO 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 important 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 #SCG0,SR ; Switch off loop control MOV.B #2,&SCFI0 ; Set bit 2^1 of tap number MOV.B #50h,&SCFI1 ; Set tap 10 If an external reference like the mains is available, then the actual MCLK frequency can be controlled simply by the counting of the MCLK output with one of the timers (e.g. for one mains period). 6.5.9 High System Frequencies together with the 14-bit ADC The maximum MCLK without input division is 1.5MHz (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 chapter Analog-to-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 Vcc. Nominal values for these dependencies are: Temperature dependence: Voltage dependence: -5.6kHz/CMHz +60kHz/VMHz

These two dependencies are brought to zero if the DCO-loop is closed (SR-bits: SCG0 = SCG1 = 375

Metering Application Report

MSP430 Family

OscOff = 0). See the next section for short term deviations of the System Clock Generator (MCLK). 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 DCO can deliver the correct system frequency fsystem which is defined for the settled state to
fsystem = N fcrystal

Therefore the System Clock Generator switches continuously between two adjacent DCO-taps: the one with a lower frequency fN and the tap with a higher frequency fN+1. This switching between the two DCO-taps NDCO and NDCO+1 is interlaced in 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 65.1 shows the use of the 10 bits of the registers SCFI0 and SCFI1. The five MSBs N DCO control the DCO-taps, the five LSBs NDCOmod control the modulation scheme of the DCO.
Bits located in the System Clock Frequency Integrator Registers SCFI0 and SCFI1
4 0 4 0

NDCO DCO Tap Control (0 ..31)

NDCOmod DCO Modulation Control (0 .. 31)

Figure 65.1: Control of the DCO by the System Clock Frequency Integrator Figure 65.2 illustrates the DCO switching between the lower and the higher DCO-tap for some values of NDCOmod.

376

MSP430 Family

Metering Application Report

NDCOmod Value of the 5 LSBs of the System Clock Frequency Integrator max max

31 24 16 15 5 4 3 2 max

Upper DCO Tap Frequency f N+1 active

1
Lower DCO Tap Frequency f active N

0 0 5 10 15 20 25 30 31 0 MCLK Cycles 1MHz One ACLK Cycle

Figure 65.2: Switching of the DCO Taps dependent on NDCOmod Table 65.1 lists the errors of the System Clock Generator. The assumptions for table 65.1 are: 1. The frequency step from the lower tap frequency fN to the higher one fN+1 is 10% (multiplication factor 1.1). 2. The two frequencies fN and fN+1 allow an errorfree system frequency during one ACLK period: the two frequencies result in zero error if used with the shown NDCOmod. 3. The crystal error is not included; the crystal is seen as errorfree. 4. The system frequency is normalized to 1MHz, for all other frequencies the resulting errors can be calculated simply by a relation to 1MHz. 5. The FLL has settled, which means, it got time enough (e.g. during calculation sequences) to switch to the appropriate DCO-taps. Three errors of the System Clock Generator are calculated in table 65.1: 1. The maximum time deviation terr during an ACLK period for a system with ideal tap frequencies (assumption 2 above). This inherent time deviation is due to the length of max mainly. 2. The worst case time deviation terrmax during an ACLK period for a system with ideal tap frequencies. To get this time deviation, the calculation is made with the DCO-frequencies for a value of NDCOmod that is one step above the correct ones. This results in the maximum possible time deviation for the FLL; independent of the tap frequencies. 3. The worst case value of the integrated time deviation terrper. This is the largest deviation seen at the end of a complete ACLK period.

377

Metering Application Report NOTE

MSP430 Family

The three errors named above do not accumulate, on the contrary they get smaller with each ACLK period and tend to get zero. This is a very important property of the System Clock Generator. Values in brackets are used for calculations only, shading indicates the used frequency (fN resp. fN+1) for the error calculation. NDCO mod 0 1 2 3 4 5 (6) 15 16 (17) 24 (25) 31 (0) Table 65.1 Error of the System Clock Generator fN [MHz] fN+1 [MHz] terr terrmax max [ns] [ns] 1.0000 1.1000 32 0 89 0.9972 1.0969 31 87 177 0.9943 1.0938 15 86 129 0.9915 1.0906 15 128 172 0.9886 1.0875 7 80 101 0.9858 1.0844 7 101 121 0.9830 1.0813 7 121 0.9574 1.0531 3 134 143 0.9545 1.0500 1 48 51 0.9517 1.0469 1 51 0.9318 1.0250 3 -73 -64 0.9290 1.0219 4 -86 0.9119 1.0031 31 -97 -100 0.9091 1.0000 32 0 NOTE The values shown in table 65.1 get smaller with increasing frequency: if fN is 2MHz the values are only one half of the table values. Where: NDCOmod fN fN+1 max terr terrmax terrper [ns] 91 91 91 93 92 92 96 0 98 100 -

terrper fsystem

Value of the five LSBs of the System Clock Frequency Integrator DCO output frequency of the DCO-tap NDCO (lower frequency) [MHz] DCO output frequency of the DCO-tap NDCO+1 (higher frequency) [MHz] Longest sequence with the same tap within the switching scheme for a given value of NDCOmod measured in MCLK cycles. See figure 65.2 for an explanation Maximum time deviation (time error) within an ACLK period due to max. terr is the inherent error for a given value of NDCOmod. [ns] Worst case time deviation (time error) within an ACLK period due to max. The higher error results from the correction with the tap frequencies for (NDCOmod +1). For a full ACLK period the error reduces to terrper [ns] Worst case time error for a complete ACLK period (30.5s). The error results from the correction with the tap frequencies for (NDCOmod+1). [ns] Nominal, errorless value of the system frequency. Here 1MHz. [MHz]

The formulas used for the error calculations are:

378

MSP430 Family 1 1 terr = max fN fsystem

Metering Application Report 1 1 terr = max fN + 1 fsystem

or for shaded cells

The formulas for terrmax are the same as for terr, but the tap frequencies fN and fN+1 of (NDCOmod+1) are used. The formula for terrper also uses the tap frequencies fN and fN+1 of (NDCOmod+1).
terrper =

(32 NDCOmod )

1 1 1 1 + NDCOmod fN fsystem fN + 1 fsystem

Conclusion: the time deviations listed in table 65.1 demonstrate the small error introduced by the modulation of the DCO. The largest time deviation inside of one ACLK period is 177ns; this is relatively small compared to the inherent digital uncertainty, which is one MCLK cycle (1s @ 1MHz). The time deviations of the System Clock Generator do not accumulate but get smaller with the next ACLK period; therefore the overall error tends to zero for a longer time period. The System Clock Generator with its output frequency fsystem (MCLK) is therefore usable for precise time measurements like a normal crystal oscillator.

379

Metering Application Report 6.6 The RESET-Function

MSP430 Family

The RESET-functions of the MSP430 family are described in depth. A lot of problems can be avoided if the RESET-functions are completely understood. Normally the internal RESEThardware together with the watchdog timer avoids these problems, but under certain circumstances additional external hardware is necessary. Several methods are described. 6.6.1 Description of the MSP430 RESET-Function The MSP430 generates two different, internal RESET-signals: The Power-On Reset signal (POR). The Power-Up Clear signal (PUC).

These two signals are not available externally; they are used only internally (on-chip). Figure 66.1 gives a simplified overview to the RESET-function. The numbers at the gate inputs refer to the explained signals in sections 6.6.1.1 and 6.6.1.2.
Vcc

1. POR Detect Delay 2. Vss RST/NMI NMI (WDTCTL.5) Delay Reset Set Q POR

Reset Watchdog Selected (WDTCTL.4) Watchdog Overflow Watchdog Flag 3. Set 4.

PUC t delay

Security Violation

Figure 66.1: Simplified MSP430 RESET-Circuitry NOTE The power-on detection circuit is not a supply voltage supervisor. A permanent control of the supply voltage is normally done with linear circuits and needs permanently supply current even in Low Power Mode 3 and 4. 6.6.1.1 The Power-On Reset Signal The power-on reset signal POR is caused by two completely different external events: 1. The power-on detection circuitry detects the coming-up of the supply voltage Vcc (PowerOn Signal). 2. The RST/NMI-pin is reset to Vss and set to Vcc afterwards. This is the case only if the reset-pin is switched to the RESET-function (default after power-on) and not to the NMIfunction. The RESET-function is used if WDTCTL.5 = 0.

380

MSP430 Family

Metering Application Report

(NMI stands for Non-Maskable Interrupt, an external interrupt input that cannot be disabled by the interrupt enable bit GIE in the Status Register SR: each interrupt event will request a granted interrupt. The NMI-function is used if WDTCTL.5 = 1). 6.6.1.2 The Power-Up Clear Signal The power-up clear signal PUC is caused by several events: 1. The power-on detection circuitry detects the coming-up of the supply voltage Vcc. This event causes also the POR signal. 2. The RST/NMI-pin is reset to Vss and set to Vcc afterwards (see above 1.1). This event causes also the POR signal. 3. The expiring of the watchdog timer if programmed to the watchdog mode (WDTCTL.4 = 0). The watchdog function is always active after PUC and POR. 4. The use of an invalid password for the writing to the watchdog control word WDTCTL (security violation). This reset generation is independent of the watchdog function: it occurs also if the watchdog is used in timer mode (WDTCTL.4 = 1)

6.6.1.3 Common Operations for Power-Up and Power-On Reset If one of the events described above occurs, then the following operations are started: 1. The digital I/O-ports (e.g. Port0 to Port4) are set to the input direction 2. The I/O-flags are set to zero like described in the description of the peripherals. 3. The address contained in the vector at address 0FFFEh is written into the Program Counter PC (software start address) 4. The Status Register SR of the CPU is reset to zero. This means: The CPU is set to the Active Mode The maskable interrupts are disabled by the reset GIE-bit (SR.4) The loop control for the System Clock Generator is switched on (the FLL is active) The System Clock Generator is set to an MCLK frequency of 1MHz @ fACLK = 32.768kHz 5. The Digitally Controlled Oscillator (DCO) in the system clock generator (FLL for MCLK) is set to its lowest output frequency (DCO tap 0). The reason for this is to include also the possible malfunction of the system clock generator. Otherwise the erroneous FLL frequency is also active during the restoring phase of the system functionality with a fatal effect: the system cannot come up correctly. 6. The RST/NMI-pin is configured to the RESET-function 7. The Watchdog Timer is configured as a watchdog driven by the system clock MCLK 8. The CPU starts operation at the address written into the Program Counter (from address 0FFFEh) after the RST/NMI-pin is set to the Vcc voltage 6.6.1.4 Differences between Power-Up and Power-On Reset The few differences between the two reset signals are mentioned below.

381

Metering Application Report 6.6.1.4.1 Special to the Power-On Reset Signal

MSP430 Family

The power-on reset signal POR generates the PUC signal too The power-on reset signal sets (1) or resets (0) the peripheral bits enclosed in round brackets (see Architecture Users Guide). These bits (e.g. all of the peripheral bits of the 16-Bit Timer_A) are not influenced by the PUC signal. An example is: rw-(0) means a readable and writable peripheral bit that is set to zero by the POR signal only, but not by the PUC signal.

The reason is that some functions may not be modified by watchdog events, these are functions where mainly software is responsible for. 6.6.1.4.2 Special to the Power-Up Clear Signal The power-up clear signal PUC does not generate the POR signal additionally. The power-up clear signal PUC sets or resets the peripheral bits not enclosed in round brackets (see Architecture Users Guide). An example is: rw-0 means a readable and writable bit that is set to zero by the POR and PUC signals.

6.6.1.5 The RST/NMI-Pin Hardware A few important facts need to be known when using the RST/NMI-pin of the MSP430: The RST/NMI-pin does not have a pull-down or pull-up resistor: it is the users responsibility to ensure a stable DVcc or Vcc voltage level at the RST/NMI-pin during normal run. Otherwise hum or noise will generate arbitrary system resets. The RST/NMI-pin is an input pin only: no RESET-signal is output if an internal RESET occurs (e.g. by a watchdog overflow). If external devices have to be reset also, then two possibilities exist (see figure 66.2 right part): 1. An O-output is used: this output is reset and set by a short software routine during the initialization phase following the RESET-signal. The state of an O-output is not defined after the power-up. 2. An I/O-pin (e.g. one of Port0 to Port4) or a TP-pin is used: this pin is connected to Vss (DVss) with a resistor (10k). While the RESET-signal is active, the pin is switched to the input direction resp. HI-Z state and the resistor pulls down the I/Opin. This low signal resets all external devices immediately. The following initialization software switches the pin to an active high signal: the external RESET-signal is terminated. (The same way a positive RESET-signal can be generated: the resistor is connected to the supply voltage Vcc, the initialization software outputs an active low signal). The power-on detection circuitry is only able to detect a new, slowly coming-up of the supply voltage Vcc after a power fail, if Vcc falls below a defined voltage Vccmin. If this cannot be guaranteed, an external hardware is recommended. See the next section for the realization of this hardware. To guarantee a successful RESET, the low signal at the RST/NMI-pin needs a minimum length treset. This time is actually 2s.

382

MSP430 Family

Metering Application Report

+3V
PUC-Signal

Vcc Rrst

P0.x,TP.y
Reset by Software

P0.y,TP.z RST/NMI MSP430 Reset Key Vss O.x 0V


Software Signal

Figure 66.2: Generation of RESET-Signals for external Peripherals 6.6.2 RESET with the internal Hardware including the Watchdog The internal power-on detection hardware of the MSP430 allows very reliable initializations for the complete system. If due to special circumstances this normal way fails, the watchdog (which is completely different to most other microcomputer systems - active after the power-on) will reset the MSP430 once more. 6.6.2.1 Restrictions The oscillator fault flag OFIFG is set as long as the system clock frequency MCLK is outside of the frequency limits. The flag information is won by the FLL hardware: if the DCO reaches its frequency limits then the flag OFIFG is set (IFG1.1 = 1). This flag must be reset by software. NOTES The oscillator fault interrupt uses the same interrupt vector 0FFFCh as the NMI-interrupt: this means the interrupt handler has to check first the reason of the interrupt if the NMIfunction is used too. This is possible by the test of the OFIFG-flag (IFG1.1) or by the test of the NMI-flag. (IFG1.4). The frequency limits of the Digitally Controlled Oscillator are reached if the System Clock Frequency Integrator register SCFI1 contains zero or 0E0h (corresponds to DCO taps 0 or 28). See the Architecture Users Guide. 6.6.2.2 Start-up of the Crystal The Ultra Low Power Design used for the crystal oscillator of the MSP430 results in a relatively long time that is needed until the full oscillating is reached: this may last up to 4 seconds. Until the crystal oscillator has reached a stable ACLK frequency (32kHz) the Digitally Controlled Oscillator (DCO) of the System Clock Generator remains at its lowest frequency (see appropriate data sheet). This is not a disadvantage for most of the MSP430 applications: the crystal oscillator is switched on only once (after power-on) and runs continuously without any off-periods. The used tap is defined by the five most significant bits of the FLL register SCFI1 at address 051h. The actual value of register SCFI1 can be stored to have a fast return to the former system clock frequency (MCLK) in case of a RESET. The stored value needs to be checked, otherwise the value that caused an oscillator fault is restored again and again which results in a system hang-up.

383

Metering Application Report 6.6.3 Secure RESET with slowly coming-up Power Supplies

MSP430 Family

To get secure RESET-conditions also for power supplies with very slowly increasing voltages (V/t) or with voltage drop-outs that do not reach the lower threshold voltage Vmin of the PORdetection circuitry (approx. 0.4V, see data sheet), some external hardware is recommended. Some possibilities are shown in this chapter. NOTE No call for emergency tasks is possible with all the shown solutions of this chapter: the RESET-signal goes low without any pre-warning to the software. If it is necessary to save important RAM contents in an external EEPROM and to execute defined emergency tasks before the RESET-signal gets active, then the solutions shown in the chapter Battery Check and Power Fail Detection should be considered: the voltage supervision is made there at the regulator input and signals the loss of the supply voltage via the RST/NMI-pin switched to the NMI-function. This early warning allows the execution of emergency tasks. 6.6.3.1 RESET with a Key This is the most simple hardware to reset the MSP430. It is used normally if the battery is soldered to the system and the calibration constants reside in the RAM. But this solution may be used for all other supply systems too. If calibration constants are stored in the RAM, then a check at the start of the initialization routine is necessary if a Warmstart (system is calibrated) or a Coldstart (RAM is non-valid) occurred. This distinction is made normally with special constants written to the RAM during the calibration process. These constants use bit patterns that are relatively improbable (e.g. 05AF0h) due to their mix of zeroes and ones. See chapter Software Applications for more details. To reset the MSP430 the key is pressed shortly and released afterwards. The Vss potential at the RST/NMI-pin initiates the POR and the PUC signals.
+3V Vcc Rrst Battery Cch RST/NMI MSP430C323 Reset Key Vss 0V P0.x,TP.y An I/Os Analog Inputs COM SEL
Error

ms

Figure 66.3: Battery Driven System with RESET Key 6.6.3.2 PNP-Transistor with Zener Diode This simple hardware may be used if the supply voltage of the MSP430 is delivered from a higher system voltage Vsys (6V to 15V). The PNP-transistor together with the 3.3V or 4.5V Zener diode delivers the supply voltage and the RESET-signal for the MSP430-system. The fast rise of the supply voltage Vcc guarantees a secure power-up.

384

MSP430 Family

Metering Application Report

Vsys +5V..+10V

SVcc Vsys Vcc MSP430C3xx DVcc AVcc Vcc Vz RST/NMI Vz Dz AVss DVss 0V Time Voltage Vz+Vd Vz+V BE
Power-up Power-down

Figure 66.4: Simple RESET-Circuit with a PNP-Transistor 6.6.3.3 Operational Amplifier with Reference Diode With an operational amplifier used as a comparator (e.g. an unused operational amplifier of a multiple pack) a simple and reliable RESET-circuit can be built-up. Figure 66.5 illustrates this solution: during the start-up phase of the supply voltage the voltage of the non-conducting reference diode is higher than the divided voltage at the non-inverting input of the comparator. This means the output voltage of the comparator is low: the MSP430 is held in the reset state. When the supply voltage reaches the minimum voltage Vccmin (defined by Vz, R2 and R3) then the comparator outputs a high signal: the MSP430 starts with its program. The value of Vccmin is: R2 Vccmin = Vref + 1 R3

Spike VC Vcc 5V R1 R2 + Cch Vref MSP430 R3


VRST VRST

Voltage Drop-out

Powerfail

+5V

Vcc
Vccmin

RST/NMI

Supply from: Accumulator Mains Rectifier Capacitor Supply

0V

Vss

undefined

Figure 66.5: RESET-Circuit with a Comparator and a Reference Diode To give reliable results, the used operational amplifier should be able to operate starting with relatively small supply voltages (approx. 1V). For the calculation of the resistor values for R2 and R3 see the formulas given below for figure 66.6: resistor R4 is simply set to infinite () to get the values for this solution.

385

Metering Application Report

MSP430 Family

Nearly the same circuitry as above is used with figure 66.6. The only difference is the SchmittTrigger characteristic of the RESET-circuitry: it omits falsely RESET-signals from hum, noise and spikes. Two independent voltage threshold voltages VTH+ and VTH- can be calculated with the reference voltage Vref and the three resistors R2, R3 and R4. The formulas follow below.
Spike VC Vcc 5V R1
+5V

Voltage Drop-out

Powerfail

+5V R2 R4

Vcc
Vth+ Vth-

+ Cch R3 Vref -

RST/NMI MSP430
VRST

Supply from: Accumulator Mains Rectifier Capacitor Supply

0V

Vss

Figure 66.6: 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: 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 Ioff. The maximum value of Ri is calculated first: Ue Ri < Ioff With the determined value of Ri the three resistors R2, R3 and R4 are calculated next:
VTH + VTH 1 R4 = Ri Vref (VTH + VTH -)

1 R3 = Ri Vref Ri + 1 1 VTH + R4
1 R2 = Ri Vref Ri + 1 VTH + R4

EXAMPLE: a RESET-circuit like shown in figure 66.6 is built with the following behavior: RST/NMI is Vss for Vcc < 2.5V RST/NMI is Vcc for Vcc > 3V Vref = 1.25V Ioffmax = 200nA (maximum offset current of the inverting input)

386

MSP430 Family Max. voltage error due to Ioff: 150mV

Metering Application Report

Ri <

150mV Ri < 0.75M 200nA

3V 2.5V 1 = 9M R4 = 0.75M 1.25V (3V - 2.5V )


1 = 1.37M R3 = 0.75M 1.25V 0.75M + 1 1 9M 3V
1 = 1.67M R2 = 0.75M 1.25V 0.75M + 1 9M 3V

Figure 66.7 illustrates the connection of an operational amplifier with an output voltage higher than Vcc (here the unregulated voltage VC) to the MSP430 RST/NMI-pin: the diode protects the RST/NMI-pin and the resistor Rrst provides the positive voltage.
+VC
Non-regulated Voltage LT1078CN

2.4R +3V

Voltage Regulator Cch

+ R 0V Reset

Vcc MSP430

Rrst Vss RST/NMI

Supply Voltage Supervisor

+
Vref

A0

+VC

Figure 66.7: RESET-Generation with a Comparator 6.6.3.4 Supply Voltage Supervisors The use of a supply voltage supervisor is the safest method to get a RESET-signal. All necessary parts like reference, programmable delay, output stage a.s.o. are integrated in a single chip. Only a few external components are necessary. Two different solutions are explained: 1. The TL770x Supply Voltage Supervisor 2. The TP3750 Supply Voltage Supervisor and Regulator: this IC integrates two functions, the supply voltage regulation and the supply voltage supervision.

387

Metering Application Report 6.6.3.4.1 TL7701 Supply Voltage Supervisor

MSP430 Family

The schematic for a supervised MSP430 is shown in figure 66.8. The TLC7701 is programmed with the resistors R1 and R2 to reset the MSP430 when the output voltage of the 5V regulator falls below Vccmin (e.g. 2.5V).
+5V 5V R1 Mains VDD Resin TLC7701 Sense Reset GND CTRL Ct Cch R2 Ct Vss 0V Vcc

Vout

RST/NMI MSP430

Figure 66.8: Power Fail Detection with a Supply Voltage Supervisor Figure 66.9 shows the different system states of the Voltage Supervisor solution. The voltage Vcc is drawn in a simplified manner for a better understanding of the system function. The different System States (shown below in figure 66.9) are: 1. Up to a certain voltage the output of the TLC7701 is undefined due to the too low supply voltage. After this voltage is reached the TLC7701 output is low until the voltage Vccmin (defined by R1 and R2) is reached. The RST/NMI-input of the MSP430 is a reset input after the power-up, so the MSP430-CPU is inactive. 2. After the reaching of the voltage Vccmin (and the expiration of the delay time trc) the MSP430 starts working. 3. If the supply voltage Vcc goes below Vccmin due to a voltage drop-out then the RST/NMIinput gets low stopping the CPU this way. 4. After the return of Vcc and the expiration of the delay time trc the RST/NMI-input gets high again and the CPU starts at the address contained in the reset vector 0FFFEh. 5. If a real power fail occurs, the RST/NMI-input stays low until the voltage region with undefined output is reached. This voltage is so low, that no serious CPU activity is possible.

388

MSP430 Family

Metering Application Report

Voltage Drop-out Vcc

Powerfail

RESET

Vccmin

Vout

trc

trc

undefined

Figure 66.9: System Voltages with a Power Supply Supervisor The threshold voltage Vccmin of the TLC7701 is:

R1 Vccmin = Vref + 1 R2
Where: Vref R2 Voltage of the internal voltage reference of the TLC7701: +1.1V Resistor from SENSE input to GND. Nominal value 100...200k

The delay trc after the return of VC is defined by the capacitor Ct shown in figure 66.8; if this delay is not wished, the capacitor Ct is omitted. The formula for the delay time trc is: trc = 21k Ct 6.6.3.4.2 TP3750 Supply Voltage Supervisor and Regulator Figure 66.10 illustrates the use of a TPS7350 (regulator plus voltage supervisor); so a highly reliable system initialization is possible. The TPS7350 also allows to use the RST/NMI-pin of the MSP430 like described in section Battery Check and Power Fail Detection: the RST/NMI-pin is used during the normal program run as an NMI-input (Non Maskable Interrupt). This gives the possibility to save important data in an external EEPROM in case of power fail. This is possible because the PG-pin outputs a negative signal starting at Vcc = 4.75V which allows a lot of activities until Vccmin of the MSP430 (2.5V) is reached. The diode D together with the series resistor Rv and the capacitor Cb allow the MSP430 system to bridge short voltage drop-outs or breakdowns of the supply voltage Vsys. The diode D prevents the fast discharge of Cb by the other peripherals connected to Vsys and enlarges the possible active time for the MSP430.

389

Metering Application Report

MSP430 Family

Vsys (+7V to +24V) D Rv IN VCb EN Cb GND


10F

TP73050 +5V OUT SENSE PG

IAM Vcc RST/NMI MSP430 Vss P0.6 P0.0 Clk EEPROM Data

0V

Figure 66.10: Power Supply from other DC-Voltages with a Voltage Regulator/Supervisor 6.6.4 Conclusion The shown possibilities and restrictions for the RESET-part of an MSP430 application can help to simplify the development phase of a project drastically. It is an old truth that a lot of difficulties normally are caused by the implementation of the RESET-parts of projects. The hardware of the MSP430 family is developed to avoid these difficulties as far as possible, but under special circumstances the solutions shown in this chapter may help.

390

MSP430 Family 6.7 The Universal Timer/Port Module

Metering Application Report

6.7.1 Universal Timer/Port used as an Analog-to-Digital Converter Applications of the Universal Timer/Port Module as an analog-to-digital converter are described in chapter Analog-to-Digital Converters. This section shows other applications, like simple timers a.s.o. 6.7.2 Universal Timer/Port used as a Timer MSP430 family members that do not contain the Timer_A, contain at least the Universal Timer Port/Module, a combination of two 8-bit timers with a common control unit. The Universal Timer/Port Module is primarily thought as an analog-to-digital converter 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 clocks into the count registers TPCNT1 and TPCNT2. When the 16-bit counter (used with the MCLK) or one of the 8-bit counters (used with the ACLK) overflows to zero, the RC2FG-flag (or RC1FG-flag) is set and an interrupt is requested. This method allows precise timings for TRIAC-control or PWM-control in the range of 128Hz to 4000Hz (repetition rate). The Universal Timer/Port Module can be used for: Low frequency pulse width modulation: up to two independent PWM-outputs. Measurement of the MCLK frequency e.g. if used without crystal (see section Use without Crystal) Triggering: time measurement starting with the zero crossing of the mains voltage Other time measurements

TPSSEL1 TPSSEL0

CMP ACLK MCLK MCLK


Event Count ACLK MCLK MCLK 0 0 1 1 0 1 0 1

0 1 2 3

0 Clk 8-bit Counter TPCNT1 EN1 Vcc LSB Data

8 Clk 8-bit Counter TPCNT2 EN2

15

RC1

RC2

Carry: Set RC2FG-Flag

MSB Data

Figure 67.1: Block Diagram of the Universal Timer/Port Module (16-Bit Timer Mode) 6.7.2.1 Continuous Mode The Universal Timer/Port Module can be used like the Timer_A in continuous mode, allowing to measure time differences. The 16 bit value is read out and corrected if an overflow to zero happened between the readings of the low and high bytes. The input frequency may be the ACLK or the MCLK. ; Read-out of the UTP/M running ; MOV.B &TPCNT1,R5 MOV.B &TPCNT2,R6 CMP.B R5,&TPCNT1 JHS L$1 as a 16-bit timer ; ; ; ; Read LSBs 00xx Read MSBs 00yy TPCNT1 still >= R5? Yes, no overflow

391

Metering Application Report

MSP430 Family

; ; Transition from 0FFh to 0 occured, read actual MSB; ; it now has the correct (value + 1). ; MOV.B &TPCNT2,R6 ; Read actual MSBs 00yy DEC.B R6 ; MSB - 1 is correct L$1 SWPB R6 ; MSBs to high byte yy00 ADD R5,R6 ; Build 16-bit value in R6 yyxx 6.7.2.2 Pulse Width Modulation Mode Figure 67.2 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 256Hz are possible. The software is described in the section PWM Digital-to-Analog Converter with the Universal Timer/Port Module

0FFh -n1 -n2 0h

t2
Output

t1

t2

t1

t2 = n2/ACLK t1 = n1/ACLK

RC2FG

RC2FG

RC2FG

RC2FG

Interrupts

Figure 67.2: Low Frequency PWM-Timing generated with the Universal Timer/Port Module

392

MSP430 Family

Metering Application Report

7 HINTS AND RECOMMENDATIONS


During the software development for the first MSP430 projects a lot of experience was acquired. The following hints and recommendations are conceived for all programmers and system designers having more experience with 4- and 8-bit microcomputers than with 16-bit systems. Also mentioned are deviations the MSP430 family shows when compared to other 16-bit architectures (e.g. the function of the carry bit as an inverted zero bit with some instructions). Frequently used Bits: these bits should be located always in bit positions 0, 1, 2, 3, 7 or 15. The first four bits can be set, reset and tested with constants coming from the Constant Generator (1, 2, 4, 8), and the last two ones can be tested easily with the conditional jump instructions JN and JGE: TST.B JGE TST JN RSTAT BIT7LO MSTAT BIT15HI ; TEST Bit7 (OV <- 0) ; JUMP IF MSB OF BYTE IS 0 ; TEST Bit15 (OV <- 0) ; JUMP IF MSB OF WORD IS 1

Use of BCD arithmetic: if simple up/down counters are used that are to be displayed: this saves time and ROM space due to the unnecessary binary-BCD conversion.

EXAMPLE: Counter1 (four BCD digits) is incremented; Counter2 (eight BCD digits) is decremented by one. CLRC DADD CLRC DADD DADD #0001,COUNTER1 ; DADD adds Carry bit too! ; INCREMENT COUNTER1 DECIMALLY

#9999h,COUNTER2 ; DECREMENT 8 DIGIT COUNTER2 #9999h,COUNTER2+2 ;DECIMALLY

Conditional Assembly: this feature of the MSP430 assembler allows to get more than one version out of one source. This reduces the effort to maintain software drastically: only one version needs to be updated if changes are necessary. See section "Conditional Assembly" and Floating Point Software Examples. Usage of Bytes: Use bytes wherever appropriate. The MSP430 allows to use every instruction with bytes. (exceptions are only the instructions SWPB, SXT and CALL) Use of Status Bytes or Words: Use status bytes or words, not flags for the remembering of states. This allows extremely fast branching with one instruction only to the appropriate handler. Otherwise a time (and ROM) consuming skip chain is necessary. See also A.2. Computing Software: Use integer routines if speed is essential; use the Floating Point Package if complex or very accurate calculations are necessary. Bit Handling Instructions:

393

Metering Application Report

MSP430 Family

With the bit handling instructions (BIS, BIT and BIC) more than one bit can be handled simultaneously: up to 16 bits can be handled with a single instruction. The BIS instruction is equivalent to the logical OR and can be used this way The BIC instruction is equivalent to the logical AND with the inverted source and can be used this way Use of the Addressing Modes: Use the Symbolic Mode for random accesses Use the Absolute Mode for fixed hardware addresses such as peripheral addresses Use the Indexed Mode for random accesses in tables Use the Register Mode for time critical processing and as the normal one Use assigned registers for extremely critical purposes: if a register contains always the same information, then it is not necessary to save it and to load it afterwards. The same is true for the restoring of the register when the task is done. Stack Operations: All items on the stack can be accessed directly with the Indexed Mode: this allows completely new applications compared with architectures that have only simple hardware stacks. The stack size is limited only by the available RAM, not by hardware register limitations. NOTE The above mentioned possibilities make rigid "house keeping" necessary: every program part which uses the stack has to ensure that only relevant information remains on the stack and that all irrelevant data is removed. If this rule is not used consequently the stack will overflow or underflow. If complex stack handling is used it is advised to draw the stack with its items and the stack pointer as shown with the examples "Argument Transfer with Subroutine Calls" in the appendix. The drawn stack allocation gives a good overview. The Program Counter PC: The PC can be accessed as every other register with all instructions and all addressing modes. Be very careful when using this feature! Do not use byte instructions when accessing the PC, due to the clearing of the upper byte when used. The Status Register SR: it can be accessed in register Mode only. Every status bit can be set or reset alone or together with other ones. This feature may be used for status transfer in subroutines. The FPP uses this way of status transfer. Enabling of the General Interrupt: The instruction following the enabling of the interrupt is executed before an interrupt is accepted: EINT CLRC ADC ; Enable interrupt (GIE) ; This instruction is executed before ; the 1st interrupt is accepted

R5

High Speed Multiplication: If highest possible speed is necessary for multiplications and the hardware multiplier is not available, then the loop overhead may be omitted. Straight through programming: the effort used for the looping can be saved if the shifts and adds are programmed straight through. The routine ends at the known MSB of the multiplicand (here, at bit 13 due to an ADC result (14 bits) that is multiplied):

394

MSP430 Family

Metering Application Report

; EXECUTION TIMES FOR REGISTER USE (CYCLES @ 1MHZ, 16 bits): ; ; TASK CYCLES EXAMPLE ;------------------------------------------------------------; MINIMUM 80 00000h x 00000h = 000000000h ; MEDIUM 96 0A5A5h x 05A5Ah = 03A763E02h ; MAXIMUM 112 0FFFFh x 0FFFFh = 0FFFE0001h ; Fast Multiplication Routine: Part used by signed and unsigned ; Multiplications. R5 x R4 -> R8|R7 ; MACUF CLR R6 ; MSBs MULTIPLIER ; RRA R4 ; LSB to carry JNC L$01 ; IF ZERO: SKIP ADD ADD R5,R7 ; IF ONE: ADD MULTIPLIER TO RESULT ADDC R6,R8 L$01 RLA R5 ; MULTIPLIER x 2 RLC R6 ; ; RRA R4 ; LSB+1 to carry JNC L$02 ; ADD R5,R7 ; ADDC R6,R8 L$02 RLA R5 ; RLC R6 ; .... ; same way for bits 2 to 12 ; RRA R4 ; MSB to carry (here bit13) JNC L$014 ; ADD R5,R7 ; ADDC R6,R8 ; No shift for multiplier necessary L$014 RET ; Return with result in R8|R7 ; 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. It must be only ensured 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 to ease software modifications. 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 if the result of an operation is zero then the carry is reset and vice versa. The instructions having this feature are: XOR, SXT, INV, BIT, AND.

395

Metering Application Report

MSP430 Family

Without using this feature a typical sequence for the conversion of an I/O-port bit to a parallel word would look as follows: RLA BIT JZ INC ... R5 #1,&IOIN L$111 R5 ; Free bit 0 for next info ; PO.0 high ? ; Yes, set bit 0 ; Info in bit 0

L$111

Using this feature the above sequence is shortened to two instructions: BIT RLC #1,&IOIN R5 ; PO.0 high ? .NOT.Zero -> carry ; Shift bit (in Carry) into R5

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 #1000,COUNT COUNTER ; COUNT >= 1000 ; If yes, (C = 1) incr. COUNTER

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. ADD ADC ADC R5,COUNT COUNT+2 COUNT+4 ; 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 I2C handler uses this mode.

; Normal way: SUBR2 is called, afterwards returned ; SUBR1 ... MOV R5,R6 CALL #SUBR2 ; Call subroutine RET ; ; "Fall Through" solution: SUBR2 is located after SUBR1 ; SUBR1 ... MOV R5,R6 ; Fall through to SUBR2 ; SUBR2 ... ; Start of subroutine SUBR2 RET

396

MSP430 Family

Metering Application Report

Shift Operations for 32-bit 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 R11 R12 R12 R11 ; MSB of low byte to carry ; RLA is wrong here! ; LSB of high byte to carry ; RRA is wrong here!

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. 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 DADD OP1,R5 #6666h,R5 R5 R5,OP2 ; Copy Op1 ; Shift OP1 to 6666h to FFFFh ; Build 9999 complement ; OP2 - OP1 -> OP2 (dec.)

397

Metering Application Report 7.1 Design Checklist

MSP430 Family

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 below. 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. Decision which hardware options are used (Supply voltage, pull-downs at the I/O-ports ?) 5. Worst case design for all of the external components. 6. Organization of the RAM and if present of the 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

398

MSP430 Family 7.2 Most often occurring Software Errors

Metering Application Report

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. 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. Missing Initialization of the Stack Pointer: the Stack Pointer needs to be initialized before the EINT instruction is executed or a CALL is used. The normal instruction to be used is: MOV #0300h,SP ; Locate stack at high RAM

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 distinguish always between signed and unsigned jump instructions. Wrong Completion Instructions. Despite their virtual similarity, subroutines and interrupt handlers need completely different actions for completion. Subroutines end with the RET instruction: only the address of the 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 falsely then a wrong item is written into the PC. This means that the software will continue at random addresses and will therefore hang-up. 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 equal fractional parts. See "Rules for the Integer Subroutines". Byte Instructions applied to Working Registers: byte instructions always clear the upper byte of the used working register (except CMP.B, TST.B, BIT.B). It is necessary therefore to use word instructions if operations in working registers can exceed the byte range. 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 PCs 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 A2.5. 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 ; Subroutines address is stored in MAIN 399

Metering Application Report CALL #MAIN

MSP430 Family ; Subroutine starts at address MAIN

The real behavior is seen easily when looking to the branch instruction: it is an emulated instruction using the MOV instruction: BR MOV MAIN ; Emulated instruction BR MAIN,PC ; Emulation by MOV instruction

The addressing for the CALL instruction is exactly the same as for the BR instruction. 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 one.

EXAMPLE: The timer interrupt handler increments a 32-bit timer. The background software uses this timer for calculations. The disabling of the interrupts avoids that a timer interrupt that occurs between the reading of TIMLO and TIMHI can falsify the read information. This is the case if TIMLO overflows from 0FFFFh to 0000h during the interrupt routine: TIMLO is read with the old information 0FFFFh and TIMHI contains the new information x+1. BT_HAN INC ADC RETI ... TIMLO TIMHI ; Incr. LO word ; Incr. HI word

; ; Background part copies TIMxx for calculations ; DINT ; GIE <- 0 NOP ; DINT needs 2 cycles MOV TIMLO,R4 ; Copy LSDs MOV TIMHI,R5 ; COPY MSDs EINT ; 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: ; INT_HAN INC CNTR ; Incr. counter CNTR RETI ; by interrupts ... MOV CLR CNTR,STORE CNTR ; Background program ; Read CNTR ; A count may be lost!

WRONG!

400

MSP430 Family ...

Metering Application Report

To avoid the loosing of a count the following solutions are possible for the background part: ; Background part switches off the interrupt during reading ; DINT ; GIE <- 0 (inactive after MOV) MOV CNTR,STORE ; Read CNTR CLR CNTR ; Clear unmodified CNTR EINT ; Enable interrupt again ; ; Background part uses difference of contents. If interrupt occurs ; after the PUSH instruction, 1 remains in CNTR. ; PUSH CNTR ; Copy CNTR SUB @SP,CNTR ; Subtract read number from CNTR POP STORE ; Place read info to STORE 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.

EXAMPLE: The return address stored at TOS is to be moved one word down to free space for an argument. PUSH PUSH @SP 2(SP) ; WRONG! 1st free word (TOS-2) is copied ; on itself ; Correct, old TOS is pushed 1 word down

EXAMPLE: The stored Stack Pointer 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 !!

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. 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) may result. The length of registers needs to be evaluated with "worst case" methods. Interrupt Blocking: long interrupt routines should be avoided. If they are necessary then the GIE bit located in the Status Register SR should be set (instruction EINT) at the start of these routines. Otherwise the disabled interrupt blocks all other interrupt sources. Real Time Processing: if the used algorithm is longer than the time slot that is available then errors will occur. "Worst case" evaluations are necessary to guarantee the fitting of the algorithm.

401

Metering Application Report 7.3 Most often occurring Hardware Errors

MSP430 Family

Crystal connection: the crystal oscillator is connected to AVcc and AVss. This means that these two pins must be connected to DVcc and DVss, otherwise the crystal will not oscillate. Open Inputs: every input must have a defined potential. Otherwise hum and noise will influence the program flow. Additionally the supply current increases. See section Correct Termination of unused Pins. Crystal turn-on 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 may last up to three seconds. No correct timing is possible until the crystal reached its nominal frequency. Up to this the DCO steps down to its lowest frequency ( 500kHz). See chapter The System Clock Generator. "Frequency Locked Loop" Considerations:. FLL turn-on Time: if woken-up from LPM3 the FLL needs approximately 6 cycles to reach the nominal frequency. This means, also 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 for the DCO is possible, it remains at the same tap. This time is spent best during initialization by a software loop with a worst case length of 28 x 32 x 30.5s = 27.3ms. To allow the system clock the adaptation of the DCO to the eventually changed tap, the FLL-loop should be closed during longer calculations. This is simply done with the instruction: BIC #SCG0,SR ; Turn on FLL-loop control

Supply Voltage for Battery driven 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 to the battery. Supply Voltage for Mains driven Systems: no hum, noise and spikes are allowed. If present the reliability of the system and the accuracy of the ADC will decrease. 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 used EEPROM.

402

MSP430 Family 7.4 Checklist for Problems 7.4.1 Hardware related Problems

Metering Application Report

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 mains frequency) are seen at the inputs. See section Correct Termination of unused Pins. 4. Crystal turn-on time not taken into account (may be up to seconds for low power 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? 7.4.2 Software related Problems 1. Register overflow (registers, memory and peripheral registers) causes negative numbers or sawtooth characteristic of results (numbers are too small then) 2. PWM applications: 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 Output frequency too high? (register load time longer than pulse length?) 3. Real Time Applications: is used algorithm shorter than the available time interval also under "worst case" conditions? 4. 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. 5. Missing "housekeeping" during stack operations? 6. 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) 7. Multiple word shifts: correct shift instruction used for the MSBs (no arithmetic shifts: they shift in always zeroes) 8. Stack Pointer Initialization: forgotten or made after the "interrupt enabling"? 9. Interrupt Handlers: long lasting parts without enabling the interrupt again (blocks all other interrupt activities)?

403

Metering Application Report 7.5 Run Time Estimation

MSP430 Family

To get a quick overview concerning the speed of a given piece of software, the following estimations may be used: If the code contains all addressing modes then the estimation for the needed runtime trun is: trun = 0.75 cycles/byte If the code contains only or predominant register mode addressing then the estimation for the needed runtime trun is: trun = 0.5 cycles/byte

404

MSP430 Family

Metering Application Report

8 ARCHITECTURE AND INSTRUCTION SET


The instruction set of the "Ultra Low Power"-microcomputer family MSP430 differs strongly from the instruction sets used by other 8 and 16 bit microcomputers. The reasons why this instruction set is appreciated although, 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 disappeared more and more during the last 20 years. A customer told us: it is an instruction set to fall in love with. 8.1 Introduction The MSP430 Family was developed to be able to fulfill the ever increasing requirements to the TEXAS INSTRUMENTS "Ultra Low Power" microcomputers. It was not possible to increase the computing power and the real time processing capability of the MSP430s predecessor TSS400 as far as needed, therefore a complete new 16 bit architecture was developed to stay competitive also in several years from now. The shown benchmark numbers in relation to competition products (used bytes, 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 The following chapters are intended to explain the different reasons why the MSP430 instruction set, which mirrors finally the architecture, has gotten so much popularity. 8.2.1 Orthogonality This notation of the 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 82.1 shows this graphically: the existing combinations fill the complete possible space.

405

Metering Application Report

MSP430 Family

Addressing Modes Source

Addressing Modes Destination Instructions

Figure 82.1: Orthogonal Architecture (Double Operand Instructions) The opposite to the above, a non-orthogonal architecture is shown in figure 82.2: any instruction can use only a part of the existing addressing modes. The possible combinations are arranged like small blocks in the available space.
Addressing Modes Source

Addressing Modes Destination Instructions

Figure 82.2: Non-Orthogonal 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 won by the indexing of an always zero containing register (Status Register SR). The single operand instructions may use all of the seven addressing modes, the double operand instructions may use all of them for the source operand and four of them for the destination operand. Figure 82.3 shows this context:

406

MSP430 Family

Metering Application Report

Double Operand Instructions


Mnemonic Source,Destination

Single Operand Instructions


Mnemonic Destination

Register Indexed

Register Indexed

Absolute Absolute Symbolic Symbolic Immediate Register indirect Register indirect autoincrement 12 Instructions 28 Combinations 7 Instructions

Register Indexed Absolute Symbolic Immediate Register indirect Register indirect autoincrement 7 Adressing Modes

Figure 82.3: Addressing Modes 8.2.2.1 Register Addressing The operand is contained in one of the registers R0 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 ; ADD R7,R8 ; (R7) + (R8) (R8) 8.2.2.2 Indirect Register Addressing The register used contains the address of the operand. The operand may be located anywhere in the complete memory space (64K). Example: ; Add the byte addressed by R8 to the contents of R9 ; ADD.B @R8,R9 ; ((R8)) + (R9) (R9) 8.2.2.3 Indirect Register Addressing with Autoincrement The register used contains the address of the operand. This operand may be located anywhere in the complete memory space (64K). After the access to the operand the used register is incremented by two (word instruction) respective one (byte instruction). Example: ; Copy the byte operand addressed by R8 to R9 ; and increment the pointer register R8 by one afterwards ; MOV.B @R8+,R9 ; ((R8)) (R9), (R8) + 1 (R8)

407

Metering Application Report 8.2.2.4 Indexed Addressing

MSP430 Family

The address of the operand is the sum of the index and the contents of the used register. The index is contained in an additional word located after the instruction word. Example: ; Compare the 2nd byte of a table addressed by R5 with the ; low Byte of R15. Result to the Status Register SR ; CMP.B 1(R5),R15 ; (R15) - (1 + (R5)) ; If the register in use is the Program Counter then two additional, important addressing modes result: 8.2.2.5 Immediate Addressing Any 16 or 8 bit constant can be used with an instruction. The Program Counter points to the following word after the reading of the instruction word. By the use of the "Register Indirect Autoincrement" addressing mode this word (the immediate value) can be read and the Program Counter is incremented by two afterwards: the word after the instruction word is treated this way as an 8 or a 16 bit immediate value. Example: ; Test bit 8 in ; Start address ; BIT ; ; The assembler ; BIT .WORD .WORD the 3rd word of a table R10 points to. of the table is 0(R10), 3rd word is 4(R10) #0100h,4(R10) ; Bit 8 = 1?

inserts for the instruction above: @PC+,4(R10) 0100h 0004h ; Executed instruction ; Source constant 0100h ; Index 4 of the destination

8.2.2.6 Symbolic Addressing This is the normal addressing mode for the random access to the complete 64K memory space. The word located after the instruction word contains the difference in bytes to the destination address relative to the Program Counter. This difference may be seen as an index to the Program Counter. Any address in the 64K memory map is addressable this way both as a source and as a destination. Example: $ = address the Program Counter points to ; Subtract the contents of the ROM word EDE from the contents ; of the RAM word TONI ; SUB EDE,TONI ; (TONI) - (EDE) (TONI) ; ; The assembler inserts for the instruction above: ; SUB X(PC),Y(PC) ; Executed instruction .WORD X ; Index X = EDE-$ .WORD Y ; Index Y = TONI-$

408

MSP430 Family 8.2.2.7 Absolute Addressing

Metering Application Report

Addresses that are fixed (e.g., the hardware addresses of the peripherals like ADC, UART) may be addressed absolute. The absolute addressing mode is a special case of the indexed addressing mode: the used register (Status Register SR) contains always zero in this case (without loosing its former information!). Example: ; Set the Power ; BIS ; ; The assembler ; BIS .WORD .WORD Down Bit in the ADC Control Register ACTL #PD,&ACTL ; Power Down Bit ADC <- 1

inserts for the instruction above: @PC+,X(SR) 01000h 00114h ; Executed instruction ; PD Bit Hardware Address ; X: Hardware Address of ACTL

8.2.3 RISC Architecture without RISC Disadvantages Classical RISC architectures provide only for the LOAD and STORE instructions several addressing modes; all other instructions can only access the (numerous) registers. The MSP430 may be programmed this way too, an example for this programming style is the Floating Point Package: 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 for this is the incrementing of a counter during an interrupt service routine: ; Pure RISC program sequence for the incrementing of a counter ; LOAD R5,COUNTER ; Load COUNTER to a register INC R5 ; Increment this register STORE R5,COUNTER ; Store back the result ; ; The MSP430 program sequence for the incrementing of a counter ; INC COUNTER ; Increment COUNTER As shown with the example above the pure RISC architecture is not optimal in cases with few calculations but necessary fast access to the memory. Here the MSP430 architecture is advantageous, due to the random access to the complete memory (64K) 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 the small numbers. Six out of them were chosen for the Constant Generator: Constant Hex Representation -1 0FFFFh Use Constant, all bits are one 409

Metering Application Report 0 +1 +2 +4 +8 00000h 00001h 00002h 00004h 00008h

MSP430 Family Constant, all bits are zero Constant, increment for byte addresses Constant, increment for word addresses Constant, value for bit tests Constant, value for bit tests

These six Constants may be used also for byte processing; only the lower byte is in use then. The use of 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 the Status Register 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 three ways shown below: 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. 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 RAM space enough. Due to the function of the Stack Pointer as a general purpose register it is possible to use all of the seven addressing modes for the Stack Pointer: 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 which use normally 128 bytes. Inside program parts it is therefore necessary only very rarely to use the Branch instruction with its normally two memory words and longer execution time. The implemented eight Jumps are classified in three categories:

410

MSP430 Family

Metering Application Report

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 of the MSP430 is divided into bytes and words as shown in figure 82.4.
15 Byte Address n+1 Byte Address n+3 Byte Address n+5 Byte Address n Byte Address n+2 Byte Address n+4 0 Word Address n Word Address n+2 Word Address n+4

Figure 82.4: Word and Byte Addresses of the MSP430

This way the complete 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 may be used as a pointer to tables. The implemented addressing modes indexed, indirect and indirect with autoincrement are intended for table processing. 8.2.9 High Register Count Additional to the Program Counter PC and the Stack Pointer SP, which are usable for several purposes, twelve identical general purpose registers (R4 to R15) are available. Anyone of these registers may be used as a data register, as an address pointer, an auto-incrementing address pointer and as an index register. The bottleneck of the accumulator architectures which have to pass any operation through the accumulator (with corresponding LOAD and STORE instructions) does not exist for the MSP430.

411

Metering Application Report

MSP430 Family

15 PC SP SR CG2 R4

0 R0 Program Counter R1 Stack Pointer R2 Status Register and CG1 R3 Constant Generator 2 R4 General-Purpose Register R4 General-Purpose Registers R5 to R14 R15 R15 General-Purpose Register R15

Figure 82.5: Register Set of the MSP430 8.2.10 Emulation of non-implemented Instructions The 27 implemented instructions allow the emulation of additional 24 instructions. This is reached normally with the help of the Constant Generator, but other ways are used too. As the used constants 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 listed completely in section 8.4.2. 8.2.11 No Paging The 16 bit architecture of the MSP430 allows the direct addressing of the complete 64K memory bytes without paging of the memory. This feature simplifies the development of software strongly.

412

MSP430 Family

Metering Application Report

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 chapter 8.2, have effects and advantages that result also in saved money. These effects and advantages are shown and explained below: 8.3.1 Less Program Space The direct access to any address, without the previous loading of the 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 respective 8K version is needed. 8.3.2 Shorter Programs Any necessary code line is a source of errors. The less code lines are necessary for a given task, the simpler a program is to read, to understand and to service. The MSP430 needs between 33% and 55% of code lines compared to its competition products. The reason for this is the same as shown above: any address can be accessed directly and that both for the source operand 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 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 of the MSP430 allows to write up from the start dense and well legible code. If the program to be developed is prepared well and coded clearly, then it is nearly impossible to reduce the program length seriously afterwards by compressing. This is no disadvantage, it simply means to have developed up from the start nearly optimized code. 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 of the simple instructions, resulting in a use of only 30% (!) of the implemented instructions. Completely different with the MSP430: As the instructions apart from the executed operation are completely uniform, 100% of them are used by the compiler and not only 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.

413

Metering Application Report 8.4 The MSP430 Instruction Set Below all implemented and emulated instructions are shown. Description of the used abbreviations: @ * 0 1 V N Z C src dst xx..B Label 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 7 Addressing Modes Destination Operand with 4 Addressing Modes Byte Operation of the Instruction xx Label of the source or destination

MSP430 Family

8.4.1 Implemented Instructions The instructions that are implemented in the CPU follow. 8.4.1.1 Two Operand Instructions Status Bits V N Z C * * * * * * * * 0 * * @Z - - - - - - 0 * * @Z * * * * * * * * - - - * * * * * * * * * * * @Z

ADD; ADDC; AND; BIC; BIS; BIT; CMP; DADD; MOV; SUB; SUBC; XOR;

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

414

MSP430 Family

Metering Application Report

8.4.1.2 Single Operand Instructions The operand (src or dst) can be addressed with all seven addressing modes. Status Bits V N Z C - - - - - - * * * * 0 * * * * * * * - - - 0 * * @Z

CALL PUSH; RETI RRA; RRC; SWPB SXT

dst PUSH.B src RRA.B RRC.B 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

8.4.1.3 Conditional Jumps The status bits are not affected by the jumps. With the signed jumps (JGE, JLT) the overflow bit is evaluated too so that the jumps are executed correctly even in the case of overflow. Some jumps are the same (JC/JHS, JZ/JEQ, JNC/JLO, JNE/JNZ) but two mnemonics are used to get a better understanding of the program code.

JC JHS JEQ JZ JGE JLT JMP JN 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

415

Metering Application Report 8.4.2 Emulated Instructions

MSP430 Family

The emulated instructions use implemented instructions together with constants coming out of the Constant Generator. Status Bits V N Z C ADC; ADC.B dst Add Carry to dst * * * * BR dst Branch indirect dst - - - CLR; CLR.B dst Clear dst - - - CLRC Clear Carry Bit - - - 0 CLRN Clear Negative Bit - 0 - CLRZ Clear Zero Bit - - 0 DADC; DADC.B dst Add Carry to dst (decimally) * * * * DEC; DEC.B dst Decrement dst by 1 * * * * DECD; DECD.B dst dst - 2 dst * * * * DINT Disable interrupts - - - EINT Enable interrupts - - - INC; INC.B dst Increment dst by 1 * * * * INCD; INCD.B dst dst + 2 dst * * * * INV; INV.B dst Invert dst * * * @Z NOP No operation - - - POP; POP.B dst Pop top of stack to dst - - - RET Subroutine return - - - RLA; RLA.B dst Rotate left dst arithmetically * * * * RLC; RLC.B dst Rotate left dst through Carry * * * * SBC; SBC.B dst Subtract Carry from dst * * * * SETC Set Carry Bit - - - 1 SETN Set Negative Bit - 1 - SETZ Set Zero Bit - - 1 TST; TST.B dst Test dst * * * *

416

MSP430 Family 8.5 Benefits

Metering Application Report

The specification for the architecture of the MSP430 CPU contained the following demands sequenced by their importance: 1. 2. 3. 4. 5. 6. 7. High processing speed Small CPU (Central Processing Unit) area on-chip High ROM efficiency Easy software development Usable also in the future High flexibility Usable for modern programming techniques

The following shows the finding of the optimum architecture out of the above 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 respective 8-bit microcomputers, software and hardware related attributes were chosen. Hardware related Attributes: - Use of 16 bit words: the analog-to-digital converter result can be processed immediately; two operands (source and destination) are possible in one instruction. - No microcoding: every instruction is decoded separately and allows therefore one-cycle instructions. This is the case for register/register addressing, the normal addressing mode used for time critical software parts. - Interrupt capability for anyone of the 8 I/O-Ports: the periodical polling of the inputs is not necessary. - Vectored interrupts: this allows the fastest reaction to interrupts. Software related Attributes: - 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. - High register count: twelve commonly usable registers allow to store all time critical values to reach the fastest possible access. 8.5.2 Small CPU area To get low overall cost for the MSP430 it was tried to reach a small CPU without limiting its processing capability: Use of a RISC structure: with few but strong instructions any algorithm may be processed. Together with the Constant Generator all normally used instructions, not contained in the implemented instructions, are executable. 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. Only three instruction formats: restriction to dual operand instructions, single operand instructions and conditional jumps.

417

Metering Application Report 8.5.3 High ROM Efficiency

MSP430 Family

To allow to solve a given task with a small ROM the following steps were taken: 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. Placing of Program Counter, Stack Pointer and Status Register inside of the register set: the possibility to address them as registers saves ROM space. 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. Use of a byte/word 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 above mentioned attributes of the architecture ease the development of software for the MSP430. 8.5.5 Usability in the Future The chosen "von-Neumann"-architecture allows a simple system expansion far beyond the currently addressable 64K bytes. If necessary memory expansion up to 16M bytes is possible. 8.5.6 Flexibility of the Architecture To ensure that all intended peripheral modules, including these ones currently unknown, can be connected easily to the MSP430 system the following definitions were made: Placing of the peripheral control registers into the memory space ("Memory Mapped I/O"). The use of the normal instructions also for the peripheral modules makes special peripheral instructions superfluous. 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 Stack Pointer SP is implemented therefore as a CPU register. 8.6 Conclusion

It was tried to demonstrate 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 assembler language has an antipathy to adapt again to the more or less unstructured architectures of the other 4-, 8 and 16 bit-microcomputers.

418

MSP430 Family

Metering Application Report

APPENDIX A1 CPU REGISTERS


All of the MSP430 CPU-registers can be used with all instructions. A1.1 The Program Counter R0 One of the main differences to other microcomputer architectures relates to the Program Counter (PC) that may be used as a normal register with the MSP430. This means that all of the instructions and addressing modes may 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 ; ; ; ; Jump to address LABEL Jump to the address contained in address LABEL Jump 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 non-predictable behavior. A1.2 Stack Processing A1.2.1 Usage of the System Stack Pointer R1 The system stack pointer (SP) 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: - Interrupt return addresses and Status Register contents - Subroutine return addresses - Intermediate results - Variables for subroutines, floating point package etc. When using the system stack one should bear in mind that the microcomputer hardware uses the stack pointer too 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 points 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. If bytes are pushed on the system stack, only the lower byte is used, the upper byte is not modified.

419

Metering Application Report PUSH PUSH.B #05h #05h ; 0005h -> TOS ; xx05h -> TOS

MSP430 Family

A1.2.2 Software Stacks Every register from R4 to R15 may be used as a software stack pointer. This allows independent stacks for jobs that have a need for this. Every part of the RAM may be used for these software stacks. EXAMPLE: R4 is to be used as a software stack pointer. MOV ... DECD MOV ... MOV #SW_STACK,R4 R4 item,0(R4) @R4+,item2 ; Init. SW stack pointer ; ; ; ; Decrement stack pointer Push item on stack Proceed Pop item from stack

Software stacks may be organized as byte stacks too. This is not possible for the system stack which always uses 16-bit words. The example shows R4 used as a byte stack pointer: MOV ... DEC MOV.B ... MOV.B #SW_STACK,R4 R4 item,0(R4) @R4+,item2 ; Init. SW stack pointer ; ; ; ; Decrement stack pointer Push item on stack Proceed Pop item from stack

A1.3 Byte and Word Handling Every memory word is addressable by three addresses as shown in the figure A1.1: 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 R0 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. The way an instruction treats data is defined with its extension: 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.

420

MSP430 Family

Metering Application Report

ADD ADD.W

&050h,R5 &050h,R5

; ADD 16-BIT VALUE TO R5 ; ADD 16-BIT VALUE TO R5

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
Bit

&050h,R5
15 Upper Byte Odd Address N+1

; ADD 8-BIT VALUE TO R5


8 7 Lower Byte Even Address N Word Address N 0

Figure A1.1: Word and Byte Configuration If registers are used with byte instructions the upper byte of the destination register is set to zero for all instructions except CMP.B, TST.B, BIT.B and PUSH.B. It is necessary therefore to use word instructions if the range of calculations can exceed the byte range. EXAMPLE: The two OP3. ; MOV.B SXT MOV.B SXT ADD.W ; signed bytes OP1 and OP2 have to be added and the result stored in word 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

A1.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: Number +0 +1 +2 +4 +8 -1 Table A1.1 Constant Generator Explanation Hexadecimal Zero positive one positive two positive four positive eight negative one (0000h) (0001h) (0002h) (0004h) (0008h) (FFFFh) Register R3 R3 R3 R2 R2 R3 Field Ad 00 01 10 10 11 11

The assembler inserts these ROM-saving addressing modes automatically if one of the above immediate constants is encountered. But only immediate constants are replaceable this way, not for example - index values. 421

Metering Application Report

MSP430 Family

If an immediate constant out of the Constant Generator is used then 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. A1.5 Addressing The MSP430 allows seven addressing modes for the source operand and four addressing modes for the destination. The addressing modes used are: Address Bits src dst 00 0 01 1 01 1 01 1 10 11 11 Table A1.2 Addressing Modes Source Modes Destination Modes Register Indexed Symbolic Absolute Indirect Indirect autoincrement Immediate Register Indexed Symbolic Absolute Example R5 TAB(R5) TABLE &BTCTL @R5 @R5+ #TABLE

The three missing addressing modes for the destination operand are not of much concern for the programming. The reason is: Immediate Mode: Not necessary for the destination; immediate operands can be placed always into the source. Only in a very few cases it is necessary to have two immediate operands in one instruction Indirect Mode: If necessary the Indexed Mode with an index of zero is usable. For example: ADD CMP #16,0(R6) R5,0(SP) ; @R6 + 16 -> @R6 ; R5 equal to TOS?

The second example above 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 is usable that saves ROMspace and reduces the number of used registers to one: EXAMPLE: The content of TAB1 is to be written into TAB2. TAB1 ends at the word preceding TAB1END. LOOP MOV MOV.B CMP JNE ... #TAB1,R5 ; Initialize pointer @R5+,TAB2-TAB1-1(R5) ; Move TAB1 -> TAB2 #TAB1END,R5 ; End of TAB1 reached? LOOP ; No, proceed ; Yes, finished

The above 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 below

422

MSP430 Family MOV MOV MOV.B INC CMP JNE ... #TAB1,R5 #TAB2,R6 @R5+,0(R6) R6 #TAB1END,R5 LOOP

Metering Application Report ;Initialize pointers ;Move TAB1 -> TAB2 ;End of TAB1 reached? ;No, proceed ;Yes, finished

LOOP

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 Indirect Mode: Table addressing via register; code saving access to often referenced addresses Indirect Autoinkrement 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 which 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 CMP.B JNE CLR.B RETI COUNTER #5,STATUS INTRET STATUS ;Increment counter ;STATUS = 5? ; ;STATUS = 5: clear it

INTRET

No loading of pointers or saving and restoring of registers is necessary. What is to be done is made immediately without any overhead. A1.6 Program Flow Control A1.6.1 Computed Branches and Calls The Branch instruction is an emulated instruction which moves the destination address into the Program Counter: MOV dst,PC ; EMULATION FOR BR dst

The possibility to access the Program Counter in the same way as all other registers gives interesting options: 1. The destination address can be taken from tables: see A.2.5 2. The destination address may be calculated 423

Metering Application Report 3. The destination address may be a constant: the normal way

MSP430 Family

A1.6.2 Nesting of Subroutines Due to the stack orientation of the MSP430, one of the main problems of other architectures does not play a role 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" instruction RET. If subroutines are left without the RET instruction then some housekeeping is necessary: popping of the return address or addresses from the stack.. A1.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 only necessary to include an EINT instruction into the interrupt handler. If the interrupt handlers are as short as possible (a good realtime practice) then nesting may not be necessary. EXAMPLE: The Basic Timer interrupt handler is woken-up with 1Hz only but has to do a lot of things. The interrupt nesting is used therefore. The latency time is 8 clock cycles only. ; Interrupt handler for Basic Timer: Wake-up with 1Hz ; BT_HAN EINT ; Enable interrupt for nesting INC.B SECCNT ; Counter for seconds +1 CMP.B #60,SECCNT ; 1 minute elapsed? JHS MIN1 ; Yes, do necessary tasks RETI ; 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 MINCNT ; Minute counter +1 CLR SECCNT ; 0 -> SECCNT ... ; Start of necessary tasks RETI ; Tasks completed A1.6.4 Jumps Jumps allow the conditional or unconditional leaving of the linear program flow. The Jumps cannot reach every address of the address space but they have the advantage to need only one word and only two MCLK cycles. The 10-bit offset field allows Jumps of 512 words maximum in the forward direction 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:

424

MSP430 Family Table A1.3: Jump Usage Applications

Metering Application Report

Mnemonic JMP JEQ JZ JNE JNZ JHS JC JLO JNC JGE JLT JN label label label label label label label label label label label label

Condition

Unconditional Jump Jump if Z = 1 Jump if Z = 1 Jump if Z = 0 Jump if Z = 0 Jump if C = 1 Jump if C = 1 Jump if C = 0 Jump if C = 0 Jump if N .XOR. V = 0 Jump if N .XOR. V = 1 Jump if N = 1

Program control transfer After comparisons: src = dst Test for zero contents After comparisons: src # dst Test for non-zero contents After unsigned comparisons: dst src Test for a set Carry After unsigned comparisons dst < src Test for a reset Carry After signed comparisons: dst src After signed comparisons: dst < src Test for 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 resp. 0 to 07Fh) both signed and unsigned conditional jumps behave similiarly. This changes completely when used with negative data (08000h to 0FFFFh resp. 080h to 0FFh): the signed conditional jumps treat negative data as smaller numbers than the positive ones, and the unsigned conditional jumps treat them as larger numbers 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. It must be only ensured that the instruction preceding the JGE resets the overflow bit V. The following instructions ensure this: AND BIT RRA SXT TST If this feature is used example: MOV TST JGE src,dst src,dst dst dst dst ; ; ; ; ; V V V V V <<<<<0 0 0 0 0

it should be noted within the comment for later software modifications. For ITEM,R7 R7 ITEMPOS ; FETCH ITEM ; V <- 0, ITEM POSITIVE? ; V=0: JUMP IF >= 0

NOTE If addresses are computed only the unsigned jumps are adequate: 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 with before): ; OV .EQU 0100h ; Bit address in SR ; BIT #OV,SR ; Test Overflow Bit and clear it JNZ OVFL ; If OV = 1 branch to label OVFL ... ; If OV = 0 continue here 425

Metering Application Report

MSP430 Family

A2 SPECIAL CODING TECHNIQUES


The flexibility of the MSP430 CPU together with a powerful assembler allows coding techniques not available with other microcomputer. The most important ones are explained below. A2.1 Conditional Assembly For a detailed description of the syntax please refer to "MSP430 Family Assembler Language Tools Users Guide". Conditional assembly provides the possibility to compile different lines of source into the object file depending on the value of an expression that is defined in the source of the program. This makes it easy to alter the behaviour of the code with modifying one single line in the source. The following example shows how to use conditional assembly. The example will allow 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 A0 in R8.

DEBUG ACTL ADAT IFG2 ADIFG

.set .set .set .set .set

1 0114h 0118h 3 4

;1= debugging mode; 0= normal mode

; get_ADC_value: ; .IF DEBUG=1 MOV #07FFh,R8 .ELSE BIC #60,&ACTL ; Input channel is A0 BIC.B #ADIFG,&IFG2 BIS #1,&ACTL ; Start conversion WAIT BIT.B #ADIFG,&IFG2 JZ WAIT ; Wait until conversion is ready MOV &ADAT,R8 .ENDIF RET ; With a little further refining of the code better results can be achieved. The following piece of code shows more built-in ways to debug the written code. The second debug code, where debug=2, returns 0700h and 0800h alternating. DEBUG ACTL ADAT IFG2 .SET .SET .SET .SET 1 0114h 0118h 3 ; 1= debug mode 1; 2= deb. mode 2; 0= ; normal mode

426

MSP430 Family ADIFG .SET 4

Metering Application Report

; get_ADC_value: ; VAR .SECT "VAR"0200h OSC .WORD 0700h .IF MOV .ELSEIF MOV SUB MOV .ELSE BIC BIC BIS BIT JZ MOV .ENDIF RET DEBUG=1 #07FFh,R8 DEBUG=2 #0F00h,R8 OSC,R8 R8,OSC #60h,&ACTL #ADIFG,&IFG2 #1,&ACTL #ADIFG,&IFG2 WAIT &ADAT,R8 ; Return a constant value

; Return alternating values

; Input channel is A0 ; Start conversion ; Wait until conversion is ready

WAIT

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 not needed parts are left out by Conditional Assembly. The big advantage is the single source that is to be maintained. An example for 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 chapter "The Floating Point Package" for details. A2.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 necessary. PIC is possible with the MSP430 mainly due to the allocation of the PC inside of the register bank. The availability of the PC is often used. Links to other PIC-blocks are possible only by references to absolute addresses (pointers). EXAMPLE: Code is transferred to the RAM from an outside storage (EPROM, ROM, EEPROM) and executed there with full speed. This code needs to be PIC. The loaded code may have several purposes: Application specific software that is different for some versions Additional code that was not anticipated before mask generation Test routines for manufacturing purposes

A2.2.1 Referencing of Code inside Position Independent Code The referenced code or data is located in the same block of PIC as the program resides.

427

Metering Application Report

MSP430 Family

Jumps Jumps are position independent anyway: their address information is an offset to the destination address. Branches ADD .WORD @PC,PC ;Branch to label DESTINATION DESTINATION-$

Subroutine Calls Calling a subroutine starting at the label SUBR: ; SC MOV ADD CALL PC,Rn #SUBR-$,Rn Rn ; Address SC+2 -> AUX. REG ; 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 DATA1,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 ... JMP Rstatus,PC STATUS0 STATUS2 STATUSn ; Rstatus = (2x status) ; Code for status = 0 ; Code for status = 2 ; Code for status = 2n

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 TABLE ADD .WORD .WORD ... .WORD TABLE(Rstatus),PC ; Rstatus = status STATUS0-TABLE ; Offset for status = 0 STATUS2-TABLE STATUSn-TABLE ; Offset for status = 2 ; Offset for status = 2n

A2.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:

428

MSP430 Family

Metering Application Report

BR

#DESTINATION

; #DESTINATION -> PC

Subroutine Calls Calling a subroutine starting at the absolute address SUBR: CALL #SUBR ; #SUBR -> PC

Operations on Data Absolute mode (indexed mode with Reg = 0) CMP ADD PUSH &DATA1,&DATA2 &DATA1,Rn &DATA2 ; DATA1 + 0 = DATA1 ; DATA2 -> stack

Branch Tables The status contained in Rstatus decides where the SW continues. Rstatus steps in increments of 2. Table is located in absolute address space: MOV TABLE(Rstatus),PC ; Rstatus = ... .sect xxx ; Table in absolute address .WORD STATUS0 ; Code for status = .WORD STATUS2 ; Code for status = ... .WORD STATUSn ; Code for status = status space 0 2 2n

TABLE

Table is located in PIC address space, but addresses are absolute: MOV ADD ADD MOV .WORD .WORD ... .WORD Rstatus,Rhelp ; PC,Rhelp ; #TABLE-L$1,Rhelp @Rhelp,PC ; STATUS0 ; STATUS1 ; STATUSn Rstatus contains status Status + L$1 -> Rhelp ; Status+L$1+TABLE-L$1 Computed address to PC Code for status = 0 Code for status = 2

L$1 TABLE

; Code for status = 2n

The above shown program examples may be implemented as MACROs if needed. This would ease the usage and transparency. A2.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 using task has not yet finished the subroutine. The main difference of a reentrant subroutine to 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 429

Metering Application Report

MSP430 Family

between the routine itself and the calling software part 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": - 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 used registers on the stack and restore them from there or they compute directly on the stack. PUSH 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

A2.4 Recursive Code Recursive subroutines are subroutines that call themselves. This is not possible with normal 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 using all of the existent checks and features of the handler without the need to write it once more. The following conditions must be met for "Recursive Code": No usage 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 PUSH R4 ; Save R4 ... CMP #70,LINES ; 70 lines printed? JLT L$500 ; No, proceed CALL #LPHAND ; .BYTE CR,FF ; Yes, output Carriage Return ... ; and Form Feed L$500 ... A2.5 Flag Replacement by Status Usage Flags have several disadvantages if used for program control: - Missing transparency (flags may depend on other flags) - Possibility of nonexistent flag combinations if not handled very carefully - 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 descriptive and prohibits "nonexistent"

430

MSP430 Family

Metering Application Report

combinations. A second advantage is the high speed of the decision: one instruction only 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 may be changed more randomly 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 STATUS0 ; Address handler for status = 0 .WORD ... .WORD ; STATUS0 .... INCD JMP STATUS2 STATUSn ; Address handler for status = 2 ; Address handler for status = 2n ; Start handler status 0 ; Next status is 2 ; Common end

Rstatus HEND

The above solution has the disadvantage to use 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, ..n) ; Usable range: TABLE4-128 to TABLE4+126 PUSH.B SXT ADD .BYTE .BYTE .... .BYTE TABLE4(R5) @SP @SP+,PC STATUS0-TABLE4 STATUS1-TABLE4 STATUSn-TABLE4 ; ; ; ; STATUSx-TABLE4 -> STACK Forward/backward references TABLE4+STATUSx-TABLE4 -> PC DIFFERENCE TO START OF HANDLER

TABLE4

; 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) ; Usable range: TABLE5 to TABLE5+254 PUSH.B CLR.B ADD .BYTE .BYTE .... .BYTE TABLE5(R5) 1(SP) @SP+,PC STATUS0-TABLE5 STATUS1-TABLE5 STATUSn-TABLE5 ; ; ; ; STATUSx-TABLE -> STACK Hi byte <- 0 TABLE+STATUSx-TABLE -> PC DIFFERENCE TO START OF HANDLER

TABLE5

; Offset for status = n 431

Metering Application Report ; The above example can be made shorter and faster if a register can be used:

MSP430 Family

; Stepping is forward only (with doubled forward range) ; Status is contained in R5 (0, 1, 2..n) ; Usable range: TABLE5 to TABLE5+254 ; MOV.B TABLE5(R5),R6 ; STATUSx-TABLE5 -> R6 ADD R6,PC ; TABLE5+STATUSx-TABLE5 -> PC TABLE5 .BYTE STATUS0-TABLE5 ; DIFFERENCE TO START OF HANDLER .BYTE STATUS1-TABLE5 .... .BYTE STATUSn-TABLE5 ; 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 RLA ADD .BYTE .BYTE ... .BYTE TABLE6(R5),R6 ; (STATUSx-TABLE6)/2 R6 ; STATUSx-TABLE6 R6,PC ; TABLE6+STATUSx-TABLE6 -> PC (STATUS0-TABLE6)/2 ; Offset for Status = 0 (STATUS1-TABLE6)/2 ; (STATUSn-TABLE6)/2 ; Offset for Status = n

TABLE6

; A2.6 Argument Transfer with Subroutine Calls Subroutines often have arguments to work with. Several methods exist for the passing of these arguments to the subroutine: - 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. A2.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). Advantages: - Usable generally; no registers have to be freed for argument passing - Variable arguments are possible

432

MSP430 Family Disadvantages:

Metering Application Report - Overhead due to necessary housekeeping - Not easy to understand

EXAMPLE: The subroutine SUBR gets its information from two arguments pushed onto the stack before the calling. No information is given back, normal return from subroutine is used. PUSH PUSH CALL ... MOV MOV MOV ADD ... RET argument0 argument1 #SUBR 4(SP),Rx 2(SP),Ry @SP,4(SP) #4,SP ; 1st ARGUMENT FOR SUBROUTINE ; 2nd ARGUMENT ; SUBROUTINE CALL ; ; ; ; ; ; COPY ARGUMENT0 TO Rx COPY ARGUMENT1 TO Ry RETURN ADDRESS TO CORRECT LOC. PREPARE SP FOR NORMAL RETURN PROCESSING OF DATA NORMAL RETURN After the RET, it looks like this:

SUBR

After the subroutine call the stack looks as follows:

TOS before CALL Argument0 Argument1

SP

Address N+4 Address N+2 Address N

SP

Return Address

Figure A2.1: Argument Allocation on the Stack EXAMPLE: The subroutine SUBR gets its information from two arguments pushed onto the stack before the calling. Three result words are returned on the stack: it is the responsibility of the calling program to pop the results from the stack. PUSH PUSH CALL POP POP POP ... MOV MOV ... PUSH MOV MOV MOV RET argument0 argument1 #SUBR R15 R14 R13 4(SP),Rx 2(SP),Ry 2(SP) RESULT0,6(SP) RESULT1,4(SP) RESULT2,2(SP) ; ; ; ; ; ; ; ; ; ; ; ; ; 1st ARGUMENT FOR SUBROUTINE 2nd ARGUMENT SUBROUTINE CALL RESULT2 -> R15 RESULT1 -> R14 RESULT0 -> R13 COPY ARGUMENT0 TO Rx COPY ARGUMENT1 TO Ry PROCESSING CONTINUES SAVE RETURN ADDRESS 1st RESULT ON STACK 2nd RESULT ON STACK 3rd RESULT ON STACK

SUBR

After the subroutine call the stack looks as follows: 433

After the RET, it looks like this:

Metering Application Report

MSP430 Family

TOS before CALL Argument0 Argument1 Address N+4 Address N+2 Address N Result0 Result1

SP

Return Address

SP

Result2

Figure A2.2: 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 to move the SP above the last item on the stack; indexed addressing is needed instead.

A2.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). Advantages: Disadvantages: - Very clear and easily readable interface - 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 .WORD .BYTE ... MOV MOV MOV MOV ... RET #SUBR START 24,0 @SP,R5 @R5+,R6 @R5+,R7 R5,0(SP) ; ; ; ; ; ; ; ; ; ; SUBROUTINE CALL START OF TABLE LENGTH OF TABLE, FLAGS 1st instruction after CALL COPY ADDRESS 1st ARGUMENT TO R5 MOVE 1st ARGUMENT TO R6 MOVE ARGUMENT BYTES TO R7 ADJUST RETURN ADDRESS ON STACK PROCESSING OF DATA NORMAL RETURN

SUBR

A2.6.3 Arguments in Registers The arguments are moved into defined registers and used afterwards by the subroutine. Advantages: - Simple interface and easy to understand - Very fast - Variable arguments are possible

434

MSP430 Family Disadvantages: - Registers have to be freed

Metering Application Report

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 ... ... RET arg0,R5 arg1,R6 #SUBR ; 1st ARGUMENT FOR SUBROUTINE ; 2nd ARGUMENT ; SUBROUTINE CALL ; PROCESSING OF DATA ; NORMAL RETURN

SUBR

A2.7 Interrupt Vectors in RAM If the destination address of an interrupt changes with the program run it is valuable to have the possibility to modify the pointer. The vector itself (which resides in ROM) cannot be changed but a second pointer residing in RAM may be used for this purpose: EXAMPLE: The interrupt handler for the Basic Timer starts at location BTHAN1 after initialization and at BTHAN2 when a certain condition is met (for example, calibration is made). ; BASIC TIMER INTERRUPT GOES TO ADDRESS BTVEC. THE INSTRUCTION ; "MOV @PC,PC" WRITES THE ADDRESS IN BTVEC+2 INTO THE PC: ; THE PROGRAM CONTINUES AT THAT ADDRESS ; .sect "VAR",0200h ; RAM START BTVEC .word 0 ; OPCODE "MOV @PC,PC" .word 0 ; ACTUAL HANDLER START ADDR. ; THE SOFTWARE VECTOR BTVEC IS INITIALIZED: ; INIT MOV #04020h,BTVEC ; OPCODE "MOV @PC,PC MOV #BTHAN1,BTVEC+2 ; START WITH HANDLER BTHAN1 ... ; 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 .WORD "BTVect",0FFE2h ; VECTOR ADDRESS BASIC TIMER BTVEC ; FETCH ACTUAL VECTOR THERE

435

Metering Application Report REFERENCES MSP430 Family Assembly Language Tools Users Guide 1994 MSP430 Family Software Users Guide 1994 MSP430 Family Architecture Guide and Module Library 1994 Data Sheet MSP430C323, MSP430P325 1995 Data Sheet MSP430C313, MSP430P313 1995 Data Sheet MSP430C336, MSP430P337 1996 "TMS320DSP Designers Notebook Number 43 1994 Linear Circuits Data Book Volume 1 1992 Linear Circuits Data Book Volume 3 1992 Power Supply Circuits 1996 TLC77XX BiCMOS Supply Voltage Supervisors 1995 TSS721 M-Bus Transceiver Application Report 1994 Mehr MIPS fr's Watt 1994 Optische Energie- und Signalbertragung fr Mesonden 1995 Data Encryption Algorithm ANSI 1981 Microchip Data Book 1994 Dallas Semiconductors Manual MSP430 Family Data Manual 1994 Power Transistors and Darlington Data Manual 1995 Mixed Signal and Logic Products Product Overview 1996 Linear Circuits Power+Products, Peripheral Drivers/Actuators International Rectifier IR2130 Data Sheet 1992 Power Products Data Book 1990

MSP430 Family

SLAUE12 SLAUE11 SLAUE10 SLASE06 SLASE08 SLASE10 SLYD003A SLYD005A SLVD002 SLVAE03 SLAAE03 ELEKTRONIK 22 ELEKTRONIK 23 ANSI X3.92-1981 DS00018G SPNS014B SLPDE08 SLYZE08 SLYD010A DB029

436

You might also like