Home

71M653X - Software User`s Guide

image

Contents

1. TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA Function Routine the LCD in milliwatt hours iptior Inpu File Nam Name Description nput Output e Name y Displays the current delta from temperature lcd the calibration temperature in Void void Meter meter c degrees C on the LCD time lcd Displays the current time Void void io tc 30 c tmr disable Halt a timer None none ioXmrO h tmr1 h Lets a timer run timer start tmr_enable does this by default none none ioXmrO h tmr1 h tmr_running Reems Pee IGS none bool io tmr0 h tmr1 h running Uint16_t time in timer units uint8_t restart_flag zero tmr start Starts a hardware timer means interrupt none TERTIO ETSI TIGE tmr1 c once void code pfn void code to execute tmr stop Stops a hardware timer None none ioXmrO h tmr1 h tmrO isr Timer interrupt for TMRO none none io tmr0 c tmrl isr Timer interrupt for TMR1 none none iotmr1 c Move data from AMR s copy of update register power registers into power Void void Meter meter c registers uwr busy wait Wait for programming complete None none io uwrdio c uwreep c2 indication uwr_init Inia are wire similanta none none io uwrdio c uwreep c2 E uWire interface il P Uint8x t pbOut uwr read Get a counted
2. INC R6 ADD A R6 ORL A R6 INC R7 ADD A R7 ORL A R7 JBC bit rel JNB bit rel JNC rel ACALL addr11 ACALL addr11 ACALL addr1 1 LCALL addr16 RETI ANL direct A RRCA RLCA ANL direct Zdata DECA ADDC A data ANL A data DEC direct ADDC A direct ANL A direct DEC QRO ADDC A RO ANL A RO DEC QR1 ADDC A QR1 ANL A QR1 DEC RO ADDC A RO ANL A RO DEC R1 ADDC A R1 ANL A R1 DEC R2 ADDC A R2 ANL A R2 DEC R3 ADDC A R3 ANL A R3 DEC R4 ADDC A R4 ANL ARA DEC R5 ADDC A R5 ANL A R5 DEC R6 ADDC A R6 ANL A R6 DEC R7 ADDC A R7 ANL A R7 Table 6 8 Instruction Set in Hexadecimal Order TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Mnemonic Mnemonic d jTERIDIAN Mnemonic JZ rel SJMP rel ORL C bit AJMP addr11 AJMP addr11 AJMP addr11 XRL direct A ANL C bit MOV C bit XRL direct Zdata MOVC A A PC INC DPTR XRL A data DIV AB MUL AB XRL A direct MOV direct direct Reserved XRL A RO MOV direct RO MOV QRO direct XRL A QR1 MOV direct R1 MOV R1 direct XRL A RO MOV direct RO MOV RO direct XRL A R1 MOV direct R1 MOV R1 direct XRL A R2 MOV direct R2 MOV R2 direct XRL A R3 MOV direct R3 M
3. 5 14 1 9 Coping with Various Current Sensors The MPU code has Imax and Imax2 The calculations automatically convert data from phase B into the same units as phase A if the dual Imax compilation option is set See meter meter c RescalePhaseB 5 14 1 10 User Interface The main user interface is an RS 232 command line interface with a help system This consumes a surprisingly large amount of code because it performs line editing There is code that controls an LCD The meter chip has bits in its I O area that turn each LCD segment on and off The segments form segments of numerals etc Software arranges to turn the right segments on and off in order to show numbers and annunciators The code for this looks up a bit mask for each character to decide which pieces of numeral to turn on and off In this demo software pressing the pushbutton changes the display items or wakes the meter from its low power mode Most meters have at least one operating switch The classic is a magnetic reed switch controlled by a magnet outside the meter enclosure Real meters but not this demo software use it to step through a menu system 5 14 1 11 Operating without User Interface The EEPROM can be initialized in a programmer with the calibration data This saves the code and data needed by the meter 5 14 1 12 Communication with a Computer This demo code implements both a CLI and the CP Code is available for FLAG The classic scheme not pro
4. 6 7 Copyright C 2003 TDK SemiConductor Corporation All Rights Reserved 8 9 gt HEHEHE HEHEHE CC 3 3 3 3 3 3 JE 3 3 3 3 3 JE 3 3 HEHEHE 3 3 3 HHH HHH 3 3 JE JE 3 JE 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 0 gt LL REE EEEE EEE 3C 3C 3 9 3 E 3 9 9 E 9 9 9 9 9 E 9 9 9 9 9 3 9 9 9 9 9 9 9 9 9 9 3 9 9 3 9 3 9 9 9 3 TL ow 12 ve DESCRIPTION 71M651x POWER METER API Exerciser Routines v4 14 vi AUTHOR MTF 16 HISTORY 2003 OCTOBER 30 First Version 1 8 Kg XXX OO CC CC CC HLH KKH KKH 9 3 E C 9 3 9 9 3 9 3 9 3 9 3 9 9 3 3 9 3 3 9 3 3 19 v 20 File APIE C sl z eee Click Project Create New Project The following screen will appear Project Creation Wizard Welcome to the Create Project Wizard This wizard helps you create project that will be used by the Chameleon debugger to save and manage all your programs data and settings To continue click Next Follow the instructions of the Cr
5. In this function the ADC sample count is shifted right 9 bits to account for the left shift operation automatically done by the ADC The measured value is not very accurate since the chip to chip variations in offset and LSB resolution are not calibrated these may have 5 variations The routine battest start may be invoked from the command line interface battest stat sets the variable bat sample cnt to 2 This signals to the XFER BUSY interrupt in ce c to take two measurement to account for the variations caused by the amplifier chopping The RTC date is recorded in the structure last day That way an automated battery test is run only once per day when the date changes right after midnight The routine battest run void is called from the part of meter run that only operates when the CE is active This is because the battery test can only run when the CE is active The routine battest run void compares the current date with last day If it detects a difference indicating that the date has just changed it calls battest start 5 4 3 6 Power Factor Measurement The power factor option provides both instantaneous and accumulated over fractions of an hour display of power factor by phase All power factor calculations are performed using floating point variables The power factor PF cosq calculation is based on the equations P S cos S PF gt PF P S with P real energy S apparent energy PF
6. The demo code is designed to run any 19 bit address Atmel EEPROM i e it will also run AT24C1024 AT24C512 AT24C128 However different sizes of Atmel EEPROMs have different page sizes The page size is set in the options h file If the EEPROM interrupt service routine INT5 returns the value 0x80 illegal command the loop should be exited all registers should be refreshed and the operation should be restarted Notes e The extended code set has non interrupting code to run both 19 and 11 bit Atmel EEPROMs e g AT24C02s as well as a variety of others The non interrupting EEPROM driver code is easier to modify because it just reads and writes the bytes that go to and from the EEPROM e For larger EEPROMs 1010xxR can be the first command R71 for read R 0 for write operation e The START command should be sent to the EEPROM before any read or write operation e The algorithms cover single and multi byte operations limited to a single page e Special precautions apply when a page boundary is crossed for write operations When the end of a page is reached the write to the next page has to be preceded by a START command e EEPROMs typically respond to START commands with 5ms delay 5 4 3 5 Battery Test The battery test is based on sampling the voltage applied to the VBAT pin during an alternative multiplexer cycle The function used for calculating the battery voltage from the count obtained from the ADC is int32 t mVBat int32 t v
7. register Power factor 0 3KB Y Y All phases are displayed with sign Volatile register Pulse count 1 2KB Y Y Both the Wh and VARh pulses are counted Mains edge count 0 3KB Y Y Counts total zero crossings and zero crossings in the last accumulation interval of element A Table 5 6 Power Registers and Pulse Output Features v1 1v1 1 TERIDIAN Proprietary 49 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation gp TERI DIAN SEMICONDUCTOR CORP 71M653X Software User s Guide Feature Creep mode 0 37KB Y Y Adjustable at calibration If V Vthreshold and Ithreshold for all elements then creep Zero accumulator N A Y Y The pulse accumulation register in the CE is cleared of CE to prevent spurious pulses from low current noise Current threshold N A Y Y Adjustable at calibration Set If max abs IA2 abs IB2 lt Current threshold then creep mode Current is calculated from RMS if possible or if below 0 1A from VA V where VA is calculated as sqrt Wh 2 VARh 2 For all elements Voltage threshold 0 12KB Y Y Adjustable at calibration If max abs VA2 abs VB2 lt Volt threshold inhibit frequency measurement frequency of zero Inhibit use of zero crossing counts main edge count is zero ilnhibit voltage phase measurement if any This feature is needed only if frequency or mains edge count is present Table 5 7 Creep Functions
8. 5 18 11 Battery Modes The battery modes strongly resemble the 6521 In particular the RAM is unpowered in sleep and LCD only mode In the 653X the LCD registers are also unpowered in sleep mode to save power The 653x has 8 bytes of nonvolatile RAM GPO GP7 At this time in A01 and A02 versions of the IC GPO 7 are cleared at reset but remain unchanged in battery modes Later versions may preserve these register in reset In the 653x fixed rate clock compensation is in hardware and continues to run in sleep mode Code is not needed to compensate the clock when leaving sleep mode The 653x sleep mode consumes less than 1 microamp far better than the 6521 5 18 12 Watchdog Reset In the 653x the watchdog reset is equivalent to the reset pin So after a watchdog reset the 653x does not require reinitialization to a reset state and the 6521 did 5 18 13 Temperature Compensation When operating with internal temperature compensation the 71M653X uses MPU based temperature compensation similar to the 6521 for the metering The real time clock s temperature compensation is also MPU based but has a different algorithm because it must set the hardware rate register TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation eA TER DIAN SEMICONDUCTOR CORR 71M653X Software User s Guide v1 1v1 1 TERIDIAN Proprietary 104 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 6 80515
9. 71M6531 71M6533 71M6534 Energy Meter IC Family SOFTWARE USER S GUIDE 5 8 2008 TERIDIAN Semiconductor Corporation 6440 Oak Canyon Rd Suite 100 Irvine CA 92618 5201 Ph 714 508 8800 Fax 714 508 8878 Meter support teridian com http www teridian com Usa 71M653X Software User s Guide TERIDIAN Semiconductor Corporation makes no warranty for the use of its products other than expressly contained in the Company s warranty detailed in the TERIDIAN Semiconductor Corporation standard Terms and Conditions The company assumes no responsibility for any errors which may appear in this document reserves the right to change devices or specifications detailed herein at any time without notice and does not make any commitment to update the information contained herein v1 1 TERIDIAN Proprietary 2 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation 71M653X Software User s Guide AUS SEMICONDUCTOR CORP 71M653X Energy Meter IC FAMILY SOFTWARE USER S GUIDE TERIDIAN Proprietary 3 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation I MERLI T E SEMICONDUCTOR CORF 71M653X Software User s Guide Table of Contents 1 DINERO DUC THON eege 11 13 Using this Document sesseregseeeegeeseEeseEEeCegkESEEEESEEEEEEESEEEEEEEEESEEEESEEEEENEEEEEEERSEEEEEEEEEEESEEeEEEEE 11 1 2 Related Documentation cc castadereudieescaudiieeecuscadereudieeccustecareustieescustacereuss
10. MATH H meter math library PRIORITY H interrupt masks and priority definitions SERIAL H serial interface structures enumerates and definitions SFRS H low level API for SFRs and memory STDINT H standard integer definitions STM H software timer definitions WD H watchdog bit definitions CE IMAGE FILES The CE code uses pre designed pre validated algorithms and calculations which are accurate to the noise floor of the integrated circuit saving substantial engineering and development time The source code for the CE is proprietary Only the code and data images binary images are available to the user The code image must be merged with the MPU code residing in flash memory Images of the CE data and program code are provided with the Demo Kits They are to be linked into the object code CE images are provided by the following files 1 CE31 CE C This file provides the image of the 71M6531 CE program in C notation CEA DAT C This file provides the image of the 71M6531 CE default data in C notation CE34 CE C This file provides the image of the 71M6534 CE program in C notation CE34 DAT C This file provides the image of the 71M6534 CE default data in C notation TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation 5 13 COMMON MPU ADDRESSES In the Demo Code certain MPU XRAM parameters have been given fixed addresses in order to permit easy external access These v
11. and these would be used up in a few years So the revenue registers are kept in a special block of memory the C structure Totals Acc This data is saved only when there is a power failure TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA SEMICONDUCTOR CORP 5 14 1 19 Managing Power Failures There is no way to delay power failure to a convenient time so the meter must always have a valid value for its revenue registers There are two copies of the register data Totals Acc and Totals AccB When Totals Acc is valid and its checksum is calculated it is copied to Totals AccB Therefore in normal operation one of these is always valid Both are saved by the power failure detection logic When the meter starts up it checks both and uses the first one with a valid checksum Version 4 6 and later implement a true power failure interrupt from the CE External interrupt INTO on the MPU is set up on DIO 89 the same pin as Y PULSE one of the spare pulse outputs from the CE see meter ce_30 c ce init The CE s configuration variable CE STATE has four additional bits 16 19 which enable and select the elements sensed for power failure The CE detects power failures as before but now checks selected status bits in order to cause an MPU interrupt When all of the elements fail the CE pulses Y PULSE causing an MPU interrupt which saves the power registers to the EEPROM see ce sag isr in Meter ce_30 c
12. Before version 4 6 the CE detected power failures by detecting when each mains voltage stayed below a threshold for a configurable number of samples usually 80 decimal about two cycles The MPU discovered this state by reading the CE s status register The polling test if the CE s status registers was done in the CE busy interrupt meter ce c ce_busy_isr that occurs once per sample time about every 396 microseconds To save the MPU s time the sample is compared only once per sample 5 14 1 20 Pulse Counting In version 4 6 and later INTO is used for the sag interrupt therefore it cannot be used to count pulses Therefore the pulse counting assigns timer 1 formerly unused to count the watt hour pulse The gate of timer 1 is set to the correct DIO and timer 1 is set to be a 16 bit counter see pcnt init in Meter pcnt_30 c The counter is read once per second in the real time clock s timer interrupt The counter is read as two 8 bit values The lower value could turn over while being read So the logic re reads the lower value if the upper value changes The exact logic is read upper read lower read upper second time If the second time of the upper counter is different from the first read the lower again After that each second the number of pulses in that second is the current value of the timer s register less the previous value This math automatically handles turn over of the counter as long as less than 32768 pulses occurr
13. In most configurations the CE uses 1K of this RAM leaving 3K for use by the MPU See Table 3 1 for a summary Address Memory SE wees Prosa e Wait States Memory Size hex Technology MOY HER wenns ud at5MHz bytes Common code area for the 0000 7FFF Flash Memory Non volatile program and non volatile 0 32K data Bank window code area for the program and non volatile data The 6531 32 8000 FFFF Flash Memory Non volatile and 33 have 3 banks yielding 128K total The 6534 has 7 banks yielding 256K total CE data actual last byte may be somewhat less than 1K depending on the CE code 0000 03FF Static RAM Volatile 0400 1000 Static RAM Volatile MPU data Miscellaneous I O RAM configuration RAM 2000 20FF Static RAM Volatile Table 3 1 Memory Map TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d jTERIDIAN 3 3 PROGRAMMING THE 71M653X CHIPS There are two ways to download a hex file to the 71M653X Flash Memory e Using a Signum Systems ADM 51 ICE e Using the TERIDIAN Semiconductor Flash Download FDBM TFP 2 Stand Alone Module Note For both programming and debugging code it is important that the hardware watchdog timer is disabled See the Demo Board User s Manual for details Before downloading code to a 71M653x e Stop the MPU e Disable the CE by writing a 0 to XDATA at address 0x2000 e Erase the flash memory 3
14. Often function pointers are used for callback routines In these cases the linker often does not detect the true caller and so cannot detect the cross bank function call Then it places a banked address into the code that sets the function pointer If this is executed from another bank the code jumps to code in the current wrong bank Using overlay commands informs the linker of the actual caller so it can detect cross bank calls To increase reliability the demo code that sets a function pointer also checks to make sure that the pointer is in common memory rather than a bank The code looks like this if uint16_t fn_ptr gt Ox7FFF only accept functions in common main_software_error report a software error at a central breakpoint return NULL indicate a failure to the caller 4 9 11 Putting Constants in Banks Space in the common code area can be precious It often helps to put large tables in a different code bank The TERIDIAN Demo Code places the help text CE code and the CE s data initialization table into banked flash In order for this to work every reference to the data must be from the same bank or from common In the demo code the largest set of constant tables is the help text The help text CLI Help c is in the same bank as the printing routines which copy the text into RAM for use by the serial interrupts see CLINo c Since the help text is in the same bank as the accessing routines no ot
15. PulseVSource Wh Pulse source VARh pulse source selection 0 wsum 1 w0sum 2 w1sum 3 w2sumt 4 varsum 5 var0sum 6 var1sum 7 var2sumt 8 i0sqsum 9 i1sqsum 10 i2sqsumt 11 insqsum 12 v0sqsum 13 v1sqsumt 142v2sqsumt 15 vasum 16 va0sum 17 vaisum 18 va2sumt 19 wsum_i 20 w0sum_i 21 w1sum_i 22 w2sum if 23 varsum i 24 var0sum_i 25 var1sum_i 26 var2sum it 27 wsum e 28 wOsum e 29 w1sum e 30 w2sum et 31 varsum e 32 var0sum_e 33 varisum_e 34 var2sum et 0 wsum 4 varsum In demo code these are the values from the element with the maximum current A different equation can be chosen as a compilation option and these become sums unsigned TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 6000 Scaling Maximum Vmax Volts ior PCB 0 1V 600 0V from the PCB s 9 unsigned 16 design Scaling Maximum 2080 ImaxA Volts for PCB element 0 1A 208 0A from the PCB s A unsigned 16 A design 0 temp nom 14 must e e T be set to a real value ppmc1 ADC linear adjust with parts per million per degree from 7B before this OG signed 16 temperature centigrade can work Then it should become 150 0 ppmc2 ADC quadratic adjust parts per million per degree Should become yc signed 16 with temperature centigrade squared 392 after setting temp_nom Pulse 3 S f ft ulse ource for software sou
16. RO OxD6 XCHD A RO SCH A R1 OxD7 XCHD A R1 XCH A RO OxD8 DJNZ RO rel XCH A R1 OxD9 DJNZ R1 rel XCH A R2 OxDA DJNZ R2 rel XCH A R3 OxDB DJNZ R3 rel XCH A R4 OxDC DJNZ R4 rel SCH A R5 OxDD DJNZ R5 rel XCH A R6 OxDE DJNZ R6 rel SCH A R7 OxDF DJNZ RT el MOVX A DPTR OxFO MOVX DPTR A AJMP addr11 OxF1 ACALL addr1 1 MOVX A RO OxF2 MOVX Q RO A MOVX A R1 OxF3 MOVX R1 A CLRA OxF4 CPLA MOV A direct OxF5 MOV direct A MOV A RO OxF6 MOV QRO A MOV A R1 OxF7 MOV R1 A MOV A RO OxF8 MOV RO A MOV A R1 OxF9 MOV R1 A MOV A R2 OxFA MOV R2 A MOV A R3 OxFB MOV R3 A MOV A R4 OxFC MOV R4 A MOV A R5 OxFD MOV R5 A MOV A R6 OxFE MOV R6 A MOV A R7 OxFF MOV R7 A Table 6 10 Instruction Set in Hexadecimal Order TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation qi TERI DIAN 71M653X Software User s Guide SEMICONDUCTOR CORP 6 1 3 Instructions that Affect Flags he Affected Flag CLRC CPL C ANL C bit ANL C bit ORL C bit ORL C bit MOV C bit CJNE XI X XX X X gt X X X oo x x Xx Table 6 11 Instructions Affecting Flags Note Operations affecting the PSW
17. SEMICONDUCTOR CORP 71M653X Software User s Guide 3 5 2 CLI Commands The Demo Board User s Manual DBUM for the 71M653x contains a complete list of the available commands 3 5 3 Command Macro Files Commands or series of commands may be stored in text ASCII files and sent to the 71M653X using the Transfer Send Text File command of Hyperterminal or any other terminal program v1 1v1 1 TERIDIAN Proprietary 20 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation ATER DIAN 71M653X Software User s Guide SEMICONDUCTOR CORP 4 TOOLINSTALLATION GUIDE This section provides detailed installation instructions for the Signum ADM 51 in circuit emulator and for the Keil compiler 4 1 INSTALLING THE PROGRAMS FOR THE ADM51 EMULATOR The AMD51 ICE interfaces with the PC is via the USB serial interface The installation process consists of the following steps 1 Installing the Chameleon Debugger used with the Signum ICE 2 Installing the ADM51 USB driver 3 Installing updates 4 Creating a project 4 2 INSTALLING THE WEMU PROGRAM CHAMELEON DEBUGGER Insert the CD from Signum Systems and connect the ICE ADM51 to the PC with the provided USB cable The following dialog box will appear this dialog box also shows the release date of the program bd Master Setup IceServer remote access to emulators Drivers Utilities Evaluation Board Program Demonstration Program Frequently Asked
18. The MPU scales these values to the PCB s voltage and current sensors see VMAX and IMAX The CE s Wh and VARh quantities are signed permitting the MPU to perform net metering by assigning negative values to export and positive values to import see meter c Wh c VAh c and VARh c The calculations needed for a meter require more precision than standard C floating point provides The Demo Code has a meter math package to add CE Wh or VARh data to a meter register without overflow see Util math c There are also routines to add a meter register to another meter register add8 and a routine to convert a meter register to a floating point value s2f useful to calculate ratios TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN The MPU also places a scaled value into the CE RAM for each pulse output meter meter c meter_run meter pulse_src c selectpulses This adjusts the pulse output frequency in such a way as to reflect that accumulation s contribution to the total pulse interval Pulse intervals are cumulative and cumulatively accurate even though the frequency is updated only periodically Placing the pulse value selection logic into the MPU software means that any quantity from any phase or combination of phases can control either pulse output see PulseSrcFunc for a list of transfer functions The MPU also performs temperature adjustments of the real time clock rtc_30 c
19. and 7 for 6534 ROM Size The memory size of ROM in kbyte 128 256 Input Compiled files name without extension Output Output file name Must have hex extension For example bank merge 3 128 banktest31 new code hex This merges the three compiled hex files banktest31 H01 banktest31 H02 banktest31 H03 and produces new code hex in a 128kbyte intel 386 hex file TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 3 DESIGN REFERENCE As depicted in Figure 1 of section 2 the 71M653X provides a great deal of design flexibility for the application de veloper Programming details are described below 3 1 PROGRAM MEMORY The embedded 80515 MPU within the 71M653X has separate program 128K or 256K bytes and data memory 4K bytes The code for the Compute Engine program resides in the MPU program memory flash The Flash program memory is addressed as a 64KB block The upper 32K is a window on a code banked It can be switched to other code banks by writing a banke numbe rto the banked register FL BANK The flash memory is further segmented in 512 byte pages which can be individually erased Selection of these individual blocks is accomplished using the function calls related to flash memory which are described in more detail below 3 2 DATA MEMORY The 71M653X has 4K bytes of Data Memory used by the embedded 80C515 MPU and shared with the proprietary computer engine CE
20. and RAM The destination table and CE was moved to start of RAM location zero The CE s output data was moved to location 0x0200 so that PDATA can still be used to access it quickly 5 14 1 15 Timing Control The chip has two high speed timers It also has an electronic clock Further there is a timer to wake the chip from its low power modes The demo code has facilities to demonstrate all of these 5 14 1 16 6531 Calculation of max VA IA VA IB Option Equation 0 The global flow of Wh calculation is an important optimization and will be selected by compile flag Vrms A sqrt vOsqsum from the CE Irms A sqrt i0sqsum from the CE Irms B sqrt iTsqsum from the CE Volts and Current are now available for all elements Figure Wh VARh and VAh for this accumulation interval If Vrms A Vthreshold i e there s no voltage probably tampering Figure watts with a default voltage but don t lie about sensed voltage Vrms A 0 if abs Irms A gt IThreshold vaOsum Irms A defaultV wOsum va0sum else set them to zero varhO 0 Repeat for element B else TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation A Get Wh wxsum and VARh varxsum from CE wOsum wisum element Wh for one accumulation interval varOsum var1sum element VARhs are from CE va0sum sqrt wOsum var0sum vadsum sqrt wOsum var0sum endif va0sum vaisum wOsum w1sum varOsum var1sum are now available Fi
21. and or constant data Intel HEX files are often used to transfer the program and data that would be stored in a ROM or EPROM Most EPROM programmers or emulators can use Intel HEX files Record Format An Intel HEX file is composed of any number of HEX records Each record is made up of five fields that are arranged in the following format llaaaatt dd cc Each group of letters corresponds to a different field and each letter represents a single hexadecimal digit Each field is composed of at least two hexadecimal digits which make up a byte as described below is the colon that starts every Intel HEX record Jlis the record length field that represents the number of data bytes dd in the record aaaais the address field that represents the starting address for subsequent data in the record ttis the field that represents the HEX record type which may be one of the following 00 data record 01 end of file record 02 extended segment address record 04 extended linear address record ddis a data field that represents one byte of data A record may have multiple data bytes The number of data bytes in the record must match the number specified by the II field ccis the checksum field that represents the checksum of the record The checksum is calculated by summing the values of all hexadecimal digit pairs in the record modulo 256 and taking the two s complement Data Records The Intel HEX file is made up of any number
22. 4 DEBUGGING OF THE 71M653X CHIPS When debugging with the ADM51 in circuit emulator the CE continues to run and this disables flash memory access because the code of the CE is located in flash memory When setting breakpoints only two breakpoints can be used because the first two breakpoints are hardware breakpoints while the rest attempt to write to flash memory 3 5 TEST TOOLS A command line interface operated via the serial interface of the 71M653X MPU provides a test tool that can be used to exercise the functions provided by the low level libraries The command line interface requires the following environment 1 Demo Code 653X demo hex must be resident in flash memory 2 The Demo Board is connected via a Debug Board to a PC running Hyperterminal or another type of terminal program 3 The communication parameters are set at 300 bps 7N2 XON XOFF flow control as described in section 3 5 1 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation q TER DIAN 71M653X Software User s Guide SEMICONDUCTOR CORP 3 5 1 Running the 653X Demo hex Program This object file is the 71M653X embedded application developed by TERIDIAN to exercise all low level function calls using a serial interface Demo Boards ship pre installed with this program To run this program e Connect a serial cable between the serial port of the Debug Board RS232 and a COM port of a Windows PC e Open a Windows Hype
23. 6533 6534 with neutral current this compilation option is normally on to enable tests of neutral current Uses same space as Threshold B Table 5 12 MPU Memory Locations TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation 71M653X Software User s Guide BA Discussion of the bits in Status CREEP 0 Indicates that all elements are in creep mode The CE s pulse variables will be jammed with a constant value on every accumulation interval to prevent spurious pulses Note that creep mode therefore halts pulsing even when the CE s pulse mode is internal MINVCt 1 Element C has a voltage below VThrshld This forces that element into creep mode PB PRESS 2 A push button press was recorded at the most recent reset or wake from a battery mode Recorded because the push button flag in the hardware must be cleared in order to reenter a power saving mode May be unused in some softwares SPURIOUS 3 An unexpected interrupt was detected MINVB 4 Element B has a voltage below VThrshld This forces that element into creep mode MAXVA 5 Element A has a voltage above VThrshldP MAXVB 6 Element B has a voltage above VThrshlidP MAXVCEf y Element C has a voltage above VThrshldP MINVA 8 Element A has a voltage below VThrshld This forces that element into creep mode It also forces the frequency and main edge count to zero
24. 7OHz or voltage is below the register threshold Wh export register 0 25KB Y Y Wh exported display reads 999 999 Wh export pulse 0 25KB Y Y Wh exported display reads 999 999 output VARh signed 0 1KB Y Y Used for autocalibration and power factor register calculations VARh import 0 4KB Y Y register VARh import 0 25KB Y Y pulse output v1 1v1 1 TERIDIAN Proprietary 48 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERI DIAN 71M653X Software User s Guide SEMICONDUCTOR CORP VARh export 0 4KB Y Y register VARh export 0 25KB Y Y pulse output Operating hours 0 36KB Y Y 99999 9 Nonvolatile count of hundredths of hours register of powered operation since first cold start RTC time register 0 18KB Y Y RTC date register 0 21KB Pulse source 0 4KB Y Y This is the ability to route most calculated energy selection values to a pulse output Dual IMAX 0 2KB Y N IMAX2 adjusts current Wh and VARh from channel B registers to same units as A Creep thresholds are required but need not be adjusted when IMAX2 changes Neutral Current 0 3KB N Y This includes not just a measurement but also a limit and a count of overcurrent events RMS current 0 2KB Y Y Implemented for all phases 000 000 Includes register element currents arithmetic sum of currents and if supported neutral current RMS voltage 0 2KB Y Y Implemented for all elements 000 000
25. Bank 0 is the common area Banks 1 2 and 3 are the banked code areas selected by FL BANK The 71M6534 has eight 32K banks 256K total Bank 0 is the common area Banks 1 through 7 are the banked code areas selected by FL BANK A reset sets FL BANK to 1 so any 71M653x IC can run 64K of non bank switching code The 71M653x ICs have two write protect registers to protect ranges at the beginning and end of flash The beginning is protected by BOOT SIZE XDATA 0x20A7 when WRPROT BT is set in FLSHCTL SFR 0xB2 The end can be protected by placing the CE program at the start of the area to protect and setting WRPROT CE in FLSHCTL SFR 0xB2 Address Range for Rem Lower Bank Upper Bank PH Eeu 0x8000 0xFFFF 0x000 0x7FFF i i 000 0x0000 0x7 FFF 0x0000 0x7 FFF 001 0x0000 0x7FFF 0x8000 0xF FFF Address Range for 010 0x0000 0x7FFF 0x10000 0x17FFF 011 0x0000 0x7FFF 0x18000 0x1FFFF 100 0x0000 0x7FFF 0x20000 0x27000 101 0x0000 0x7FFF 0x28000 0x2FFFF 110 0x0000 0x7FFF 0x30000 0x37FFF 111 0x0000 0x7FFF 0x38000 0x3FFFF XX X Xx CK x Table 4 1 Code Bank Memory Addresses and Availability The 71M653x ICs flash memory are very similar to the ROM arrangement in Keil s example Banking With Common Area of chapter 9 linker of Keil s Macro assembler and Utilities manual 4 9 2 Software Overview Teridian s demonstration code uses the Keil compiler s standard bank switch
26. Finish again Note USB 1 1 is sufficient for operation of the ADM51 If higher performance is desired and no USB 2 0 port is available on the host PC a USB 2 0 card can be installed as an option 4 4 INSTALLING UPDATES TO THE EMULATOR PROGRAM AND HARDWARE If the Wemu51 program is revision 3 11 4 or later no special precautions have to be taken Otherwise the program should be updated using the Signum Systems web site www signum com When running the Wemu51 program revision 3 11 4 or later the firmware in the ADM51 will be checked automatically ADM51 emulators with outdated firmware will not function properly The Wemu51 will offer an automatic update for the ADM51 if necessary For a successful upgrade it is vital to follow the instructions on screen precisely v1 1v1 1 TERIDIAN Proprietary 23 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation eA TER DIAN SEMICONDUCTOR CORF 71M653X Software User s Guide 4 5 CREATING A PROJECT Double click on the WEMUS51 icon to start the Chameleon debugger Signum Systems Wemus51 ADM51 Emulator 6513 File Edit view Debug Project Options Window Help ppp p see Se Source 1 APIE C Follow code focus d Ke EE 2 This code and information is provided as is without warranty of any 3 kind either expressed or implied including but not limited to the 4 implied warranties of merchantability and or fitness for a particular 5 purpose
27. Licensed Software Limitation of Damages Liability IN NO EVENT WILL TSC NOR ITS VENDORS OR AGENTS BE LIABLE TO LICENSEE FOR INDIRECT INCIDENTAL SPECIAL OR CONSEQUENTIAL DAMAGES IN CONNECTION WITH OR ARISING OUT OF THIS LICENSE AGREEMENT OR USE OF THE LICENSED SOFTWARE Export Licensee shall adhere to the U S Export Administration Laws and Regulations EAR and shall not export or re export any technical data or products received from TSC or the direct product of such technical data to any proscribed country listed in the EAR unless properly authorized by the U S Government Termination TSC shall have the right to terminate the license granted herein in the event Licensee fails to cure any material breach within thirty 30 days from receipt of notice from TSC Upon termination Licensee shall return or at TSC s option certify destruction of all copies of the Licensed Software in its possession Law This Agreement shall be construed in accordance with the laws of the State of California The Courts located in Orange County CA shall have exclusive jurisdiction over any legal action between TSC and Licensee arising out of this License Agreement Integration This License Agreement constitutes the entire agreement of the parties as to the subject matter hereof No modification of the terms hereof shall be binding unless approved in writing by TSC TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation eA
28. MPU REFERENCE An 80515 core is implemented on the TERIDIAN 71M653X chips This section is intended for software engineers who plan to use the 80515 The MPU core is described in detail in the 6531 6533 and 6534 data sheets except for the instruction set which is presented in this chapter 6 1 THE 80515 INSTRUCTION SET All 80515 instructions are binary code compatible and perform the same functions as they do with the industry standard 8051 The following tables give a summary of the instruction set cycles of the 80515 MPU core Table 6 7 and Table 6 8 contain notes for mnemonics used in instruction set tables Table 6 9 through Table 6 17 show the instruction hexadecimal codes the number of bytes and the number of machine cycles required for each instruction to execute Rn Working register RO R7 direct 256 internal RAM locations any Special Function Registers Ri Indirect internal or external RAM location addressed by register RO or R1 data 8 bit constant included in instruction data 16 16 bit constant included as bytes 2 and 3 of instruction bit 256 software flags any bit addressable I O pin control or status bit A Accumulator Table 6 1 Notes on Data Addressing Modes Destination address for LCALL and LUMP may be anywhere within the 64 kB of program memory address space Destination address for ACALL and AJMP will be within the same 2 kB page of program memory as the first byte of th
29. PROJECT MANAGEMENT TOOLS With large software projects involving a multitude of source object list and other files in various revisions it is very helpful to use a version control tool To manage file versions under Windows Tortoise CVS a free version control utility might be useful This utility can be found at http www tortoisecvs org 4 11 ALTERNATIVE COMPILERS The Demo Code was written for the Keil compiler However alternative compilers may be used if the code is modified to ensure compatibility with the alternative compiler One example of an alternative compiler is SDCC a free compiler available from www Sourceforge net Note The Keil extensions for the 8051 are not compatible with the 8051 extensions used by the SDCC The batch file BUILD653X BAT is provided with the Demo Kit to support building object files using alternative compilers This batch file uses the Keil compiler calls with the applicable compiler options and can therefore serve as examples on how to invoke alternative compilers The linker control file LINK653x TXT called by the batch files can show how to properly invoke linkers To compile with DOS style tools arrange for a DOS batch file to invoke the tools and set the properties of the batch file to leave the window open so that errors can be seen Then to compile double click on this batch file in Windows explorer 4 12 ALTERNATIVE EDITORS Many modern text editors have a feature called tag jumpin
30. Questions Intel s Data Sheets Intel s Application Builder Version Information Signum Installation Information Systems CD Release 2 14 2005 Win XP 2000 NT 4 0 ME 9x Web Site www signum com Technical support www signum com support htm Exit rg To install tun a program please doubleclick its label Click on Chameleon Debugger and then select ADM51 Emulator Follow the instructions given by the installation program TERIDIAN Proprietary 21 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation of T ERIDAN SEMICONDUCTOR CORF 71M653X Software User s Guide 4 3 INSTALLING THE ADM51 USB DRIVER The Wemu51 program communicates with the emulator ADM51 via the USB interface of the PC The USB driver for the ADM51 has to be installed prior to using the emulator After plugging in the USB cable into the PC and the ADM51 ICE the status light of the ADM51 emulator should come on A dialog box will appear asking you to install the ADM51 driver Add New Hardware Wizard Click Next Another screen not shown will appear asking to locate the driver Select Specific Path and browse to C Program Files Signum Systems Wemu51 Drivers USB Click Next v1 1v1 1 TERIDIAN Proprietary 22 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation SEU DIAN 71M653X Software User s Guide SEMICONDUCTOR CORR Add New Hardware Wizard Click Finish Setup Complete Click
31. RESET input e PB input powered down the 71M653x Demo Code will cause the chip to enter Brownout mode and stay in Brownout mode It is possible that the VBAT pins of the chip draws up to 1mA in this state since the I O pins are not initialized when Brownout mode is entered from a state where the chip is powered down if Brownout mode is entered from Mission mode the I O pins are properly initialized and the chip will enter Sleep mode automatically causing much lower supply current into the VBAT ue Precautions when adding a battery When a battery or other DC supply is added to a Demo Board that is In general to work in an operational meter not a demo meter the firmware has to be written to ue handle the case of connecting a battery to a powered down board since in a factory setting e batteries will most likely be added to meter boards that are powered down The firmware must immediately enter sleep mode in this situation TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 5 6 DATA FLOW The ADC collects data from the electrical inputs on a cycle that repeats at 2520Hz On each ADC cycle the compute engine CE code digitally filters and adjusts the data using gain parameters CAL_Ix CAL_Vx and phase adjustment parameters PHADJ x Normally a calibration operation during manufacturing defines these adjustments and stores them in flash or EEPROM to be placed into CE memory The Demo Code
32. RTC_Trim RTC_Adjust_Trim The Demo Code can adjust the clock speed to a resolution of 1 part per billion roughly one second per thirty years The adjustments include offset Y_CAL temperature linear Y_CALC and temperature squared Y_CALC2 parameters Once a human readable quantity is available it can be translated into a set of segments meter c lcd c to display on the liquid crystal display or read from a register in memory by means of the command line interface cli c or possibly some other serial protocol such as Flag see flag c or NEMA 5 7 CE MPU INTERFACE The interface between the CE and the MPU is described completely in the 71M653x Data Sheet 5 8 BOOT LOADER It is possible to implement code that functions as a boot loader This feature is useful for field updates and various test scenarios See the TERIDIAN Application Note number 031 for details 5 9 SOURCE FILES The functionality of the Demo Code is implemented in the following files and directories 1 CLI Command Line Interface General Commands access c SFR I O RAM MPU and CE memory access routines access X C extended memory access routines c serial c parser for command line interface cli c command line interface routines cmd ce c sub parser for CE commands cmd misc c sub parser for RTC EEPROM trim and PS commands help c display of help text io c number conversion functions and auxiliary routines for CLI load c upload and download profile c
33. Semiconductor Corporation AA LIMITED USE LICENSE AGREEMENT Acceptance By using the Application Programming Interface and or other software described in this document Licensed Software and provided by TERIDIAN Semiconductor Corporation TSC the recipient of the software Licensee accepts and agrees to be bound by the terms and conditions hereof Acknowledgment The Licensed Software has been developed for use specifically and exclusively in conjunction with TSC s meter products 71M6531 71M6534 and 71M653xB Licensee acknowledges that the Licensed Software was not designed for use with nor has it been checked for performance with any other devices Title Title to the Licensed Software and related documentation remains with TSC and its licensors Nothing contained in this Agreement shall be construed as transferring any right title or interest in the Licensed Software to Licensee except as expressly set forth herein TSC expressly disclaims liability for any patent infringement claims based upon use of the Licensed Software either solely or in conjunction with third party software or hardware Licensee shall not make nor to permit the making of copies of the Licensed Software including its documentation except as authorized by this License Agreement or otherwise authorized in writing by TSC Licensee further agrees not to engage in nor to permit the recompilation disassembly or other reverse engineering of the Lice
34. TER DIAN SEMICONDUCTOR CORR 71M653X Software User s Guide v1 1v1 1 TERIDIAN Proprietary 10 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 1 INTRODUCTION TERIDIAN Semiconductor Corporation s TSC 71M653X single chip Energy Meter Controllers are a family of Systems on Chip that supports all the functionalities required to build energy meters Demo Boards are available for each chip 71M6531 71M6532 71M6533 71M6534 to allow development of embedded applications in conjunction with an In Circuit Emulator Development of a 71M653X application can be started in either 80515 assembly language or preferably in C using the Demo Boards TSC provides along with the 71M653X Demo Boards a development toolkit that includes a demonstration program Demo Code written in ANSI C that controls all features present on the Demo Boards This Demo Code includes functions to manage the low level 80515 core such as memory clock power modes interrupts and high level functions such as the LCD Real Time Clock Serial interfaces and I Os The use of Demo Code portions will help reduce development time dramatically since they allow the developer to focus on developing the application without dealing with the low level layer such as hardware control timing etc This document describes the different software layers and how to use them The Demo Code should allow customers to evaluate various resources of the 653X ICs but shou
35. XFER busy ce xfer busyz isr EXT6 shared Meter ce c 0x6B 2 w RTC RTC rtc_isr EXT6 shared lO rtc_30 c 0x6B 2 w XFER NEAR OVERFLOW xfer rtc isr EXT6 shared MeterNo653x c Ox6B 2 w XFER TimerO tmrO isr lO tmr0 c 0x0B 0 Timer1 tmr1 isr IOWmr1 c 0x1B 3 UART 0 es isr IO serial c 0x23 0 UART 1 es1 isr IO serial c 0x83 0 Table 5 10 Interrupt Service Routines In general a higher priority interrupt can preempt lower priority interrupt code The interrupt priority hardware is controlled by two registers IP and IP1 named IPL and IPH in the demo code The MPU supports four priorities and a fifth is possible with a small amount of software support The best practice is to set priorities once near the start of initialization Setting priorities dynamically while interrupts occur can have undefined results Since some of the interrupts detect power failures that can occur at any time changing interrupt priorities in the middle of the code is not recommended In the 653x demo code interrupt priorities are set higher for urgent tasks Among equally urgent tasks priorities are set higher for faster interrupts The following describes interrupt priorities for the version 4 3 3 of the Demo Code The priority is set once in main init of main Main c It is also cleared to Os in the soft reset routine but this is followed by logic that calls four RTIs to reset the interrupt acknowledge logic for all four
36. a convenient way to verify that the abs and hex file have the same content To use it invoke the menu File gt Load then check the verify box but not the load box 4 9 9 Placing Interrupts in Banked Code The interrupts must start in the common code TSC starts most interrupts from a trampoline routine that saves and restores the bank register The demo code s trampoline routines are in Meter io653x c with the stub interrupts and decoded interrupts An example of a trampoline is this serial interrupt from Meter io653x c used to service UARTO pragma save pragma REGISTERBANK ESO BANK void est trampoline void small reentrant interrupt ESO IV using ESO BANK uint8_t my_fl_bank FL_BANK save the bank register FL_BANK BANK_DEFAULT BANK_DEFAULT is 1 esO_isr FL_BANK my_fl_bank restore the bank register pragma restore This is clumsy and slow Why do this A trampoline lets most interrupt code be in bank switched code space with other code from the same file This may make the code easier to read It also leaves more space in common memory and permits a larger system to exist The penalty is a few tens of microseconds per interrupt Very frequent interrupts should not use trampoline routines In TSC s demo code the CE code Meter ce c has an interrupt that runs every 396 microseconds ce busy isr ce c is placed in the common area and ce_busy s trampoline is disab
37. and C va0sum va2sum wOsum w2sum varOsum var2sum are now available Figure current the best available way If Irms A noise floor of current measurement amp amp Vrms A 0 Irms A va0sum Vrms A Repeat for elements B and C Do the creep calculation If Vrms A lt Vthreshold creep mode set element A s voltage current and watts to zero else if Irms A Ithreshold creep mode set element A s current and watts to zero Repeat for element B and C Set the pulse outputs Sum positive values to normal registers negative values to export registers 5 14 1 18 How Register Data is Stored The registers cannot just be kept as a floating point number When floating point numbers are added the mantissa of the smaller number has to be shifted to the right losing precision so that it can be added to the mantissa of the larger In less than an hour a meter implemented with 32 bit floating point arithmetic begins losing billing revenue because of underflow In the Teridian implementation a variable wh cnt contains the number of CE counts per Wh The registers are stored as a 32 bit count of Wh and a 32 bit remainder in CE counts The math adds the new CE value to the fractional part and then transfers even Whs to the Wh count To do that it divides the fraction by wh cnt to get the new Wh to add to the count of Wh Then it multiples the number of Wh by wh cnt to get the number of CE counts to subtract from the fractional CE cou
38. and calendar calculations Julian and Unjulian Julian converts a date and time to a count of seconds since 00 00 January 1 2000 Unjulian takes a number of seconds and converts it to a date and time The routines are based on standard astronomical julian day calculations The spreadsheet used to develop the algorithm is Doc JulianDays xls The combination of routines is powerful One can easily figure the day of week or day of year find the time between two dates adjust from GMT to civil time and validate dates The routines were validated by having another piece of code implement a simulated clock and calendar and then running the combination on a PC The test verified that all three routines agreed about the time and date for every second of a day and for every day between January 1 2000 and December 31 2100 5 5 MANAGING MISSION AND BATTERY MODES After a reset or power up the processor must first decide what mode it is in and then take the appropriate action It is useful to concentrate all activities related to power modes and reset into one centralized module The Demo Code revision 4 4 does the switching of modes in the main routine based on decisions made in batmodes c It first decides what the next state should be then enters the state The code uses the following inputs and flags to determine which mode to enter e Battery mode enable jumper see the DBUM for a detailed description of this input e PLL OK flag e
39. c onek c asm oscope h priority h sfrs c startup a51 startup boot a51 TERRAN initiali zation configuration interrupt read and write routines for TMRO initialization configuration interrupt read and write routines for TMR1 3 wire interface using direct control of DIO4 and DIO5 It can be adapted to nonstandard clock polarities and edges 4 wire SPI EEPROMs and TSC chips other than the 71M653x see comments in the source file a 3 wire interface using the high speed 3 wire interface hardware of the 71M653x Code for the Varitronix VIM 828 Display Code to describe which segments are on and off for each character Displays modes correctly Tables for the segments used on a 71M6531 demo PCB Tables for the segments used on a 71M6534 demo PCB Main top level tasks 653x specific battery mode logic contains the table of start up default values main with startup sequence and main task switch initialization and main loop Metering Functions auto calibration initialization configuration interrupt read and write routines for the compute engine data exchange between CE data RAM and XRAM error recording and logging routines to calculate and display frequency control of analog front end multiplexer RTM I O pins contains overall meter logic to calculate and display meter data unused legacy code for managing interrupts and priorities code for counting output pulses detects out of range line values calculates and dis
40. calculation This calculation is especially useful to prevent creep using shunts ApplyCreepThreshold meter meter c clears the Wh to zero if either the volts or current are below the minimum thresholds VThrshld and Threshid The calculation is designed for use in an AMR system Basically as long as XFER UPDATE is true the meter calculation is in progress TSC has code for a FLAG interface in the all options code set Wh Accumulate meter Wh c adds up the watt hours Since the CE s output is signed true four quadrant metering is possible The demo code separates code into imports and exports Antitamper absolute value versions are available as well The phase shift behavior DC response and other signal processing traits depend on the CE s code For special signal processing needs contact the factory VARh Accumulate meten VARh c adds up the volt amp reactive hours Since the CE s output is signed true four quadrant metering is possible The demo code separates VARh into imports and exports Antitamper absolute value versions are available as well The 6530 does IEEE pure signed VARh measurements They have the same accuracy as the Wh measurements The phase shift behavior and other signal processing traits depend on the CE s code For special signal processing needs contact the factory SelectPulses meter pulse_src c selects the pulse sources to emit to the pulse outputs Every element s Wh VARh and VAh are availa
41. cccssccccssecceeesseeeeeesseeeeeeesseeceeseseeeeeseseeneeseseeneeseseeneeees 87 un Mgr RD 98 5 17 Porting 71M6511 6513 Code to the 71M653Xx cesses ennt nnne 99 v1 1v1 1 TERIDIAN Proprietary 6 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation ATER DIAN 71M653X Software User s Guide pr SEMICONGUGTOR GORR 5 17 1 Flashy Klee iieiea a a a ttc E A E a TEE EEE 99 5 17 2 Exira RAM soer a A a 99 5 17 3 CE Data Location is at XDATA OxOOO0 enn ene ennnnen ener 99 5 17 4 CE Data Access is Transparent to the ML 99 5 17 5 Read only areas in MPU RAM sse ene nenennennnnen enr en nennen nnne nenne 99 5 17 6 EE rium eieiei EES See 99 5 17 7 CE Causes Flash VWrte Protecton ene ene em nne 99 5 17 8 Watchdog Location m 100 5 17 9 Software Watchdog Now Deprecated AAA 100 5 17 10 Real Time Clock Compensation 2 eicere tetra eter tede ntn aver Pea pa CREES EAEE 100 5 17 11 Battery Modes c 100 5 18 Porting 71M6521 Code to the 71M653x eeeeeeeeesseeseeeeen nnne nnne 101 5 18 1 lee secte ios M DUE mu AE 101 5 18 2 Extra RAM p 101 5 18 3 CE Data Location is at XDATA OxOOO0 eene nennen nennen enne 102 5 18 4 CE Data Access is Transparent to the ML 102 5 18 5 Read only areas in MPU RAM eene nennen nnne enne nene nennen enn 102 5 18 6 CE Code Loan eege see 102 5 18 7 CE
42. few high speed counters in DATA a fast data space This is intentionally underutilized to make room for customer data The code makes very little use of IDATA in order to conserve stack space The CE s output registers are mapped to PDATA This gives the math fast access to the CE output values XDATA is used for most variable data CODE is used for code and a few large tables like the CE s code and initialization data 5 14 1 6 Object Oriented Design First is it worth it An object oriented design can use the same control code to run similar electronics or data This has several advantages The big one for firmware is that the higher levels of the firmware can quickly change to use other related devices with a minimum of introduced defects The trick in a small embedded system is to implement a base class the integration interface in a way that is efficient and not too hard to understand In this design a base class is an include file of macros i e a h file Two schemes will be used When there are several devices or data structures and switching is not needed each device will have its own h file The macros and function prototypes will provide an interface that is the same for all callers For example instead of including ser h and calling sert getc this scheme will have the caller include serO h and then call ser getc By including ser1 h the same calling code can be instantly ported to serial port 1 If dyn
43. for the timer code and the software timer code These call an error function when they get function pointer addresses greater than Ox7FFF 5 14 1 4 Economic Usage of RAM The IC has only 3K of RAM for use by the MPU There are two main tricks to fit the data in e The main loop organization lets Keil s linker use overlays to maximum advantage multiplying the utility of the small amount of RAM e Also the big pieces of stable data are global and shared Most of them are in Totals a large C structure defined in meter meter h Totals contains all MPU calibration and register items The CE interface is in CE a large C structure defined in meter ce653x h The largest unshared items are the serial buffers defined in serialOcli c and serialicli c For most people removing serial1 has no effect at all on the usability of the debug interface and it frees the port and RAM for use by an AMR system 5 14 1 5 Trading Space for Speed The 8051 has seven types of memory space If used correctly they can help code run faster The Keil compiler provides memory type names like data xdata and pdata so that the programmer can place particular data items in particular memory spaces See the manual for more information Some memory areas are faster to access because the code to access the memory is shorter In decreasing order The code keeps a few critical high speed bit flags in BDATA the fastest rarest memory The code keeps a
44. function is called from a caller in a different bank This forces the linker to put the callee function into the page table To use the overlay command in the linker see the discussion of overlay in the Keil linker s documentation Here s an example of the overlay commands from the demo code They map the callback routines that are called from the software timer and hardware timer interrupt O Options for Target 2 element 3 wire delta default Device Target Output Listing C51 A51 BL51 Locate BL51 Misc Debug Utilities Warnings Disable Warning Numbers use linker control file este Bome edt Overlay stm run ser free timer zer free timer timer kwh timer kvarh timer kvah timer kva timer kw timer kvar timer a timer v ce start io timer meter timer fn J Im er stm int Mise BANK3 CO CE31 CE OxDFFE CO CE31 DAT OxEFFE controls Linker TO 6531 banked abs BankArea 0x8000 0sFFFF REGFILE 6531_banked abs 0RC ps RAMSIZE 256 string Cancel Defaults Figure 4 3 Setting Keil s Linker for Bank switched Code However if there should be other problems there is a way to isolate them 1 Remove code from the project until all code fits in common and bank 1 2 Move modules individually each to a bank until the problem occurs 3 Atsome point the problem is likely to show up as an unexpected reset What is happening is that the call to code in bank 1 is probably going to uninit
45. hardware interrupt levels The system priority value is assembled from constants in Main options_gbl h The constants are defined in Util priority2x h The highest priority interrupt group is the PLL OK interrupt external interrupt 4 see Main batmodes c and timer 1 PLL OK is urgent because it indicates power supply failure and the software must start battery modes Timer 1 shares the same priority bits and is currently unused sample code is in loXmr1 c amp h though earlier versions used it to set the real time clock TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Me The high priority interrupt group is used for CE_BUSY external interrupt 3 see Meter ce c pulse counting external interrupts O and 1 Meter pcnt c and Serial 1 lo ser1 c amp h External interrupt 3 and 1 share priority bits as does external interrupt 0 and serial 1 CE_BUSY is urgent because it occasionally reads the CE s status to detect sag The pulse counting interrupts are less urgent but they are small and run very quickly Serial 1 is intended for AMR so making its interrupts high priority should help its data transfer timing to be more reliable The low priority group contains Serial O and Timer 0 These can generally wait a millisecond and if necessary can afford to miss fast interrupts Serial 0 is the command line interface See the directory Cli and Timer 0 is run at a 10 millisecond interval as the timebase for
46. includes a fast self calibration function that can typically reach 0 0596 accuracy See Calibration in meter calphased c called from meter run 0 in meter meter c The calibration save and restore operations cal save and cal restore save and restore all adjustment variables such as the constants for the real time clock not just the ones for electrical measurements On each ADC cycle 2520 times per second the CE performs the following tasks 1 It calculates intermediate results for that set of samples 2 It runs a debounced check for sagging mains with a configurable debounce 3 It has three equally spaced opportunities to pulse each pulse output On each ADC cycle an MPU interrupt ce busy see ce c ce busy isr is generated Normally the interrupt service routine checks the CE s status word for the sag detection bits and begins sag logic processing if a sag of the line voltage is detected In the event of a sag detection announcing a momentary brownout condition or even a blackout the cumulative quantities in memory are written to the EEPROM By the end of each accumulation interval each second on the Demo Code the CE performs the following tasks 1 It calculates deviation from nominal calibration temperature TEMP X It calculates the frequency on a particular phase FREQ X It calculates watt hours Wh for each conductor and the meter WxSUM X It calculates var hours VARh for each phase and the
47. level To call a paged subroutine Keil s linker arranges to call one of the entries of the page table The page table consists of one entry per subroutine Each entry is a small piece of code that loads the address of the banked subroutine into the 8051 register DPTR and then jumps to paging code The paging code sets the bank register FL BANK and then jumps to the banked code s address contained in the DPTR v1 1v1 1 TERIDIAN Proprietary 37 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDIAN SEMICONDUCTOR CORP 71M653X Software User s Guide Keil s linkers minimize the size of the page table A subroutine has an entry in the page table only if 1 The subroutine is in a bank and 2 The subroutine is called from outside its bank Most problems with banking code occur because the linker omits a function from the page table The result is that the call to a function in a different bank goes to code in the current bank causing unexpected code in the current bank to be executed One major cause of this is a callback subroutine called via a function pointer Another is an interrupt defined in banked assembly language file fortunately Keil detects and flags banked interrupts in C code To solve problems stemming from callback routines all subroutines called from other banks should be made global so that the linker can use their data Next overlay commands should be used to inform the Keil linker that a banked
48. main loop in Main main c main run The tasks are called repeatedly by the main loop giving each of them many opportunities to use the MPU They usually check for data present and then either exit or process the data and then exit Prominent examples include meter run in meter meter c the meters main process cli in cli cli c the command line interface s process stm run in Util stm c the software timers update task This scheme is well suited to such a small system but it also has problems when an IO process must wait for input or output This happens in only two major subsystems the serial command line interface and the metering system While the serial command logic is waiting for another serial character it calls a subset of the main loop in Main main c main background main background does all of the meter s main loop except for serial protocols In that way the meter keeps running while the serial IO is waiting The main metering routine Meter meter c meter run skips most of its logic until a flag ce update is set At this point meter run runs to completion meter run performs many calculations These calculations stop the rest of the main loop from running for up to several hundred milliseconds depends on clock speed This delay is nearly impossible for a person to see so it does not affect human I O at all The time critical machine I O during this period is handled by interrupts that buffer data
49. meter VARxSUM X It calculates summed squares of currents for each phase IXSQSUM X o a A Qo N It calculates summed squares of voltages for each phase VXSQSUM X 7 It counts zero crossings on the same phase as the frequency MAINEDGE X The CE code see ce ce3x_ce c digitally filters out the line frequency component of the signals eliminating any long term inaccuracy caused by heterodyning between the line frequency and the sampling or calculation rates This also permits a meter to be used at 50 or 60Hz or with inaccurate line frequencies The CE has several equations of calculation so that it can calculate according to the most common methods Once per accumulation interval the MPU requests the CE code to fetch an alternative measurement alternate multi plexer cycle At the end of each accumulation interval an MPU interrupt the xfer interrupt occurs see meter ce c xfer busy isr occurs This is the signal for the MPU to use the CE s data At this time the MPU performs creep detection ce c Apply Creep If the current or the accumulated energy watt hours are below the minimum no current or watts are reported If volts are below the threshold no frequency or edge counts are reported The MPU s creep thresholds are configurable VThrshld IThrshld If Ithrshld is 0 creep logic is disabled The MPU calculates human readable values and accumulates cumulative quantities see meter meter c meter run
50. none none Cli cmd_misc c send_short sends a 0 99 999 Value fo Int16 tn none cli io c DTE send short hex sends a 0 FFFF value to DTE uint16 tn none cli io c EE tlh Disable the receive interrupt Void void lo ser0 h ser1 h EE M edy Disable the transmit interrupt Void void lo ser0 h ser1 h ser enable rcv rdy Enable the receive interrupt Void void lo serO h ser1 h EE EE Enable the transmit interrupt Void void lo ser0 h ser1 h configures the serial port Ser initialize specified in the include file enum baud none lo ser0 h ser1 h ser0 h or ser1 h ser rcv Get a byte from the serial port Void uint8 t lo ser0 h ser1 h ser rev err Returns true if the last received Leg bool lo ser0 h sert h im byte had an error Returns true if the serial port ser rcv rdy has gotten another byte Void bool lo ser0 h ser1 h ser xmit Send a byte to the serial port Uint8 t void lo ser0 h ser1 h ser xmit err Returns true if the last sent byte scis bool lo ser0 h ser1 h TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA Function Routine Name Description Input Output File Name Unimplemented routine to ser xmit free permit other uses of transmit Void void lo ser0 h ser1 h electronics ser xmit_off Diiniipl sine nied routine to Void void lo ser0 h ser1 h disable transmit electronics ser xmit_on Unimpleme
51. of 2520 bytes per second If the MPU disables interrupts at all the write can miss the window and fail In this case the write can detect a failure to write by examining and clearing the FWCOLO bit If the FWCOL1 bit is set the write was in progress when the CE pass should have started In this case the code must count the failed CE code passes and prorate the metering data Prorating the metering data is unacceptable to many users 5 17 8 Watchdog Location The watchdog reset bit moved to bit 7 of SFR OxF8 The other bits of this register are read only 5 17 9 Software Watchdog Now Deprecated The 651x series had a software watchdog that was part of the 8051 core and which could be disabled by software The 653x series no longer supports the core s watchdog Instead use the standard watchdog which cannot be disabled by software 5 17 10 Real Time Clock Compensation The real time clock compensation is very different from the 651x series Fixed rate adjustments are nonvolatile and automatic so that they continue when the MPU is not operating The 32 KHz crystal rate can be measured precisely in the factory by using a precision frequency counter to measure the 1 second or 4 second output from the TMUX pin During this measurement the RTCA ADJ register should be set to the middle of its range 0x40 and PREG and QREG should be set to the middle of their range After this the capacitance driving the crystal can be adjusted by have the meter
52. or bits in the PSW will also affect flag settings v1 1v1 1 TERIDIAN Proprietary 113 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation eA TER DIAN SEMICONDUCTOR CORR 71M653X Software User s Guide v1 1v1 1 TERIDIAN Proprietary 114 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 7 APPENDIX 7 1 ACRONYMS AC AMR ANSI ANSI C API C CE CR COM CPU DC EEP EEPROM FLAG GB ICE IDE IEC INT ISO ISR KB LCD LF LSB MB MPU Alternating Current current with changing polarity Automated Meter Reading usually performed via an optical port or modem American National Standardization Institution part of ISO C Programming Language standardized by ANSI in 1983 Keil C used throughout this User s Guide is not strictly ANSI compliant Application Programming Interface The C Programming Language as defined by Kernighan and Ritchie Computation Engine Carriage Return or Enter Key on PC Keyboard Communication Port Control Processor Unit MPU Direct Current Engineering Evaluation Platform Demo Board Electrically Erasable PROM An international protocol for reading of meters using an optical port initially developed by Ferranti and Landis amp Gyr Gigabyte s In Circuit Emulator Integrated Development Environment usually a combination of editor compiler assembler linker debugger ICE International Electrotechnical Commission Geneva Switze
53. power factor TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e or VAh divided by Wh 5 4 4 Watchdog Timer The Demo Code revision 4 4 uses only the hardware watchdog timer provided by the 80515 This fixed duration timer is controlled with SFR register INTBITS OxF8 The hardware watchdog timer requires a refresh by the MPU firmware i e bit 7 of INTBITS set at least every 1 5 seconds If this refresh does not occur the hardware watchdog timer overflows and the 80515 is reset as if RESETZ were pulled low When overflow occurs the bit WD_OVF is set in the configuration RAM Using the WD_OVF bit the MPU can determine whether a reset or a hardware watchdog timer overflow occurred The WD_OVF bit is cleared when RESETZ is pulled low 5 4 5 Real Time Clock RTC The RTC is accessible through the UO RAM Configuration RAM registers RTC_SEC through RTC YR addresses 0x2015 through 0x201B as described in the data sheets The RTC can be updated any time after the second turns over So when the clock is set the demo code clears the subsecond counter forcing the second to start now and then writes the rest of the data to the clock One tricky part of the code is the calculation of the digital adjustment PREG and QREG based on temperatures The code first calculates the adjustment in parts per billion and then scales it to the adjustment register Another tricky part is that the code includes date
54. supplied by the MPU in GA N ADJ This external type of compensation enables the MPU to control the CE gain based on any variable and when EXT TEMP 15 GAIN ADJ is an input to the CE 5 14 2 4 Temperature Compensation for the RTC The flexibility provided by the MPU allows for compensation of the RTC using the substrate temperature To achieve this the crystal has to be characterized over temperature and the three coefficients Y CAL Y CALC and Y CAL C2 have to be calculated Provided the IC substrate temperatures tracks the crystal temperature the coefficients can be used in the MPU firmware to trigger occasional corrections of the RTC seconds count using the ETC DEC SEC or RTC INC SEC registers in I O RAM Example Let us assume a crystal characterized by the measurements shown in Table 5 14 Deviation from Measured Deviation from Nominal Frequency Hz Nominal Temperature C Frequency PPM 50 32767 98 0 61 25 32768 28 8 545 0 32768 38 11 597 25 32768 08 2 441 50 32767 58 12 817 Table 5 14 Frequency over Temperature The values show that even at nominal temperature the temperature at which the chip was calibrated for energy the deviation from the ideal crystal frequency is 11 6 PPM resulting in about one second inaccuracy per day i e more than some standards allow As Figure 5 3 shows even a constant compensation would not bring much improvement since th
55. the CE program memory from being erased or reprogrammed while the CE is running When programming flash memory from an emulator the CE must first be disabled by writing 00 to XDATA 0x2000 Only then programming of the flash memory can occur Most practical flash write code simply disables the CE writes the flash and enables the CE This is the fastest way to write the flash and the metering values for the disabled period can be interpolated Automated flash writes with the CE running are theoretically possible The writes have to be synchronized with an interrupt from the correct trailing edge of the CE BUSY signal Also with three phase CE code there is usually only enough time to write one byte before the next CE run starts This would confine a transparent flash write scheme to a maximum data rate of 2520 bytes per second If the MPU disables interrupts at all the write can miss the window and fail In this case the write can detect a failure to write by examining and clearing the FWCOLO bit If the FWCOL41 bit is set the write was in progress when the CE pass should have started In this case the code must count the failed CE code passes and prorate the metering data Prorating the metering data is unacceptable to many users 5 18 8 Watchdog Location The watchdog reset bit moved to bit 7 of SFR OxF8 The other bits of this register are read only 5 18 9 Software Watchdog Now Deprecated The 652x series had a software watchdog that was
56. the normal reset indications when doing simulated resets because when debugging electrostatic discharge problems displaying reset indications causes engineers to try to fix the reset pin rather than V1 5 4 2 5 EEPROM Isr The IC s two wire interface operates at the standard clock rate of about 30kHz It can be operated reasonably efficiently with a polling interface or an interrupting interface The interrupting interface IOYeeprom c is installed in the demo code as an example It uses less CPU time and interacts less with other system software The interrupt steps through a state machine that writes the needed bytes to read or write data to an Atmel EEPROM with 19 bit addressing A polling interface to the IC s two wire interface works well and TSC uses one to support drivers for many other types of EEPROMs To install them see the all options code set in io iiceep c io eepromp c io eep24c08 c or contact factory support Bit banging drivers are not recommended for the two wire interface In the two wire interface each 8 data bits sent are followed by a received ACK bit Some EEPROMS start the ack bit as soon as 50 nanoseconds after the clock line falls This can easily be before the bit banging driver switches the data line to an input The resulting brief high frequency electrical short can cause system anomalies Typical EEPROMs delay 1 5 microseconds before asserting ACK so bit banging will usually work on the bench but in
57. to brownout mode The MPU will start code execution at address 0x000 The sleep and LCD modes shut down all of the 71M653x s internal and XDATA RAM as well as the pin drivers for DIOs and most of the memory cells that store the hardware configuration The lack of nonvolatile memory during the battery modes can be disconcerting at first Only GPO GP7 and the clock are guaranteed nonvolatile GPO GP7 are cleared on reset In particular the meter should be designed so that the DIO pins and serial port outputs do not need to be powered in battery modes The data sheet for the 71M653x shows which bits are reset and which are maintained in the battery modes The transitions between the modes are managed by changes in supply voltage transitions of the push button pin signal and a wake up timer TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation of US 71M653X Software User s Guide SEMICONDUCTOR CORR The push button operation is very simple Pressing the button wakes the part from LCD or sleep mode into brownout mode Afterward a bit is set IE PB bit 4 of IFLAGS SFR E8 One of the characteristics of the 71M653x is that it is not able to enter LCD or sleep mode if IE_PB or IE_WAKE the wake timer s bit see below are set The Demo Code clears these bits at the earliest convenient instant transferring their state to bits in the demo firmware s status variable This technique preserves data about ho
58. uint8_tx uint8 t Util math c wv uint8 tx u uint8 tx divide u 7 v v m n uint8_tx none Utillmath c wv divide 1 x 2 y uint8 tx x y n none Util math c TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA Function Routine interrupts Name Description Input Output File Name done exits control uint8 td c CG Cli cli c connects disconnects DIO4 5 bool access lOteeprom c EEProm Config for I2C interface to serial uint16 t page size none ICONE 3 EEPROM uint8 ttWr peu esO_isr serial port O service routine none none IO ser0 c esl isr serial port 1 service routine none none lO ser1 c frequency lcd 1 dd His wedgeneyondpe void void Meter freq c Copies CE configuration constants to a data structure so e get ce constants they can be viewed in the void void Meter ce c emulator get char Ee EE none uint8_t cli io c E TI Bal SOM TEM uint8 t idata d uint8_t cli io c poss gets next decimal or hex digit x re get digit from CLI buffer uint8 t idata d uint8 t cli io c get long EE De or hex none int32_t cliNio c get dong decimal E EE long to ung tc int32_t cli io c converts ASCII hexadecimal Xs get long hex number to binary number none U32 cli io c Bt aun converts ascii decimal or hex sona S08 cliNio c ger number to binary number get num decimi converts
59. version 3 33 Note this version comes with Keil Compiler version 8 03a e Signum Systems software Wemu51 comes with Signum Systems ADM 51 ICE hardware The following software tools programs are included in the 71M653X development kit and should be present on the development PC e Demo Code with Command Line Interface CLI Used to interface directly to metering functions and to the chip hardware e Source files e Demo Code object file hex file TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation SEU RIDIAN SEMICONDUCTOR CORP 71M653X Software User s Guide In order to generate and test software the Keil compiler and the Signum in circuit emulator ICE must be installed per the instructions in section 4 The include files and header files must also be present on the development PC Typically a design session consists of the following steps e Editing C source code using uVision2 e Compiling the source code using the Keil compiler e Modifying the source code and recompiling until all compiler error messages are resolved e Using the assembler and linker to generate executable code e Downloading the executable code to the ICE e Executing the code and watching its effects on the target 2 3 SOFTWARE ARCHITECTURE The 71M653X software architecture is partitioned into three separate layers 1 The lowest level is the device or hardware layer i e the layer that directly communicates with the dis
60. 11 6513 and the 71M653x is that the CE code now resides in the flash It is not copied to the CE program RAM as in the 71M651X chips Instead the register CE LCTN bits 0 7 at XDATA 0x20A8 is set to the most significant 8 bits of the program flash address where the CE program resides It is best to place the CE program in a high code bank so it does not compete with the MPU for flash The demo code puts it near the end of the last bank 5 17 7 CE Causes Flash Write Protection Since the CE resides in flash memory there are safeguards that prevent the CE program memory from being erased or reprogrammed while the CE is running When programming flash memory from an emulator the CE must first be disabled by writing 00 to XDATA 0x2000 Only then programming of the flash memory can occur Most practical flash write code simply disables the CE writes the flash and enables the CE This is the fastest way to write the flash and the metering values for the disabled period can be interpolated Automated flash writes with the CE running are theoretically possible The writes have to be synchronized with an interrupt from the correct trailing edge of the CE BUSY signal Also with three phase CE code there is usually only TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERINAN enough time to write one byte before the next CE run starts This would confine a transparent flash write scheme to a maximum data rate
61. 14 1 4 Economic Usage of RAM iter e tr pi ce ea eden EEN 78 5 14 1 5 Trading Space for Gpeed sess nennen 78 5 14 1 6 Object Oriented Design eene nennen nnne nnns 78 5 14 1 7 Reconfiguring Glue Logo 79 5 14 1 8 DSP Operatons eren nennen nns n enhn SENEE EEEn Ennn nnn nnns 79 5 14 1 9 Coping with Various Current Sensors sss eene 79 5 14 1 10 User Interface eee ete ats edt tete eta ten Ree eder AER 79 5 14 1 11 Operating without User Interface 79 5 14 1 12 Communication with a Computer 79 5 14 1 13 Support of Automatic Meter Reading sssssssssseeeemeneeenenes 79 5 14 1 14 Communication between MPU and CE 80 5 14 1 15 guide RE 80 5 14 1 16 6531 Calculation of max VA IA VA IB Option Equation 0 80 5 14 1 17 6534 Calculation of VA IA VB IB VC IC Option Equation P 81 5 14 1 18 How Register Data is Stored ssssssssssssseeee eene 82 5 14 1 19 Managing Power Failures nennen mnes 83 5 14 1 20 Pulse Counting 2 reino t ete eget AE eyed I ibd wate ited ibe ae 83 5 14 1 21 Battery lee 83 5 14 1 22 Real Time bertormance eene n nene ernst nnns 83 5 14 2 Firmware Application Selected Taeks A 84 5 14 2 Sag Detection EE 84 5 14 2 2 Temperature Measurement ennemis 84 5 14 2 3 Temperature Compensation for Measurements nnne 85 5 14 2 4 Temperature Compensation for hebbt 85 9 14 2 5 Validating the Battery anie eie ted nail edie aie eed eee aes 86 5 15 Alphabetical Function Reference
62. 3 6534 SE From a real PCB at 23C Scaling Maximum 2080 ImaxB amps for PCB 0 1A 15 unsigned 16 element B 208 0A The time that neutral Curent can ege Count of accumulation ncount INThrsld before the 10 10 secs HS unsigned 16 intervals neutral bit is asserted 513421 6531 433199 6533 amp Starting current 516 6534 A IThrshidB sqrt i0sqsum 2 16 unsigned 32 element B 0 08A same rationale as Ithrshid 641776 2 Maximum valid e spa e INThrshld neuial current sqrt i0sqsum 2 16 unsigned 32 0 1A O0x00E54D4C 6531 0x00723D00 6533 VBatMin E yalid battery Same as Vbat below S 17 unsigned 32 current 2V on a real PCB should be adjusted for battery and chip Counts number of times CalCount Count of calibrations calibration is saved to a 18 unsigned 8 maximum of 255 19 Nonvolatil f be onvolatile copy o i 1B RTC copy the most recent time eee Min Hr Day Date 1C unsigned Month Year each the RTC was read 1D 1E 1F Difference between deltaT raw temperature and en ot TEE TRAY indi 20 signed 32 temp_nom f Frequency Frequency Units from CE 21 unsigned 32 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d J TERIDIAN Last measured battery voltage Note battery D 2 9 ADC counts Vbat Hes b E
63. 8 TERIDIAN Semiconductor Corporation d jTERIDIAN Function Routine had an error Name Description Input Output File Name 40 bits of precision Use only to calculate ratios s g nast Converts seconds to clock ticks Any number uint16_t UtiNstm h usually for a software timer Selects pulse sources for 2 CE pulse outputs and optionally for SelectPulses EE pulse Void void Meter pulse_src c outputs The controls are in MPU variables initialized from the default table send a result ws passed re ulticode to uint8_tc none Cli cli c send_byte sends a 0 255 byte to DTE S08 n none cli io c send char sends single character uint8 tc none cliNo c send crlf sends lt CR gt lt LF gt out to UART None none cli io c be od sends single ASCII hex or ge send_digit decimal digit out to SERIALO uint8 t c none cli io c send_help sends town code at specified uint8 tr code s none Cli cli c location to serial port send hex sends byte out SERIALO in HEX uint8 tn none cli io c sends a 0 9 999 999 999 x send long value to DTE Int32 tn none cliNo c send long hex p SI FPEFEFEETVSIMO to U32n none cliNo c sends a 0 9 999 999 999 int32 t n uint8 t a send num F none cli io c value to DTE size send_result loks up result code primes none none Cli cli c pump for result codes send_rtc displays RTC data
64. AM and 256 bytes of internal memory The compiler treats uncalled subroutines as possible interrupt routines and starts new hierarchies which can rapidly fragment each type of memory and interfere with its reuse To combat this the following measures were taken when generating the Demo Code e The code is organized as a control loop keeping most code in a single hierarchy of subroutines e The programmers eliminated unused subroutines by commenting them out when the linker complained about them Also the Demo Code explicitly defines interrupt code and routines called from interrupt code as reentrant so that the compiler keeps their variables on a stack e When data has a stable existence the Demo Code keeps a single copy in a shared static structure With these measures applied the Demo Code uses memory efficiently and normally no memory issues are en countered The Demo Code does not have deep call trees from the interrupts so small reentrant definitions can be used which keep the stack of reentrant variables in the fast small internal RAM The register sets are also in internal memory The C compiler has special interrupt declaration syntax to use them The noaregs pragma around reentrant routines stops the compiler from accessing registers via the shorter absolute memory references This is because the Demo Code uses all four sets of registers for different high speed interrupts Using noaregs lets any interrupt routine c
65. ARhe A Exported VARh element A Me signed 64 VARhe_B Exported VARh element B 50 signed 64 VARhe_C Exported VARh element C i 52 signed 64 Whn Net metered all elements LSB of wOsum 54 signed 64 Whn A Net metered Wh element A for autocalibration 56 signed 64 Whn B Net metered Wh element B for autocalibration 58 signed 64 Whn CT Net metered Wh element C for autocalibration 5A signed 64 VARhn Net metered VARh sum all elements LSB of wOsum 5c signed 64 VARhn_A Net metered VARh element A forla Be signed 64 autocalibration TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Es VARhn_B Net metered VARh element B for autocalibration 60 signed 64 VARhn_C Net metered VARh element C for autocalibration 62 signed 64 MainEdgeCnt Count of edges Count of zero crossings 64 unsigned 32 Wh Default sum of Wh nonvolatile LSB of wOsum 65 signed 64 Wh_A Wh element A nonvolatile 67 signed 64 Wh_B Wh element B nonvolatile 69 signed 64 Wh Ct Wh element C nonvolatile P 6B signed 64 StatusNv Nonvolatile status See Status 6D n a 32 t Three phase chips i e 6533 6534 only Two phase chips i e 6531 this compilation option is normally on to enable mixing a shunt and CT as current sensors Uses same space as neutral current threshold Three phase chips i e
66. Brownout mode 0 1KB Y Y Used to enter sleep and LCD modes Command line interface is available 32KB when resetting into this mode Command prompt in this mode to be B gt LCD mode 0 5KB Y Y Is entered automatically when power fails Displays the Wh register waits 7 sec using wakeup timer then initiates sleep mode Wake button 0 5KB Y Y When in sleep mode enters LCD mode Wake timer 0 5KB Y Y Used to exit the LCD mode and enter sleep mode Table 5 8 Operating Modes Note The sleep mode does not require any support by MPU code The mission mode performs the other code features v1 1v1 1 TERIDIAN Proprietary 50 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation QS TERI DIAN 71M653X Software User s Guide SEMICONDUCTOR CORP Feature Reception of 2 0KB Y Y Simple serial calibration system to read and set data calibration and calibration values including CE data MPU parameters via calibration and RTC settings Meter operation is not the serial interface required when this feature is in use Intel hex records are used Count of 01 KB Y Y Counts calibrations 0 254 255 many The count calibrations since is protected by a checksum The first cold reset is first cold reset detected by an invalid EEPROM This is a tamper detection feature Auto calibration 3 5KB Y Y Internal automatic calibration from command line interface Calibration adjusts phase as in t
67. Calibration and Various Services eene eene nneen nennen enne nennen nene 51 Table 5 10 Interrupt Service Routines iine ise seeds cientes eai ttn der data da innu dan de daa nta ann das ae dan daga atn 53 Table 5 11 Interrupt Priority Assignment uiii teer eenean Ere A a ae Hong a ERE Lupa ER Cc a n nue Edge un a MO 54 Table 5 12 MPU Memory Locations iucci tercero Ln dare osi ee Erreur eiia ee EENS o ade eed Rd ia 74 Table 5 13 MPU status Bits ERA 76 Table 5 14 Frequency over Temperature iicecic ccadee stecwss csnedececsteedepenaucuhdeveste Ves ub riedenia ssiendesietostdes dE Eeer 85 Table 6 7 Notes on Data Addressing Modes AA 105 Table 6 8 Notes on Program Addressing Modes A 105 Table 6 9 Anthmetic OPSratlOnS p EEN 106 Table 6 1 0 LOGIC OPO rations etr 107 Table 6 11 Data Transfer Operattons ene nennen nennen neneen eer en nennen inns e nennen nennen 108 Table 6 12 Program Branches E 109 Table 6 13 Boolean Manipulations ene eene nennen enne ener inneren enne e nennen nennen 109 Table 6 14 Instruction Set in Hexadecimal Order 110 Table 6 15 Instruction Set in Hexadecimal Order 111 Table 6 16 Instruction Set in Hexadecimal Order 112 Table 6 17 Instructions Affecting Flags cecinere etr tnu eue dnte doce hdd denda tna danda ose d ua daga den 113 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN
68. Causes Flash Write Protection ose iec iiec ice enint tne Fuer En nate Panne dene 102 5 18 8 Watchdog LOCationy e estes 102 5 18 9 Software Watchdog Now Deprecated AAA 102 5 18 10 Real Time Clock Compensation essen nennen nnne 103 5 18 11 crar 103 5 18 12 liem E 103 5 18 13 Temperature Compensation c crinis rit tesa ront para nana rk Lese ch anta EHE iah gaiiean 103 6 80515 MPU REFERENCE iren ceee adeleg Seege 105 6 1 The 80515 Instruction Set iie eieeii oec ee ttece rere esas e nantes uoce cane ce ka scavesaaceseotect 105 6 1 1 Instructions Ordered by Function ccc ccccceeseceedeseneeesessedeedeceedeedeceedesdanendectecsedecdeeendandensece 106 6 1 2 Instructions Ordered by Opcode Hexadecimal seen 110 6 1 3 Instructions that Affect Flags 2 oec crm eee trece tae nee tne che rote E taa cee 113 7 ele Ir Aaea a EAS AE E E A 115 CO WE ee Lu 115 Ta Revision FHIStOTY nuina a e a EE 116 v1 1v1 1 TERIDIAN Proprietary 7 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation e List of Figures Figure 2 1 Sotware SUM CU HH 14 Figure 3 1 Port Speed and Handshake Getup eee nnns en erre nnne entren nnns 19 Figure 4 1 Setup of Keil Compiler for bank switched code A 36 Figure 4 2 Sel
69. Include in Target Build Size Always Build last change Generate Assembler SRC File Assemble SRC File Link Publics Only Code Bank Bank 2 vi Stop on Exit Code Not specified Select Modules to Always Include Custom Arguments Cancel Defaults Figure 4 2 Selecting a Bank for a File Group in Keil C 4 9 5 Startup TSC provides special start up code on the CD ROMs shipped with the 71M653X Demo Kits The code can be found at UtiNstartup 30 banked a51 This file sets up the bank switching logic It must be included in the build Any other startup a51 file must be removed 4 9 6 Bank Switching Code TSC has already ported Keil s bank switching code Util L51_bank a51 TSC s version of this file should be included in the build TSC has already selected the fastest standard bank switching method as the default During performance testing TSC made a good faith attempt to port the other bank switching methods in this code including features needed by Keil s advanced Lx51 linker However these versions are not extensively tested 4 9 7 Page Table Setup and Debug Keil s linkers produce the page table automatically once paging is selected in the Microvision options gt target dialogue Keil usually places the page table at an address of 0x100 in the common bank It is visible in the linker m51 file To see how it works one can use the emulator to single step through at a banked function call at the assembly language
70. LC2 MPU addresses 0x04 0x05 0x06 For the Demo Code the coefficients have to be entered in the form Y CAL Y CALC n Y CALC2 T AT 10 100 1000 Note that the coefficients are scaled by 10 100 and 1000 to provide more resolution For our example case the coefficients would then become after rounding Y CAL 109 Y_CALC 12 Y CALC2 7 Alternatively the mains frequency may be used to stabilize or check the function of the RTC For this purpose the CE provides a count of the zero crossings detected for the selected line voltage in the MAIN EDGE X address This count is equivalent to twice the line frequency and can be used to synchronize and or correct the RTC CORRECTION ppm 5 14 2 5 Validating the Battery For applications that utilize the RTC it is very important to validate the battery A brief loss of battery power when the 653X IC is powered down may result in corrupted RTC data The battery monitor function can be used to obtain the battery charge status After battery power is lost the RTC is usually invalid and the MPU start up code will then set it to read the year 2001 the month January and the day 1 2001 01 01 The time information will be 01 01 01 If the MPU firmware program detects the date 01 01 2001 upon power up or reset it is safe to conclude that the RTC is corrupted most likely due to a missing or low voltage battery TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corp
71. OV R3 direct XRL A R4 MOV direct RA MOV RA direct XRL A R5 MOV direct R5 MOV R5 irect XRL A R6 MOV direct R6 MOV R6 direct XRL A R7 MOV direct R7 MOV RJ direct JNZ rel MOV DPTR data16 ANL C bit ACALL addr11 ACALL addr11 ACALL addr11 ORL C direct MOV bit C CPL bit JMP A DPTR MOVC A A DPTR CPL C MOV A data SUBB A data CJNE A data rel MOV direct data SUBB A direct CJNE A direct rel MOV RO data SUBB A RO CJNE RO data rel MOV R1 data SUBB A QR1 CJNE R1 data rel MOV RO Zdata SUBB A RO CJNE RO data rel MOV R1 data SUBB A R1 CJNE R1 data rel MOV R2 data SUBB A R2 CJNE R2 data rel MOV R3 data SUBB A R3 CJNE R3 data rel MOV R4 data SUBB A R4 CJNE R4 data rel MOV R5 data SUBB A R5 CJNE R5 data rel MOV R6 data SUBB A R6 CJNE R6 data rel MOV R7 data Table 6 9 Instruction Set in Hexadecimal Order Copyright 2005 2008 TERIDIAN Semiconductor Corporation SUBB A R7 TERIDIAN Proprietary CJNE R7 data rel d jTERIDIAN Mnemonic Opcode Mnemonic PUSH direct OxDO POP direct AJMP addr11 OxD1 ACALL addr1 1 CLR bit OxD2 SETB bit CLR C OxD3 SETBC SWAP A OxD4 DAA SCH A direct OxD5 DJNZ direct rel XCH A
72. They map to cli0_in and c1i0 out in CLI serOcli c An AMR routine can be spliced in just by writing the input and output code and changing the options h file In this ISR the UART data is sent and received using XON XOFF flow control Parity and other serial controls are managed in this ISR The guts of the code are in serOcli c clip in takes a character in and decides if it is XON or XOFF If not it puts it into a circular buffer and counts it The circular buffer s index is made to restart by masking logical anding it If the count of data in the buffer is too big it sends an XOFF The XON is sent later by the code that takes data out of the buffer see the code that calls flow on cliO out first sees if it has to write a flow character If not then if there s no more characters to send it disables the transmit interrupt If there s more to send and the flow is enabled it gets a character out of the circular transmit buffer and sends it If the flow is turned off it disables the transmit interrupt The output code is designed to switch a driving pin as well There s a flag has run which is polled by a software timer routine serz0 free timer lfhas run is not set the timer switches off the external pin or driver In the demo code this switches DIO2 between OPT TX from serial output 1 and WPULSE The timer is used so that the output switches well after the last character is sent The serial interrupt overhea
73. WD DETECT 9 The most recent reset was a watchdog reset This usually indicates a software error MAXIN 10 The neutral current is over INThrshld In a real meter this could indicate faulty distribution or tampering MAXIA 11 The current of element A is over IThrshld In a real meter this could indicate overload MAXIB 12 The current of element B is over IThrshld In a real meter this could indicate overload MAXICt 13 The current of element C is over IThrshld In a real meter this could indicate overload MINT 14 The temperature is below the minimum 40C established in option gbl h This is not very accurate in the demo code because the calibration temperature is usually poorly controlled and the default temp nom is usually many degrees off 40C is the minimum recommended operating temperature of the chip MAXT 15 The temperature is above the maximum 85C established in option gbl h This is not very accurate in the demo code because the calibration temperature is usually poorly controlled and the default temp nom is usually many degrees off 85C is the maximum recommended operating temperature of the chip BATTERY BAD 16 Just after midnight the demo code sets this bit if VBat VBatMin The read is infrequent to reduce battery loading to very low values When the battery voltage is being displayed the read occurs every second for up to 20 seconds CLOCK TAMPER 17 Clock set to a new value more than two hours from the pre
74. X wh sum import positive yielding a total of oes S int32i t void meter wh c imported power in w m E Wh sum nett Adds w1 to S yielding a net sum uintx t S int32i t vold instenwiie ADU of watthours in s wl Convert a 64 bit internal watts count to a 6 digit value i e this wh to long is the routine that precalculates uint8 t val uint32 t meter wh c values for wh_brownout_to_Icd 5 16 ERRATA The up to date list of known issues with revision 4 4 15 of the Demo Code can be found in the readme txt file contained in the 653x_demo ZIP file shipped with the Demo Kits The factory should be contacted for updates to the Demo Code Known Firmware Errata for version 4 4 15 are listed in the table below v1 1v1 1 TERIDIAN Proprietary 98 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 5 17 PORTING 71M6511 6513 CODE TO THE 71M653X 5 17 1 Flash Use The biggest issue when moving code from the 6511 6513 to the 71M653x is the increased program memory While the 71M6511 and 6513 have 64K the 71M6531 has 128K and the 71M6534 has 256K The 653x defaults to a 64K configuration so code from earlier meter chips will fit easily Creating banked code that uses the extra flash is a substantial discussion in itself See the section Creating banked code 5 17 2 Extra RAM The MPU now has access to 4K of RAM up from 2K Roughly 1K is allocated to the CE leaving 3K 5 17 3 CE Da
75. XDATA in 71M653x ICs CeData is the array of 32 bit integers containing the CE s default data NumCeData is the count of data words in the table a constant value that precedes the CE default data table 4 9 12 Write Protecting Flash in the 653X Besides safety interlocks in software that prevent accidental write operations to flash the 71M653x ICs also have a write protection mechanism implemented in hardware Some systems might permit code or customization tables to be downloaded to flash and designers might wish to assure that this process cannot corrupt other code or data TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA To protect flash starting at address 0x00000 write the number of 1 024 byte blocks into BOOT_SIZE at XDATA 0x20A7 and set WRPROT_BT bit 5 of SFR 0xB2 Since this range covers the code s interrupt vectors it is perfect for protecting a boot loader i e code that can load other code into the system It is also the logical choice for general purpose write protection To protect flash near the end of memory place the CE s data area at that point and set CE LCTN XDATA 0x20A8 and set the WRPROT CE bit 4 of SFR OxB2 This protects not only the CE code but also all flash memory after it This is excellent for protecting the CE code and calibration tables stored in flash The demo code uses this method to protect the CE code and its default initialization table 4 10
76. ackground executes background none none main c processing main edge cnt lcd Displays either the Uint8 t select void Meter freq c TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERRIAN Function Routine Name Description Input Output File Name instantaneous edge count or the cumulative edge count main soft reset initiates soft reset none none main c returns maximum of unsigned uint16 ta uint16 t max int a and b b uint16_t options_glib h gt Int32x_t pDst memcpy_cei Copies from IDATA to the CE int32i t pSrc void Meter ce c memory A uint8_t len Int32x t pDst memcpy cer Copies from fashito the CE int32r_t pSrc void Meter ce c memory uint8_t len Int32x t pDst memcpy cex E OPI TOM XDATAIONE CE int32x t pSrc void Meter ce c memory uint8 t len Int32i t pDst memcpy ice Copies fromthe CE memory to int32x t pSrc void Meter ce c IDATA uint8 t len Int32x t pDst memcpy xce Ee ihe CE memonyito int32x t pSrc void Meter ce c uint8 t len memget ce Reads a word of the CE int32i_t pDst int32_t Meter ce c memory int32i_t pDst memset ce Sets a word of the CE memory int32_t src void Meter ce c Display the current quantity on meter lcd the LCD Void void Meter meter c meter run E meter dala Void void Meter meter c pr
77. ad data code download upload none none Cli load c cmd meter processes M commands none none Meter meter c lani dc ca EE m m context for MPU none nona Cli access c cmd power save Gre power sen none none Cli cmd_misc c cmd rtc processes RTC commands none none Cli cmd_misc c cmd trim processes trim commands none none Cli cmd_misc c cmin returns minimum of unsigned weg ta vinto tb uint8_t Util math c char a and b ER Computes the V I phase angle void void Meter phase_angle c Compute RMSY Computes Vrms and Irms void void Meter rms c calculates standard 16 bit CRC uint8 tr ptr CRC Calc polynomial per ISO IEC 3309 on uint16 t len U01 bool UtiMlash c flash memory x x 2491 set calculates the 16 bit CRC uint8 tx ptr CRC Calc NVR polynomial per ISO IEC 3309 on uint16 t len U01 bool Util math c NVRAM set ctoh Converts Ascii hex haracterto E uint8_t Cli load c hexadecimal digit date lcd Displays the current date void void IO rtc_30 c Figure the elapsed time struct RTC t start int32 t Delta timet between two times struct RTC_t end seconds Lene Det e F Sets the frequency Uses sag sre ortegueney status and voltage thresholds to void void Meter freq c return 0 if the voltages are off Sets status bits if voltages Determine Peaks currents or tomperature are void void Meter peak_alerts c outside limits Sag tests are in xfer_busy_int uint8_tx u uint8_tx divide u v v m n
78. all any reentrant routine without overwriting a different interrupt s registers TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d ATERI DIAN 4 SEMICONDUCTOR CORP There is a known defect in version 7 50a of the Keil compiler Memory types must be explicitly defined in local variables Using a predefined type is not explicit enough i e char xdata c is ok typedef char int8 t int8 t data c is OK but typedef char data int8d t int8d t c is not OK 5 2 DEMO CODE OPTIONS AND PROGRAM SIZE Since the 71M6531 is single phase and the 71M6534 is tree phase different versions of the Demo Code are provided that take into account the different features see Table 5 3 An attempt has been made to provide the most common features in each version of the Demo Code Flexibility is provided by the source code for users when recompiling the source code If a certain feature is not required it can be left out and replaced with a different feature The object files contained in the Demo Kits have been generated with the following Keil compiler versions e Ccompiler C51 exe V8 05a e Assembler A51 exe V8 00b e Linker Locator BL51 exe V6 05 e Librarian LIB51 exe V4 24 e Hex converter OH51 exe V2 6 Flash is Version Code Size Description Single Phase 45KB Demonstrates a single phase meter The software offers calibration and nonvolatile energy registers It utilizes one set of CE
79. amic calling is needed the h file can conceal switching code that tests a bit and selects a daughter class s methods For example CliNsercli c conceals an interface that can write to either UART based on a port parameter These schemes are efficient in the 8051 producing code as fast as individual calls for each daughter class TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA a The classic C scheme uses a table of subroutine pointers for each class It performs poorly on the 8051 The 8051 accesses tables of indirect addresses rather slowly 5 14 1 7 Reconfiguring Glue Logic Compilation switches enable cases In many cases code can include a different include h file to customize for a different device If code is not enabled it shouldn t run or be in the code For released code or other point releases an unifdef utility will be used to remove unused conditional code This makes the code easier to read but reduces flexibility 5 14 1 8 DSP Operations Teridian s solution for providing a superios electricity metering IC has been to use a simplified 32 bit digital signal processor the CE triggered by the ADC multiplexer Since DSP Code is too hard to develop prewritten DSP code is provided for the CE This code is suitable for most metering applications with optimized performance going right to the chip s noise floor It helps that metering is a standard application for most customers
80. ariables can be read via the command line interface if available with the n command and written with the n xx command where n is the word address Note that accumulation variables are 64 bits long and are accessed with n read and n hh 7ll write in the case of accumulation variables EA Name Purpose LSB Signed Bits Default IK 513421 6531 433199 6533 sqrt i0sqsum 2 6534 IThrshldA Starting current element A ee ae ge than 0 14 Without JO unsigned 32 both element A and B high accuracy CE code the noise floor is around 0 076A bit 0 reserved 0 VA Vrms Irms 1 VA2sqrt Wh VARh bit1 0 Config Dm E A 1 clear accumulators n N A 8 e g 1 2 Do nothing bit2 1 Calibration mode bit3 Reserved 1 Enable Tamper 906156350 6531 764569660 6533 VPThrshld error if exceeded sqrt vOsqsum 2 amp 6534 2 unsigned 32 240V sqrt 2 120 544498635 6531 275652520 6533 IPThrshld error if exceeded sqrt i0sqsum 2 amp 6534 3 unsigned 32 50 9A 30A sqrt 2 120 0 Y Cal DegO RTC adjust 100ppb Read only at reset 4 signed 16 in demo code Y Cal Deg1 RTC adjust linear by temp 10ppb AT in 0 1 C 0 signed 16 Y Cal Deg2 RTC adjust squared by temp 1ppb AT in 0 1 C 0 6 signed 16 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e PulseWSource
81. ascii decimal NUMBSF l pane S08 clilio c to binary number get num hex converts ascii hexdecimal byte none uint8_t cli io c to binary number converts ascii decimal or hex e e get_short short to binary number none int16_t cli io c get_short_decimal n A short to none int16_t cli io c get_short_hex converts ascii hexdecimal short ione uint16_t cli io c to binary number htoc eee Monge uint8_t Cli load c IICGetBit SE Dit deed EE none uint8_t io iiceep c IICInit eie LUIS aS EEPROM none none io iiceep c IICStart IIC bus s start condition none none io iiceep c IICStop IIC bus s stop condition none none io iiceep c init_meter od meter to default none none defaults c Defines variables used by IRQ_DEFINES macros to enable and disable n a n a utiNrq h TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d jTERIDIAN Function Routine lescriptior Jutpul File Nam Name Description Input Output e Name irq disable Disables interrupts void void util irg c The fastest way to disable interrupts Requires IRQ DISABLE IRQ_DEFINES to be earlier in n a n a util irg h the code or that the needed symbols be defined irq enable Enables interrupts void void util irq c The fastest way to enable interrupts Requires IRQ_ENABLE IRQ_DEFINES to be earlier in n a n a util irq h the code
82. ation to SAGA causes the power registers to be saved because the demo PCB is powered from element A For a multiphase power supply modify the bit mask constant POWERED PHASE in options h to select the sag bits from the most significant 8 bits of Status then recompile In this case all the bits in POWERED PHASE must become asserted to cause a save of the powered registers SAGB 26 Element A has a sag Set in real time by the CE and detected by the ce busy interrupt ce busy isr in ce c within 8 sample intervals about 2 6ms On the 6520 the demo code operates with an equation that does not use element B s voltage but the meter simulates this by wiring element A s V to VB on the chip SAGCI 27 Element C has a sag Works like other sag bits FO_CE 28 A square wave at the line frequency with a jitter of up to 8 sample intervals about 2 6ms The jitter is caused because the ce_busy interrupt only executes all of its code every g sample interval ONE SEC 31 Changes each accumulation interval i Three phase chips i e 6533 6534 only v1 1v1 1 Table 5 13 MPU Status Bits TERIDIAN Proprietary 76 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 5 14 FIRMWARE APPLICATION INFORMATION 5 14 1 General Design Considerations 5 14 1 14 Multitasking The meter appears to do many things at once How does this happen Each task is a subroutine call in the
83. ator Table 6 3 Arithmetic Operations TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e lU ch LI sch 1 sch IM hl gt 9 DO gt e PM dP NI Ph dM a gt db gt I O Os wo wl ms gt V os Ms AI MOL M NM MLM MO a gt MO NM NM d jTERIDIAN Description AND register to accumulator AND direct byte to accumulator AND indirect RAM to accumulator AND immediate data to accumulator AND accumulator to direct byte AND immediate data to direct byte OR register to accumulator OR direct byte to accumulator OR indirect RAM to accumulator OR immediate data to accumulator OR accumulator to direct byte OR immediate data to direct byte Exclusive OR register to accumulator Exclusive OR direct byte to accumulator Exclusive OR indirect RAM to accumulator Exclusive OR immediate data to accumulator Exclusive OR accumulator to direct byte Exclusive OR immediate data to direct byte Clear accumulator Complement accumulator Rotate accumulator left Rotate accumulator left through carry Rotate accumulator right Rotate accumulator right through carry 2 0 MI MI Al M O MIM N gt VININ gt IN Bio mNm PFKNINI RIOo MMI M SBIOIN F N PK Swap nibbles within the accumulator Table 6 4 Lo
84. be configured easily by loading the file 653X_demo uv2 using the Project Menu and selecting the Open Project command The window shown below should appear when the project control file is opened D 6521_CLI pVision2 Z Meters Firmware Test 6521 Main main c Bl eie Edit View Project Debug Flash Peripherals Tools SVCS Window Help 8 KA gege A 75 h SO S J SQ RDF 8a m amp Xx AN Target 1 EI E main c L I defaults c L I batmodes c mj Meter xf Utils JRERRRRRERERERERERERER RRR RARERERERERE RARER ERR RERERER ARERR RERERARERERAR A NAA T This code and information is provided as is without warranty of any kind either expressed or implied including but not limited to the implied warranties of merchantability and or fitness for a particular D purpose Copyright C 2005 Teridian Semiconductor Corp All Rights Reserved VXTERAZTA TAA ART XA AAT 4 Y Y PYRTA Y Y 4 4 XC V AH Y HA ORARE ERR ETE A PRRRRRERERRERERREREEREREEERER ERE ER EERE AREER ER EEE RE EERE IEEE DEERE DERE IR DESCRIPTION 71M652x POWER METER Main te AUTHOR MTF RGV ff HISTORY See end of file GASTRO ERENT REE ER ER ER EERE EERE EER ER LEER UU File MAIN C Hu include options h compile flags and system constants include irq h interrupt disabling logic include priority h interrupt priorities finclude defaults h default tables for use w
85. ble as well as totals A2h and V2h DetermineFrequency meterMreq c handles the creep associated with frequency and the mains edge count The mains edge count is important when the real time clock is slaved to the line frequency DeterminePeaks meter Peak c detects peaks and sags over current and also temperature excursions which can be a sign of over current ComputePowerFactor performs the power factor calculation once and caches it TSC also has sample code to calculate phase angles and phase to phase voltages Contact the factory or see the code set with all options GainCompensation adjusts the meter s rate for the current temperature using a quadratic adjustment This is the logic that uses PPMC1 and PPMC2 to adjust for the ADC s voltage reference and temperature based changes in the current and voltage sensors RTCCompensation adjusts the rate of the meter s real time clock for temperature using a quadratic adjustment This is the logic that uses Y CALO Y CAL1 and Y CAL2 5 4 3 2 Command Line Interpreter CLI The command line interpreter is cli in cli cli c called from main run in main main c In main run cmd pending in CLINo c gets a line of text from the user Then it returns a nonzero to indicate that the line buffer has data cmd pending is complicated because it echos the characters and edits the line using backspace main run then calls c1i to interpret the characters in the
86. code as possible is called from the main loop This helps the Keil linker to use less RAM when it organizes the overlays for the temporary variables Also code for the main loop is easier to write than interrupt code For example the software timers update routine stm_run UtiNstm c is called from the main loop see main background in main main c instead of a timer interrupt because it reduces the chances that a timer routine will be called in an unexpected way at an unexpected time The meter has to keep running while waiting for serial input or output from the user So the main loop has two parts see main run and main background in main main c The serial input and output routines call main background to keep the meter running while waiting for serial input from or output For example see Serial0_CTx in cliserOcli c main background calls the task subroutines needed to keep the meter running main run calls the serial input and output code e g the command line interface or an AMR system in addition to calling main background to run the meter Thus no routine called from main background should perform serial UO because the serial UO might try to call main background and this could cause an infinite recursion that would overflow the stack The Keil linker automatically generates a recursion error if such code is written The second part is the interrupt driven code Foreground such as the CE BUSY Interrupt Time
87. code for 1 element two wire meters and another set for 1 element three wire and 2 element three wire delta Three Phase 49KB Demonstrates a three phase meter The software is easy to reconfigure by recompiling It has calibration and nonvolatile energy registers The software demonstrates a full feature set Table 5 3 Demo Code Versions In addition to providing flexibility an attempt has been made to leave a certain amount of unoccupied memory space when generating the Demo Code This should provide some room for users who want to modify the Demo Code and experiment with small changes The tables presented below show the features available for the three versions of the Demo Code plus the code size required for each feature Entries for code size are approximated and depend on code module combination Y means that the feature is implemented N means that it is not N opt means that the feature may be implemented if enough memory space is available Feature Code 16 36 Description Size CT and shunt 1KB to Y Y Configurations include all 2 element 3 wire delta and resistors 2 5KB 3 element 4 wire wye with neutral current These were selected for demonstration because they permit easy measurements of individual elements Rogowski coils 2 5KB N N Needs special CE code contact factory Table 5 4 Current Sensing Options TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporat
88. crete functional blocks of the chip and the peripheral components hardware such as serial interfaces AFE LCD etc 2 The second layer consists of buffers needed for some functions 3 The third layer is the application layer This layer is partially implemented by the Demo Code for evaluation purposes but extensions and enhancements can be added by the application software developer to design suitable electronic power meter applications Figure 2 1 shows the partitions of each software component As illustrated there are many different designs an application can develop depending on its usage Section 5 describes in more detail the functions within each component Hardware UARTO UART1 AFE Display Sensors Terminal AMR PC Figure 2 1 Software Structure v1 1v1 1 TERIDIAN Proprietary 14 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation A The Demo Code is modular Each device in the chip and on the Demo Board has a corresponding set of driver software in the Hardware Layer These driver software modules are very basic enabling customers to easily locate and reuse the logic For the serial devices and for the CE the buffer handling has been separated from the driver modules Where there are several similar devices e g serO ser or tmrO tmr1 the Demo Code simulates a virtual object base class using C preprocessor macros For example to initialize the first serial in
89. d is low because the timer routine is only allocated once at the start of transmission Pulse outputs change so slowly that they are invisible to most UARTs The alternative serial port UART 1 uses an ISR with identical code structure and function esi isr in lOWser1 c and CLI ser cli c The code can be identical because it uses a different h file to define different serial IO macros that have the same names The buffer level code was written once and then ported instantly by copying the code and just testing it Both serial ports are enabled at all times 5 4 3 Background Tasks 5 4 3 1 meter run This does all the metering calculations It s in Meter meter c called from the main loop main background in MainWmain c Putting the calculations in the background makes the code faster because the local variables don t have to be on Keil s reentrant stack They can be statically allocated overlays instead First it checks to see if there s more meter data That is whether an accumulation interval finished and caused a xfer busy interrupt It checks the flag vier update set by the vier busy interrupt in meten ce c If the flag is clear then there s no new meter data so it returns to the main loop If there s new data it processes it In the processing first it checks to see if there was a request to clear the metering registers 1 2 clears the metering registers The clearing has to be synchronized with the meter calcula
90. da per day except logically shifted right 9 bits 22 unsigned 32 Vrms A Vrms element A sqrt vOsqsum 2 24 unsigned 32 Irms_A Irms element A sqrt i0sqsum 2 25 unsigned 32 Vrms_B Vrms element B t sqrt v1sqsum 2 26 unsigned 32 Irms_B Irms element B sqrt i1sqsum 275 27 unsigned 32 Vrms C Vrms element Ct sqrt v2sqsum 2 28 unsigned 32 Irms_C Irms element Cf sqrt i2sqsum 2 29 unsigned 32 Status Status of meter B DA unsigned 32 See table below CAI usd e m intervals since reset or count y2b signed 32 Whi Imported Wh all elements LSB of wOsum 2c signed 64 Whi_A Imported Wh element A i 2e signed 64 Whi_B Imported Wh element B 30 signed 64 Whi C r Imported Wh element C 32 signed 64 VARhi Imported VARh all elements LSB of wOsum 34 signed 64 VARhi A Imported VARh element A 36 signed 64 VARhi_B Imported VARh element B 38 signed 64 VARhi CT Imported VARh element C 4 DA signed 64 VAh Volt amps all elements LSB of wOsum DC signed 64 VAh_A Volt amps element A 3e signed 64 VAh_B Volt amps element B 40 signed 64 VAh C t Volt amps element C 42 signed 64 Whe Exported Wh all elements LSB of wOsum 44 signed 64 Whe_A Exported Wh element A 46 signed 64 Whe_B Exported Wh element B is 48 signed 64 Wie C r Exported Wh element C B MA signed 64 VARhe Exported VARh all elements LSB of wOsum AC signed 64 V
91. data 16 bytes 0x20 toOx2F addressed directly and bit addressable typedef unsigned char bdata typedef unsigned short bdata typedef unsigned long bdata typedef signed char bdata typedef signed short bdata typedef signed long bdata uint8b t uintl6b t uint32b t int8b t int16b t int32b t Bit addressable memory is the fastest available memory but it is not battery backed up It competes with stack registers bools data and idata for space The space is valuable for boolean globals and should not be wasted Booleans are not a normal part of stdint h but they are fairly portable When using the Keil compiler the Booleans are stored in the address range 0x20 to Ox2F Keil functions return bools in the carry bit which makes code that s fast and small typedef bit bool define TRUE 1 define FALSE 0 define ON 1 define OFF 0 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Type definitions for internal data 256 bytes in the u AA er 128 bytes addressed indirectly typedef unsigned char idata typedef unsigned short idata typedef unsigned long idata typedef signed char idata typedef signed short idata typedef signed long idata uint8i t uint16i t uint32i t int8i t int16i t int32i t Indirectly addressed internal memory is fairly fast not battery backed up slower than the data in the lower 128 bytes of internal memory Competes with data for space Type defini
92. data collection for support of profile command serOcli c ser1cli c sercli c buffer serial I O for the CLI These files take about 19Kbytes of program space In production meters this code can easily be removed without major changes to the software 2 10 Input Output cal_ldr c load routines for calibration factors eep24C08 c routines supporting the 24C08 EEPROM eeprom c interrupt driven serial EEPROM routines eepromp c high speed polling EEPROM routines eepromp3 c polling interface for uWire EEPROM iiceep c I2C bus interface using the chip s I2C hardware iolite c IO subroutines for use by the calibration loader cal ldr c Icd c initialization configuration read and write routines for LCDs rtc 30 c RTC read write reset and trim routines Ser c baud rate table shared by ser0 c and ser1 c ser0 c initialization configuration interrupt read and write routines for SERO ser1 c initialization configuration interrupt read and write routines for SER1 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation tmr0 c tmr1 c uwrdio c uwreep c LCD_VIM828 Lcd symbols h Lcd vim828 ext c Lcd vim828 31 c Lcd vim828 34 c Main batmodes c defaults c main c main c Meter calphased c ce c ce653X c error c freq c i0653X c meter c misc c pcnt c peak alerts c phase angle c psoft c pulse src c pwrfct c rms c vah c varh c vphase c wh c Util dead c dio h flash c irq c library c math
93. data into the CE code s internal data area and vice versa 5 18 4 CE Data Access is Transparent to the MPU The MPU can now simply read and write the CE RAM No special buffering or access routines are required The demo code for example no longer copies data from the CE s output area to the MPU RAM The Keil C code simply uses the CE s output data It s fast to access the CE s output as PDATA variables so in the demo code the PDATA page register SFR 0xB7 is set to 0x200 The CE output registers begin on a page boundary 0x200 5 18 5 Read only areas in MPU RAM The direct memory access ADC writes automatically to XDATA locations 0x0000 0x000E so these are not stable for memory tests and there is no way to disable the writes Also OxOO0F is a write only alternate location of the chip s version identification 5 18 6 CE Code Location The 6521 also keeps CE code in flash However the CE LCTN register in the 653x series has 6 or 7 bits It s prudent to move the CE code out of page zero Page zero often becomes crowded with data and tables in a banked application and the CE code and data initialization are relatively large tables that are easy to move It is best to place the CE program in a high code bank so it does not compete with the MPU for flash The demo code puts it near the end of the last bank 5 18 7 CE Causes Flash Write Protection Like the 6521 since the CE resides in flash memory there are safeguards that prevent
94. direct Pop direct byte from stack XCH A Rn Exchange register with accumulator Exchange direct byte with accumulator Exchange indirect RAM with accumulator Exchange low order nibble indirect RAM with A Table 6 5 Data Transfer Operations TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation rM M mM a alalal alas rm rms INI wol rm ms rms rm rm dh Mnemonic Description d J TERIDIAN ACALL addr11 Absolute subroutine call o LCALL addr16 Long subroutine call Return from subroutine Return from interrupt Absolute jump LJMP addr16 Long jump SJMP rel Short jump relative addr JMP A DPTR Jump indirect relative to the DPTR Jump if accumulator is zero Jump if accumulator is not zero Jump if carry flag is set Jump if carry flag is not set Jump if direct bit is set Jump if direct bit is not set JBC bit direct rel Jump if direct bit is set and clear bit CJNE AJirect rel Compare direct byte to A and jump if not equal CJNE A data rel Compare immediate to A and jump if not equal CJNE Rn Zdata rel Compare immed to reg and jump if not equal CJNE Ri data rel Compare immed to ind and jump if not equal DJNZ Rn rel Decrement register and jump if not zero DJNZ direct rel Decrement direct byte and ju
95. e Figure 5 1 The occurrence of sags can announce an impending loss of power Since accumulated energy values etc in the meter will have to be saved to non volatile memory in the case of loss of power a sag can be used to initiate data saving operations Some applications may instead save or count the sag event for the purpose of recording power quality data dip ee se sag AJ UO UN Figure 5 1 Sag and Dip Conditions Sag detection is performed by the CE based on the CE DRAM registers SAG THR and SAG CNT SAG THR defines the threshold which the input voltage has to be continuously below and SAG CNT defines the number of samples required to trigger the sag bit see Figure 5 2 SAG THR 84 samples Te Tonn SAG_CNT Figure 5 2 Sag Event When the CE detects a sag that meets the sag conditions specified in SAG_THR and SAG_CNT on one of the input voltage channels it will reflect this in the corresponding bit SAG for single phase or SAG A SAG B SAG C for poly phase of the CE STATUS Word See the CE Interface section in the 653X Data Sheet for details The demo code saves the power registers to the EEPROM when a sag is detected It also has a timer to avoid multiple saves because of grid switching from a recloser or noisy power when the grid starts up See the 5 4 2 3 about the CE BUSY interrupt for more information See Application Note AN651X 044 for more information 5 14 2 2 Temperature Measurement The temperatur
96. e data image CE DAT Both CE CE and CE DAT must be in Intel HEX format i e both files are not in the source format but in the compiled format intel hex These files will be made available from Teridian in the cases when updates to the CE images are necessary To merge the object file old 653x demo hex with CE CE and CE DAT into the new object file new 653x demo hex use the command TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation MYTERI DIAN ce_merge old_653x_demo hex ce ce ce dat 653x_demo hex 2 4 3 BANK_MERGE If using Keil s professional package bank_merge exe is not needed to produce Intel 386 files from banked code Simply go to the pull down hex file selection in the output section of the project configuration of uVision and select i386 Keil s premium OHX51 hex file converter will automatically produce a single intel 386 file containing all the code banks If producing banked code with Keil s standard package the BL51 linker is tightly coupled to the OC51 and OH51 code converters These produce one 64K Intel hex file for each code bank The Signum emulator and TSC s TFP in circuit programmer require that banked code be in a different format a single Intel 386 hex file Bank merge exe is a program that converts Keils multiple hex files into a single Intel 386 hex file Usage bank merge Number of Banks ROM Size Input Name Output An Number of Bank 3 for 6531
97. e following instruction SJMP and all conditional jumps include an 8 bit offset byte Range is 127 128 bytes relative to the first byte of the following instruction Table 6 2 Notes on Program Addressing Modes TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d J TERIDIAN 6 1 1 Instructions Ordered by Function Mnemonic Description Bytes Cycles ADD A Rn Add register to accumulator 1 1 ADD A direct Add direct byte to accumulator ADD A Ri Add indirect RAM to accumulator ADD A data Add immediate data to accumulator ADDC A Rn Add register to accumulator with carry flag ADDC A direct Add direct byte to A with carry flag ADDC A Ri Add indirect RAM to A with carry flag ADDC A data Add immediate data to A with carry flag SUBB A Rn Subtract register from A with borrow SUBB A direct Subtract direct byte from A with borrow SUBB A Ri Subtract indirect RAM from A with borrow SUBB A data Subtract immediate data from A with borrow INC A Increment accumulator INC Rn Increment register INC direct Increment direct byte Increment indirect RAM Increment data pointer Decrement accumulator Decrement register DEC direct Decrement direct byte DEC Ri Decrement indirect RAM Multiply A and B Divide A by B Decimal adjust accumul
98. e output of the on chip temperature sensor TEMP RAW is provided by the CE in CE DRAM location Ox7B The relative chip temperature de taT MPU location 0x20 is derived by subtracting the raw temperature from the nominal temperature TEMP_NOM and multiplying it with a constant factor Thus once the raw temperature obtained at a known environmental temperature is stored in TEMP_NOM deltaT will always reflect the deviation from nominal temperature The scaling is in tenths of Centigrades i e a reading of 75 means that the measured temperature is 7 5 C higher than the reference temperature TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA a 5 14 2 3 Temperature Compensation for Measurements The internal voltage reference of the 653X ICs is calibrated during device manufacture Trim data is stored in on chip fuses The temperature coefficients TC1 and TC2 are given as constants that represent typical component behavior The bandgap temperature is provided to the embedded MPU which then may digitally compensate the power outputs This permits a system wide temperature correction over the entire system rather than local to the chip The incorporated thermal coefficients may include the current sensors the voltage sensors and other influences Since the band gap is chopper stabilized via the CHOP_EN bits the most significant long term drift mechanism in the voltage reference is removed The CE applies the gain
99. e temperature characteristics of the crystal are a mix of constant linear and quadratic effects 32768 5 32768 4 32768 3 32768 2 32768 1 32768 32767 9 32767 8 32767 7 32767 6 32767 5 50 25 0 25 50 Figure 5 3 Crystal Frequency over Temperature TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Me One method to correct the temperature characteristics of the crystal is to obtain coefficients from the curve in Figure 31 by curve fitting the PPM deviations A fairly close curve fit is achieved with the coefficients a 10 89 b 0 122 and c 0 00714 see Figure 32 f fnom 1 a 10 T b 10 T2 c 109 When applying the inverted coefficients a curve see Figure 5 4 will result that effectively neutralizes the original crystal characteristics The frequencies were calculated using the fit coefficients as follows 32768 5 32768 4 32768 3 32768 2 32768 1 32768 32767 9 32767 8 32767 7 32767 6 32767 5 crystal curve fit inverse curve 50 25 0 25 50 Figure 5 4 Crystal Compensation The MPU Demo Code supplied with the TERIDIAN Demo Kits has a direct interface for these coefficients and it directly controls the QREG and PREG registers This interface is implemented by the MPU variables Y_CAL Y_CALC and Y CA
100. eate Project Wizard by selecting Next v1 1v1 1 TERIDIAN Proprietary 24 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation 4 ETAN 71M653X Software User s Guide SEMICONDUCTOR CORP When prompted for the project name to be used type a convenient project name Click Next Project Creation Wizard Please select name and optional comment for your project The project name may consist up to 32 chars and is displayed on debugger s title bar when a project is opened The comment is optional and usually is a brief up to 256 chars description of project features It may be left blank now and set later from PROJECT gt INFORMATION menu Name USERS Comment optional lt Back Nest When prompted for the project directory to be used select an existing folder on the PC Do NOT select any folder in the Wemu51 installation directory Click Next Project Creation Wizard Please select project directory for your project Project directory is a folder for files and subfolders where all project files will be stored Main project settings will be stored in the project configuration file wWemu51 CNF located in the project directory Other files stored in the project directory will be project command startup file wemub1 INI program executable and source code files definitions of custom toolbar buttons various project related data files Note that project directory
101. ecting a Bank for a File Group in Keil C nennen 37 Figure 4 3 Setting Keil s Linker for Bank switched Code 38 Figure 5 1 Sag and Dip Conditions rrr tH ERES HR HER EEEE EE ERR P ERR t RE ERR RPER ERR Epara EE 84 Figure 5 2 Sag EE 84 Figure 5 3 Crystal Frequency over Temperature esce sees de ice a aE eran Ina ra dna Enn ean naue aan des 85 Figure 5 4 Crystal Compensation D gee 86 Figure 5 5 State Diagram of Operating Modes sese nennen nennen nenne entree nns 101 List of Tables Table 3 1 M moiy Map EE 17 Table 4 1 Code Bank Memory Addresses and Availability seen enne 35 Table 5 1 Internal Data Memory Map ni ii tuin nana cubare auae peoe tk EENS PERDE Ya vest e d Ei Ca weave SERE E 43 Table Eni ENEE NRI R 46 Table 5 3 Demo ee 47 Table 5 4 Current Sensing Optons nennen nennen enne ener enne nennen nennen nennen 47 Table 5 5 Compensation FO atures o i c cn cuserecstaceeeesectesagesdecsecenegavicetendaaseeasscacesdsecesneuateeebenctenseaze duqre s sseeshunseseseauarbabane 48 Table 5 6 Power Registers and Pulse Output Features 200 0 eee ceeeeeee sence eeenneeeeeneeeeeeaeeeseeeaeeeseeeeeeeeeeseenaeeeenneeeeneaa 49 TLable 5 Creep ien Le 50 Ei rmeul Br g c 50 Table 5 9
102. ed This section is supposed to help you learn to find and change things in the demo code not just learn theory So please put the demo code sources on a PC now and sit next to it v1 1v1 1 TERIDIAN Proprietary 51 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation MES 5 3 1 Startup and Initialization The top level functionality of the Demo Board is controlled by the high level functions The start up code and main loop is in the main program in main main c It performs the following steps 1 Reset watchdog timer 2 Process the pushbutton PB when in BROWNOUT mode 3 Initialize hardware pointers metering variables UART buffers and pointers CE restoration of calibration co efficients initialization of LCD w HELLO message enabling CE and pulse generators 4 Execute the main_run routine in an endless loop In this loop the background tasks such as metering processing of timers etc are performed In this loop if a command is waiting the command line interface CLI reads it and does it Before the MPU gets to execute the main program it will execute the startup code contained in the STARTUP A51 assembly program This code jumps form the reset vector at address 0x0000 to C_START the startof the initialization code After disabligninterrupts setting the security bit if needed and clearing memory STARTUP A51 jumps to C START in Keil s assembly program init A51 in Keil C51 LIB I
103. ed in the last second For example say the timer turns over from OxFFFE to 0x0002 In signed 16 bit math this is 2 2 or 4 int1 is still used to count VARh with one interrupt per pulse Before version 4 6 intO counted watt hour pulses and int1 counted var hour pulses 5 14 1 21 Battery Modes The IC has several battery modes See the section on the battery mode logic for more information including a state diagram and special problems The demo code displays the main watt hours when the pushbutton is pressed as an example of a typical need in a real meter It does this with full use of the battery modes for minimum power 5 14 1 22 Real Time Performance The main figure of merit is the time to update the registers and display a new result This is about 50 milliseconds when the MPU runs at 5MHz This is faster than earlier demo codes i e 200ms on the 6513 because 1 The data from the CE is not copied 2 CEdatais accessed as PDATA This permits any register to be used as an indirection pointer 3 The calculations use fast floating point logic rather than the custom written 64 bit multiple precision math of some earlier versions TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Me 5 14 2 Firmware Application Selected Tasks 5 14 2 1 Sag Detection A sag is an undervoltage condition that persists for more than one period A shorter undervoltage condition is called a dip see Figur
104. efaults v1 1v1 1 TERIDIAN Proprietary 29 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation I AMAL Ela SEMICONDUCTOR CORP 71M653X Software User s Guide 4 7 3 Manually Controlling the Keil Compiler Settings If the method described in section Adjusting the Keil Compiler Settings is not used the Keil compiler settings can also be controlled manually The target options should be selected in order to adapt the compiler controls properly to the target The uVision compiler environment is started by selecting Programs gt Keil uVision2 uVision should start up and present the following window JS iBi xi i Hello p ision2 C Program Files kKeil Ein Edt view Project Debug Flash Peripherals Tools SVCS Window Help 8smg ee cb5e ux w aalala amla m X WP RISimuator O sl E553 Simulator ca Source Group 1 E HELLO C 7 CH Documentation LA ABSTRACT TXT 1 Examples Hello HELLO C ifndef MONITORSl SCON 0x50 TMOD 0x20 SCON mode 1 8 bit UART enable rcvr TMOD timer 1 node 2 8 bit reload THl reload value for 1200 baud B 16MHz TRL timer 1 run set TI to send first char of UART Note that an embedded program never exits because there is no operating system to return to It must loop and execute forever while 1 Pl 0x01 printf Hello World n Toggle P1 0 each time we print Print Hello World X lBuild target Simulato
105. er data is available for use by the protocol When the AMR system logs off or the AMR interface times out the flags are reset to mark the stable copy invalid 5 14 1 14 Communication between MPU and CE The communication between CE and MPU has evolved since early versions The current best practice is to divide the CE s data into four parts 1 Configuration data set by the MPU and read by the CE This includes gains and other static adjustments 2 Constant data needed by the CE and never adjusted by the MPU The MPU simply sets it It could be fixed stored in the CE s program code but isn t 3 Data read and written by both CE and MPU These usually begin execution as constant values This includes pulse input values set by the MPU which can alternatively be set by the CE s native code and the main gain adjustment for making the meter run at different speed in different temperatures 4 Data written by the CE and initialized by the MPU to zero This includes all of the CE s output values Parts 1 2 and 3 are set to defaults from a table of constants in the MPU s code area Part 1 is saved and restored as part of the EEPROM configuration as an overlay of the constants Part 4 is cleared to zero by the MPU to permit the table of constants to be as small as possible In the 6530 unlike earlier versions reading and writing the CE is transparent because the CE and MPU share the RAM No copy is necessary which saves both MPU time
106. ertcli c this port Seriall RxFlowOn dia EES None none CliNser1cli c i Uint8x t buffer Seriall Tx Transmit a string of any length uint16 tlen none CliNser1cli c SFR Read reads from SFR uint8 ts S08d pc enum Utilsfrs c S P SFR RC i uint8 t s uint8 t enum SFR Write writes to SFR c set uint8 tc clr SFR RC Util sfrs c start tx ram sends RAM string out PC UART uint8 tx c none cli io c start tx rslt sends ROM string out PC UART uint8 tr c none cliNo c This counts down the software stm run timers when called from the Void void Util stm c main loop Starts a software timer If restart is zero the timer stops Uint46 t otherwise it continues volatile Sis tick count uint8 t e stm_start indefinitely When a timer e uint16x_t Util stm c eege restart void code P expires its function is run fn ptr void cnt ptr Timers count down and are P deallocated if they cease to run Uses a count pointer from start Volatile uint16x t stm stop to identify which software timer void Util stm c cnt_ptr to stop stm wait Waits for the passed numberof Uint4e t void Utilstm c e clock ticks Steiere d een EL NETTE ITE uint6 t UtilVibrary c strlen x returns length of string in xdata uint8 tx src uint16 t UtiMibrary c Sub8 4 r wh ce register r CE units ioc r long none Util math c sub8 8 r0 r1 register rO register r1 uint8 tx x uint8 tx none Util math c
107. esi ins n ta ress sss r sss h nere nE nasa nenne renes 35 4 9 3 Software Tool Versions ener nnn en entente tten s enne nr sl sns nnn nnns 36 v1 1v1 1 TERIDIAN Proprietary 4 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation MATERI DIAN 71M653X Software User s Guide SEMICONDUCTOR CORF 4 9 4 setup of the Compiler Project siririn eara ani dee ERES EE e deg d 36 4 9 5 SEENEN 37 4 9 6 Bank Switching COG Ht 37 4 9 7 Page Table Setup and Debug c c cecccctscesscenecrocarvessenetesseeceendtanseeasdenesevcoceeseecereeavecernesness 37 4 9 8 Producing a Banked Hex File 39 4 9 9 Placing Interrupts in Banked Code 39 4 9 10 Calling Banked Functions via Function Pointers eeeseeeeiesriieeriereriresriresriireerrenesinnsrns 39 4 9 11 Putting Constants in Banks enm eene enr en tenen nnne nns 40 4 9 12 Write Protecting Flash in the G nn 40 4 10 Project Management Tools 1eseeeeeeee sienne eene nnne nnn nennen nnn arret nri nn nnns 41 4 11 Alternative Compilers 1 1ocoeec cuite eene ecu cuti teca ame REESEN CEEEEEEEeEEE 41 4 12 Alternative EdilOrs i occiiuecciiuiimaci iiia neci annasan nuut VEER SEEEEEEESEEEEEERESESEEEERSSEEEEEE ER 41 4 13 IECH ICT 42 5 Demo Code Description Seege 43 5 1 80515 Data Types and Compiler Specific Information eese 43 5 1 1 RECKEN 43 5 1 2 C
108. et tab and enter the values in the fields as shown above Confirm by clicking OK Options for Target Simulator Large variables in XDATA El Large 54K program v1 1v1 1 TERIDIAN Proprietary 31 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation Me SEMICONDUCTOR CORP 71M653X Software User s Guide Under the Output tab select a name for the executable object file with abs extension in the field labeled Name of the executable and check the fields by Debug Information Browse Information and Create HEX File This will guarantee that high level source information will be embedded in the output file Select HEX 80 as the output format as shown below Options for Target Target 1 h 21x Device Target Output Listing C51 A51 BL51 Locate BUS Misc Debug Utiities Select Folder for Objects Name of Executable ee 3 main abs Create Executable 45513 main abs v Debug Information IV Browse Information J Merge32K Hexfile ile HEX Format Jugen x C Create Library 6513_main abs LIB Create Batch File r After Make v Beep When Complete Start Debugging Run User Program 1 Browse Run User Program 2 Browse OK Cancel Defaults Under the C51 tab provide path names for the source files to be included as shown below Options for Target Target 1 2x Device Target Out
109. ets up transmission buffer and SERIAL_PORT SERIAL_RC lo sercli c starts transmission port uint8_tx data buffer uint16_t len enum Serial_TxLen returns the number of bytes left SERIAL PORT uint16_t lo sercli c to transmit port i Receive a string up to a Uint8x_t buffer uint16 t Sertalo GR N maximum length uint16 tlen length SEET TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Se Function Routine Name Description Input Output File Name received Serial0 CTx Transmit a string up toa Uint8x_t buffer uint16_t Cli serOcli c maximum length uint16 tlen length sent Uint8x t buffer Serial0_Rx Receive a string of any length uint16_t len none Cli serOcli c SerialO RxFlowOff Foren DEE None none Cli serOcli c this port SerialO RxFlowOn iba an AON SdBHOR IS None none Cli serOcli c f Uint8x t buffer gt SerialO Tx Transmit a string of any length uint16 tlen none CliNserOcli c A uint16 t Seriall CRx Resolver sing Upto a pines puller length Cli sertcli c maximum length uint16_t len received i Transmit a string up to a Uint8x_t buffer uint16 t cde ces maximum length uint16_t len length sent Piper e Uint8x_t buffer e Seriall Rx Receive a string of any length uint16 tlen none Cliser1cli c Seriall RxFlowOff Fore SuSE SO URRBenEOD None none Cli s
110. evel as the main loop For example this permits preemptive software timers that run at the same priority as the main loop All interrupt service routines ISRs must be declared small reentrant Also all routines called by ISRs must be re entrant as well Priorities are set using the IPO and IP1 SFRs as follows e IPO SFR OxAQ9 Ox1A 0001 1010 e IP1 SFR 0xB9 0x2C 0000 1100 This results in the priority assignment shown in Table 5 11 Affected Interrupts 0 External interrupt UART 1 interrupt 0 DIO Timer 0 interrupt Ext 2 comparators External interrupt Ext 3 CE_BUSY 1 DIO Timer 1 interrupt Ext 4 comparators UART 0 interrupt Ext 5 EEPROM Ext 6 XFER BUSY RTC 1S Table 5 11 Interrupt Priority Assignment 5 4 2 1 Pulse Counting Interrupts The pulse count code is in meter pcnt c There are four digital pulse outputs and these outputs share a pin with DIO 6 7 8 or 9 DIOs from 0 the push button to 12 can be configured to generate interrupts gate a timer or count a timer See the data sheet D O RPB DIO RRX starting at 0x2009 The pulse counting interrupts count Wh and VARh pulses by setting up intO and int1 generic external interrupts to read the Wh and VARh pulse outputs on DIO 6 and DIO 7 Although the demo code does not do it the timers could also be used to count pulses especially at high rates The demo code does not currently use timer 1 and uses ti
111. for the main loop 5 14 1 2 Synchronization Interrupts do the work that needs immediate attention then set a flag or count to start code that runs in the main loop To keep the main loop simple the flag the routine to run in the main loop and the interrupt code should be defined in the class s c file The main loop should just call the run routine continually Software timers Utilstm c h are started by an interrupt that counts every 10 milliseconds in real time In the main loop stm run decrements software timer variables and runs the associated callback routine if a timer expires stm run calculates the real interval since its last invocation in order to reduce jitter The code also has a shared calibrated delay loop routine in lO delay c It s calibrated in the normal clock modes and runs at reasonable rates in all clock modes including brownout mode State machines are invoked in the main loop The main loop will just call a run routine with no parameters and no returns No state variables or other state machine logic will be defined in the main loop 5 14 1 3 Bank Switching The code has to be able to grow to fill the 128KB to 256KB memory space of this chip So it is bank switched Keil s standard bank switching schemes were all tested for speed and then the fastest was left installed See Util L51_BANK A51 for the modified Keil assembly file that performs the bank switching The selected Keil scheme sets the ba
112. g that helps a programmer to read and understand unfa miliar code TERIDIAN Semiconductor recommends using such an editor to read understand and modify demonstration code Tag jumping is a feature that is not supported by the Keil uVision editor This is how tag jumping works 1 A tag file generator program is run on some directories full of c or h files TERIDIAN Semiconductor recommends placing the tag file generator in a DOS batch file in the same directory as the project s make file Wattmeter demonstration code includes such a batch file T BAT To run a batch file double click it in windows explorer A DOS batch file is just an ASCII file like a C file containing DOS commands DOS commands are described at http www computerhope com msdos htm 2 The tag file should then be copied to convenient places for a text editor TERIDIAN Semiconductor recommends copying the tag file into each source code directory In that way the default tag file location for most editors becomes just Mags for all projects and multiple projects do not conflict Copying the tag file can be an automatic part of the DOS batch file that generates the tag file 3 Itis easiest if Windows explorer opens C files automatically with the editor when they are clicked To do this change file associations See Windows help 4 Inside the editor select a subroutine name or variable then use the editor s tag jump feature The editor immediately opens
113. gic Operations TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d J TERIDIAN Description Move register to accumulator MOV A direct Move direct byte to accumulator MOV A Ri Move indirect RAM to accumulator MOV A data Move immediate data to accumulator MOV Rn A Move accumulator to register MOV Rn direct Move direct byte to register MOV Rn data Move immediate data to register MOV direct A Move accumulator to direct byte MOV direct Rn Move register to direct byte MOV direct direct2 Move direct byte to direct byte MOV direct Ri Move indirect RAM to direct byte MOV direct data Move immediate data to direct byte MOV Ri A Move accumulator to indirect RAM MOV Ri direct Move direct byte to indirect RAM MOV Ri data Move immediate data to indirect RAM MOV DPTR data16 Load data pointer with a 16 bit constant MOVC A A DPTR Move code byte relative to DPTR to accumulator 2 2 2 2 4 2 3 3 4 4 3 3 5 3 3 3 MOVC A A PC Move code byte relative to PC to accumulator Co MOVX A Ri Move external RAM 8 bit addr to A MOVX A DPTR Move external RAM 16 bit addr to A MOVX Ri A Move A to external RAM 8 bit addr MOVX DPTR A Move A to external RAM 16 bit addr PUSH direct Push direct byte onto stack POP
114. gure current the best available way If Irms A lt noise floor of current measurement amp amp Vrms_A gt 0 Irms A va0sum Vrms A If Irms N lt noise floor of current measurement amp amp Vrms A gt 0 Irms B vaisum Vrms A Do the creep calculation If Vrms A Vthreshold creep mode set element A and B s voltage current and watts to zero else if Irms A Ithreshold creep mode set element A s current and watts to zero if Irms B Ithreshold creep mode set element B s current and watts to zero Set the pulse outputs Sum positive values to normal registers negative values to export registers 5 14 1 17 6534 Calculation of VA IA VB IB VC IC Option Equation 5 The global flow of Wh calculation is an important optimization and will be selected by compile flag Vrms_A sqrt vOsqsum from the CE Irms A sqrt i0sqsum from the CE etc for B and C Volts and Current are now available for all elements Figure Wh VARh and VAh for this accumulation interval If Vrms A Vthreshold i e there s no voltage probably tampering Figure watts with a default voltage but don t lie about sensed voltage Vrms A 0 if abs Irms A gt IThreshold vaOsum Irms A defaultV wOsum va0sum else set them to zero varhO 0 else TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN Get Wh wOsum and VARh var0sum from CE va0sum sqrt wOsum var0sum endif Repeat for elements B
115. h_applied Wh_measured V_gain VARh_applied VARh_measured V_gain i_gain is the real part of multiplying the rotation matrix by the linear adjustment vector i_gain cos Phi Wh_Applied Wh_measured V_gain sin Phi VARh_Applied VARh_measured V gain But the applied signal s VARh applied 0 so that term is negligible i gain cos Phi Wh Applied Wh measured V gain Further cos Phi Wh measured VAh measured So substituting one gets a classic fast current calibration equation for a meter i gain Wh applied VAh measured V gain VAh measured is easy to calculate and the meter s signal processing gives it good linearity and repeatability so we keep it and calculate it VAh measured sqrt Wh measured 2 VARh measured 2 The CE s value for unity is 16384 Substituting TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA ce_i_gain 16384 Wh_applied VAh_measured V_gain See the source file meter calphased c for more details 5 4 3 4 EEPROM Read Write The interrupt code is eeprom_isr in io eeprom c The read and write commands set variables and then start the interrupt On each interrupt the code reads or writes the next byte to send or receive to the EEPROM data register EEDATA SFR Ox9E and then writes a command to the command register EECTRL SFR Ox9F For information on the sequence and content of bytes see the data sheet for an Atmel AT24C256
116. has to have file create and write rights We strongly recommend to avoid use of debugger s installation directory C Program Files Signum Systems Wemu51 as a project directory Cancel When prompted for the emulator to be used select ADM51 Emulator Click Next Project Creation Wizard Please select target you want to use in your project from the following list of available targets USP 51 In Circuit Emulator emm ES S Tag DoCD DCD on Chip Debug System Sim 8051 Simulator lt Back JL Next gt Cancel v1 1v1 1 TERIDIAN Proprietary 25 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation HAMA Se SEMICONDUCTOR CORF 71M653X Software User s Guide When prompted for the communication device to be used select USB ADM51 Click Next Project Creation Wizard Please select communication device for your project from the following list of detected devices Detected Devices USB device properties ADM51 41807 USB ver 1 10 IceServer host Name or IP address When prompted for the processor to be used select the correct IC Click Next Piana vg deen you ward towne in you gel ors hes Sollen tal of poemos A yes Carnet let eot soc v rana piama adata Click Finish v1 1v1 1 TERIDIAN Proprietary 26 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation 71M653X Software User s Guide 4 6 INSTALLING THE KEIL COMPILER Af
117. he fast calibration described in the DBUM Command Line 23KB Y Y Text based commands give access to CE data RAM Interface CLI IO registers Includes on line help No profile or load features Save registers 0 75KB Y Y Saves power and error registers on sag detection when sag occurs Save to flash 0 9KB N opt N opt Compilation option to save calibration error and memory power register data to internal flash When a flash area is used up it is marked and the next one is used When all areas are used up an error is recorded and write operations are inhibited Save to and 0 7KB Y Y Saves and restores calibration error and power restore from register data to and from EEPROM EEPROM When an EEPROM area is used up it is marked and the next one is used When all areas are used up an error is recorded and write operations are inhibited Checksum 0 2KB Y Y Each revenue affecting data area is protected by a simple checksum Error recording 0 4KB Y Y Errors are recorded Error data is protected by a and saving checksum The time stamp minute hour day and month of assertion and the bit number of the five most recent errors are saved Microwire 0 2KB N opt N opt Compilation option EEPROM DC EEPROM 0 2KB Y Y For an Atmel AT24C256 Table 5 9 Calibration and Various Services 5 3 PROGRAM FLOW This section should be read with a PC that has demo code s source code install
118. he cal begin routine starts the calibration state machine by setting the flag cal flag to YES after setting the calibration factors to default values recording the calibration temperature calculating the temperature compensation coefficients and setting the counter cs for calibration cycles The calibration state machine is the routine Calibrate in meter calphased c called by meter run in meter meter c After calibration is started by cal begin meter run calls Calibrate once per accumulation interval when new metering data is available Calibrate uses the variable cs count of seconds to control the stabilization delay measurement time and adjustment phase cs counts down 1 If cs gt Scal The state machine waits for the CE to settle after the unity gain and temperature compensation data are loaded in the routine cal begin 2 Ifcs Scal The variables for cumulative V Wh and VARh are cleared 3 IfO 2 cs lt Scal For V Wh and VARh are added to the variables Using two accumulation intervals is enough because it covers both chop polarities of temperature measurements 4 Ifcs 0 This signals the end of the calibration measurements are then used to calculate and set the calibration coefficients for phase voltage and currents in CE DRAM 5 The adjustments are saved to nonvolatile memory The calibration is fast because the measurements are collected from all the elements simultaneously during the measu
119. heck for bad data When the meter starts up it uses the first copy with good data Many power grids have reclosers circuit breakers that reset automatically several times When a recloser trips the power grid rapidly switches from two to ten times The time between reclosings varies but is usually near 100 milliseconds Some utilities simulate recloser operation and test meters for anomalies Some meters have anomalies from recloser operation The demo code copes with reclosers by saving registers on the first power failure and then ignoring following power failures for up to 1 3 second It ignores them by testing a counter sag_timer for zero before saving registers It restarts the counter when the CE starts up and each time power fails It counts down on normal ce busy interrupts This interrupt occurs very often 2500 times per second So the interrupt saves MPU time by running all the logic only 1 8 of the time It has a counter 5 4 2 4 PLL ISR When V1 goes below the comparison voltage the meter IC switches to battery power At the same time the IC s electronics automatically takes action to reduce the power use It switches off the CE ADCs and phase locked loop and switches the MPU clock from the phase locked loop to 28kHz 7 8 of the crystal rate but able to operate the serial ports at 300 BAUD It then sets the PLL FALL bit which causes an interrupt The interrupt code p11 isr in main batmodes c tests to see if a batte
120. hen an extended linear address record is read the extended linear address stored in the data field is saved and is applied to subsequent records read from the Intel HEX file The linear address remains effective until changed by another extended address record The absolute memory address of a data record is obtained by adding the address field in the record to the shifted address data from the extended linear address record The following example illustrates this process Address from the data record s address field 2462 Extended linear address record data field FFFF Absolute memory address FFFF2462 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 4 9 WRITING BANK SWITCHED CODE The 80515 microcontroller contained in the 71M653X Energy Meter chips can only address 64Kbytes of code This section explains how to design firmware with more than 64K of code for the 71M653X Energy Meter chips 4 9 1 Hardware Overview In the 71M6531 there is a 32K area from code address 0x0000 to Ox7FFF The code in this area is always available to the 8051 This area is common and is the same memory area as bank 0 Since it is always present it never needs to be switched into the bank area A 32K bank is selected by writing the bank s number in the register FL BANK an SFR at OxB6 After this the bank s code is visible to the MPU in addresses 0x8000 to OxFFFF The 71M6531 has four 32K banks 128K bytes total
121. her special coding is needed In the demo code the CE code is referenced from the Meter ce c ce c could not be placed in the last bank with the tables because it also has a very fast interrupt ce_busy_isr so ce c was placed in common Also the CE code is in the last bank so the code in ce c had to explicitly switch it in to read it Designers must be careful that any code in common is smaller than the data table Some systems may need a library routine in common to copy part of the banked data to RAM for use by banked code Next the data should be located in the desired bank using compiler and linkers BANK commands See the compiler and linker command figures 0 2 0 3 The code using the banked data should include Util bank h which defines switchbank to access banked data In the code that accesses the data the bank must be switched in For example when the demo code copies the starting data for the CE ce init in Meter ce c it executes the following code switchbank BANK CE memcpy cer int32x t CE DATA BASE int32r t amp CeData 0 uint8 t Oxff amp NumCeData i switchbank sets the bank register without side effects for other bank switching It is defined in Util bank h BANK CE is the bank number containing the CE initialization table in Main 6531Yoptions h or Main 6534YOptions h memcpy cer copies 32 bit words from code to CE memory CE DATA BASE is the start of CE memory 0x0000 in
122. high volume production an occasional EEPROM will cause bus contention lt is possible to reduce the contention current by placing a 1K resistor in the data line but it s even better to use non contending driver software using the IC s two wire electronics 5 4 2 0 Timer Interrupt timerO of the MPU is the main system timer IO tmr0 c h The demo code has it call a callback routine so that the timer code can be applied to any need Also the timer code can automatically run the timer as a periodic timer In the demo code timer 0 is used to generate a 10ms timer tick which is adjusted for the MPU s clock speed The timer tick variable tck_cnt is started from and used to update the software timers See Util stm c The software timers are updated by the stm run function in the main loop of the background task Eight software timers can be simultaneously running If itis desired to change the system timer to timer1 the include file called out in stm c has to be changed to tmr1 h timer1 is unused and may be used for other purposes Tested code to operate timer 1 is available in the extended code release Various macros are available to control the timers e tmr start A B C has three parameters A is the timer time the number of ticks to reload on each interrupt B is true if the timer should restart itself when it expires C is a pointer to a reentrant function e tmr stop stops the timer e tmr running returns TRUE if the
123. ialized code memory in another bank It will execute until the program counter wraps around to zero and begins executing the reset vector 4 Place a break point near the end of the other bank to catch the erroneous execution 5 After trapping the error set the program counter to the address of a RET instruction and single step The code will return to the code that called the wrong bank 6 Fixthe calling routine and all similar problems v1 1v1 1 TERIDIAN Proprietary 38 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA SEMICONDUCTOR CORP 4 9 8 Producing a Banked Hex File The BL51 linker and its associated hex converter produce a separate Intel hex file for each bank These files end with names such as H01 for bank 1 H02 for bank 2 etc The emulator and the production programmer expect a single Intel 386 hex file with a HEX ending TSC s demo CD ROM has a utility called bank merge exe It runs in a DOS command window and merges the bank files from Keil s hex converter into one Intel 386 hex file This can be placed in the build automatically how Another manual solution is to erase the flash load the abs file to an emulator and then use the file gt save range All menu selection to save a copy of flash as an Intel hex file When using Keil s Lx51 advanced linker the output dialog contains a pull down list of hex formats Select the i386 hex file option The emulator s verification option is
124. id meter phase_angle c psoft_init inializes sonare pulse Void void Meter psoft c outputs Generates two additional pulse psoft_out outputs Call from ce busy isr void void Meter psoft c The inputs are watt hours as generated by the CE and set the extra pulse generators to blink at the same rate as CE int32 t pulse3 in EES EES pulse outputs with the same int32_t pulse4_in void Meter psoft c units This should be called each time a new accumulation interval has data put char puts character into CLI buffer uint8 t idata c none cli io c Read Trim reads the trim value for selected Shum eTRIM select S08 Meter io653x c trim word rms I lcd Displays current Uint8 t phase void Meter rms c rms v lcd Displays voltage Uint8 t phase void Meter rms c RTC Adjust Trim Safely sets the compensation Bool clr cnt rona lO rtc_30 c variables int32_t value Calculates and adjusts the RTC Compensation temperature compensation for None none lO rtc_30 c the RTC rtc isr Interrupt code to adjust clock agi void lO rtc_30 c each second RTClk Read reads current values of RTC none none IO rtc_30 c RTClk Reset resets the RTC none none lOvtc 30 c RTC Trim a eee natae none int32_t ppb lO rtc_30 c compensation using Y_Cals RTClk Write writes sets to RTC none none IO rtc_30 c Returns the floating point CE s2 units value closest to the uint8x_t register float util math c TERIDIAN Proprietary Copyright 2005 200
125. ied with the PK51 kit http www keil com c51 1x51 asp is capable of code compression by up to 896 by rearranging code segments for AJMP and ACALL usage All executables supplied with the Demo Boards were generated using the conventional compilers and linkers from Keil That way the supplied sources compile and link to the same code size as the pre compiled object files If it is desired to add more options to the source code than the BL51 linker can pack into a given code space the LX51 Enhanced Linker should be considered TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation A 5 DEMO CODE DESCRIPTION 5 1 80515 DATA TYPES AND COMPILER SPECIFIC INFORMATION 5 1 1 Data Types The 80515 MPU core is an 8 bit micro controller MPU thus operations that use 8 bit data types such as char or unsigned char work more efficiently than operations that use multi byte types such as int or long The Keil C51 compiler supports ANSI C data types as well as data types that are unique to the generic 8051 controller family Table 5 2 lists available data types Please refer to the Keil Cx51 Compiler User s Guide for more details Various types of address spaces are available for the 80515 MPU core of the 71M653X and in order to utilize the various memory space types efficiently the Demo Code uses variable type definitions typedefs presented in this chapter To understand the data types it helps to examine the i
126. ing from an actual calibration can be inserted into the object file e CE MERGE EXE allows combining the object file with an updated image of the CE code e BANK MERGE EXE combines the hex files the Keil tools provide for each code bank All utilities are executed from a DOS window DOS command prompt To invoke the DOS window the command prompt option is selected after selecting Start All Programs Accessories The GUI subdirectory contains an unsupported MS Windows NET implementation of a FLAG hand held unit 2 4 1 D MERGE Many changes to the firmware s defaults can be made permanent by merging them into the object file The first step for this is to create a macro file macro txt containing the commands adjusting the I O RAM or other defaults such as the following commands affecting calibration 182416381 192416397 E4237 The d merge program updates the 653x demo hex file with the values contained in the macro file The d merge program must be in the same directory as the source files or a path to the executable must be declared Executing the d merge program with no arguments will display the syntax description To merge the file macro txt and the object file old 653x demo hex into the new object file new 653x demo hex use the command d merge old 653x demo hex macro txt new 653x demo hex 2 4 2 CE MERGE The ce merge program updates the 653x demo hex file with the CE program image contained in the CE CE file and th
127. ing system www Keil com This is completely supported by Keil a major compiler vendor for 8051s and Signum the emulator vendor Code can be ported from non banked projects and full symbolic banked debugging is available Keil s scheme puts a page table in common memory Code calls an entry in the page table Each entry is a bit of code that switches to the subroutine s bank and jumps to the subroutine in the bank Keil s linker automatically produces the page table In Teridian s demo code the size of this table is less than 1K Code using the page table is slower than native 16 bit code because it has to set the page register TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDIAN SEMICONDUCTOR CORP 71M653X Software User s Guide Interrupts must start in the common non banked area because the bank register could have any value Calls via function pointers e g callback routines are supported but need to be made global and mapped to their caller with the linkers overlay functions Keil s linker often omits callback routines from the page table when it optimizes the page table and this causes incorrect operation Constant values have to be accessed from the same bank or common code When accessed from common code the bank has to be switched manually with switchbank a subroutine in the bank logic 4 9 3 Software Tool Versions The development software used with these examples
128. ings stored in the 653x UV2 file Directory structures and drive names vary from PC to PC The settings for the compiler can be adjusted using the following method 1 Select target1 in the leftmost window 2 Select project from the top menu and then select options for target 1 3 Selectthe C51 tab 4 Click the button right next to the Include Paths window Three paths will be listed pointing to meter projects meter projects demo and meter projects demo header files 5 f necessary delete these path entries X button and replace them with the corresponding path entries for your PC O button The dialog box should look like shown below After making the necessary changes the project file 653X demo UV2 should be stored Options for Target Target 1 Device Target Output Listing C51 451 BL51 Locate BL51 Misc Debug Utilities Preprocessor Symbols Define Undefine Code Optimization Warnings Warninglevel 2 Y Level 9 Common Block Subroutines M Bits to round for float compare 3 Emphasis Favor size Global Register Coloring d be ef Don t use absolute register accesses Keep variables in order IV Enable ANSI integer promotion rules Include main EE 2 cli 6513 Meter util io cli E Paths Misc Controls Compiler LARGE OPTIMIZE D SEI BROWSE INCDIR main PI Act 6513 Meter M t Nio cli control DEBUG OBJECTEXTEND string Cancel D
129. ion S OMOIOT La SEMICONDUCTOR CORP 71M653X Software User s Guide Chopping of 0 06KB Y Y Control of the chopping bit VREF Temperature 0 1KB Y Y Digital compensation using the GAIN_ADJ input of compensation of the CE based on linear and quadratic temperature VREF coefficients RTC compensa 0 2KB N opt N opt Optional compensation of RTC by counting cycles on tion using mains mains frequency Correction does not occur when frequency measurement is inhibited by low voltages Full RTC 0 2KB Y Y 2n order compensation of RTC to 4ppm using compensation temperature Temperature based correction does not occur when the ADC mux is off line Temperature 0 0K Y Y Provides difference from calibration temperature to measurement precision of 0 1 C when calibrated Table 5 5 Compensation Features Wh imports Y Y Standard option of milliwatt hours 999 999 Pulse output for 0 23KB Y Y Standard option of 1 kh pulse on both DIO 6 and DIO Wh imports 2 VAn pulse output 0 25KB Y Y Volt amperes 1 kh pulse Wh equation 0 0 2KB N opt N 1 element 2 wire Wh equation 1 0 2KB N opt N 1 element 3 wire Wh equation 2 0 2KB Y N 2 element 3 wire delta Wh equation 3 0 2KB N N opt 2 element 4 wire delta Wh equation 4 0 2KB N N opt 2 element 4 wire wye Wh equation 5 0 2KB N Y 3 element 4 wire wye Frequency 0 1KB Y Y Inhibited if freq gt
130. ion If the comments in OPTIONS H are not clear feel free to use grep or another code searching tool to locate where the flags occur in the code While TERIDIAN has made a good faith effort to test representative combinations of compile flags there are too many combinations to test exhaustively When OPTIONS H is changed in the all options code there are three usual results Either the build complains that it needs some subroutines or it complains that it has too many subroutines or it is good When it needs subroutines enable the option flags for the needed subroutines When it has too many subroutines try to disable the option flags for the unneeded subroutines On smaller ICs if the resulting build is too big to fit the available program memory then more features must be disabled Usually this is not an issue on the 653x series Usually the option flags are tested either right after options h is included in a file or around the subroutines 5 11 2 Register Definitions Register definitions can be found in the following files e REG80515 H Register definition for the 80515 MPU core e REG653X H Register definition of 653X SFRs and I Os es O653X H and IO653x c I O RAM register definitions e CE653X H and CE653X C CE data and structure declarations 5 11 3 Other Include Header Files Other Include Header files are e CLI H Result code and Common ASCII code definition used for CLI e HELP H HELP message prototype declaratio
131. ith iomerge c include batnodes h battery mode logic include wd h software watchdogs include stn h software timers include ce h compute engine hardware access include ser0 h uart 0 hardware access include serl h uart 1 hardware access include rtc h real time clock hardware access include lcd h liquid crystal display s include neter h meter logic EI E Fies G ws 4 eg o dior ri x H H 3 e 3 TD T Nsuita Command FindinFiles lL b For Help press F1 NUM RW The Project Workspace screen on the left side of the window shows the main components of the source CE CLI IO Main Meter Utils in folders Folders can be opened by clicking on the plus sign next to them Opening the folders will display the source files associated with them v1 1v1 1 TERIDIAN Proprietary 28 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation q ATER DIAN 71M653X Software User s Guide SEMICONDUCTOR CORP It should be noted that not all header files are physically present in the project directory The files absacc h string h ctype h and setjmp h are provided by the compiler manufacturer and they are located in the Keil C51 INC directory 4 7 2 Adjusting the Keil Compiler Settings Once the Keil compiler is installed the most convenient method to start the project is to double click on the file 653x UV2 or 653x UV3 This will start the Keil compiler with the proper sett
132. ld not be regarded as production code The Demo Code and all its components with the exception of the CE code are only example code and the use of it is as is and without implied guarantees Customers may use the Demo Code as a starting point at any given released revision level but should keep themselves informed about subsequent revisions of the Demo Code Demo Code revisions may not be directly compatible with previously released revisions and or embedded software used by customers Customers need to adapt the Demo Code or other example code supplied by TERIDIAN Application Engineering to their own code base and in this context TERIDIAN Semiconductor can only provide indirect assistance and support This Software User s Guide provides information on the following separate subjects e General software architecture and minimum requirements Design Guide e Memory model programming test tools Design Reference e Demo code structure data flow functions Demo Code Description e Installing and using the EEP compiler ICE Tool Installation Guide e Understanding and using the 80515 micro controller 80515 Reference 1 14 USING THIS DOCUMENT The reader should have a basic familiarity with microprocessors particularly the 80515 architecture firmware software development and power meter applications Prior experience with or knowledge of the applicable ANSI and or IEC standards will also be helpful This document presents the feat
133. led in Meter io653x c If an interrupt calls code in a bank as above it must save and restore the bank switching register FL_BANK Keil s Lx51 advanced linker has an option to automatically save and restore the bank register in an interrupt TSC s L51 bank a51 code provides the necessary symbols 4 9 10 Calling Banked Functions via Function Pointers In a banking system functions placed in function pointers cannot have the word static in front of their definition They must be global Also the linker must be informed of the actual caller of the function in the function pointers For example in the TERIDIAN Demo Code the software timer module Util stm c calls many routines There is also an interrupt for hardware timer 1 that calls the software timer s interrupt code This linker dialogue tells the linker the true relationship The command to the linker is caller callee or caller callee 1 callee 2 See the linker command figure 0 3 Why do this If a function pointer points at a function s entry in the page table the function pointer can be executed from any bank at any time So in theory function pointers are supported via the page table TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e In practice the Keil linker tries to save space in the page table So it only puts global functions into the page table if they are in a bank area and are called from outside the bank
134. line buffer c1i calls routines like get upper CLI io c to get characters from the line buffer While the idea is simple the code is surprisingly large and resists simplification 5 4 3 3 Auto Calibration The auto calibration is an automated version of the fast calibration discussed in the DBUM This section describes the code then derives the mathematics Before the calibration starts the applied ideal voltage and current have to be entered by the user in the MPU memory locations VCAL and ICAL TSC s experience is that optimal results are obtained with the default two second calibration but this time can be extended by writing the number of accumulation intervals to SCAL The procedure of this calibration method is the same as for the fast calibration procedure as described in the DBUM The tangent of the ratio of VARh and Wh determines the phase angle The ratio between applied ideal and measured voltage determines the voltage gain However whereas the calibration spreadsheet uses extensive trigonometric TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation A a functions the same equations were rewritten in the Demo Code to use much simpler mathematical operations that are closer to the capabilities of the MPU As with the procedure presented in the DBUM a signal with the described voltage and current should be applied to the meter and held constant during the auto calibration process T
135. mer 0 as described below in the section on the timer interrupt TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation A Once per second the RTC_1_SEC interrupt runs It calls a pulse counting routine that takes the counts from the pulse interrupts and adds them to global pulse counts These pulse counts roll over at one million 1x10 This step is needed to synchronize the pulse counts with real time since most tests of the pulse counts compare them against real time TSC deprecates pulse counting because the direct CE registers are more precise and easier to synchronize The accuracies are the same because the pulse outputs are driven from CE register data 5 4 2 2 FWCOLO and FWCOL1 These occur when the CE is active and there s an attempt to erase or write to flash TSC s demo code has no flash write routines in the standard release so these interrupts are directed to a stub that detects spurious interrupts 5 4 2 3 CE BUSY Interrupt The CE_BUSY interrupt ce_busy_isr in meter ce c detects mains power failure by reading the CE s status If there s a power failure it saves two copies of the power registers Why two copies The meter cannot predict when a power failure will occur So it always has to have valid data The first copy is updated by the meter calculations The second is copied after the first one is done So one copy or the other always has good data Both copies have ac
136. mory used to communicate with the MPU meter io653X h defines the memory mapped registers of the 653X chips util reg653X h defines the special function registers of the 653X chips Util reg80515 h defines the registers common to TSC meter chip 8051s util stdint h defines standard integers for TSC meter chips using 8051s OPTIONS H TSC normally can provide two versions of the demo code One version has optional code removed using the utility SUNIFDEF EXE This code is small and easier to read but inflexible In this code options h documents the features that are present and absent in the code TSC s software engineers develop meter code from a single code set with optional configurations the all options version It is more complex and has files for most TSC meter ICs all meter equations and other optional features that TSC has developed It is usually provided as is with minimal or no testing The two code sets are validated during release by assuring that both code sets produce the same binary when compiled with the same compiler TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA The file OPTIONS H controls entire features in the all options code set When an option is 1 it means that the feature is to be compiled and linked into the build The idea is that by adding or subtracting features a customer or TSC application engineer can quickly tune the code to approximate a desired meter configurat
137. mp if not zero No operation Table 6 6 Program Branches Description gt 1WIM WLW OW vlv v WIM DO OD hD PM W NM gt O2 AJAJ HR 5 Ei RI AIAJ OO W WI NIV AIV HRI o Clear carry flag Clear direct bit Set carry flag Set direct bit Complement carry flag Complement direct bit AND direct bit to carry flag AND complement of direct bit to carry OR direct bit to carry flag OR complement of direct bit to carry Move direct bit to carry flag Move carry flag to direct bit Table 6 7 Boolean Manipulations TERIDIAN Proprietary NI MPMI MI PM PLM gt hM gt Ph Copyright 2005 2008 TERIDIAN Semiconductor Corporation WIM MPMI MM W gt oo eo d J TERIDIAN Mnemonic 6 1 2 Instructions Ordered by Opcode Hexadecimal Mnemonic Mnemonic NOP JB bit rel JC rel AJMP addr11 AJMP addr11 AJMP addr11 LJMP addr16 RET ORL direct A RRA RLA ORL direct data INCA ADD A data ORL A data INC direct ADD A direct ORL A direct INC RO ADD A RO ORL A RO INC R1 ADD A R1 ORL A R1 INC RO ADD A RO ORL A RO INC R1 ADD A R1 ORL A R1 INC R2 ADD A R2 ORL A R2 INC R3 ADD A R3 ORL A R3 INC R4 ADD A R4 ORL A R4 INC R5 ADD A R5 ORL A R5
138. nd el cei 61 5 4 3 6 Power Factor Measurement sss eene enne nennen nennen 61 5 4 4 Ateenale lote MA UIT PE 62 5 4 5 Real Time Clock HTC 62 5 5 Managing Mission and Battery Modes eese enne nnne 62 LIB cio eee 63 5 7 e TER EE 64 v1 1v1 1 TERIDIAN Proprietary 5 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation e SEMICONDUCTOR CORP 71M653X Software User s Guide 59 D dero DM P M X II 64 59 Source Files em E 64 5 10 Auxillary PiUlC Siiciiccccicsictessccccssscccccusscccsausseaecaesscceeavsocaeervescasesvebesveteascaeeseaceeesvabeceeteaccadesuecavive 66 5 11 Include Header Files eee elerce inire aaeain eaa eaa 66 5 11 1 elena WEE 66 5 11 2 Register Dettpfl png 67 5 11 3 Other Include Header Files AAA 67 5 12 CE Image File ce 68 5 13 Common MPU Addresses cecccsscccseeeeeeeeeeeeeeeseeeeneeeeeesaesesaeeneeeeeeeeesaesaseaeeeeeeeseesesneneesenanas 69 5 14 Firmware Application Information eere eee 77 5 14 1 General Design Considerations ene ener 77 5 14 1 1 Multitasking eee ern tenner tenet enm emm nennen nnn en nennen nennen enr nnne 77 5 14 1 2 Synchronization eee 77 S1413 Bank Switching enenda E he hte eee 77 5
139. ne meter c thaty read line power Uint8 t meter totals piod selected quantity on select uint8 t void meter c phase eee tee Converts to timer s count Number uint16 t tmrO h tmr1 h Converts milliseconds to clock milliseconds ticks usually for a software Any number uint16_t stm h timer nca EE Converts to timer s count Number uint16 t tmrO h tmr1 h min returns minimum of unsigned int uint16 ta uint16_t uint16_t options glib h a and b b MPU Clk Select selects MPU clock speed ee bool IO serial c Enum Describes the clock speed of SERIAL PORT HUE ee the MPU to a serial interface port enum SES SE eMPU_DIV speed Describes the clock speed of Enum eMPU_DIV MPU Clk SelectO the MPU to the serial interface speed bool Cli serOcli c Describes the clock speed of Enum eMPU_DIV gt F MPU_Clk_Select1 the MPU to the serial interface speed bool Cli ser1cli c d uint8 tx w multiply 1 W x y uint8_tx x y n uint8 t Util math c uint32_t w uint32 t x uint8 tx w multiply 4 1 uint8 Dy uint8 tx x y uint8 t Util math c EE ai uint8 tx w multiply 4 4 Kerg y uint32_t x uint8_tx x uint8_tx none Util math c y i uint64_t w uint64_t x uint8_tx w F multiply 8 1 uint8 Du uint8 1x x y uint8 t Util math c p uint8 tx w multiply 8 4 pice e uint64_t x uint8_tx x uint8_tx none Util math c y Puts a register into normal form l e fractional part i
140. nit A51 sets up the 8051 for Keil C and jumps to main The startup files are described in section 5 10 The stack is located at 0x80 growing to higher values while the reentrant stack is located at OxFF growing down wards Once operating the main program expects regular interrupts from the CE The main program calls the main init and the main run routines main init initializes the meter s hardware and software main run is the main loop 5 4 BASIC CODE ARCHITECTURE The TERIDIAN 71M653X firmware can be divided into two code parts the main loop or background and the interrupts or foreground The initialization and main loop takes care of the non time critical functions After the meter is initialized the main loop runs all the time The main loop is a small loop near the end of main in main main c The main loop performs multitasking by calling a different subroutine for each major system task The subroutines called in the main loop are usually either waiting for data or the data is available and they can process it If they are waiting they test a flag or counter and then return to the main loop freeing the MPU to call other subroutines The meter doesn t have many tasks so checking flags is much faster than putting event records in a queue and then interpreting them Queuing is the other common scheme It s also easier to read the code These task routines will be discussed more below As much
141. nk sfr register FL BANK directly from code Keil s bank switching scheme has the linker build a table of global subroutine entry points in common memory Calls to global subroutines are actually to an entry in the table which switches the bank and jumps to the the bank switching routines The SUG has more details including debugging suggestions Fast interrupts has to be in the common page so that their code is always available Slower interrupts have a trampoline in the common page that performs a bank switching call to the main interrupt code This permits entire modules to be placed in different banks so that the code s functionally pure structure doesn t have to be damaged in order to do bank switching The trampolines are in Meter io653x c with other shared interrupt logic TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN The Keil linkers dependency command must be used to tell the linker about the caller of every routine called via a function pointer If this is not done Keil s address for the called routine is often in a bank and the bank is rarely the current bank So the caller goes to the called routine s address but in the wrong bank This doesn t work When the linker is told that a called routine is called from a caller then it places a bank switching stub for that routine in the common bank and the call via function pointer works splendidly The function pointer issue is a problem
142. ns These calculations assume that during the meter s calibration measurements the CE gains are unity 16384 and the phase adjustments are zero The applied signal is assumed to be a sine applied to both the current and voltage measurement with no phase shift A non trignometric derivation for the fast calibration is generally superior because the cos of the typically tiny corrective angle is just not that accurate TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN Here s how it is derived To calculate phase correction tan VARh_measured Wh_measured The value of tan can be used directly without calculating trigonometric values For 60Hz metering from the data sheet ce phase corr 1048576 0 02229 tan 0 1487 0 0131 tan For 50Hz metering from the data sheet ce phase corr 1048576 0 0155 tan 0 1241 0 009695 tan For the volts V gain Volts applied Volts measured But the CE s value for unity is 16 384 so ce v gain 16384 V gain For the current The meter s signal is a vector sum of the real Wh and imaginary VARh parts of the power i gain the current gain needs scaling to eliminate power errors and rotation in the complex plane to eliminate phase error Let be the phase adjust angle A vector is rotated by multiplying by a 2x2 matrix cos sin sin cos The linear adjustment vector is W
143. ns e O H I O subroutines for CLI e SEROCLI H SER1CLI H hardware access layer for UARTO UART 1 e SERCLI H include definitions for UART 0 1 debug routines e FLAGO H FLAG1 H FLAG H shared logic for all FLAG interfaces e EEPROM H EEPROM e I2 H I2C Interface e LCD H LCD e RTC H Real Time clock e SEROH SER1 H GER H serial interface e SERIAL H serial interface API prototypes and definitions e TMROH TMR1 H timer routines e UWR H microwire wire or three wire interface e BATMODES H battery modes BROWNLOUT LCD SLEEP e DEFAULTS H default values e OPTIONS GBL H global compile time options e OPTIONS H general compile timeoptions defining meter functionality e CALIBRATION H calibration e CE H compute engine interface includes e FREQ H frequency and main edge count e METER H meter structures enumerates and definitions es PCNT H pulse counting e PEAK ALERTS H voltage current peak alerts TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e 5 12 PHASE_ANGLE H phase angle calculation PSOFT H pulse generation by MPU software external pulse generation PULSE SRC H pulse source definitions and support RMS H RMS calculation VAH H VAh accumulation VARH H VARh accumulation WH H Wh accumulation DIO H DIO structures enumerations and definitions FLASH H flash copy and CRC routines IRQ H interrupt kernel LIBRARY H library routines
144. nsed Software License Grant TSC grants Licensee a limited non exclusive non sub licensable non assignable and non trans ferable license to use the software solely in conjunction with the meter devices manufactured and sold by TSC Non disclosure and confidentiality For the purpose of this Agreement Confidential Information shall mean the Licensed Software and related documentation and information received by Licensee from TSC All Confidential Information shall be maintained in confidence by Licensee and shall not be disclosed to any third party and shall be protected with the same degree of care as the Licensee normally uses in the protection of its own confidential information but in no case with any less degree than reasonable care Licensee further agrees not to use any Confidential Information received from TSC except as contemplated by the license granted herein Disclaimer_of Warranty TSC makes no representations or warranties express or implied regarding the Licensed Software including any implied warranty of title no infringement merchantability or fitness for a particular purpose regardless of whether TSC knows or has reason to know Licensee s particular needs TSC does not warrant that the functions of the Licensed Software will be free from error or will meet Licensee s requirements TSC shall have no responsibility or liability for errors or product malfunction resulting from Licensee s use and or modification of the
145. nt This logic is in normalizes inUtil math c This scheme has no underflow It has a tiny controlled round off of 72 of a CE LSB per Wh which the CE calibration arranges to average to zero Otherwise all the fractional data is preserved The overflow is perfectly controlled and is made to wrap around to zero at a decimal limit The register logic is applied so that the registers only increase Negative values of watt hours are subtracted from an export register wh cnt does not usually change in a real meter this would be a constant not a variable However in TSC s demo meter the Imax and Vmax see glossary are variables and therefore so must the CE counts per Wh So wh cnt is recalculated on each accumulation interval by the routine wh cnt set defined in Util math c Unlike earlier demo code versions this register math is easy to modify to use realistic units The WwH RESOLUTION in Util mmath h is already realistic number 1 0 Wh with a UNITS RANGE limit of a billion 1x10 Wh The display routines in Meter wh c can divide the registers by 1000 in order to display KWh This is controlled by a compilation flag DISPLAY KWH which also changes the decimal points and labels for the LCD The registers cannot be kept only in RAM If there is a power failure they would be lost The logical scheme is to write them to the EEPROM once each accumulation interval The problem is that the EEPROM has only 1 million writes
146. nted routine to Void void lo ser0 h sert H enable transmit electronics Returns true if the serial port ser xmit rdy can send another byte Void bool lo ser0 h ser1 h Enum uint16_t Serial CRx RECEIVE a string up to a SERIAL PORT length Cli sercli c maximum length port uint8x_t received buffer uint16_t len Enum Serial CTx Transmit a string up to a SERIAL PORT uint16 t Cli sercli c maximum length port uint8x_t length sent buffer uint16_t len enum Serial CRx gets additional bytes from the SERIAL PORT uint16_t lo sercli c receive buffer port uint8_tx buffer uint16 tlen enum Serial CTx puts additional bytes into the SERIAL PORT uint16_t lo sercli c transmit buffer port uint8_tx buffer uint16_t len Enum i F e SERIAL_PORT x Serial Rx Receive a string of any length port uinf8x_t none Cli sercli c buffer uint16_t len enum enui Serial Rx sets up receive buffer and starts SERIAL_PORT SERIAL_RC lo sercli c receiving port uint8_tx data buffer uint16_t len Enum Serial RxFlowOff Force an XOFF to be senton SERIAL_PORT none Cli sercli c the selected port port Enum Serial RxFlowon Force an XON to be senton the SERIAL_PORT none Cli sercli c selected port port enum Serial RxLen retums Me number ar Bytes SERIAL_PORT uint16_t lo sercli c received port Enum SERIAL PORT Serial Tx Transmit a string of any length port uint8x_t none lo sercli c buffer uint16_t len enum Shum Serial_Tx s
147. nternal data memory map of the 80515 MPU core as shown in Table 5 1 Address Direct addressing Indirect addressing OxFF Special Function Registers SFRs RAM Byte addressable area Bit addressable area Register banks RO R7 Table 5 1 Internal Data Memory Map TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN The demo software defines standard integers in util stdint h following the industry standard notation General data type definitions typedef unsigned char typedef unsigned short typedef unsigned long typedef signed char typedef signed short typedef signed long uint8_t an 8 bit byte unsigned uint16_t a 16 bit unsigned integer uint32_t a 32 bit unsigned integer int8_t a signed 8 bit integer int16 t a signed 16 bit integer int32 t a signed 32 bit integer Type definitions for internal data lower 128 bytes addressed directly typedef unsigned char data typedef unsigned short data typedef unsigned long data typedef signed char data typedef signed short data typedef signed long data uint8d t uintl6d t uint32d t int8d_t int16d_t int32d_t Internal data is the fastest available memory except registers not battery backed up but competes with stack registers booleans and idata for space Note For portability see uint_fast8_t and its sisters which are POSIX standard Type definitions for internal
148. ocessing uint8_tr rsrc memcmp rx compares xdata to flash code uint8_tx xsrc S08 library c uint16 tlen uint8 tx xsrc1 mememp xx compares xdata to xdata uint8_ tx xsrc2 S08 library c uint16 tlen uint8 ti dst memcpy ix copies xdata to idata uint8 tx src none library c uint8 t len IOYeeprom c memcpy px Copies data to serial EEPROM ips Dst inte tx enum lO eepromp c pSrc uint16_t len IOYeepromp3 c int32 tr dst memcpy rce reads from or writes to flash int32 tx erc none UtiMlash c uint8 t len uint8 tr dst memcpy rx Copies xdata to code flash uint8 tx src bool Util flash c uint16 tlen uint8 tx dst memcpy xi Copies idata to xdata uint8 ti src none library c uint8 t len mene gf copies data from serial uint8_tx pDst U32 ann c py 28 EEPROM Src uint16 tlen Gier IOYeepromp3 c memcpy xr copies xdata from code flash uint8 tx dst none library c TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Se Function Routine from the last valid mark Name Description Input Output File Name uint8 tr src uint16 tlen uint8 tx dst memcpy xx copies xdata to xdata uint8 tx erc none library c uint16 tlen uint8 tx dst memset x sets xdata to specified value uint8 t s uint16 t none library c len EDEN initializes most I O functions meter initialize none no
149. ode banks It is derived from the Keil compiler package STARTUP SECURE 30 A51 This file is almost identical to STARTUP A51 The only difference is that this variation sets the SECURE bit This bit enables security provisions that prevent external reading of flash memory and CE program memory The code segment below sets the security bit located at SFR register address OxB2 STARTUPI CLR 0xA8 7 Disable interrupts MOV 0B2h 40h Set security bit MOV OE8h 40FFh Refresh nonmaskable watchdog L51 BANK A51 This file provides bank switching logic for a 6530 using code banks It is derived from the Keil compiler package INIT A51 A secondary startup file It is part of the Keil compiler package This code is executed if the application program contains initialized variables at file level STARTUP BOOT A51 This startup file is to be used when the code is to be compiled as a bootloader INCLUDE HEADER FILES In line with common industry practice each C file in the Demo Code source code has a corresponding header file that ends in H and that provides the interface to the C file s code A number of include files are special cases and provide global data or hardware definitions 5 11 1 Main 653x options h selects the features used by the code main option_gbl h defines global configuration values used in all meter versions meter meter h defines the meter s configuration and power registers meter ce653X h defines the CE me
150. of data records that are terminated with a carriage return and a linefeed Data records appear as follows 10246200464C5549442050524F46494C4500464C33 This record is decoded as follows CC Checksum B DD gt Data TT gt Record Type AAAA gt Address LL gt Record Length 10246200464C5549442050524F46494C4500464C33 LLLI LII III gt Colon where n 10 is the number of data bytes in the record n 2462 is the address where the data are to be located in memory i 00 is the record type 00 a data record n 464C 464C is the data n 33 is the checksum of the record TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN 4 8 2 Intel Hex386 File Format For banked code the Intel Hex386 file format Extended Linear Address Records is used Extended linear address records are also known as 32 bit address records and HEX386 records These records contain the upper 16 bits bits 16 31 of the data address The extended linear address record always has two data bytes and appears as follows 02000004FFFFFC where 02 is the number of data bytes in the record 0000 is the address field For the extended linear address record this field is always 0000 04 is the record type 04 an extended linear address record FFFFisthe upper 16 bits of the address FCisthe checksum of the record and is calculated as 01h NOT 02h 00h 00h 04h FFh FFh W
151. ompiler Specific Information ene nennen enne nennen 46 5 2 Demo Code Options and Program Size eeeeeeeeesesseeeeee enne nennen nnn 47 53 Program bio 51 5 3 1 Startup and Wl EE 52 5 4 Basic Code Architecture recie nieeer eie einn trn tanec unte aacra s ansa aac na EE EE EENS 52 5 4 1 Initialization c 53 5 4 2 huuc e 53 5 4 2 1 Pulse Counting Interrupts ssssssssssssseeeeneneneeee nennen neret enn 54 5 4 2 2 FWGOLO and FWOQOODL T1 accede te eder edere kid adea va eg arae ae 55 5423 CE BUSY gll ue TTT 55 SIMA IMMEIT M 55 54 2 5 EEPROMIISE cete tene eed e EE RU eie ra dee ek svenska tenis 56 54 2 0 Timer Interrupt e ofer ae utei HERR ER CORRI IER FREE cceaadgadeetasacensvensnneteedce YN ARA ee ERU 56 5 4 2 7 The XFER BUSY RTC and NEAR_OVERFLOW Interupt nena 56 5 4 2 8 SERIAL Interr pt it rt Fra neuer rea qn ra de enero ee MER ee rate een eR exu pa Pe exa bod 57 5 4 3 Background NK m T MH 57 5 4 3 1 meter unt 57 5 4 3 2 Command Line Interpreter CL 58 54 3 3 A t Calibratio DEET 58 54 34 EEPROM Read Write ect eec erae dee n e RR KAAR EAA 61 544 3 5 Battery Testen ceni etre e Du e i ane a
152. on 4 4 11 2007 07 15 or later The revision 4 15 of the Demo Board Code is the basis for all discussed sources commands register addresses and so forth If applicable known issues with revision 4 15 are disclosed within the code description and workarounds or improvements are shown TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 2 DESIGN GUIDE This section provides designers with some basic guidance in developing power meter applications utilizing the TSC 71M653X devices There are two types of applications that can be developed e Embedded application using the sources provided by TERIDIAN or e Embedded application using only customer generated functions 2 1 HARDWARE REQUIREMENTS The following are the minimum hardware requirements for developing custom programs e TERIDIAN 71M6531 Demo Board This board interfaces with a PC via the RS232 serial interface COM port e AC Adaptor AC DC output or variable power supply e PC Pentium with 512MB RAM and 10GB hard drive 1 COM port and 1 USB port running either Windows 2000 or Windows ME or Windows XP e Signum Systems ADM 51 In Circuit Emulator for loading and debugging the embedded application and its associated cables Signum references this device as ADM 51 2 2 SOFTWARE REQUIREMENTS The following are the minimum software requirements for embedded application programming e Keil Compiler version 8 03a or later e yVision2
153. or that the needed symbols be defined irq init Initializes interrupt control void void util irg c labsx returns the absolute value int32_t x 332 Util math c latan2 returns the arcTangent re sy int32_t U32 Util math c LCD CE Off displays CE OFF on LCD none none io Icd c LCD_Command EE uint8_t LedCmd none io lcd c display uint8_t num enum i eLCD mode bias LCD Config configures LCD parameters enum LCD CLK none io lcd c clock LCD Data_Read reads from selected icon of LCD uint8 t Icon uint16 t io lcd c i uint8 t icon LCD Data Write writes to selected icon of LCD uint16_t Mask none io lcd c LCD Hello displays HELLO on LCD none none io lcd c LCD Init Magis LCD enables LCD none none io lcd c segment drivers LCD Mode Display a mode number Uint8_t mode none io lcd c Int32 t number uint8 t num digits before LCD Number Displays a number on the LCD decimal point none io lcd c uint8_t num_digits_after_d ecimal_point Imax EES iis quas U32 Util math c long a and b Imin returns minimum of unsigned U32 a U32 b U32 Utilmath c long a and b log2 returns binary logarithm uinti6_tk uint8 t Util math c Calculates a longitudinal Pointer LRC Calc NVR redundancy check bitwise Bool ok bad UtiNibrary c length set parity Returns long rounded from float Lroundf Standard C99 library routine not Long Float Util math c provided by Keil main b
154. oration 5 15 ALPHABETICAL FUNCTION REFERENCE A Function Routine scription InpL lu File Nam Name Descriptio nput Output e Name Adds Wh inCE counts to a add8_4 r wh ce register C converting to display uint8_tx r in32_t none Util math c units No underflow or fractional value is lost adds 8 r0 r1 Adds register r1 to register rO inte x ro none Util math c uint8_ tx r1 SE EE Prevents creep void void Meter meter c batmode duds Returns true if battery mode is o HOGS CB ATONU brownout False is mission void bool Main batmode c mode Enters LCD only mode from batmode_lcd brownout mode Exit from LCD void void Main batmode c only mode resembles a reset Enters sleep mode from batmode_sleep brownout mode Exit from sleep void void Main batmode c mode resembles a reset rea Ne rine Sets the wake timer in minutes uint16_t minutes none Main batmode c batmode wait seconds e A 0 m Sets the wake timer in seconds uint16 t seconds none Main batmode c cal begin starts auto calibration process none bool Meter calphased c Restores calibration from cal restore EEPROM none bool Meter calphased c saves calibration data to cal save EEPROM none none Meter calphased c Calculates phase angles Calc Voltage Phase between voltages of different void void Meter vphase c phases Calibration processes Measurements none none Meter calphased c d
155. ormation of TERIDIAN Semiconductor Corporation TSC and is made available for informational purposes only TERIDIAN assumes no obligation regarding future manufacture unless agreed to in writing If and when manufactured and sold this product is sold subject to the terms and conditions of sale supplied at the time of order acknowledgment including those pertaining to warranty patent infringement and limitation of liability TERIDIAN Semiconductor Corporation TSC reserves the right to make changes in specifications at any time without notice Accordingly the reader is cautioned to verify that a data sheet is current before placing orders TSC assumes no liability for applications assistance TERIDIAN Semiconductor Corp 6440 Oak Canyon Road Suite 100 Irvine CA 92618 5201 TEL 714 508 8800 FAX 714 508 8877 http www teridian com 5 8 2008 TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation
156. p Fan eee o ER chee beg oa pa 20 4 TOOL INSTALLATION GUIDE eseeeseseeeeeeeeeeeen nennt nnne nn anna snnm ann tn nn sn nasa sane nnn anna 21 4 31 Installing the Programs for the ADM51 Emulator eene 21 4 2 Installing the Wemu Program Chameleon Debugger eere 21 4 3 Installing the ADM51 USB Driver eeeeeeeeeeeeees einen nennen enne nnnm nnne nni nn sana nennt nnn 22 4 4 Installing Updates to the Emulator Program and Hardware 23 4 5 Creating a lte E cocci cie ce ono cur oascu ane e tue se cuoco aan ek aic daadaa ad ame d sn tasa S cao aumaia 24 4 6 Installing the Keil Compiler e cciiceere ium iccurueneca unser ie teu an cuan reca ic era u ainsana 27 4 7 Creating a Project for the Keil Compiler eese ener nnne 28 4 7 1 Directory Eeer EE 28 4 7 2 Adjusting the Keil Compiler Settings mene 29 4 7 3 Manually Controlling the Keil Compiler Geitings 30 48 Output File E 32 4 8 1 Basic Intel Hex Format 33 4 8 2 Intel Hex386 File Fommet cece eaaece sees ca geaaaeaeeeeeegeseaaeeeeeeeseseesaaeeeeees 34 49 Writing Bank Switched Code iccic cciscccccsecscecccsstecsnccccasccteceeeasdeesseceessciezcatedsncccescie sczeatsueeeeses 35 4 9 1 ele UE lee US 35 4 9 2 Software Overview eesssssssssssssesseeseseenenene enhn ener tenete d
157. part of the 8051 core and which could be disabled by software The 653x series no longer supports the core s watchdog Instead use the standard watchdog which cannot be disabled by software TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation dis SEMICONDUCTOR CORP 5 18 10 Real Time Clock Compensation The real time clock compensation is very different from the 652x series Fixed rate adjustments are nonvolatile and automatic so that they continue when the MPU is not operating The 32 KHz crystal rate can be measured precisely in the factory by using a precision frequency counter to measure the 1 second or 4 second output from the TMUX pin During this measurement the RTCA ADJ register should be set to the middle of its range 0x40 and PREG and QREG should be set to the middle of their range After this the capacitance driving the crystal can be adjusted by have the meter software write and preserve a value for the real time clock analog adjustment RTCA ADJ XDATA 0x2011 After RTCA ADJ is set the clock rate can be remeasured using the frequency counter with TMUX In operation the clock s rate can be digitally adjusted for temperature or to follow the line frequency by adjusting the PREG and QREG registers These are actually a single register that adds or subtracts a count after a certain number of counts Setting PREG and QREG to zero will cause the seconds register to count at 72 Hz rather than 1 Hz
158. plays voltage to current phase angles generates two additional pulse outputs using DIO pins directs line measurements to any pulse output routines for calculating the power factor calculates and displays Vrms and Irms calculates VAh calculates VARh calculates voltage to voltage phase angles for multiphase meters calculates Wh Utilities defines unused flash space for the boot loader defines high level access to DIO pins flash memory read write erase compare and checksum calculation securely disables and enables interrupts routines for memory copy compare CRC calculation string length contains routines for multiple precision math test code that must be included in ROMmable images a utility to trigger oscilloscope loops using DIO7 header file defining priorities for IPO and IP1 access to SFRs startup assembly code startup_boot_secure a51 startup secure a51 stm c timers c wd c software timer routines unused software timer legacy code routines that support the hardware watchdog TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN 5 10 AUXILIARY FILES A variety of startup files is provided with the Demo Kits The function of these files is as follows 1 5 11 STARTUP 30 A51 This file provides memory and stack initialization It is derived from the Keil compiler package STARTUP 30 BANKED A51 This file provides memory and stack initialization for a 6530 using c
159. put Listing C51 Jop BL51 Locate BL51 Misc Debug Utiities m Preprocessor Symbols Define Undefine r Code Optimization Warnings waminglevel 2 evet z L Bits to round for float compare s zl Emphasis Favor speed zi T Global Register Coloring JV Interrupt vectors at address bam Linker Gode Packing max AJMP ZACALO Keep variables in order IV Enable ANSI integer promotion rules Include ENMetersNFimwareN Tests m Paths Misc Controls Don t use absolute register accesses Compl LARGE BROWSE INCDIR Z Meters Firmware T est DEBUG OBJECTEXTEND a control string I Cancel Defaults Click OK to set all the options selected for project and return to the main menu With the source and header files now existing in the newly created project the files can be compiled using the Build Target option under the Project menu 4 8 OUTPUT FILE FORMAT Both the Keil compiler and the Signum WEMU51 emulator program accept executable programs for download to the 653X ICs in Intel Hex format v1 1v1 1 TERIDIAN Proprietary 32 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA SEMICONDUCTOR CORP 4 8 1 Basic Intel Hex Format The Intel HEX file is an ASCII text file with lines of text that follow the Intel HEX file format Each line in an Intel HEX file contains one HEX record These records are made up of hexadecimal numbers that represent machine language code
160. r compiling HELLO C linking Program Size data 30 1 xdata 0 code 1096 HELLO 0 Error s 0 Warning s Under Project gt Options for Target select the Device tab and check the selected device Newer versions of the Keil Compiler offer selection of TERIDIAN labeled TDK 71M653x devices Select Device for Target Target 1 cru Vendor TDK Device 71M6513 P Use Extended Linker LX51 instead of BL51 Toolset C51 Use Extended Assembler 4X51 instead of A51 Data base E ST Microelectronics H SyncMos e Synopsys S Syntek Semiconductor Cc TDK 3 71M6511 3 BEA 3 7342801 3 73M2301CL 3 73M2910L 3 73511 v1 1v1 1 Description 80515 based power meter IC with Interrupts 4 Priority Levels B Sensor Inputs 22 1 0 Lines 2 Timers Counters Real Time Clock Watchdog Timer 2 U amp RTs SSI LCD Driver Power Fail Monitor Integrated ICE Support 64K Bytes Flash or ROM 7K Bytes On chip RAM TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation A 4 TERIDIAN 71M653X Software User s Guide w SEMICONDUCTOR CORP For older versions of the Keil compiler select the TERIDIAN folder labeled TDK open it by clicking on the sign and select 73M2910L as the target device Confirm by clicking OK Select Device for Target Simulator Assembler A551 instead of ASI Under Project gt Options for Target1 select the Targ
161. r This is the slowest but largest space nonvolatile programmable flash memory It should be used for constants and tables If the table is in banked space the banking function switchbank defined in utils bank h and L51 BANK A51 may be needed to bring the code bank into the address space TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN Note Throughout the Demo Code an attempt has been made to put the most frequently used variables in the fastest memory space Data Type Notation Bg Bytes Comments bit bool Unique to 8051 sbit Unique to 8051 SFR 1 Unique to 8051 SFR16 Unique to 8051 signed unsigned char uint8 t 1 ANSI C enum enum ANSI C unsigned short uint16 t ANSI C signed short int16 t 2 ANSI C unsigned int uint16 t ANSI C signed int int16 t ANSI C unsigned long uint32 t ANSI C float float ANSI C Table 5 2 Internal Data Types 5 1 2 Compiler Specific Information The 8051 has 128 bytes of stack and this motivates Keil C s unusual compiler design By default the Keil C compiler does not generate reentrant code The linker manages local variables of each type of memory as a series of overlays and uses a call tree of the subroutines to arrange that the local variables of active subroutines do not overlap The overlay scheme can use memory very efficiently This is useful because the 71M653X chips only have 2k of R
162. r Interrupt and other Interrupt service routines The interrupt service routines ISRs get the data and set a flag or counter to tell the background routine to stop waiting These will be discussed more below TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation BA SEMICONDUCTOR CORP 5 4 1 Initialization When the power applied for the first time or RESETZ is asserted the 71M653X device executes the code pointed to by the reset vector 5 4 2 Interrupts There are 13 interrupts available for the 80515 and the revision 4 4 Demo Code uses 11 interrupts Table 5 10 shows the interrupt service routines ISRs the corresponding vectors Table 6 58 in section 6 3 5 4 and their priority as assigned by the MPU using the IPO and IP1 registers see section 6 3 5 2 In general stubbed interrupts or shared interrupt code is defined in meter io653x c Interrupt Source Interrupt Service External or In source file Vector Priority Routine Internal Interrupt highest Pulse count pcnt w isr EXTO Meter pcent c 0x03 0 Pulse count pcnt v isr EXT1 Meter pcnt c 0x13 3 Flash Write collision fwcol isr EXT2 Meter io653x c Ox4B 0 fwcolO Flash Write collision fwcol isr EXT2 Meter io653x c Ox4B 0 fwcol1 CE Busy ce busyz int EXT3 Meter ce c 0x53 3 Power fail power return pll_isr EXT4 Main batmodes 0x5B 3 C EEPROM eeprom_isr EXT5 IOYeeprom c 0x63 0
163. rce pulse output EL Indexed as y wsum requires D unsigned 8 software pulse module 4 Pulse 4 pes i m Indexed as 7 varsum JE unsigned 8 SOUE pues pH requires software pulse module 2 Scal Accumulation intervals Count of accumulation 2 accumulation F unsigned 16 of autocalibration intervals of calibration intervals covers both chop polarities 2400 Volts of 0 1V rms of AC signal applied Vcal autocalibration to all elements during 240V is a standard full ug unsigned 16 calibration scale set up for meter test 0 1A rms of AC signal applied 300 Ical Amps m of to all elements during 30A is a standard full 11 unsigned 16 autocalibration calibration Power factor must scale set up for meter be 1 test 88992958 6531 75087832 6533 amp Volts at which to 6534 measure X frequency VThrshld q 9 sqrt vOsqsum 2 40V 12 unsigned 16 zero crossing etc A real meter should use sag but the demo operates with a power supply TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation MES microseconds 50 i Maximum time pulse 2 PulseWidth 1 397 PUISE Vd is on OxFF disables this feature ws signed 15 Takes effect only at start up 10ms 0x408D1800 Nominal temperature 847662 6531 temp_nom the temperature _at Units of TEMP RAW from 0x30CC7800 14 unsigned 32 which calibration CE 653
164. rement interval When the gains and phases are adjusted the code quickly steps through a table of indexes reading the data from each element and writing the adjustments for each element The calibration is so fast that TSC believes that it may pay to use this method to calibrate a meter in equation 2 or 5 and then change to the actual metering equation possibly even reloading the code High accuracy temperature calibration For accuracies up to 0 596 standard values can compensate the ADC and voltage regulator for temperature For 0 296 or better accuracy high accuracy trimmed parts are usually required The trimmed parts have a temperature response that is characterized at the factory and programmed into the part The demo code has sample code to adjust the quadratic temperature parameters of a meter containing a trimmed part See compensation in meter calphased c In these meters the current and voltage sensors also usually have temperature compensation curves and these usually need to be compensated as well The demo code has an explicit place to combine the data into a single quadratic compensation See compensation in meter calphased c Contact factory support for information about trimmed parts Linear non phase adjusted calibration In the extended code set TSC maintains autocalibration code that does a linear adjustment of the gains for current and voltage without adjusting phase Derivation of the calibration equatio
165. rland Interrupt International Standards Organization Interrupt Service Routine Kilobyte s 1 024 bytes Liquid Crystal Display Line feed character Least Significant Bit Megabyte s 1 024 kilobytes Microprocessor microcontroller Unit TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation MES MSB Most Siginificant Bit NV Non Volatile PC Personal Computer Program Counter PROM Programmable ROM PSU Power Supply Unit PSW Program Status Word RAM Random Access Memory ROM Read Only Memory SFR Special Function Register of the 8051 MPU TOU Time of Use variable metering tariffs usually based on time of day TSC TERIDIAN Semiconductor Corporation USB Universal Serial Bus VA Volt Amperes apparent power unit VAh Volt Ampere Hour apparent energy unit VAR Reactive Power VARh Reactive energy unit W Watt power unit WD Watchdog WDT Watchdog timer WEMU51 The emulator control program by Signum Systems Wh Watt Hour energy unit 7 2 REVISION HISTORY Revision Date Description 1 0 11 2 2007 Initial release Added useful excerpts from the SDD Removed most of 80515 MPU core 1 1 5 7 2008 description contained in data sheets except op code tables Added description of Intel Hex File formats for regular and banked code Software User Guide This User Guide contains proprietary product definition inf
166. rterminal session at 2400 or 300 bps depending on jumper settings see the DBUM 8N1 one stop bit with XON XOFF flow control enabled The setup dialog box is shown in Figure 3 1 Port Speed and Handshake Setup e Power on the Demo Board and hit lt CR gt a few times on the PC keyboard until gt is displayed on the Hyperterminal screen e Type a command from the CLI Reference 3 5 2 e All references to c lower case c indicate any ASCII character all other lowercase letters are one byte numbers e Numbers can be entered in decimal by preceding them with a plus sign e g hex 20 32 The 71M653x Demo Board User s Manual contains instructions on how to connect the serial cable COM3 Properties Port Settings Bits per second v Data bits 8 O O B Parity None v Stop bits 1 a Flow control Xon 7 Soft v Figure 3 1 Port Speed and Handshake Setup Note HyperTerminal can be found by selecting Programs Accessories gt Communications from the Windows start menu The connection parameters are configured by selecting File gt Properties and then by pressing the Configure button Port speed and flow control are configured under the General tab bit settings are configured by pressing the Configure button Figure 3 1 Port Soeed and Handshake Setup as shown below v1 1v1 1 TERIDIAN Proprietary 19 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation MYTERI DIAN
167. ry exists Since some meter ICs can operate the MPU with VCC as low as 1 5V when there is no battery the MPU can corrupt some EEPROMs by trying to write to them So if there s no battery the interrupt waits forever for the power to come back If the power does not return the loop in this high priority interrupt prevents the MPU from trying to write to the EEPROM Basically the loop confines the MPU s low power behavior to the loop If there s no battery and the power returns while the interrupt is waiting the code simulates a reset to start up the meter again When leaving brownout the code could just restore the system state in some way but the CE was turned off and its filters have unlocked from the mains A simulated reset reuses reliable pre existing code and still starts up the meter well before the CE could regain PLL lock If there is a battery the code immediately performs a simulated reset to quickly get to the battery mode code in main main c The simulated reset in the battery case keeps the battery mode code in one place The sleep and LCD only states start the MPU from the reset vector So some location on the reset path is the only place in which all system restart TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN execution paths can be made to occur The early part of main is convenient and a simulated reset is an easy reliable way to get there The code does not display
168. s less than normalizes one display unit both unitsand Uintg tx r void Util math c fraction are positive or zero and display units is less than the UNITS_RANGE operating Tea Displays the number of hours of eid void lo rtc_30 c operation OperatingHours EECHER None int32 t hours lo rtc_30 c TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA Function Routine register value Can lose up to Name Description Input Output File Name OSCOPE_INIT Defines DIO_7 the VAR pulse N a n a UtiNoscope h output as a DIO Set DIO_7 the same pin as the e OSCOPE_ONE VARh pulse output to high N a n a Utilloscope h Inverts DIO_7 the same pin as e OSCOPE_TOGGLE the VARh pulse output N a n a Utilloscope h Set DIO_7 the same pin as the OSCOPE_ZERO VARh pulse output to low N a n a Utilloscope h pent accumulate Accumulates counts from the Void void Meter pent c previous second pent init Initialize logic to count output Void void Meter pcnt c pulses pent lcd Display pulse count on LCD uint8_t select void Meter pcnt c pent start Starts pise counting for a fixed Int16_t seconds void Meter pcnt c number of seconds pent_update Synchronizes pulse counts with Void void Meter pcnt c noninterrupting code phase angle lcd Displays a V I phase angle Uint8_t phase vo
169. software write and preserve a value for the real time clock analog adjustment RTCA ADJ XDATA 0x2011 After RTCA ADJ is set the clock rate can be remeasured using the frequency counter with TMUX In operation the clock s rate can be digitally adjusted for temperature or to follow the line frequency by adjusting the PREG and QREG registers These are actually a single register that adds or subtracts a count after a certain number of counts Setting PREG and QREG to zero will cause the seconds register to count at 72 Hz rather than 1 Hz 5 17 11 Battery Modes One of the most significant innovations for the 71M653x is the battery power feature This feature provides three operational modes that apply when the supply voltage is removed and the chip is powered by the battery The operation modes and their transitions are shown in Figure 5 5 State Diagram of Operating Modes In the brownout mode operation continues at 32kHz and RAM and DIO pins remain powered However the clock slows down and is so slow that the timers and serial port give dramatically different timings Only the RTC and its 1 second interrupt run at an unchanged speed In addition to the flags given in Figure 5 5 State Diagram of Operating Modes the following considerations apply to state transitions e Mission to brownout mode The MPU keeps running but the clock slows down e Brownout to mission mode The MPU keeps running but the clock speeds up e LCD or sleep mode
170. string of bytes uint16 t cnt none io uwrdio c uwreep c2 Select a chip by passing its uwr select address 0 none This must be Uint8 t address none io uwrdio c uwreep c2 ported to new PCBs du write Transmit a counted string of Uint8x_t pbOut bool true lo uwrdio c uwreep c2 bytes uint16 t cnt Success Ah Accumulate Calculates VAh void void meter vah c VARh Accumulate Calculates VARh void void meter varh c voltage phase lcd Display voltage phases on LCD Uint8_t select void meter vphase c wd_create Creates a software watchdog Uint8 t wd void util wd c wd destroy Destroys a software watchdog Uint8_t wd void util wd c Resets a software watchdog If wd_reset af sciens watchdogs neve Uint8_t wd void utillwd c been reset the hardware watchdog is reset wh_accumulate Calculate watt hours Void void meter wh c wh brownout to lcd Displays a precalculated 6 digit Uint32_t number void meter wh c number Ss Sets wh_cnt to the number of wh cnt set CE Wh units per display unit void void util math c wh lcd Displays d welt Hour valueon uint8 t val void meter wh c TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation A Ek SEMICONDUCTOR CORF 71M653X Software User s Guide Adds 0 w1 to s only if w1 is 3 E o wh_sum_export negative yielding a total of a s int32i_t void meter wh c exported power in w Adds w1 to s only if w1 is e
171. ta Location is at XDATA 0x0000 CE data now resides in roughly the first 1K bytes of RAM from 0x0000 to OxOSFF The exact CE RAM usage varies with different CE code versions with single phased CE codes taking less RAM and three phase CE codes taking up to the limit Nonstandard CE codes may take more than 1K but these will come with instructions Standard CE configuration begins at 0x0010 Standard CE output areas begin at 0x0200 The Keil compiler must be configured to avoid the CE RAM If not both the CE code and MPU code will misbehave when the MPU writes data into the CE code s internal data area and vice versa 5 17 4 CE Data Access is Transparent to the MPU The MPU can now simply read and write the CE RAM No special buffering or access routines are required The demo code for example no longer copies data from the CE s output area to the MPU RAM The Keil C code simply uses the CE s output data It s fast to access the CE s output as PDATA variables so in the demo code the PDATA page register SFR 0xB7 is set to 0x200 The CE output registers begin on a page boundary 0x200 5 17 5 Read only areas in MPU RAM The direct memory access ADC writes automatically to XDATA locations 0x0000 0x000E so these are not stable for memory tests and there is no way to disable the writes Also Ox0OOF is a read only alternate location of the chip s version identification 5 17 6 CE Code Location Another difference between 71M65
172. tcereude 12 1 3 Compatibility Statement ccccccsseeeesnee sees eesneeenseeeeseeseeneeeenseeeeeaesesaaesaaeaeeneeeeseaesaseaeenseeeeeeas 12 2 DESIGN GUIDE c 13 2 1 Hardware Requirements cccceesenceceseeeeeeeeeeeseseeneeseeeeenenseseeneeseseeneeseseeneeseseeneeseseenenseeeeenanes 13 2 2 Software Requirements cccccccseccesseeceseeeeeeeeeseeeeneeeeeseaeseseaeenseaeseeeeesaeseseeeseeeeeseeseseeeeeseeeeas 13 2 3 Software Architecture liie cui scaedenccadcenens scaresncadcececsadiessnsaccenecssacerenatadceneedes 14 MEEUglul 15 2 4 1 Ba MERGEN 15 2 4 2 E TEE ETT 15 2 4 3 hausit E 16 3 Izzlco riddzli elfe M 17 9 4 Program Memory eege eege 17 3 2 Data Memory uiciseescciiea noci eannan ca iae adipa teni dart nd aao ni oiana niii AANA ann SE SEV da DRE ER SES See 17 3 3 Programming the 71M653X Chips eese REENEN eee ne nennen nn nn ani nnns annman nna 18 3 4 Debugging of the 71M653X Chips eeeeeeseeeeseeeeeeneeeee eene nn enhn nnn n nannte nnne 18 KE WRC A 18 3 5 1 Running the 653X Demo hex Program 19 3 5 2 CLI Command PE 20 3 5 3 Command Macro Files iiu gege crt theo t a Con La o Fou R
173. ter inserting the Keil CD ROM into the CD drive of the PC the on screen instructions should be followed to install the Keil compiler The installer will display the following screen 7 Keil Development Tools Release 04 2004 b Ael x Yo J S TFECESIL seed ais uals A SOFTWARE Install Products amp Updates Thanks for taking the time to review this CD ROM Install Evaluation Software Here you will find the latest information about the Keil Software Development Tools Evaluation Boards N This CD includes the latest product updates Introduction amp Tutorials evaluation software datasheets support solutions and FAQs about our products Click on the Brochures r buttons at the left for more information Newsletters n If you have any questions about this disc click on Technical Information How To Contact Us and give us a call How To Contact Us Select Install Products amp Updates r nt Tools Release 04 20 Agi xl FCESIL Ee tools hy SOFTWARE Sor Compier S T0085 Install Products amp Updates C51 Getting Started ESSEN The C51 package includes the uVision2 C166 Compiler amp Tools Integrated Development amp Debugging Environment and all the utilities you need to create embedded application programs for all 8051 microcontroller families C166 Getting Started 251 Compiler amp Tools C251 Getting Started The C51 setup program performs new installations as well as updates to
174. terface serO the source file can include serO h and then call ser initialize To transmit a byte on sert the file can include serO h and then call ser xmit The convenience is that high level code can be ported to another device by just for example including ser1 h rather than serO h Just by making variables static entire high level protocols can be written and maintained by copying the code debugged on one device and having it include the other device s h file The demo firmware uses this technique for the command line interface serOcli c sercli c the FLAG AMR interface flagO c flag1 c and for the software timer module stm c The base class emulation uses macros because on the 80515 MPU macros execute faster and are also more compact than the standard C object oriented design with an implicit structure containing function pointers The Demo Code is also designed with an options h file which enables and disables entire features in the firmware The macro approach combined with the options h file permitted the firmware team to adapt the same Demo Code to both the 6531 and 6534 versions 2 4 UTILITIES Three utilities are offered that make it possible to perform certain operations on the object HEX files without having to use a compiler e D MERGE EXE allows combining the object file with a text script in order to change certain default settings of the program For example modified calibration coefficients result
175. the current ARM Development Tools version Please have your add on disk and serial number ready when you begin installation Acrobat Reader lt Back To Main Menu Select C51 Compiler and Tools Follow the on screen instructions of the installation program When prompted for the add on disk insert the disk in the floppy drive and click Next or browse to the location of the files if they were previously copied to the hard drive of the PC by clicking Browse v1 1v1 1 TERIDIAN Proprietary 27 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation OTERI DIAN SEMICONDUCTOR CORP 71M653X Software User s Guide 4 7 CREATING A PROJECT FOR THE KEIL COMPILER 4 7 1 Directory Structure The following directory structure is established when the files from the archive 653X Demo zip are unpacked while maintaining the structure of subdirectories drive letter gt meter project drive letter gt meter project CE drive letter gt meter project CLl drive letter gt meter project docs drive letter gt meter project flag drive letter gt meter project lO lt drive letter gt meter project Main drive letter gt meter project Main_653x_CLI lt drive letter gt meter project Meter lt drive letter gt meter project Util The project control file 653X_demo uv2 will be in the directory lt drive letter gt meter project The Keil compiler can
176. the file at the line where the subroutine or variable is defined Or if the same symbol is in several places it offers a choice of files TERIDIAN Semiconductor recommends the exuberant CTAGs utility for generating tag files The code can be found for free at http ctags sourceforge net The choice of a text editor is very personal Many editors support Exuberant CTAGS See the list of supporting tools at http ctags sourceforge net tools html TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERINAN Some editors to be considered are e VIM see http www vim org a free VI editor VIM is available in full featured versions for Windows VI is part of the POSIX standard so using it is a portable skill VIM wins awards for usability e UltraEdit http www ultraedit com an inexpensive not free professional Windows programming editor This editor works like all other Windows applications with extra features to support programming languages NEDIT The Nirvana Editor is very similar at http www nedit org NEDIT runs on Unix with Motif and also supports exuberant CTAGs e GNU Emacs a free editor also supports exuberant CTAGs See http www gnu org software emacs emacs html 4 13 ALTERNATIVE LINKERS Compiled and linked code can be significantly compacted by using the linker available with the Professional Compiler Kit PK51 from Keil www keil com The LX51 Enhanced Linker suppl
177. the software timers Util tmr c lo tmr0 c amp h Serial O shares its priority bits with the interrupt of the EEPROM external interrupt 5 currently unused code is available in lo eeprom c Timer 0 shares its interrupt priority bits with FWCOL the flash write timing interrupt also unused flash code is in Util flash c The lowest priority is xfer_busy_isr Meter ce c and the rtc_isr interrupts lo rtc_30 c both share external interrupt 6 Meter io653X c These can usually wait up to half a second The XFER_BUSY interrupt in particular takes up to 4 milliseconds to copy data from the CE so though it is very important it needs to be low priority in order to let other interrupts run The RTC can be calibrated by using the 1 seconds and 4 second outputs of TMUX and measuring the external square wave against a traceable time standard All unused interrupts have stub routines that record and count a spurious interrupt and then disable the interrupt These are in meter io653x c Although the demo code does not do this it is possible to run preemptive code at the same interrupt priority as the main loop This creates a fifth priority below the lowest priority To do this set an interrupt to the lowest priority This interrupt s service routine must push the address of the fifth priority code on the stack and run RTI RTI clears the fourth priority hardware and then returns into the fifth priority code running it at the same interrupt l
178. timer is running These routines are very similar to the software timer commands in stm h 5 4 2 7 The XFER BUSY RTC and NEAR OVERFLOW Interrupt All of these slow events share one external interrupt The interrupt is decoded by an interrupt routine in Meter io653x c The XFER Busy interrupt x er busyz isr in Meter ce c is requested by the CE at the conclusion of every accumulation interval In the 6530 series waits until the CE is operating then it enables the pulse outputs After that for every interrupt it just sets a flag to tell the background data that fresh metering data is available The CE s data is read directly from CE RAM After reset the first second of data from the CE is discarded It takes about one second for the PLL in the CE to settle and therefore for the filtering to be reliable variable ce irst pass TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA The RTC interrupt performs any resynchronization of the real time clock In the 6530 this loads the latest timing adjustment and transfers pulse counts The near overflow interrupt is a diagnostic tool to find code that causes a watchdog interrupt 5 4 2 8 SERIAL Interrupt est isr lO ser0 c CLI serial0 c is the ISR servicing UART 0 This isr is just the hardware layer It calls an input macro SERO_RCV_INT and an output macro SERO_XMIT_INT that buffer the data The macros are defined in the options h include file
179. tion Next it counts accumulation intervals variable cai This count is useful to find the exact number of accumulation intervals for calibration or meter tests In a real meter this number is useful in a demand calculation because the average demand in a demand interval is the total VAh in a demand interval divided by the number of accumulation intervals UtiNmath c has a routine s2f to convert a power register into a floating point number Accumulating demand in a power register and then dividing avoids any possibility of floating point underflow in the demand calculation The demo code does not include a demand calculation because most customers have preferred algorithms The while loop synchronizes the meter calculation with the CE s accumulation interval RescalePhaseB is used only in the single phase demo code Some customers use a shunt on one element and a current transformer on the other These elements have different Wh count and rescaling adjusts PhaseB usually the lower accuracy in terms of PhaseA usually the higher accuracy current sensor TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation Me ComputeRMS derives the voltages and current numbers used for creep detection ComputeSmallRMS divides the Wh or VAh by the voltage to derive more accurate current values at small currents This works because the Wh and VARh have better filtering and a lower noise floor than the basic current
180. tions for external data 256 bytes of 2K of CMOS RAM typedef unsigned char pdata uint8p_t typedef unsigned short pdata uint16p t typedef unsigned long pdata typedef signed char pdata typedef signed short pdata typedef signed long pdata uint32p t int8p t int16p t int32p t The upper byte of the XDATA address is supplied by the SFR OxBF ADRMSB or USERP on the 71M653x meter ICs On other 8051 processors P2 is used for this purpose This memory range is accessed indirectly still fairly fast not battery backed up This is a logical place for nonvolatile globals like power registers and configuration data Type definitions for external data 2Kbytes of CMOS RAM accessed indirectly via a 16 bit register This is the slowest but largest memory area not battery backed up It can be used for everything possible On Keil s large memory model this is the default typedef unsigned char xdata typedef unsigned short xdata typedef unsigned long xdata typedef signed char xdata typedef signed short xdata typedef signed long xdata uint8x t uint16x t uint32x t int8x t int16x t int32x t Type definitions for external read only data located in code space typedef unsigned char code typedef unsigned short code typedef unsigned long code typedef signed char code typedef signed short code typedef signed long code uint8r t uint16r_t uint32r t int8r t int16r t int32r t Access is indirect via a 16 bit registe
181. ures included in the 71M653X Demo Boards in terms of software and some hardware To get the most out of this document the reader should also have available other 71M653X publications such as the 71M653X Demo Board User s Manual respective data sheets errata list and application notes for additional details and recent developments TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e 1 2 RELATED DOCUMENTATION Please refer to the following documents for further information e 71M653X Demo Board User s Manual for the IC of interest e 71M653X Data Sheet for the IC of interest e Signum Systems ADM 51 In Circuit Emulator Manual Software Version 3 11 4 or later e Keil Compiler Manual Version 7 5 or later e yVision2 Version 2 20a or later Manual TERIDIAN s web site http www teridian com should be frequently checked for updates application notes and other helpful information Questions to TERIDIAN Applications Engineering can be directed via e mail to the address e meter support teridian com 1 3 COMPATIBILITY STATEMENT Information presented in this manual applies to the following hardware and software revisions e 71M6531 and 71M6534 Demo Code Revision 4 4 15 e 71M6531 and Demo Board D6531N12A1 68 pin QFN Revision 1 0 or later es 71M6534 Demo Board D6534T4A1 120 pin LQFP Revision 1 0 or later e Signum Systems Wemu51 Software 4 4 11 8 15 2007 or later e Signum Systems ADM51 firmware versi
182. uring auto calibration ce active returns CE status none bool Meter io651x c ce enable Enables or disables the CE bool enable none Meter io651x c ce init Initializes the CE none bool Meter ce c ce reset resets the CE none none Meter io651x c cli command Line Interpreter none none Cli cli c enum SERIAL_PORT EE SIE Initializes the SLI s interface to port enum cli init any serial port SERIAL SPD bool Cli sercli c speed bool xon_xoff enum ok DEE Initializes the SLI s interface to SERIAL_SPD e cliO init SERO speed bool bool Cli serOcli c xon_xoff SN n enum clii init Initializes the SLI s interfaceto SERIAL_SPD bool Cli sertcli c SER1 speed bool TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation d jTERIDIAN Function Routine iptior Inpu Jutpul File Nam Name Description Input Output e Name xon xoff cmax EE HEET ia tia an E de Util math c cmd ce processes CE commands none none cmd ce c cmd ce data access Processes context for CE DATA none none Cli access c downloads uploads code data cmd download between various sources and none none Cli load c serial port cmd eeprom processes EEPROM commands none none Cli cmd_misc c cmd error assigns generic command mode none none Cli cli c error result code implements user dialog for cmd lo
183. vided by this demo code is to use a serial port communicating via either an infra red LED and phototdiode or a low speed current loop The infrared interface is popular in areas where the meter reader has access to the meter The current loop is popular when the meters are inside a building In this case a connector is avialable on the outside of the building to read all the meters within it 5 14 1 13 Support of Automatic Meter Reading The meter must keep running but must also present a consistent set of data for the asynchronous meter reading System The solution is to make a stable copy at a controlled time in the metering cycle and then let the AMR system read the stable data When the hand held unit logs on the serial protocol sets a flag update register asking the meter to copy the registers to stable storage See Meter Wmeter c the call to Update register inmeter run When the stable copy is available the flag register available is setto true If a read request occurs while the copy is going on i e xzegister available is false the protocol requests that the message be resent see Flag Flag0 c orflag1 c case R of the NoError case of do cmd This negative TERIDIAN Proprietary Copyright 2005 2008 TERIDIAN Semiconductor Corporation e acknowledge is supposed to occur when the message was garbled but in this case has the effect of delaying the read command until the copy is complete and a stable copy of the met
184. vious value CAL BAD 18 Set after reset when the read of the calibration data has a bad longitudinal redundancy check or read failure CLOCK UNSET 19 Set when the clock s current reading is A More than a year after the previously saved reading or B Earlier than the previously saved reading or C There is no previously saved reading In this case the clock s time is preserved but clock software cannot compensate for drift while it was turned off because it cannot find the interval of the power failure POWER BAD 20 Set after reset when the read of the power register data has a bad longitudinal redundancy check or read failure in both copies Two copies are used because a power failure can occur while one of the copies is being updated GNDNEUTRAL 21 Indicates that a grounded neutral was detected TAMPER 22 Tamper was detected 1 v1 1v1 1 TERIDIAN Proprietary 75 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation eA TER DIAN SEMICONDUCTOR CORF 71M653X Software User s Guide SOFTWARE A software defect was detected error software was called E g In banked code a subroutine address outside common code is given as a callback routine Or irq_enable interrupt disable is called more than irq disable SAGA 25 Element A has a sag Set in real time by the CE and detected by the ce busy interrupt ce busy isr in ce c within 8 sample intervals about 2 6ms A transition from normal oper
185. w the chip last woke but also permits the chip to transition to the LCD and sleep modes easily RESET V1 gt VBIAS BROWNOUT Figure 5 5 State Diagram of Operating Modes 5 18 PORTING 71M6521 CODE TO THE 71M653X 5 18 1 Flash Use The biggest issue when moving code from the 6521 to the 71M653x is the increased program memory While the 71M6521 has 32K most 653x series have at least 128K and the 71M6534 has 256K The 653x defaults to a 64K configuration so code from earlier meter chips will fit easily Creating banked code that uses the extra flash is a substantial discussion in itself See the section Creating banked code 5 18 2 Extra RAM The MPU now has access to 4K of RAM up from 2K Roughly 1K is allocated to the CE leaving 3K v1 1v1 1 TERIDIAN Proprietary 101 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation TERIDAN 5 18 3 CE Data Location is at XDATA 0x0000 CE data now resides in roughly the first 1K bytes of RAM from 0x0000 to 0x03FF The exact CE RAM usage varies with different CE code versions with single phased CE codes taking less RAM and three phase CE codes taking up to the limit Nonstandard CE codes may take more than 1K but these will come with instructions Standard CE configuration begins at 0x0010 Standard CE output areas begin at 0x0200 The Keil compiler must be configured to avoid the CE RAM If not both the CE code and MPU code will misbehave when the MPU writes
186. was Keil C version 8 03 with the BL51 linker the Lx51 linker is actually easier to use but not shown The Signum emulator software used was version 3 11 04 4 9 4 Setup of the Compiler Project This dialogue is for the project options of a 71M6531 which has 4 banks see Figure 4 1 Options for Target 2 element 3 wire delta default Device Target Qutput Listing c51 A51 BL51 Locate BL51 Misc Debug Utilities Teridian Semiconductor Corp 71M6513 Xtal MHz Use On chip ROM 0x0 OxFFFF Memory Model Large variables in XDATA Code Rom Size Compact 2K functions 64K progran D Use On chip XRAM Ox0 Ox1AFF Operating system None DI Use multiple DPTR registers Off chip Code memory Off chip Xdata memory Start Size Start Size Eprom 0x0000 010000 Ram 0x0400 01000 Eprom Ram Eprom Ram lv Code Banking Start End fr Banks 4 Bank Area 08000 DxXFFFF Li Cancel Defaults Figure 4 1 Setup of Keil Compiler for bank switched code When opening individual files by right clicking on the file names after opening the group folders listed under Target file options can be edited These options can be set to assign code to pages as shown in Figure 4 2 v1 1v1 1 TERIDIAN Proprietary 36 of 116 Copyright 2005 2008 TERIDIAN Semiconductor Corporation AA 71M653X Software User s Guide Options for Group CLI Properties csi A51 Path File Type 4

Download Pdf Manuals

image

Related Search

Related Contents

TCSHーBA - 東芝ライテック  Chefman RJ15-25-TR Use and Care Manual  添付文書 - マニー  Fisher & Paykel 420182 User's Manual    Final Report - Calvin College  Peindre sur béton  

Copyright © All rights reserved.
Failed to retrieve file