Home

71M652X - Software User`s Guide

image

Contents

1. H cli indexes N N 0 v Y put char amp c N CLI BASE cli index Y cli_index cli_index cli index CLI BASE cli but cli index NUL_ Y gt lecho 0 cli index CLI BUFF SIZE Y v tatus Serial Tx port cli buff cli id slatus Serial_Tx port cl_buff cl_idx status Serial_Tx portcl_bulf c_idx len N S_EMPTY status Y send off call when waiting Gall when waiting l gt y v dom cli index CLI BASE send crlf y T return TRUE ch buff NUL cli index CLI_BASE return TRUE return FALSE END Figure 5 17 cmd pending 1 7 TERIDIAN Proprietary 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDIAN SEMICONDUCTOR CORP EEPROM Read Write EEDATA 0xA0 write command EECTRL 0x03 transmit data command interrupt rcvd INT5 EEDATA address of MSB EECTRL 0x03 transmit data command interrupt rcvd INT5 EEDATA address of LSB EECTRL 0x03 transmit data command interrupt rcvd INT5 READ WRITE write or read EEDATA OxA1 read command EEDATA destination EECTRL 0x03 transmit data command EECTRL 0x03 transmit data command gn rcvd pv rcvd INT5 INT5 Multi byte operations continue here EECTRL 0x06 receive data command Bee rcvd IN
2. meter_run _run e Compute_Phase_Angle no xfer_update TRUE Y Determine Frequenc v s _Frequency v gain compensation v RTC Compensation v Compute RMS v Determine Peaks v Wh accumulate v Calc Voltage Phase v VARh accumulate v Calculate operating time v VAh accumulate Calibration requested v SelectPulses eo calibrate 4 yes Update registers for AMR v totals_ready TRUE v v pcnt update v meter LCD Figure 5 11 ce update TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA meter_LCD meter Icd active FAL no C Tic TRUE yes v no LCD Clear ce totals rdy TRU A Display CE OFF yes v beat my_beat ce_totals_ready FALSE yes y Save accumulated energy to my beat beat BROWNOUT cache arrange for blinking of decimal point no select_total gt MAX TOTAL yes yes Y meter totals select total decimal point on Clear display select phase y y DATE decimal point off select scroll date yes display display y other than date LCD mode select scroll
3. Name Function or LSB Value Format Lin XDATA bits Vrms_A Vrms element A 216 JVOSQSUM 23 unsigned 32 0x004B Irms_A Irms element A SCH a LOSOSUM 24 unsigned 32 0x004F Vrms_B Vrms element B t a JVISQSUM 25 unsigned 32 0x0053 Irms_B Irms element B SCH JJI1SQSUM 27 unsigned 32 0x0057 STATUS Status of meter See table for STATUS register DA unsigned 32 0x0063 CAI Count of accumula count 28 signed 32 0x0067 tion intervals since reset or last clear Whi Imported Wh all LSB of WOSUM JC signed 64 0x006B elements Whi_A Imported Wh i JE signed 64 0x0073 element A Whi_B Imported Wh 30 signed 64 0x007B element B VARhi Imported VARRh all LSB of WOSUM 34 signed 64 0x008B elements VARhi_A Imported VARh 36 signed 64 0x0093 element A VARhi_B Imported VARh i 38 signed 64 0x009B element B VAh VAh all elements LSB of WOSUM J3C signed 64 0x00AB VAh A VAh element A DE signed 64 0x00B3 VAh_B VAh element B 40 signed 64 0x00BB Whe Exported Wh all LSB of WOSUM M4 signed 64 0x00CB elements Whe_A Exported Wh 7 46 signed 64 0x00D3 element A Whe_B Exported Wh R A8 signed 64 0x00DB element B VARhe Exported VARh all LSB of WOSUM MC signed 64 Ox00EB elements VARhe_A Exported VARh i ME signed 64 Ox00F3 element A VARhe_B Exported VARh 50 signed 64 Ox00FB element B
4. 48 Figure 5 5 main Role m 49 b lSxxnctEme 52 Figure 5 7 stm run Process Software Timers non Jh eene menn enemies 52 Figure 5 8 CE SIM c aaa aida 53 Fig re 5 9 XFER_BUSY RTC ISR caes ditte sets on bad ee FL eei aida 54 Figure 5 10 Seral and NEE 55 ltr hM 56 gleti demsPAM IATER 57 Figure 5 13 Command Line un EE 58 Figure 5 14 Auto Calibration sesssseseseee ene eene nennen nennen ener en nene se enne s enhn senten rre 59 Figure 5 15 ce default Calibration cosida 60 Figure 5 16 Calibration Continue 61 Figure S 17 ue Pending seg vee oc te I um Lu 62 Figure 5 18 Single Byte Read Wifite i ciens iine cese rnnt ERA RA AIRE Aten 63 Figur 5 19 Multi Byte Read e EES 64 Figure 5 20 M lti Byte Wirte uendere r VLLL Peu AVE QUE CH A XR RD denna EU Lee Poe ERE Pro gea AY haue 65 Figur 5 21 Power Up Sequence tpe canned ren Ia e RE a EE e uad iirin eniai 67 Figure 5 22 Sag and Dip Conditions ccoo rere REENEN loce Yi be on Eo CUR FH LED HERR REO CERES EX EXE D E Fu a Ee ei eee 79 lei AMAT I de 79 Figure 5 24 Crystal Frequency over Temp
5. Wh absolute Y Y Y Standard option of kilowatt hours 3 999999 The value annunciator 3 at the beginning is optional if no other registers are supported Pulse output for 0 23KB Y Y Y Standard option of 1 kh pulse on both DIO 6 and DIO Wh absolute 2 8K version s pulse output is controlled by the CE value without MPU intervention VAn register 1KB N N opt N opt Optional volt amperes 999999 replaces Wh options VAn pulse output 0 25KB N N opt N opt Optional volt amperes 1 kh pulse replaces Wh options Wh equation 0 0 2KB Y Y Y Revision 1 7 TERIDIAN Proprietary 42 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide MERI DIAN SEMICONDUCTOR CORP Wh equation 1 0 2KB N N opt N opt Wh equation 2 0 2KB N opt N opt N opt Frequency 0 1KB N Y Y Inhibited if freq gt 70Hz or voltage is below the register threshold Wh net metering 0 4KB N N opt Y Used only for automatic calibration No display is provided Wh export register 0 25KB N N opt N opt Wh exported display reads 3 999999 Wh export pulse 0 25KB N N opt N opt Wh exported display reads 3 999999 output VARh register 0 1KB N N opt Y For autocalibration and power factor calculation signed net metering VARh pulse 0 25KB N N opt Y output VARh import 0 4KB N N opt Y
6. O Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDIAN Proprietary DEMHAN SEMICONDUCTOR CORP 71M652X Software User s Guide Whn LSB of WOSUM signed 64 elements A Whn_A Net metered Wh LSB of WOSUM 56 signed 64 0x0113 element A for autocalibration Whn_B Net metered Wh D 58 signed 64 0x011B element B for autocalibration VARhn Net metered VARh LSB of w0sum 5C signed 64 0x012B all elements VARhn A Net metered VARh LSB of w0sum 5E signed 64 0x0133 element A for auto calibration VARhn_B Net metered VARh J60 signed 64 0x013B element B for auto calibration MainEdgeCnt Count of voltage zero count 64 unsigned 32 0x014B crossings Wh Default sum of Wh LSB of w0sum J65 signed 64 0x014F nonvolatile Wh A Wh element A 67 signed 64 0x0157 nonvolatile Wh_B Wh element B 69 signed 64 0x015F nonvolatile StatusNV Nonvolatile status See Status JD n a 32 0x016F M6521F 32K only compilation option in M6521D 16K Compilation option available Demo Code variable present but not in use T Requires features not in standard demo PCB Table 5 12 MPU Memory Location Revision 1 7 TERIDIAN Proprietary 78 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation A a 5 14 FIRMWARE APPLICATION INFORMATION 5 14 1 Sag Detection A sag is defined as an undervoltage condition that persists fo
7. This project consisting of several files demonstrates the use and test of the software timer using a hardware timer that is multiplexed into many slower timers The Keil project file is stmtest uv2 5 18 8 Interrupt Test This Test Module is written in 8051 assembler and can be used for testing the function of the INTO INT1 TMRO and TMR1 control using DIO Rx When the code is run it configures all possible DIO pins as DIO input pins When testing a breakpoint should be set on the vector for one of INTO INT1 TMRO TMR1 Also one of the I O RAM registers DIO RO DIO R11 should be set to the resource code for that vector When the DIO pin under test is probed with GND or V3P3 the programmed interrupt is generated The code sets up DIO 4 5 6 and 7 for one each of four interrupts The Keil project file is inttest uv2 TERIDIAN Proprietary 100 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation A a 6 80515 MPU REFERENCE An 80515 core is implemented on the TERIDIAN 71M652X chips This section is intended for software engineers who plan to use the 80515 6 1 80515 OVERVIEW The 80515 is a fast single chip 8 bit micro controller MPU core It is a fully functional 8 bit embedded controller that executes all ASM51 instructions and has the same instruction set as the 80C31 The 80515 provides software and hardware interrupts an interface for serial communications a timer system and a watchdog timer 6 1 1 8
8. BROWNOUT mode v display selected v quantity on LCD meter_totals select_scroll 0 decimal point on yes v increment select scroll reset selector after it reached maximum select scroll 0 d Figure 5 12 meter LCD TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN Command Line Interpreter cli v U08 data d cli result NULL z i result NULI e amp d FALSE toupper d cli result OK ID Y N Y toupper d cmd ce data access N Y toupper d cmd mpu data access y N Y toupper d C cmd_ce N Y toupper d E cmd eeprom N Y n Y toupper d l cmd i N Y y toupper d M cmd meter N toupper d P cmd power save N cmd profile toupper d 7 R cmd go cmd sfr Y toupper d 7 T cmd mpu data access N Y toupper d Z cmd Ce ele Li toupper d 0 send help Usage y N cmd_H d toupper d 7 cmd i d cmd_meter M Ai Y 20 Figure 5 13 Command Line Interpreter on 1 7 TERIDIAN Proprietary 58 of 138 O Copyright 2005 2007 TERIDIA
9. Convert a 64 bit internal watts count to a 6 digit value i e this is the routine that precalculates values for wh brownout to Icd uint8 t val uint32_t wh c 5 16 ERRATA The up to date list of known issues with the current revision of the Demo Code can be found in the readme txt file contained in the 6521_demo ZIP file shipped with the Demo Kits The readme txt file also contains a list of corrected issues that might assist customers who utilized older versions of Teridian demo code The factory should be contacted for updates to the Demo Code Revision 1 7 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 95 of 138 e 5 17 PORTING 71M6511 6513 CODE TO THE 71M6521 5 17 1 Memory Use The biggest issue when moving code from the 6511 6513 to the 71M6521 is the reduced program memory While the 71M6511 and 6513 have 64K the 6521 has 32K 16K and 8K versions The standard 6521 CE code has 414 bytes and takes up space in flash In order to make the code fit and reduce the risk of running out of memory TERIDIAN s firmware engineers coded to a space budget and adopted a coding standard that permits entire features to be added and removed easily This method proved to be very useful when there were changes of scope in one or another version of the demonstration firmware 5 17 2 CE Code Location Another difference between 71M6511 6513 and the 71M6521 is that the CE
10. 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 7a does the switching of modes in the main routine based on decisions made in batmodes_20 c Figure 5 21 shows the actions taken by the Demo Code and chip hardware after entering the main routine 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 RESET input e PB input Start here 1 On power up 2 On HWDT Overflow 3 If PB pressed 4 On wake up from LCD or Sleep Modes 5 6 If Reset Button Pressed Soft Reset function invoked Restart Hardwrare WDT Check if HWDT has overflowed Set Status register Clear Overflow flag Invoke Soft Reset On power up will remain in this loop till PLL ok flag is set and Brownout interrupt occurs which invokes a Soft Reset Is battery mode enabled Checked by Hardware Already in Is Reset Is Push Is V3P3 N N N N Y Is PLL ok Brownout Button Button Sys mode Pressed Pressed Present Yy Mission mode Sleep mode Brownout Mode LCD mode Sleep mode Initialise
11. 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 A direct 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 jump if not zero No operation Table 6 12 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
12. on this port none none sertcli c Seriall RxFlowOn den AON ioo png none none sertcli c Transmit a string of any uint8x_t buffer uint16_t Seriall Tx length len none sertcli c SFR Read reads from SFR uint8 t s SO8d pc enum SFR RC sfrs c i uint8 t s uint8 tc set SFR Write writes to SFR uint8 t c clr enum SFR RC sfrs c start tx ram Tus RAM string out PG uint8_tx c none io c start tx rslt mes ROMistring out PE uint8_tr c none io c This counts down the stm run software timers when called void void stm c from the main loop Starts a software timer If restart is zero the timer stops otherwise it contin y gt ERA uint16 ttick count ues indefinitely When a zi Se Sa volatile uint16x_t stm atart timer expires its function is EE cnt_ptr SR run Timers count down and P are deallocated if they cease to run Uses a count pointer from aas stm stop start to identify which soft e om void stm c ware timer to stop P Revision 1 7 TERIDIAN Proprietary 93 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation aes 71M652X Software User s Guide Waits for the passed stm wait numberof dock ticks uint16 t void stm c strlen r returns length of string in uint8_tr src uint16_t library c flash code strlen x bela length of string in uint8 tx src uint16 t library c subs 4 uint64 t x uint32_t
13. 71M6521D 71M6521F 71M6521B Energy Meter IC Family SOFTWARE USER S GUIDE 8 6 2008 Revision 1 7 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 71M652X 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 Revision 1 7 TERIDIAN Proprietary 2 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide 1 TEMDAN SEMICONDUCTOR CORP Revision 1 7 71M652X Energy Meter IC FAMILY SOFTWARE USER S GUIDE TERIDIAN Proprietary 3 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation MATERI DIAN SEMICONDUCTOR CORF 71M652X Software User s Guide Table of Contents EE INTRODUCTION 13 1 1 Using this Document P 13 1 2 Related Documentation eese esee eseeeee nennen nennen nannten ananas sse nenas status asses n aeter anat anna nnn 14 1 3 Co
14. EX3 Enable external interrupt 3 IEX3 External interrupt 3 flag EX4 Enable external interrupt 4 IEX4 External interrupt 4 flag EX5 Enable external interrupt 5 IEX5 External interrupt 5 flag EX6 Enable external interrupt 6 IEX6 External interrupt 6 flag EX_XFER Enable XFER_BUSY interrupt IE XFER XFER BUSY interrupt flag EX RTC SFR special function register enable bits must be set to permit any of these interrupts to occur Likewise each interrupt has its own flag bit which is set by the interrupt hardware and is reset automatically by the MPU interrupt handler 0 through 5 XFER BUSY and RTC_1SEC which are OR ed together have their own enable and flag bits in addition to the interrupt 6 enable and flag bits see Table 6 52 and these interrupts must be cleared by the MPU software Enable RTC_1SEC interrupt IE RTC RTC 1SEC interrupt flag Table 6 55 Control Bits for External Interrupts Interrupt Priority 0 Register IPO MSB MSB OWDS WDTS IPO 5 IPO 4 IPO 3 IPO 2 IPO 1 EE Table 6 56 The IPO Register Note OWDS WDTS are not used for interrupt controls Interrupt Priority 1 Register IP1 LSB IP1 5 IP1 4 IP1 3 IP1 2 IP1 1 IP1 0 Table 6 57 The IP1 Register Priority Level LevelO lowest Level1 Level2 Table 6 58 Priority Levels External inter
15. Move register to direct byte MOV direct direct 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 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 11 Data Transfer Operations TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation aj in 2 N N afaja aja a O0O N N 0O N O0O N N N N N a n Mnemonic Description d J TERIDIAN ACALL addr11 Absolute subroutine call o LCALL addr16
16. temp nom 4 74074 bga 500 310000 900 p ifdef M6511 td tn 27L 64L 128L th S32 trimbga 500 tj th 370000L tf td tj c tf 5L 9L td S32 trimbgb 100 tj th 14L 5L 10L d td tj th S32 trimm 100L 50L td 28L c tf td 330000L 5L 10L th tf d 5000L 10000L tl 33L c 50L 100L tn tl 790L a th tn td 2L c tf td 20000L th tf d 500L 1000L b th 460000L Figure 5 16 Calibrati on continued TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation c temp_nom 2 bga 500 370000 900 d bgb 10 Hm 0 5 0 14 a 0 28c 33 d 0 33c 7 9 b 0 0002c 0 02 d 0 46 SEMICONDUCTOR CORP Command Pending cmd pending no entry N L Merz Serial CRx port CMD_BUFF_SIZ Y return FALSE UARTO echo echo0 status Serial_Tx port cb len per CR m S EMPTY l status memcpy_xx cp 1 cp len i 1 Y cp LF_ call when waiting leni SE cp cb i len Y len c cp got A
17. 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 P Master Setup IceServer remote access to emulators Drivers Utilities Evaluation Board Program Demonstration Program Frequently Asked 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 d To install run 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 23 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation of T ERIDAN SEMICONDUCTOR CORF 71M652X 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
18. External interrupt 2 Ip1 2 IPO 2 External interrupt 1 External interrupt 3 Ip1 3 IPO 3 Timer 1 interrupt External interrupt 4 Ip1 4 IPO 4 UART 0 interrupt External interrupt 5 IP1 5 IPO 5 Table 6 53 Priority Level Groups External interrupt 6 Each group of interrupt sources can be programmed individually to one of four priority levels by setting or clearing one bit in the special function register IPO and one in IP1 If requests of the same priority level are received simultaneously an internal polling sequence determines which request is serviced first The functionality and edge polarity of the external interrupts are described in Table 6 51 Revision 1 7 Digital I O High Priority see DIO Fix 0 automatic 1 Digital UO Low Priority see DIO_Rx automatic 2 Comparator falling automatic 3 CE_BUSY falling automatic TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 131 of 138 d jTERIDIAN Comparator rising automatic EEPROM busy falling automatic XFER BUSY OR RTC 1SEC falling manual Enable Bit Table 6 54 External MPU Interrupts Description Flag Bit Description EXO Enable external interrupt 0 IEO External interrupt 0 flag EX1 Enable external interrupt 1 IE1 External interrupt 1 flag EX2 Enable external interrupt 2 IEX2 External interrupt 2 flag
19. Move carry flag to direct bit Table 6 13 Boolean Manipulations TERIDIAN Proprietary NI MPMI MI PM PLM gt hM gt Ph Copyright 2005 2007 TERIDIAN Semiconductor Corporation WIM MPMI MM Ww gt oo eo d jTERIDIAN Mnemonic 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 ffdata 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 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 ARO ADDC A RO ANL A RO DEC R1 ADDC A QR1 ANL A R1 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
20. Revision 1 7 TERIDIAN Proprietary 29 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation ATERI DIAN SEMICONDUCTOR CORP 71M652X 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 652X 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 CLI_652X drive letter gt meter project docs lt drive letter gt meter project flag drive letter gt meter project lO lt drive letter gt meter project Main_6521 drive letter gt meter project Main_6521_ CLI lt drive letter gt meter project Meter lt drive letter gt meter project Util The project control file 652X_demo uv2 will be in the directory lt drive letter gt meter project The Keil compiler can be configured easily by loading the file 652X_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 6521_CLI pVision2 Z Meters Firmware Test 6521 Main main c B file Edit View Project Debug Flash Peripherals Tools SVCS Window Help PX SET EECH MECHER WE 7401390000970 E 9 Target zl Project workspace DECH R
21. cal ldr c initialization configuration read and write routines for LCDs routines for driving Varitronix VIM 808 LCS RTC read write reset and trim routines baud rate table shared by ser0 c and ser1 c initialization configuration interrupt read and write routines for SERO initialization configuration interrupt read and write routines for SER1 legacy code that implements a fully buffered interrupt driven serial driver initialization 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 71M6521 see comments in the source file a 3 wire interface using the high speed 3 wire interface hardware of the 71M6521 Main top level tasks 6521 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 interru
22. fwcolO Flash Write collision fwcol isr EXT2 flash c 0x4B 0 fwcol1 CE Busy ce busyz int EXT3 ce c 0x53 3 Power fail power return pll_isr EXT4 batmodes 20 c Ox5B 3 EEPROM eeprom isr EXT5 eeprom c 0x63 0 XFER busy ce xfer busyz rtc int EXT6 shared ce c 0x6B 2 w RTC RTC rtc_isr EXT6 shared rtc c 0x6B 2 w XFER TimerO tmrO Iert tmr0 c 0x0B 0 Timer1 tmr1 isr tmr1 c 0x1B 3 UART 0 es isr serial c 0x23 0 UART 1 es1 isr 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 6521 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 re
23. primes none none cli c pump for result codes send rtc displays RTC data none none cmd misc c send short sends a 0 99 999 value to int16 tn none io c DTE send short hex sends a 0 FFFF value to uint16 tn none io c DTE Ser disable rcv rd Disable the receive void void ser0 h ser1 h yO interrupt ser disable xmit_r Disable the transmit void void ser0 h ser1 h dy interrupt ser enable rcv rdY Enable the receive interrupt void void sert bh ser1 h Ser enable xmit rd Enable the transmit void void ser0 h ser1 h yO interrupt configures the serial port Ser initialize specified in the include file enum baud none serO h ser1 h ser0 h or ser1 h E sin byte from the serial Lig uint8_t ser0 h ser1 h Returns true if the last ser rcv err received byte had an error void bool serO h ser1 h Returns true if the serial ser rcv rdy port has gotten another void bool Ser bh ser1 h byte ser mit Es SEENEN uint8_t void serO h ser1 h ser xmit err Returns true if the last sent void bool ser0 h ser1 h byte had an error Unimplemented routine to ser xmit free permit other uses of void void serO h ser1 h transmit electronics ser xmit_off Unimplemented routine to gei void ser0 h ser1 h disable transmit electronics ser_xmit_on Unimplemented routine to void void serO h ser1 h enable transmit electronics TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporati
24. 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 If the resulting build is too big to fit the available program memory then more features must be disabled 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 REG652X H Register definition of 652X SFRs and I Os e O652X H and 106512X C I O RAM register definitions e CE652X H and CE652X C CE data and structure declarations TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA 5 11 3 Other Include Header Files Other Include Header files are CLI H Result code and Common ASCII code definition used for CLI HELP H HELP message prototype declarations IO H I O subroutines for CLI SEROCLI H SER1CLI H hardware access layer for UARTO UART 1 SERCLI H include definitions for UART 0 1 debug routines FLAGO H FLAG1 H FLAG H shared logic for all FLAG interfaces EEPROM H EEPROM 112 H 12C Interface LCD H LCD RTC H Real Time clock SERO H SER1 H
25. y uint8 tx x uint8_tx y none math c sub8_8 uint64 t x uint64_t y uint8 tx x uint8 tx y none math c Displays the current delta temperature lcd uu enc ds C void void meter c on the LCD time lcd Displays the current time void void rtc c tmr disable Halt a timer none none tmrO h tmr1 h Lets a timer run timer start tmr enable does this by default none none tmr0 h tmr1 h tmr running See Ue INING METIS none bool tmrO h tmr1 h uint16 t time in timer units uint8 t restart flag zero means tmrO h tmr1 h tmrO c tmr start Starts a hardware timer interrupt once void none tmr1 c code pfn void code to execute tmr_stop Stops a hardware timer none none tmrO h tmr1 h tmrO isr Timer interrupt for TMRO none none tmr0 c tmrl isr Timer interrupt for TMR1 none none tmr1 c Move data from AMR s copy update register ofpower registers into void void meter c power registers uwr busy wait Wait for programming com hone none uwrdio c uwreep c2 plete indication ved Initialize a 3 wire similar to uwr init uWire interface none none uwrdio c uwreep c2 uwr read Get a counted string of uint8x t pbOut none uwrdio c uwreep c2 bytes uint16 t cnt Select a chip by passing its address 0 none This uwr select must be ported to new uint8 t address none uwrdio c uwreep c2 PCBs i Transmit a counted string of uint8x_t pbOut bool true uwr_write bytes uint16 t cnt Succ
26. 10 none none calibration c EEPROM Calculates phase angles qo ie ane between voltages of void void vphase c different phases Revision 1 7 TERIDIAN Proprietary 82 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation d jTERIDIAN Function Routine Description Input Output File Name Name P P P calibrate processes measurements none none calphased c during auto calibration ce active returns CE status none bool ce c ce enable Enables or disables the CE bool enable none ce c ce init Initializes the CE none bool ce c ce_reset resets the CE none none ce c cli command Line Interpreter none none cli c enum SERIAL PORT eli initi Initializes the SLI s interface port enum bool sercli c3 to any serial port SERIAL_SPD speed bool xon_xoff clio initi Initializes the SLI s interface enum SERIAL_SPD bool serOcli c3 to SERO speed bool xon_xoff clil initi Initializes the SLI s interface enum SERIAL_SPD bool sertcli c3 to SER1 speed bool xon_xoff omax bola sol PR uint8 ta uint8 tb uint8_t math c unsigned char a and b cmd ce processes CE commands none none cmd ce c Parc access io usd context for CE nona ndna decessit downloads uploads cmd download code data between various none none load c Sources and serial port processes EEPROM cmd eeprom none none cmd mis
27. 2007 TERIDIAN Semiconductor Corporation MERI DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP 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 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 6521 UV2 or 6521UV3 This will start the Keil compiler with the proper settings stored in the 6521 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 Select the 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
28. Before downloading code to a 71M6521 e Stop the MPU e Disable the CE by writing a 0 to XDATA at address 0x2000 e Erase the flash memory 3 4 DEBUGGING OF THE 71M652X 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 71M652X 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 652X 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 2007 TERIDIAN Semiconductor Corporation q ATER DIAN 71M652X Software User s Guide icin GORR 3 5 1 Running the 652X_Demo hex Program This object file is the 71M652X 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
29. Controlling the Keil Compiler Settings 32 4 8 Project Management Tools seeeeeseeeeeeeeeeeeee eene rr 35 4 9 Alternative Compilers pe 35 4 10 Alternative Editors 5rornssiciiisie tiki na ieu in statis ti cie 35 4 11 Alternative Linkers R 36 Denies Demo Code Description 37 5 1 80515 Data Types and Compiler Specific Information cccccecceseeseneeeeeeeeeeeeeeeeneeeeseeeeneeeseeeeneeeeeee 37 5 1 1 Data Types 37 5 1 2 Compiler Specific Information 40 5 2 Demo Code Options and Program Size eeeeseeeeeeeeeeeee nennen enn enne nnnm nnne satin anite nnns 41 Revision 1 7 TERIDIAN Proprietary 4 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide Y A TERIDIAN SEMICONDUCTOR CORP 5 3 Program ioo e is 46 5 3 1 Startup and Initialization 46 5 4 Basic Code Architecture iio ii 49 5 4 1 Initialization 49 5 4 2 Foreground 50 Timeless 51 CE iudi tarea 53 XFER BUSY and RTC IntermpL iua oet rero tn eerta ene een 53 5 4 2 1 SERIAL Interrupt nene eter Dre Ere Dor e Eve Fi Deva a eco RE eect 55 5 4 3 Background Tasks 56 Meter MUM mem T daeete 56 uz Ce e E 57 Command Line Interpreter iii ii a EU go ox LE dg Hee toc 58 Aut6 Calib ration et 59 CE Default Callbrati n 2 2 12 rire erre eda atada 6
30. Copyright 2005 2007 TERIDIAN Semiconductor Corporation Se 71M652X Software User s Guide IICStart IIC bus s start condition none none iiceep c IICStop IC bus s stop condition none none iiceep c init meter Initializes MEIR to derau none none defaults c m values Defines variables used by IRQ DEFINES macros to enable and n a n a irq h disable interrupts irq disable Disables interrupts void void irq c The fastest way to disable interrupts Requires IRQ DISABLE IRQ DEFINES to be earlier n a n a irg h in the code or that the needed symbols be defined irq enable Enables interrupts void void irq c The fastest way to enable interrupts Requires IRQ ENABLE IRQ_DEFINES to be earlier n a n a irq h in the code or that the needed symbols be defined irg init Initializes interrupt control void void irg c labs returns the absolute value int32_tx 332 math c latan2 returns the arcTangent int32 t sy int32 t sx U32 math c LCD CE Off displays CE OFF on LCD none none Icd c LCD Command ume BoE eon ol clears uint8 t LcdCmd none Icd c display uint8_t num enum LCD_Config configures LCD parameters eLCD_mode bias enum none Icd c LCD CLK clock LCD Data Read cs from selected icon of ue ticon uint16_t ed o i writes to selected icon of uint8_t icon uint16_t LCD Data Write LCD Mask none Icd c LCD Hello displa
31. 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 Revision 1 7 TERIDIAN Proprietary 24 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation SEU DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Add New Hardware Wizard Click Finish Setup Complete RD Click 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 07 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 07 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 Revision 1 7 TERIDIAN Proprietary 25 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation SEU DIAN SEMICONDUCTOR CORR 71M652X Software User s Guide 4 5 CREATING A PROJECT Double click on the WEMUB1 icon
32. MOVX A Ri or MOVX A DPTR instruction There is an improved variable length access for the MOVX instructions to access fast or slow external RAM and external peripherals The three low ordered bits of the CKCON register define the stretch memory cycles Setting all the CKCON stretch bits to one allows access to very slow external RAM or external peripherals Table 6 2 shows how the signals of the External Memory Interface change when stretch values are set from 0 to 7 The widths of the signals are counted in MPU clock cycles The post reset state of the CKCON register which is in bold in the table performs the MOVX instructions with a stretch value equal to 1 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERMINAN CKCON register Stretch Value Read signals width Write signal width CKCON 2 CKCON 1 CKCON O memaddr memrd memaddr memwr 0 0 0 1 1 O OINI DD O AJOJN zl OI oa AJOJN gt o INIIAI AJ Ww rym Table 6 2 Stretch Memory Cycle Width There are two types of instructions differing in whether they provide an eight bit or sixteen bit indirect address to the external data RAM In the first type MOVX Ri the contents of RO or R1 in the current register bank provide the eight lower ordered bits of address The eight high ordered bits of address are specified with the USR2 SFR This method allows the user page
33. Main Run Main Loop Figure 5 21 Power Up Sequence TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation e powered down the 71M6521 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 S In general to work in an operational meter not a demo meter the firmware has to be written to yo handle the case of connecting a battery to a powered down board since in a factory setting S batteries will most likely be added to meter boards that are powered down The firmware must immediately enter sleep mode in this situation 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 EEPR
34. Scaling maximum 0 1A JA unsigned 16 0x0017 current for PCB element A equi valent to 176mV at the IA pin ppmc1 ADC linear adjust PPM per degree centigrade JB signed 16 0x0019 with temperature ppmc2 ADC quadratic adjust PPM per degree centigrade JC signed 16 0x001B with temperature squared Pulse 3 source Source for software See table for PulseWSource and D unsigned 8 0x001D pulse output 3 PulseVSource Pulse 4 source Source for software See table for PulseWSource and JE unsigned 8 0x001E pulse output 4 PulseVSource Scal Duration for auto Count of accumulation intervals to F unsigned 16 0x001F calibration in be used for auto calibration seconds Vcal Voltage value to be Nominal RMS voltage applied to 10 unsigned 16 0x0021 used for auto calibration all elements during auto calibration LSB 0 1V O Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDIAN Proprietary ALERTAS 71M652X Software User s Guide Ical Current value to be Nominal RMS current applied to y11 unsigned 16 0x0023 used for autocalibra all elements during auto calibra tion tion LSB 0 1V Power factor must be 1 VThrshld Voltage at which to LSB 2 5 IVOSOSUM 12 unsigned 16 0x0025 measure frequency zero crossing etc This feature is approximated using the CE s sag detection PulseWidth Maximum time p
35. Start Procedure Refreshing the WD Timer Special Function Registers for the WD Timer Software Watchdog Timer Interrupt Enable 0 Register IENO Interrupt Enable 1 Register IEN1 Interrupt Priority O Register IPO Watchdog Timer Reload Register WDTREL The Interrupt Service Routine Unit 6 3 5 1 Interrupt e NEE 6 3 5 2 Special Function Registers for Interupts esesseeeiierirsrrirssrrireerrnrerrsnrens Interrupt Enable Interrupt Enable Interrupt Enable 0 Register IEO 1 Register IEN1 2 Register IEN2 Timer Counter Control Register TCON Interrupt Request Register IRCON 6 3 5 9 External INterrupis iie rrt RB rpm PIRE REPRE Interrupt Request register T2CON 6 3 5 4 Interrupt Priority Level Structure emen Interrupt Priority Interrupt Priority 0 Register IPO 1 Register IP1 6 3 5 5 Interrupt Sources and Vechors eee External Interrupt Edge Detect Appendix ACRONYMS Revision HIStory TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN List of Figures Figure 2 1 Sotware SUturo 16 Figure 3 1 Port Speed and Handshake Getup eene nennen nnne entren nennen renes 21 Figure 15S TARTU PIAS Vises EE 46 Figure S ZANTAS eerie EM 46 Figure 5 3 main PO ro 47 Fig r 5 4 main init FUNGUO E
36. 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 GZ a Z Meters Firmware T est 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 Revision 1 7 TERIDIAN Proprietary 34 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA 4 8 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 9 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 BUILD6521 BAT is provided with the Demo Kit to support b
37. any time 6 3 5 The Interrupt Service Routine Unit The 80515 provides 11 interrupt sources with four priority levels Each source has its own request flag s located in a special function register TCON IRCON SCON Each interrupt requested by the corresponding flag can be individually enabled or disabled by the enable bits in SFRs IENO IEN1 and IEN2 6 3 5 1 Interrupt Overview When an interrupt occurs the MPU will vector to the predetermined address as shown in Table 6 58 Once interrupt service has begun it can be interrupted only by a higher priority interrupt The interrupt service is terminated by a return from instruction RETI When an RETI is performed the processor will return to the instruction that would have been next when the interrupt occurred When the interrupt condition occurs the processor will also indicate this by setting a flag bit This bit is set regardless of whether the interrupt is enabled or disabled Each interrupt flag is sampled once per machine cycle then samples are polled by the hardware If the sample indicates a pending interrupt when the interrupt is enabled then the interrupt request flag is set On the next instruction cycle the interrupt will be acknowledged by hardware forcing an LCALL to the appropriate vector address if the following conditions are met e No interrupt of equal or higher priority is already in progress e Aninstruction is currently being executed and is not completed e The
38. between Mode 2 and Mode 3 is that in Mode 3 either the internal baud rate generator or timer 1 can be use to specify the baud rate Note The common FLAG protocol requires the data format to be 7E1 This can be implemented using one of the 8 bit modes where the MSB bit 0 is the parity bit In this mode the MPU calculates parity Serial Interface 0 Control Register SOCON The function of the serial port O depends on the setting of the Serial Port Control Register SOCON MSB LSB sus swr E Tee me 76 m Table 6 27 The SOCON Register Bit Symbol Function SOCON 7 SMO Sets baud rate SOCON 6 SM1 Sets baud rate SOCON 5 SM20 reserved SOCON 4 RENO If set enables serial reception Cleared by software to disable reception SOCON 3 TB80 The 9 transmitted data bit in Modes 2 and 3 Set or cleared by the MPU depending on the function it performs parity check multiprocessor communication etc SOCON 2 In Modes 2 and 3 it is the 9 data bit received In Mode 1 if SM20 is O RB80 is the stop bit In Mode O this bit is not used Must be cleared by software SOCON 1 Transmit interrupt flag set by hardware after completion of a serial transfer Must be cleared by software SOCON O Receive interrupt flag set by hardware after completion of a serial reception Must be cleared by software Table 6 28 The SOCON Bit Functions TERIDIAN Proprietary O Copyright 2005 2007 TERIDIAN Semiconducto
39. 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 4 at XDATA 0x20A8 is set to the most significant 5 bits of the program flash address where the CE program resides It is best to place the CE program within the first 8Kbytes so that the program design adapts easily to the three size variants of the chip 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 the CE must first be disabled then the code must wait until the CE is halted Only then programming of the flash memory can occur Should there be an attempt to modify flash memory while the CE is running the FWCOLO and FWCOL1 interrupt bits are set If the interrupt is enabled recovery action can occur TSC s demo firmware has not found a use for the FWCOL interrupts 5 17 3 Battery Modes One of the most significant innovations for the 71M6521 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 26 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 RT
40. during multiply and divide instructions It can also be used as a scratch pad register to hold temporary data Program Status Word PSW MSB LSB CV AC FO RS1 RS OV P Table 6 18 PSW Register Flags Function Carry flag Auxiliary Carry flag for BCD operations General purpose Flag 0 available for user Register bank select control bits The contents of rs1 and rsO select the working register bank as follows 0 0 Bank 0 0x00 0x07 0 1 Bank 1 0x08 OxOF 1 0 Bank 2 0x10 0x17 1 1 Bank 3 0x18 0x1F Overflow flag User defined flag Parity flag affected by hardware to indicate odd even number of one bits in the Accumulator i e even parity Table 6 19 PSW Bit Functions TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN The state of bits RS1 and RSO select the working registers bank as follows RS1 RSO Bankselected Location 00 Bank 0 00H 07H 01 Bank 1 08H OFH 10 Bank 2 10H 17H 11 Bank 3 18H 1FH Table 6 20 Register Bank Location Stack Pointer The stack pointer is a 1 byte register initialized to 07H after reset This register is incremented before PUSH and CALL instructions causing the stack to begin at location 08H Data Pointer The data pointer DPTR is 2 bytes wide The lower part is DPL and the high
41. helpful information Questions to TERIDIAN Applications Engineering can be directed via e mail to the address e meter support g teridian com 1 3 COMPATIBILITY STATEMENT Information presented in this manual applies to the following hardware and software revisions e 71M6521 Demo Code Revision 4 7a e 71M6521 Demo Board D6521T12A1 68 pin QFN Revision 1 0 or later e 71M6521 Demo Board D6521T4A8 64 pin LQFP Revision 8 or later e Signum Systems Wemu51 Software 3 07 00 2 14 2005 or later e Signum Systems ADM51 firmware version 3 2005 02 08 or later The revision 4 7a of the Demo Board Code is the basis for all discussed sources commands register addresses and so forth Known issues with this revision are disclosed within the code description and workarounds or improvements are shown TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA 2 DESIGN GUIDE This section provides designers with some basic guidance in developing power meter applications utilizing the TSC 71M652X 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 71M6521 Demo Board This board interfaces with a PC via the RS232 serial interface COM port e AC
42. include file called out in stm c has to be changed to tmr1 h timer1 is used for delay functions e g for EEPROM or RTC access control Timer 1 is enabled and starts functioning by calling the Add Delay Func function as defined in the timer c module 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 timer is running These routines are very similar to the software timer commands in stm h TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN tmrO isr tmr1 isr yes v Reload with THO TLO Stop timer Reload with TH1 TL1 Stop timer pplication nee no plication nee no timer0 timer1 yes Y yes Y Run timer routine for Run timer routine for application application v v Reset tmr0 SW watchdog Reset tmr1 SW watchdog Figure 5 6 Timer ISRs stm run _Y pTimers tick cnt lt gt 0 amp Timers NUM_TIMERS y pTimers i NUM_TIMERS amp Timers NUM_TIMERS v N i NUM TIMERS gt Y Timer pre
43. inexpensive it saves the resistor is to complete the last data write without any special modes then send another 8 bits of zero with the wait for ready and high Z bits set for that transfer Note that sending one bit of zero works in simulations but not in the lab for reasons that are not yet clear The demo source code also includes a programmed lO bit banging driver uwrdio c This driver lets 71M6511 and 71M6513 chips use 3 wire EEPROMs so meter product lines can share an inventory of identical EEPROMSs Also the 71M6521 s 3 wire interface hardware is not flexible enough to drive some items designed for SPI It only supports one clock polarity one clock edge and the data line is half duplex The programmed lO driver is designed to be easily modified for these environments TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA SEMICONDUCTOR CORP 5 17 5 Temperature Compensation When operating with internal temperature compensation the 71M6511 and 71M6513 ICs use the CE as the compensation mechanism Compensation is then based on the temperature deviation from nominal and the PPMC and PPMC2 factors that are either derived from the on chip fuses 71M6511H 6513H or standard values 71M6511 6513 that apply to the average chip In the 71M6521 the CE is no longer in charge of temperature compensation In the 71M6521 the temperature calculations are performed once per second in the MPU firmware see Gai
44. interval as the timebase for the software timers Util tmr c lo tmr0 c amp h Serial O shares its priority bits with TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA 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 c both share external interrupt 6 Meter io652x 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 RTC 1 Second interrupt to toggle a DIO pin and measuring the external square wave against a traceable time standard In this case a calibration mode must temporarily turn off the CE it shares the interrupt set external interrupt 6 to the highest priority and the code leading from the vector to the RTC s DIO toggle should have an unchanging execution time 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 interrup
45. is below the threshold no frequency or edge counts are reported If the current is below the minimum no current Wh VARh or VAh are reported The MPU s creep thresholds are configurable VThrshld IThrshld The MPU calculates human readable values and accumulates cumulative quantities see meter c meter run ce c ce update The MPU scales these values to the voltage and current sensors used on the PCB see VMAX and IMAX 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 Meters require more precision than standard C floating point provides The Demo Code has reusable calculations for meter math mmath c These automatically convert CE counts into a major running count of Wh and a minor remainder of CE counts The MPU also places a scaled value into the CE RAM for each pulse output meter c meter run 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
46. latest information about the Keil Software Development Tools Evaluation Boards This CD includes the latest product updates evaluation software datasheets support solutions and FAQs about our products Click on the buttons at the left for more information Introduction amp Tutorials Brochures Newsletters 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 B Keil Development Tools Release 04 2004 Development Tools bs gt ES Awan ee Install Products amp Updates C51 Getting Started Bae The C51 package includes the uVision2 EU Integrated Development amp Debugging 6 Getting Started Environment and all the utilities you need to create embedded application programs for all c25 hpller amp Tools 8051 microcontroller families 251 Getting Started The C51 setup program performs new installations as well as updates to 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 Ge 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
47. performs temperature adjustments of the real time clock rtc 10 c 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 71M6521 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 aux
48. phase void phase_angle c psoft_init Initializes software pulse outputs void void psoft c psoft out Generates two additional pulse outputs Call from ce busy isr void void psoft c Revision 1 7 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 89 of 138 aes 71M652X Software User s Guide The inputs are watt hours as generated by the CE and set the extra pulse generators to blink at the int32 t pulse3 in psoft update same rate as CE pulse out void psoft c puts with the same units inte tpulse4 In This should be called each time a new accumulation interval has data put char EE character Into oH uint8_t idata c none io c uffer reads the trim value for Read Trim selected trim word enum eTRIM select S08 ce c rms i lcd Displays current uint8 t phase void rms c rms v lcd Displays voltage uint8 t phase void rms c RTC Adjust Trim Safely sets the bool dr cnt int32 t ione icc Se compensation variables value Calculates and adjusts the RTC_Compensation temperature compensation none none rtc c for the RTC Interrupt code to adjust rtc isr clock each second void void rtc c RTClk Read reads current values of RTC none none rtc c RTClk Reset resets the RTC none none rtc c i Calculates the temperature e RTC_Tr
49. register for Timer O and Timer 1 respectively The 3 high order bits of TLO and TL 1 are held at zero 0 1 Mode 1 16 bit Counter Timer 1 0 Mode 2 8 bit auto reload Counter Timer The reload value is kept in THO or TH1 while TLO or TL1 is incremented every machine cycle When tl x overflows a value from th x is copied to tl x 1 1 Mode 3 If Timer 1 m1 and m0 bits are set to 1 Timer 1 stops If Timer 0 m1 and mO bits are set to 1 Timer O acts as two independent 8 bit Timer Counters Table 6 23 Timers Counters Mode Description Note In Mode 3 TLO is affected by TRO and gate control bits and sets TFO flag on overflow while THO is affected by TR1 bit and the TF1 flag is set on overflow Timer Counter Control Register TCON MSB LSB TF1 TR1 TFO TRO IE1 IT1 IEO ITO Table 6 24 The TCON Register Revision 1 7 TERIDIAN Proprietary 121 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation ALERTAS 71M652X Software User s Guide The Timer 1 overflow flag is set by hardware when Timer 1 overflows This flag TCON 7 TF1 can be cleared by software and is automatically cleared when an interrupt is processed TCON 6 TR1 Timer 1 Run control bit If cleared Timer 1 stops ICONS TFO Timer O overflow flag set by hardware when Timer 0 overflows This flag can be i cleared by software and is automatically cleared when an interrupt is processed
50. startup boot a51 startup boot secure a51 startup secure a51 stm c software timer routines timers c unused software timer legacy code wd c routines that support the hardware watchdog 5 10 AUXILIARY FILES A variety of startup files is provided with the Demo Kits The function of these files is as follows 1 STARTUP A51 This file provides memory and stack initialization It is part of the Keil compiler package STARTUP_SECURE 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 STARTUP1 CLR 0xA8 7 Disable interrupts MOV 0B2h 40h Set security bit MOV OE8h 40FFh Refresh nonmaskable watchdog 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 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN 5 11 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
51. the CE in CE DRAM location Ox7B The relative chip temperature deltaT 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 2007 TERIDIAN Semiconductor Corporation TERIDAN 5 14 3 Temperature Compensation for Measurements The internal voltage reference of the 652X 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 supplied by the MPU in GA N ADJ This external type of compens
52. 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 6521 demo hex into the new object file new 6521 demo hex use the command d merge old 6521 demo hex macro txt new 6521 demo hex 2 4 2 CE MERGE The ce merge program updates the 6521 demo hex file with the CE program image contained in the CE CE file and the 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 Verilog 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 6521 demo hex with CE CE and CE DAT into the new object file new 6521 demo hex use the command ce merge old 6521 demo hex ce ce ce dat 6521 demo hex TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation eA TER DIAN SEMICONDUCTOR CORR 71M652X Software User s Guide Revision 1 7 TERIDIAN Proprietary 18 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation q ATER DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP 3 DESIGN REFERENCE As depicted in Figure 1 of section 2 the 71M652X 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 wi
53. uVision should start up and present the following window 16 Hello p ision2 C Program Files KeilC51Examples Hello HELLO C 10 x Ein Edt view project Debug Flash Peripherals Tools SVCS window Help la x lasua erjoc 22 aj alala nala m jX S simulator O 7 E553 Simulator E 3 Source Group 1 e HELLO C ca Documentation s ABSTRACT TXT fifndef MONITORS1 0x50 SCON mode 1 8 bit UART enable rcvr 0x20 TMOD timer 1 mode 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 Toggle P1 0 each time we print printf Hello Worldin Print Hello World XlBuild target Simulator 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 Target1 select the Device tab and check the selected device Newer versions of the Keil Compiler offer selection of TERIDIAN labeled TDK 71M6511 devices Select Device for Target Target 1 cru Vendor TDK Device 71M6513 Use Extended Linker X51 instead of BL51 Toolset C51 Use Extended Assembler tead of A51 Data base Description ST Microelectronics 80515 based power meter IC with Interrupts 4
54. uint8x t buffer none sercli c length uint16 tlen sets up transmission buffer Banc E okie Serial Tx p E port uint8 tx buffer enum SERIAL RC data sercli c and starts transmission uint16 tlen Serial TxLen returns the number of bytes enum SERIAL PORT vint16 t sercli c left to transmit port SerialO CRx Receive a string up to a int8x Ruler HIRETO E uint16 tlength received serOcli c maximum length len SerialO CTx Trane a string up to a BEE SEHR uint16_t length sent serOcli c maximum length len Serialo Rx Receive a string of any uint8x_t buffer uint16_t Rone serOcli c length len Serial0_RxFlowOff Force an XOFF to be sent none sona ser0cli c on this port Serial0_RxFlow0n Force an XON tobe sention none none serOcli c this port Serial0_Tx Transmit a string of any uint8x_t buffer uint16_t none serOcli c length len Serial1_CRx Receive a string up to a Unte ee t uint16 tlength received ser1cli c maximum length len TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide MERI DIAN SEMICONDUCTOR CORP i Transmit a string up to a uint8x_t buffer uint16_t Serial1_CTx maximum length len uint16_t length sent sertcli c i Receive a string of any uint8x_t buffer uint16_t Seriall Rx length len none ser1cli c Seriall RxFlowOff Force an XOFF to be sent i
55. 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 71M652X 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 internal 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 2007 TERIDIAN Semiconductor Corporation TERIDAN General data type definitions typedef unsigned char uint8_t typedef unsigned short uint16_t typedef unsigned long uint32_t typedef signed char int8_t typedef signed short int16 t typedef signed long int32 t 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 d
56. uses all four sets of registers for different high speed interrupts Using noaregs lets any interrupt routine call any reentrant routine without overwriting a different interrupt s registers TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation d TER 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 71M6512 is available with three different memory sizes different versions of the Demo Code are provided that take into account the available memory size 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 re compiling the source code If a certain feature is not required it can be left out and replaced with a different feature of equal or smaller code size The object files contained in the Demo Kits have been generated with the following Keil compiler versions e Ccompiler C51 exe V8 02 e Assembler A51 exe V8 00 e Linker Locator BL51 exe V6 00 e Librarian LIB51 exe V4 24 e Hex converter OH51 exe V3 03 e Dialog DLL DP51 dll V2 47 e Target DLL bin mon
57. 0 Command Pending crasse eret etae edad t eda e dap le aep ea e Ran oda cune Render tee recede geh 62 EEPROM Read Write meesi AA 63 Eum 65 Power Factor EE enne errem nene entre en nennen nennen 66 5 4 4 Watchdog Timer 66 5 4 5 Real Time Clock RTC 66 5 5 Managing Mission and Battery Modes cccccssseessseeeesseceeeenseeeseaseeeusesseeeeesseneesaseeeeeuseeeeeenseeeeeneeeeees 67 5 6 Data 0 m M M 68 5 7 CE MPU Interface 69 5 8 Boot Loader ssccccisshscicsescssedsesnscvaccnnctecvestccueseansavsetecssvadsnesvonscesscenstassaiertasaensedsbseudecdondsdeadesensdeunseansaniveacecess 69 5 9 Source AAA unaenea 69 5 10 Auxiliary MUI 71 5 11 Include Header d UE 72 5 11 1 OPTIONS H 72 5 11 2 Register Definitions 72 5 11 3 Other Include Header Files 73 S pe Mae NCS oia latencia 74 5 13 Common MPU Addresses ccecceseceeeeeeeeeeeeeneeneeeeneneeneeeeneneeaseeeeeeeensaeeeseeeasaeeeeeesaseeeeseeeasaeeeseeeeeeeesenenes 74 5 14 Firmware Application Information ccssseeeessseeesssceeeenseceeeeseseeeesseeeeeesseeeeaseeeeuseeeeeuseneeeaseceeenseeeesnes 79 5 14 1 Sag Detection 79 5 14 2 Temperature Measurement 79 5 14 3 Temperature Compensation for Measurements 80 5 14 4 Temperature Compensation for the RTC 80 5 14 5 Validating the Battery 81
58. 0515 Performance The architecture eliminates redundant bus states and implements parallel execution of fetch and execution phases Normally a cycle is aligned with a memory fetch therefore most of the 1 byte instructions are performed in a single cycle The 80515 uses 1 clock per cycle leading to an 8x performance improvement in terms of MIPS over the Intel 8051 device running at the same clock frequency Note The original 8051 had a 12 clock architecture A machine cycle needed 12 clocks and most instructions were either one or two machine cycles Thus except for the MUL and DIV instructions the 8051 used either 12 or 24 clocks for each instruction Furthermore each cycle in the 8051 used two memory fetches In many cases the second fetch was a dummy and extra clocks were wasted Table 6 1 shows the speed advantage of the 80515 over the standard 8051 A speed advantage of 12 means that the 80515 performs the same instruction twelve times faster that the 8051 Speed advantage Number of Number of instructions opcodes 24 1 1 12 27 83 9 6 2 2 8 16 38 44 89 1 2 18 31 9 Average 8 0 Sum 111 Sum 255 Table 6 1 Speed Advantage Summary The average speed advantage is 8x however the actual speed improvement observed in a system will depend on the instruction mix TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN 6 1 2 80515 Features Below i
59. 2 Table 6 33 Table 6 34 Table 6 35 Table 6 36 Table 6 37 Table 6 38 Table 6 39 Table 6 40 Table 6 41 Table 6 42 Table 6 43 Table 6 44 Table 6 45 Table 6 46 Table 6 47 Table 6 48 Table 6 49 Table 6 50 Table 6 51 Table 6 52 Table 6 53 Table 6 54 Table 6 55 Table 6 56 Table 6 57 Table 6 58 Table 6 59 Table 6 60 Serial 1 MOd S iii oie 124 The SICON colm ade 124 The S1CON Bit FUNCIONS EE 125 The IENO e 127 ThE IENO Bit FUNCHONS oi ae 127 TING EN REQISter iire M 127 The s Bit FURCHONS EE 127 TNE Lcde 127 The IPO Bit FUNCHONS ec 128 The WDTREL Register c0c i 2ccsenecesescdeeesteneeensteenentescenemesunsstnsedestemsecessaadneesteneteindeandesescecnsesconseaseneceeseuneedestse 128 The WT REL due fM M 128 Indc TEE 129 The WENO Bit EUnctlols occu vic ape cabin eue enne cer ope ta ce wg cage any aeri ure annie ka onu e Yu cards 129 Bull 129 TIENT Bit FUNCIONS uaa tice RN 129 TINGIEN2 REOISLCM 129 The IENZ Bit FUNCIONS coin eir diadanan iiini raini 129 The TEON Register vecina ca 130 Th TCON Bit FUNCIONS cte A il ino 130 Iprheec i
60. 5 15 Alphabetical Function Reference eeeeeeeeeee esee nn nacer 82 A GC TO 95 5 17 Porting 71M6511 6513 Code to the 71M6521 ceceseeeseeeseeeeeeeeeenneeeseeeseeaseeneenseasseeesaeeuseeeeeaseeeeeeneas 96 Revision 1 7 TERIDIAN Proprietary 5 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN 71M652X Software User s Guide Copyright 2005 2007 TERIDIAN Semiconductor Corporation 5 17 1 Memory Use 96 5 17 2 CE Code Location 96 5 17 3 Battery Modes 96 5 17 4 Three Wire EEPROM Hardware 98 5 17 5 Temperature Compensation 99 5 18 TEST Uc KREEG 99 5 18 1 6513 CE Example 99 5 18 2 Serial Port Tests 99 5 18 3 Timer Tests 99 5 18 4 EEPROM Tests 99 5 18 5 Generating DIO Pulses on Reset 99 5 18 6 Testing the Security Bit 99 5 18 7 Software Timer Test 100 5 18 8 Interrupt Test 100 6 80515 MPU REFERENCE 101 6 1 ugue ii nonp annnka aoar bn ernea nee Aa Snr O RAONS Tanben ISANDE MNP Nan hEN KA AN PARVA AN SARK DEANNA TEENETE 101 6 1 1 80515 Performance 101 6 1 2 80515 Features 102 6 2 80515 Architectural Overview o oomcnnncconnnncccnnnncnnnncr rn 103 6 2 1 Memory organization 103 Program Memory EE 103 External Data Memory eet eo ota 103 Dual Data zio C E 104 Internal Data MemoOfy Lorient eens leigh een eee OR eed e 104 Special Function Registers Location enm ener 105 Generic Special Function Register OvervieW ssssssesissrriiesriiissr
61. 51 dll V2 40 e Dialog DLL TP51 dll V2 47 T Flash eT Version Code Size Description Basic 8KB Demonstrates a meter with 8KB of code space The software offers tamper protection Wattmeter calibration and nonvolatile energy registers It utilizes special CE code This implementation has a 0 82KB margin of empty code space Intermediate 16KB Demonstrates a meter with 16KB of code space The software is easy to reconfigure by Meter recompiling and offers full tamper protection calibration and nonvolatile energy registers This implementation has a 3 2KB margin of empty code space Demonstration 32KB Demonstrates a meter with 32k of code space The software is easy to reconfigure by Meter recompiling It shall has full tamper protection calibration and nonvolatile energy registers The software demonstrates a full feature set This implementation has a 6 4KB margin of empty code space not including the command line interpreter but including a calibration interface 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 approx
62. A The Demo Code is highly 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 abstracted and separated from the driver modules Where there are several similar devices e g serO ser or tmr0 tmr1 the Demo Code simulates a virtual object base class using C preprocessor macros For example to initialize the first serial interace sert the source file can include serO h and then call ser initialize To transmit a byte on sert the file can include sert bh 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 ser1cli 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 w
63. 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 ajajafjaja 2 0 N N N 0 N N N O0O N NDN DMN afaj fa a a 2 A O N N N a BA O N N N a B O0O N N N Swap nibbles within the accumulator Table 6 10 Logic Operations TERIDIAN Proprietary O Copyright 2005 2007 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
64. 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 Switzerland Interrupt International Standards Organization Interrupt Service Routine Kilobyte s 1 024 bytes Liquid Crystal Display Line feed character TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MES LSB MB MPU MSB NV PC PSU PSW RAM SFR TOU TSC USB VA VAh VAR VARh W WD WDT WEMUS1 Wh Least Significant Bit Megabyte s 1 024 kilobytes Microprocessor microcontroller Unit Most Siginificant Bit Non Volatile Personal Computer Program Counter Power Supply Unit Program Status Word Random Access Memory Special Function Register of the 8051 MPU Time of Use variable metering tariffs usually based on time of day TERIDIAN Semiconductor Corpor
65. Adaptor AC DC output or variable power supply e PC 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 not included in the demo kit 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 7 5 or later e yVision2 version 3 05c Note this version comes with Keil Compiler version 7 5 e Signum Systems software Wemu51 comes with Signum Systems ADM 51 ICE hardware The following software tools programs are included in the 71M652X 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 2007 TERIDIAN Semiconductor Corporation SEU RIDIAN SEMICONDUCTOR CORP 71M652X 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 Editing C source code us
66. C and its 1 second interrupt run at an unchanged speed In addition to the flags given in Figure 5 26 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 to brownout mode The MPU will start code execution at address 0x000 The sleep and LCD modes shut down all of the 71M6521 s internal and XDATA RAM as well as the pin drivers for DIOs and many of the memory cells that store the hardware configuration 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 71M6521 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 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 71M6521 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 dat
67. DUCTOR CORP 71M652X Software User s Guide 5 15 ALPHABETICAL FUNCTION REFERENCE X abs x0 Take absolute uint8 tx x uint8 tx x0 abs x value of n byte x0 none math c x y where x amp y are uint8 tx x uint8_tx y F add n bytes wide n uint8 t math c x y where x is n bytes 4 add 1 wide y is single byte uint8 tx x y n uint8 t math c add8 4 uint64 t x uint32 t y uint8 tx x uint8 tx y none math c add8 8 uint64 t x uint64 t y uint8 tx x uint8 tx y none math c adds two unsigned 8 byte T e add8 8 numbers uint8 tx x uint8 tx y none ce c neo Prevents creep void void meter c old batmode de browauou Returns true if battery mode E ERRONEO is brownout False is void bool batmode_20 c mission mode Enters LCD only mode from brownout mode Exit from batmode lcd LCD only mode resembles void void batmode 20 c a reset Enters sleep mode from brownout mode Exit from A batmode sleep sleep mode resembles a void void batmode 20 c reset batmode wait minut Sets the wake timer in es minutes uint16 t minutes none batmode 20 c batmode wait secon Setsthe wake timer in uint16 t seconds none batmode_20 c ds seconds i starts auto calibration cal begin process none bool caphased c Restores calibration from T cal restore EEPROM none bool calibration c cal save save Calphalon Hats
68. E 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 Teridian provides two files for each ce code One file is the code for the computeOengine The other is a set of data to copy into the CE s RAM area to initialize the CE program variables Teridian has two standard CE codes for the 6521 For one element two wire single phase meters use ce21a04 ce c and ce21a04 dat c the CE code and data files When the hardware field EQU is 0x00 this CE code provides two metering elements using VA and IA and VA and IB The equations are WhA VA IA and WhB VA IB There are two metering elements so that the neutral current can be measured for tamper detection The MPU software must decide which element is more accurate at any given time This gives a perfectly flexible method for detecting and mitigating tampering For one element three wire split phase meters also use ce21a04_ce c and ce21a04 dat c the CE code and data files When the hardware field EQU is 0x01 this ce code provides two metering elements One has an equation of Wh VA IA 1B 2 The other has WhB VA IB There are two metering elements so that the sec
69. EH A E e SCH Target 1 This code and information is provided as is without warranty of any H a E kind either expressed or implied including but not limited to the cu implied warranties of merchantability and or fitness for a particular 10 purpose a 3 Main P Copyright C 2005 Teridian Semiconductor Corp All Rights Reserved 2 defaults c L I batmodes c f PRRRERERERERRERERERREREREREREREERERER ERE ERERERER EERE RAR ER RR RRRRARARARARANA DESCRIPTION 71M652x POWER METER Main Meter de utils AUTHOR MTF RGV y HISTORY See end of file D RATA AERERERER ER RE RE RARE ERE RARER File MAIN C 14 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 with iomerge c include batmodes h battery mode logic include wd h software watchdogs include stm h software timers include ce h compute engine hardware access include ser0 h uart 0 hardware access include serl h uart l hardware access include rtc h real time clock hardware access include Led br liquid crystal display a include meter h meter logic y Files a gt X D E E B ST Deua A Command FindinFies Lo pf For Help press F1 NUM Rw Revision 1 7 TERIDIAN Proprietary 30 of 138 Copyright 2005
70. FH and can be accessed by either direct or indirect addressing The Special Function Registers occupy the upper 128 bytes This SFR area is available only by direct addressing Indirect addressing accesses the upper 128 bytes of Internal RAM The lower 128 bytes contain working registers and bit addressable memory The lower 32 bytes form four banks of eight registers RO R7 Two bits on the program memory status word PSW select which bank is in use The next 16 bytes form a block of bit addressable memory space at bit addressees 00H 7FH All of the bytes in the lower 128 bytes are accessible through direct or indirect addressing Table 6 3 shows the internal data memory map TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MATERI DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Special Function Registers SFRs Byte addressable area Bit addressable area Register banks RO R7 Table 6 3 Internal Data Memory Map Special Function Registers Location A map of the Special Function Registers is shown in Table 6 4 Only a few addresses are occupied the others are not implemented SFRs specific to the 652X are shown in bold print see 71M652X data sheet for descriptions of these registers Any read access to unimplemented addresses will return undefined data while any write access will have no effect The registers at 0x80 0x88 0x90 etc are bit addressable all others are
71. Function Register S1CON In mode B the internal baud rate generator specifies the baud rate Serial Interface 1 Control Register S1CON The function of the serial port depends on the setting of the Serial Port Control Register S1CON MSB LSB sw T suet Ren Te wer W 08S Table 6 31 The S1CON Register TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation RA Bit Symbol Function S1CON 7 SM Sets baud rate S1CON 5 SM21 Enables the multiprocessor communication feature see description above S1CON 4 REN1 If set enables serial reception Cleared by software to disable reception S1CON 3 TB81 The 9 transmitted data bit in Mode A Set or cleared by the MPU depending on the function it performs parity check multiprocessor communication etc S1CON 2 RB81 In Modes 2 and 3 it is the 9 data bit received In Mode B if sm21 is O rb81 is the stop bit In Mode 0 this bit is not used Must be cleared by software S1CON 1 TI1 Transmit interrupt flag set by hardware after completion of a serial transfer Must be cleared by software S1CON 0 RI1 Receive interrupt flag set by hardware after completion of a serial reception Must be cleared by software Table 6 32 The S1CON Bit Functions 6 3 3 1 Baud Rate generator Serial 0 modes 1 and 3 only Fclk MPU clock rate Timer1 baud rate generator WDCON 7 0 smod F clk 2 384 256 thl Internal baud r
72. JE 3 3 9 3 9 3 9 3 9 3 9 9 3 3 3 3 3 J 22 20 gt File APIE C y SES e 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 Create Project Wizard by selecting Next Revision 1 7 TERIDIAN Proprietary 26 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide 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 lo 256 chars description of project features It may be left blank now and set later from PROJECT gt INFORMATION menu Back Next J When prompted for the project directory to be used select an existing folder on the PC Do NOT select any folder in the Wemub51 installation directory Click Next Project Creation Wizard Please select project directory for your project Project directory is a folder for file
73. N Semiconductor Corporation ATER DIAN SEMICONDUCTOR CORP Auto Calibration The auto calibration option not compiled in the executable Demo Code is a simplified calibration procedure based on voltage real energy and reactive energy measurements Before the calibration starts the desired accumulation time SCAL and the applied ideal voltage and current have to be entered by the user in the MPU memory locations VCAL and ICAL The procedure of this calibration method is the same as for the fast calibration procedure as described in the DBUM The tangens 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 functions the auto calibration procedure implemented in the Demo Code utilizes much simpler mathematical operations that are closer to the capabilities of the MPU As with the procedure presented in the DBUM the target values should be applied to the meter and held constant during the auto calibration process The routines shown in Figure 5 14 show how the auto calibration is started The cal begin routine starts a 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 actua
74. OM I2C EEPROM 0 2KB Y Y Y Table 5 9 Calibration and Various Services 5 3 PROGRAM FLOW 5 3 1 Startup and Initialization The top level functionality of the Demo Board is controlled by the high level functions As with every C program the core of the function is in the main program The main program is contained in the main c source file It performs the following steps see Figure 5 1 Figure 2 1 and Figure 5 2 1 Reset watchdog timer 2 Process the pushbutton PB when in BROWNOUT mode 3 Initialization for hardware pointers metering variables UART buffers and pointers CE restoration of calibration coefficients 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 Afterwards if a command is pending the command line interface CLI is serviced RESET v Disable All Interrupts v Disable 651x Watchdog v Init IDATA v Init STACK Figure 5 1 STARTUP A51 Revision 1 7 INIT Figure 5 2 INIT A51 TERIDIAN Proprietary 46 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA Before the MPU gets to execute the main program it will execute the startup instructions contained in the STARTUP A51 assembly program Figure 5 1 Upon compl
75. OM to be placed into CE memory by the MPU when the meter powers up The Demo Code includes a basic linear self calibration function that can typically reach 0 0596 accuracy meter c meter run calphased c cal begin calibration Better calibration schemes are possible 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 function 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 busyz 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 2 It calculates the frequency on a particular phase FREQ X 4 It ca
76. ON Bit Functions Note Only TFO and TF1 timer O and timer 1 overflow flag will be automatically cleared by hardware when the service routine is called Signals tOack and t1ack port ISR active high when the service routine is called 6 3 5 3 External Interrupts The 71M6521 MPU allows seven external interrupts These are connected as shown in Table 46 The direction of interrupts 2 and 3 is programmable in the MPU Interrupts 2 and 3 should be programmed for falling sensitivity using the I2FR and I3FR bits of the T2CON register see Table 6 50 Revision 1 7 TERIDIAN Proprietary 130 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide Interrupt Request register T2CON MSB Q5 TERI DIAN SEMICONDUCTOR CORP LSB I3FR I2FR Table 6 51 The T2CON Register T2CON 7 T2CON 6 I3FR This bit controls the polarity of external interrupt 3 T2CON 5 I2FR This bit controls the polarity of external interrupt 2 T2CON 4 T2CON 3 T2CON 2 T2CON 1 T2CON 0 6 3 5 4 Table 6 52 The T2CON Bit Functions Interrupt Priority Level Structure All interrupt sources are combined in groups as shown in Table 6 52 The priority of each group is controlled by the bits of SFR registers IP1 and IPO Ip1 0 IPO 0 External interrupt O All ted interrupt UART 1 interrupt Ip1 1 IPO 1 Timer 0 interrupt
77. OV 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 16 Instruction Set in Hexadecimal Order TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation ATER DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Instructions that Affect Flags CLR C CPL C ANL C bit ANL C bit ORL C bit ORL C bit MOV C bit CJNE XIX lt XXXIX O a x x xjojo x x x C Table 6 17 Instructions Affecting Flags Note Operations affecting the PSW or bits in the PSW will also affect flag settings 6 3 80515 HARDWARE DESCRIPTION The 80515 core implemented in the 71M652X chips consists of 1 Control processor unit CPU also referred to as MPU throughout this document 2 Arithmetic logic unit 3 Clock control unit 4 Memory control unit 5 RAM and SFR control unit 6 Ports registers unit 7 Timer 0 1 unit 8 Serial O 1 interfaces 9 Watchdog timer 10 Interrupt service routine unit Revision 1 7 TERIDIAN Proprietary 117 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN 6 3 1 Block Diagram to from XRAM
78. Priority Levels Q amp SyncMos 6 Sensor Inputs 22 140 Lines 2 Timers Counters Real Time Clock B e Synopsys Watchdog Timer 2 UARTs SSI LCD Driver Power Fail Monitor Integrated ICE Support 64K Bytes Flash or ROM 7K Bytes On chip RAM Syntek Semiconductor Cc amp TDK 3 71M6511 3 RNE 3 7342801 3 73M2901CL 3 73M2910L 3 73511 Revision 1 7 TERIDIAN Proprietary 32 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation A 4 TERIDIAN 71M652X 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 d amp ssembler 55551 instead of 451 Under Project gt Options for Target1 select the Target tab and enter the values in the fields as shown above Confirm by clicking OK Options for Target Simulator Large variables in XDATA Large 54K program si Revision 1 7 TERIDIAN Proprietary 33 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation A ATERIDIAN SEMICONDUCTOR CORP 71M652X 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
79. R4 ADDC A R4 ANL A R4 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 14 Instruction Set in Hexadecimal Order TERIDIAN Proprietary Copyright 2005 2007 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 ARO 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 MOV 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
80. SER H serial interface SERIAL H serial interface API prototypes and definitions TMRO H TMR1 H timer routines UWR H microwire wire or three wire interface BATMODES H battery modes BROWNLOUT LCD SLEEP DEFAULTS H default values OPTIONS GBL H global compile time options OPTIONS H general compile timeoptions defining meter functionality CALIBRATION H calibration CE H compute engine interface includes FREQ H frequency and main edge count METER H meter structures enumerates and definitions PCNT H pulse counting PEAK ALERTS H voltage current peak alerts 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 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 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN 5 12 CE IMAGE FILES The C
81. T5 source EEDATA store data EECTRL 0x05 stop command Clear all registers Figure 5 18 Single Byte Read Write TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN Registers and memory locations e EEDATA SFR 0x9E e EECTRL SFR Ox9F e source pointer to EEPROM address for read or write e destination pointer to XRAM address e count byte count for multiple read write 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 EEDATA 0xA1 read command EECTRL 0x03 transmit data command E rcvd INT5 source EEDATA source EEDATA EECTRL 0x02 multiple read with ACK command count EECTRL 0x05 stop command Clear all registers Figure 5 19 Multi Byte Read TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA EEDATA destination EECTRL 0x03 multiple write with ACK command count rcvd INT5 EECTRL 0x05 stop command Clear all registers Figure 5 20 Multi Byte Write Notes 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 oper
82. TCON 4 TRO Timer 0 Run control bit If cleared Timer 0 stops TCON3 IE1 Interrupt 1 edge flag is set by hardware when the falling edge on external pin int1 is observed Cleared when an interrupt is processed Interrupt 1 type control bit Selects either the falling edge or low level on input TCON 2 IT1 pin to cause an interrupt TCON 1 IEO Interrupt O edge flag is set by hardware when the falling edge on external pin intO is observed Cleared when an interrupt is processed TCON O ITO Interrupt 0 type control bit Selects either the falling edge or low level on input pin to cause interrupt Table 6 25 The TCON Register Bit Functions 6 3 2 1 Allowed Combinations of Operation Modes Table 6 25 specifies the combinations of operation modes allowed for timer 0 and timer 1 Not allowed Not allowed Table 6 26 Timer Modes 6 3 3 Serial Interface 0 and 1 The serial buffer consists of two separate registers a transmit buffer and a receive buffer Writing data to the Special Function Register SOBUF or S1BUF sets this data in the serial output buffer and starts transmission Reading from the SOBUF or S1BUF reads data from the serial receive buffer The serial port can simultaneously transmit and receive data It can also buffer 1 byte at receive preventing the receive data from being lost if the MPU reads the first byte before transmission of the second byte is completed Serial Interface 0 Modes The Seri
83. TERIDAN The demo software is designed so that the serial port always runs at 300 bd in both mission mode and brownout mode The 6521 has special clock interpolation logic in the baud rate generation so that 300 baud works in brownout mode The designers chose this 300 bd especially because it is compatible with some AMR applications such as FLAG and it was achievable in the chip The Demo Code tests for brownout mode and sets the 300 bd values in the serial ports bd rate generator in this case In brownout mode the code runs 150 times slower than in mission mode and it can easily fail to reset the watchdog The Demo Code arranges to reset the watchdog from both the main loop and the RTC s 1 second interrupt which has unchanged timing It uses a software watchdog scheme to try to keep this respectable The idea is that as soon as all the needed places have called the watchdog routine the hardware watchdog is reset Code for brownout mode should minimize calculations because brownout mode is 150 times slower than mission mode To minimize the calculations in the Demo Code every accumulation interval in mission mode caches a pre calculated Wh value for use in a transition to brownout mode When the interrupt for brownout mode executes this value is converted to the digits of the LCD registers The LCD registers are nonvolatile in sleep and LCD modes so they are not lost in any battery mode transitions Later when the Demo Code awa
84. a about how the chip last woke but also permits the chip to transition to the LCD and sleep modes easily TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation A a SEMICONDUCTOR CORP MISSION pro V1 VBIAS V3P3SYS rises V3P3SYS 1 rises BROWNOUT R ESET amp PB gt 1 VBAT_OK IE WAKE gt 1 PB SLEEP or E ORNO VBAT_OK timer ES i Ch i i PB ES VBAT_OK BATOK a RESET amp E i VBAT_OK Figure 5 26 Operation Modes State Diagram The wake up timer is a little trickier to use than the pushbutton To use it one must first write the timer data and then after a brief delay about 32us enter LCD or sleep mode The timer does not measure elapsed time Instead it counts the RTC s transitions For example if one programs a two minute delay at 00 00 30 the timer will actually wake the chip at 00 02 00 Properly used this is a feature of course but it can be surprising The wake up timer LCD and sleep modes are controlled by the bits in the WAKE register XDATA address 0x20A9 The lack of nonvolatile memory during the battery modes can be disconcerting at first There are usually a few bytes worth of available nonvolatile space in the unused LCD segment control bits in XDATA addresses 0x2036 0x2056 The transition from mission mode to brownout and from brownout to mission mode is invisible to the code without special care First there is a
85. able 6 35 The IEN1 Register IEN1 6 Ej Watchdog timer start refresh flag Set to activate refresh the watchdog timer When directly set after setting WDT a watchdog timer refresh is performed Bit SWDT is reset by the hardware 12 clock cycles after it has been set Table 6 36 The IEN1 Bit Functions Note The remaining bits in the IEN1 register are not used for watchdog control Interrupt Priority 0 Register IPO MSB LSB OWDS WDTS IPO 5 IP0 4 IP0 3 IP0 2 IP0 1 IP0 0 Table 6 37 The IPO Register Revision 1 7 TERIDIAN Proprietary 127 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation ALERTAS IP0 6 WDTS Watchdog timer status flag Set by hardware when the watchdog timer was started Can be read by software Table 6 38 The IPO Bit Functions Note The remaining bits in the IPO register are not used for watchdog control Watchdog Timer Reload Register WDTREL MSB LSB 7 6 5 4 3 2 1 0 Table 6 39 The WDTREL Register Bit Function WDTREL 7 Prescaler select bit When set the watchdog is clocked through an additional divide by 16 prescaler WDTREL 6 Seven bit reload value for the high byte of the watchdog timer This value is to loaded to the WDT when a refresh is triggered by a consecutive setting of bits WDTREL O WDT and SWDT Table 6 40 The WDTREL Bit Functions The WDTREL register can be loaded and read at
86. after a hard reset 5 17 4 Three Wire EEPROM Hardware The 71M6521 includes a new three wire serial EEPROM interface which is designed to be compatible with MicroWire EEPROMs The new 3 wire interface hardware is very fast transferring a byte in only 16us This high speed has made it relatively uneconomical to use the interrupt provided on this interface At 16us per byte the interrupt overhead would be most of the delay in the EEPROM control firmware Therefore the Demo Code uses a polling driver that reads the ready bit Some 3 wire serial EEPROMs e g the Microchip 93C76C signal completion of a write operation by driving the data line from low to high The 71M6521 handles this with two controls First there is a HIZ bit in EECTRL that forces the output of the 71M6521 to a high impedance state after the last bit is sent Also the bit WFR wait for ready in EECTRL makes the 71M6521 s BUSY status bit stay true until the data line becomes high However there is a period during which the data line is not driven If the data line is not pulled down a trailing 1 on the last data bit will leave the line capacitance holding the line well above the transition voltage causing BUSY to become prematurely false But if the pull down is too powerful the EEPROM may not be able to drive it e g the 93C76C has only 400pA of drive on the high state of the data line An alternative method uwreep c in the Demo Code that is clumsy but reliable and
87. al Interface O can operate in 4 modes Mode 0 Pin rxdO serves as an input and an output TxdO outputs the shift clock 8 bits are transmitted starting with the LSB The baud rate is fixed at 1 12 of the MPU frequency Reception is initialized in Mode 0 by setting the flags in SOCON as follows RIO 0 and RENO 1 In other modes when RENO 1 a start bit initiates receiving serial data Revision 1 7 TERIDIAN Proprietary 122 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation BA Mode 1 Pin rxdO serves as an input and txdO serves as a serial output No external shift clock is used 10 bits are transmitted a start bit always 0 8 data bits LSB first and a stop bit always 1 On receive a start bit synchronizes the transmission 8 data bits are available by reading SOBUF and the stop bit sets the flag RB80 in the Special Function Register SOCON In mode 1 either the internal baud rate generator or timer 1 can be use to specify the baud rate Mode 2 This mode is similar to Mode 1 with two differences The baud rate is fixed at 1 32 or 1 64 of the oscillator frequency and 11 bits are transmitted or received a start bit 0 8 data bits LSB first a programmable 9 bit and a stop bit 1 The 9 bit can be used to control the parity of the serial interface at transmission bit TB80 in SOCON is output as the gr bit and at receive the 9 bit affects RB80 in the Special Function Register SOCON Mode 3 The only difference
88. alco 113 Table 6 13 Boolean Marilpulations nitor ete teet etre tt Pg eu pa e ne a rne c 113 Table 6 14 Instruction Set in Hexadecimal Order 114 Table 6 15 Instruction Set in Hexadecimal Order 115 Table 6 16 Instruction Set in Hexadecimal Order 116 Table 6 17 Instructions Affecting Eloge 117 Table 0 18 PSW Register Flags rrr rta 119 Table 6 19 PSW Bit Functions coooonccnnonnccnnnoccncnanoncno nono cocoa nn cr nana nennen nennen nennen neri nen nene eter en tenes nenne eerie 119 Table 6 20 Register Bark Location arcoiris o ia 120 Table 6 21 The EMOD Register arsure pense daca i E ea aa r Aa A eatae Taa TGs iNO re AANE E EaR Aia rra 121 Table 6 22 The TMOD Register Bits Description 121 Table 6 23 Timers Counters Mode Description 121 Tabl 6 24 The TCON Register e 121 Table 6 25 The TCON Register Bit Functions eee ceci nece tine enitn nnno nonna inten ua nde aaar nonc ununi nani 122 Table 6 26 Timer M deS c ninironireanar ireira a iia ar eai aaa PE A A raU EN EAEE 122 Table 6 27 The SOCON Register cocina ctas cdi oh 123 Table 6 28 The SOCON Bit F nctlons nini ettet rotate te ege create eg eade eese ca goede vans bed uo cpu enu Ya clades 123 Table 6 29 Serial Port 0 Modest Lv cap oae 124 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN Table 6 30 Table 6 31 Table 6 3
89. an output ERASE FLSH ERASE 0x94 This register is used to initiate either the Flash Mass Erase cycle or the Flash Page Erase cycle Specific patterns are expected for FLSH ERASE in order to initiate the appropriate Erase cycle default 0x00 0x55 Initiate Flash Page Erase cycle Must be proceeded by a write to FLSH_PGADR SFR 0xB7 OxAA Initiate Flash Mass Erase cycle Must be proceeded by a write to FLSH_MEEN sfr 0xB2 and the debug CC port must be enabled Any other pattern written to FLSH_ERASE will have no effect PGADDR FLSH PGADR Flash Page Erase Address register containing the flash memory page address page 0 thru 127 that will be erased during the Page Erase cycle default 0x00 Must be re written for each new Page Erase cycle EEDATA I2C EEPROM interface data register EECTRL I2C EEPROM interface control register If the MPU wishes to write a byte of data to EEPROM it places the data in EEDATA and then writes the Transmit code to EECTRL The write to EECTRL initiates the transmit FLSHCRL This multi purpose register contains the following bits Bit 0 FLSH PWE Program Write Enable 0 MOVX commands refer to XRAM Space normal operation default 1 MOVX DPTR A moves A to Program Space Flash DPTR This bit is automatically reset after each byte written to flash Writes to this bit are inhibited when interrupts are enabled Bit 1 FLSH MEEN Mass Er
90. ange The Keil project files are ser0test uv2 and serltest uv2 5 18 3 Timer Tests These Test Modules build simple routines for testing of the interrupting timers run both once and periodically The routines include an extended 30 second test that can be used with a stop watch timer to measure accuracy Note that tmrOtest c and tmritest c use identical text except for the include file This is a very convenient technique for moving a timer IO to a different port when requirements change The Keil project files are tmr0test uv2 and tmrltest uv2 5 18 4 EEPROM Tests This routine demonstrates the use and test of the eeprom interface The Keil project file is eepromtest uv2 5 18 5 Generating DIO Pulses on Reset This Test Module is written in 8051 assembler and is executed after processor reset It pulses DIO7 on a meter chip This function is useful as a scope loop to discover if the chip resets when expected The Keil project file is RESET PULSES DIO7 UV2 5 18 6 Testing the Security Bit This Test Module is written in 8051 assembler and is executed after processor reset It sets the security bit and then displays the security bit on DIO 7 It is useful to test the behavior of the security bit under various system conditions TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN The Keil project file iS RESET_READ_SE UV2 5 18 7 Software Timer Test
91. ap The overlay scheme can use memory very efficiently This is useful because the 71M652X chips only have 2k of RAM 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
92. ase Enable 0 Mass Erase disabled default 1 Mass Erase enabled Must be re written for each new Mass Erase cycle Bit 6 SECURE Enables security provisions that prevent external reading of flash memory and CE program RAM This bit is reset on chip reset and may only be set Attempts to write zero are ignored Bit 7 PREBOOT Indicates that the preboot sequence is active TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA Only byte operations on the whole WDI register should be used when writing This multi purpose register contains the following bits Bit 0 IE XFER XFER Interrupt Flag This flag monitors the XFER BUSY interrupt It is set by hardware and must be cleared by the interrupt handler Bit 1 IE RTC RTC Interrupt Flag This flag monitors the RTC_1SEC interrupt It is set by hardware and must be cleared by the interrupt handler Bit 7 WD RST WD Timer Reset The WDT is reset when a 1 is written to this bit INTBITS INTO INTG Interrupt inputs The MPU may read these bits to see the input to external interrupts INTO INT1 up to INT6 These bits do not have any memory and are primarily intended for debug use Table 6 6 SFRs Specific to the 652X 6 2 2 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 gi
93. ata typedef signed short data typedef signed long data uint8d t uintl6d t uint32d t int8d_t int16d_t int32d_t This is the fastest available memory except registers not battery backed up but competes with stack registers booleans and idata Note For portability see uint_fast8_t and its sisters which are POSIX standard Type definitions for internal data 16 bytes 0x20 to0x2F 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 This is the fastest available memory but it is not battery backed up It competes with stack registers bools data and idata The space is valuable for boolean globals and should not be wasted Booleans are not a normal part of stdint h but 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 2007 TERIDIAN Semiconductor Corporation AA Type definitions for internal data 256 bytes in the upper 128 bytes addressed indirectly typedef unsigned char data uint8i_t typedef unsigned short idata uint16
94. ate generator WDCON 7 1 baudrate s mod F clk 2 baudrate T 64 2 sOrel Note sOrel is a 10 bit value formed by concatenating SORELH and SORELL as follows sOrel SORELH 1 0 SORELL 7 0 Serial 1 all modes Fclk MPU clock rate Internal baud rate generator only F clk baudrate T 32 2 slrel Note strel is a 10 bit value formed by concatenating STRELH and S1RELL as follows strel S1RELH 1 0 STRELL 7 0 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN 6 3 4 Software Watchdog Timer The watchdog timer is a 16 bit counter that is incremented once every 24 or 384 clock cycles After an external reset the watchdog timer is disabled and all registers are set to zero Software Watchdog Timer structure The watchdog consists of a 16 bit counter wdt a reload register WDTREL prescalers by 2 and by 16 and control logic fc1k 12 swd Control wdt logic swdt Figure 6 3 Watchdog Block Diagram 6 3 4 1 WD Timer Start Procedure During an active internal reset signal the programmer can start the watchdog later It will occur when the SWD signal becomes active Once the watchdog is started it cannot be stopped unless the internal reset signal becomes active When the WDT registers enters the state Ox7CFF an asynchronous WDTS signal will become active The signal WDTS sets bit 6 in the IPO register and requests a r
95. ation Universal Serial Bus Volt Amperes apparent power unit Volt Ampere Hour apparent energy unit Reactive Power Reactive energy unit Watt power unit Watchdog Watchdog timer The emulator control program by Signum Systems Watt Hour energy unit 7 2 REVISION HISTORY Revision Date Description 1 0 Initial release 1 1 1 2 Ten doe 1 Added description of TCON2 register in MPU section 1 4 August 11 Improved formatting and numbering deleted reference to CE 2006 development tools 1 5 Sc 12 Added explanation on interrupt priorities Fixed interrupt priorities table 1 6 Deleted list of CLI commands and description of hex records all this in May 15 formation is contained in the 6521 DBUM Added explanation on han 2007 dling battery modes Fixed formulae for baud rate generator and diagram meter LCD Updated SW revision to 4 3 4 in compatibility statement 1 7 August 6 Updated SW revision to 4 7a in compatibility statement Eliminated refer 2008 ences to ROM code Corrected baud rate for CLI Updated variable and routine names to match usage in revision 4 7a Completely revised chapter 5 6 Data Flow Updated Teridian street address TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation of TERIDIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Revision 1 7 TERIDIAN Proprietary 137 of 138 Copyright 2005 2007 TERIDIAN Semi
96. ation 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 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 RTC 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 13 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 13 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 24 shows even a constant compensation would not bring much improvement since the temperature characteristics of the crystal are a mix of constant l
97. ations limited to a single page e EEPROMs are organized in pages In general ATMEL EEPROMs have 1Kbyte per page 256 x 32 bits When reading no special requirements with respect to page boundaries apply 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 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 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 th
98. bit PLL OK in the I O RAM at address 0x2003 that reflects whether the phase locked loop PLL is running or not In order to save power the PLL does not run when the part runs from any battery mode PLL OK also drives logic that sets the bits IE PLLRISE and IE PLLFALL in IFLAGS SFR E8 These are logically ored and routed to external interrupt 4 which is an edge triggered interrupt This interrupt could be called the brownout mode interrupt because it signals any transition between brownout and mission mode It is very important that both IE PLLFALL and IE PLLRISE be cleared at the end of the interrupt in the same instruction otherwise the edge needed for the next interrupt might fail to occur The brownout mode interrupt has to manage the transition to and from brownout mode The Demo Code s brownout interrupt handles this by displaying a watt hour value and then performing a soft reset The chip starts a normal power up in brownout mode and then transitions to mission mode about 4 1 milliseconds after power is applied The code is often quite far along the brownout mode path at this point and must gracefully transition to mission mode The soft reset in the brownout interrupt handles this requirement very well The Demo Code still includes a belt and suspenders test for a change to or from brownout mode in the main loop This also performs a soft reset TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation
99. byte addressable F8 INTBITS FF FO B F7 ES WDI EF EO A E7 D8 WDCON DF DO PSW D7 C8 T2CON CF CO IRCON C7 B8 IEN pi SORELH S1RELH USR2 BF BO FLSHCTL PGADR B7 A8 IENO IPO SORELL AF MAA 98 SOCON SOBUF IEN2 S1CON S1BUF S1RELL EEDATA EECTRL ep 90 fen GC DPS ERASE 97 88 TCON TMOD TLO TL1 THO TH1 CKCON 8F 80 reo SP DPL DPH DPLI DPH1 WDTREL PCON 87 Table 6 4 Special Function Registers Locations Revision 1 7 TERIDIAN Proprietary 105 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation ALERTAS Generic Special Function Register Overview All generic SFRs are explained in detail in section 6 3 2 Register Description Program status word The PSW contains program status information Accumulator The accumulator register Mmemonics for instructions involving the accumulator refer to the accumulator as A B register B This register is used for multiply and divide operations It may also be used as a scratchpad temporary register Stack pointer SP The stack pointer is 8 bits wide and is incremented before data is stored with PUSH and CALL operations SP is initialized to 0x07 after reset Data pointer DPL DPH Since the DP consists of two bytes DPH and DPL it can hold a 16 bit address It may be manipulated as a 16 bit register or as two separate 8 bit re
100. c c commands assigns generic command cmd error none none cli c mode error result code cmd lcd processes D commands none none display c implements user dialog for cmd load data code download upload none none load c cmd meter processes M commands none none meter c cmd mpu data acces processes context for MPU s DATA none none access c processes power save cmd power save none none cmd misc c command cmd rtc processes RTC commands none none cmd misc c cmd trim processes trim commands none none cmd misc c emin een eet SEN uint8 ta uint8 tb uint8 t math c unsigned char a and b x X0 1s takes ones uint8 tx x uint8 tx x0 complement x m none math c complement of n byte xO n Compute Phase Angl Computes the V I phase void void phase angle c e angle Compute RMS Computes Vrms and Irms void void rms c TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation aes 71M652X Software User s Guide calculates longitudinal parity uint8 tx ptr uint16 t LRC Calc NVR on NVRAM len U01 set bool library c ctoh converts quod nex character uint8_t c uint8_t load c to hexadecimal digit date lcd Displays the current date void void rtc c Figure the elapsed time struct RTC t start struct Delta Time between two times RTC tend int32_t seconds rtc c Sets the frequency Uses D
101. cme 130 The RCON Bit FUNCOMS me 130 The T2CON Register iio m ect ee 131 The T2C ON NEE 131 Priority evel GroupSisic sie E 131 External MPU Interrupts A 132 Control Bits for External Interrupts AA 132 Nei e EE 132 ThedP 1 Ce LEE 132 Pronty Levels ttt A LE 132 Polllng SEquence RR 133 niue feo 5 POSO OO OO PP 133 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN 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 71M6521D 71M6521F and 71M6521B 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 transf
102. conductor Corporation MYTERI DIAN Software User Guide This User Guide contains proprietary product definition information 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 Rd Suite 100 Irvine CA 92618 5201 TEL 714 508 8800 FAX 714 508 8877 http www teridian com 2005 2007 TERIDIAN Semiconductor Corporation 8 6 2008 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 00
103. d access 256 pages of 256 bytes each to the full 64KB of external data RAM In the second type of MOVX instruction MOVX DPTR the data pointer generates a sixteen bit address This form is faster and more efficient when accessing very large data arrays up to 64 Kbytes since no additional instructions are needed to set up the eight high ordered bits of address It is possible to mix the two MOVX types This provides the user with four separate data pointers two with direct access and two with paged access to the entire 64KB of external memory range Dual Data Pointer The Dual Data Pointer accelerates the block moves of data The standard DPTR is a 16 bit register that is used to address external memory or peripherals In the 80515 core the standard data pointer is called DPTR the second data pointer is called DPTR1 The data pointer select bit chooses the active pointer The data pointer select bit is located at the LSB of the DPS register DPS 0 DPTR is selected when DPS 0 0 and DPTR1 is selected when DPS 0 1 The user switches between pointers by toggling the LSB of the DPS register All DPTR related instructions use the currently selected DPTR for any activity The second data pointer may or may not be supported by certain compilers Internal Data Memory The Internal data memory interface services up to 256 bytes of off core data memory The internal data memory address is always 1 byte wide The memory space is 256 bytes 00H to F
104. 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 15 Instruction Set in Hexadecimal Order Copyright 2005 2007 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 0xD4 DAA XCH A direct OxD5 DJNZ direct rel XCH A 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 M
105. e Demo Code the coefficients have to be entered in the form Y CAL Y CALC ya Y CALC 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 5 14 5 Validating the Battery CORRECTION ppm For applications that utilize the RTC it is very important to validate the battery A brief loss of battery power when the 652X 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 will 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 this date 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 If invalid time date information is detected it sets them to 01 01 01 1 1 2001 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation ATER DIAN SEMICON
106. e discarded The copy operations stated in the flow chart are implemented with the MEMCPY MCE macro which moves data between internal RAM and CE DRAM or vice versa Due to the wait states that apply to accesses of CE DRAM this operation cannot be done directly TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN XFER_busy_rtc_int gt IE_XFER no es y Clear IE_XFER yes alt mux cycle yes v Configure for alt mux cycle yes Not first CE pass yes Y Copy data from CE DRAM to IRAM Decrement ce first pass v Apply creep threshold ce first pass 0 yes Y Enable pulses lt v Reset XFER BUSY watchdog IE RTC yes Clear IE RTC v Accumulate pulse counts v Clock compensation Y Watchdog reset Figure 5 9 XFER_BUSY RTC ISR The interrupt service routine includes a loop Without this loop there is the chance of a rare subtle timing error because interrupt EXT6 is edge triggered and the two interrupt sources or into it The timing error will occur if the TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 00 A RTC interrupt happens and then the XFER interrupt happens after the IE_XFER flag is already tested but b
107. e 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 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation Ee Power Factor Measurement The power factor option not compiled in the executable Demo Code 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 cos calculation is based on the equations P S cos S PF gt PF P S with P real energy S apparent energy PF power factor or VAh divided by Wh 5 4 4 Watchdog Timer The Demo Code revision 4 03 uses only the hardware watchdog timer provided by the 80515 This fixed duration timer is controlled with SFR register WDI 0xE8 The software watchdog timer is described in section 6 3 4 but should not be used The hardware watchdog timer is more reliable since it cannot be accidentally disabled The hardware watchdog timer requires a refresh by the MPU firmware i e bit 7 of WDI 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 o
108. ed measurements of current and voltage are added to the variables Using two accumulation intervals covers both chop polarities of temperature measurements 4 Ifcs 0 This signals the end of the calibration Cumulative current and voltage measurements are then used to calculate and set the calibration coefficients for voltage and currents in CE DRAM See the source file calphased c for details CE Default Calibration ce_def_calibration Y Copy CE DATA image to RAM v set tc1 tc2 Figure 5 15 ce default Calibration Revision 1 7 TERIDIAN Proprietary 60 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation set_tc1_tc2 Y fppmc1 ppmc1 from CE fppmc2 ppmc2 from CE v tn calibration temperature from CE temperature compensation for adc a calibration temperature exists Y tppmc1 tppmc2 no temperature compensation 4 pmc1 trimbgb Read Trim _TRIMBGB b AA constants are not set read a trim value untrimmed untrimmed a 6680 b 341000 y timm Read_Trim _TRIMM trimbga Read_Trim _TRIMBGA 128 127 e tppmc1 22463L a 50000L 100000L tppmc2 1150L b 500000L 1000000L v Write values to CE ppmc1 tppmc1 ppmc2 tppmc2 c
109. efore the RTC interrupt is cleared In this case the signal to EXT6 will remain set and never have an edge to cause another interrupt 6 Therefore the XFER_BUSY interrupt will hang forever thus preventing delivery of the data to the meter To prevent this error condition at the end of the XFER_BUSY_RTC service routine both interrupt flags are again checked and when at least one of them is active the processing starts again Both interrupts have a backup check the main watchdog timer is never reset unless both interrupts run 5 4 2 1 SERIAL Interrupt est Ier is the ISR servicing UART 0 In this ISR the UART data is sent and received along using flow control if enabled Parity and other serial controls are managed in this ISR The alternative serial port UART 1 uses an ISR with identical code structure es1_isr est Iert es1 isr no RX interrupt no RX interrupt RI TRUE RI TRUE yes yes y y Call high level protocol to Call high level protocol to receive byte receive byte gt gt no T TRUE TX interrupt no T TRUE TX interrupt yes yes Call high level protocol to Call high level protocol to transmit byte transmit byte Figure 5 10 Serial 0 and 1 isr TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MES 5 4 3 Background Tasks meter_run
110. enient 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 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 2007 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 ww
111. er 1 IP1 B9H 00H Interrupt Priority Register 1 SORELH BAH 03H Serial Port 0 Reload Register high byte S1RELH BBH 03H Serial Port 1 Reload Register high byte USR2 BFH 00H User 2 Port high address byte for MOVX Ri IRCON COH 00H Interrupt Request Control Register T2CON C8H 00H Timer 2 control register only bits I2FR and I3FR are used PSW DOH 00H Program Status Word WDCON D8H 00H Baud Rate Control Register only WDCON 7 bit used A EOH 00H Accumulator B FOH 00H B Register Table 6 5 Special Function Registers Reset Values TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation e Special Function Registers Specific to the 652X Register Alternative SFR R W Description Name Address DIOO DIO 0 0x80 Register for port O read and write operations pins DIOO DIO7 DIO8 DIO DIRO OxA2 Data direction register for port O Setting a bit to 1 means that the corresponding pin is an output DIO9 DIO_1 0x90 Register for port 1 read and write operations pins DIO8 DIO15 DIO10 DIO DIR1 0x91 Data direction register for port 1 Setting a bit to 1 means that the corresponding pin is an output DIO11 DIO 2 OxAO Register for port 2 read and write operations pins DIO16 DIO21 DIO12 DIO DIR2 OxA1 Data direction register for port 2 Setting a bit to 1 means that the corresponding pin is
112. erator selector WDCON This register determines whether UARTO is controlled by timer 1 or by the internal baud rate generator TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation d jTERIDIAN Generic Special Function Registers Location and Reset Values Table 6 5 shows the location of the SFRs and the value they assume at reset or power up Register Location Resetvalue Description PO 80H FFH Port 0 SP 81H 07H Stack Pointer DPL 82H 00H Data Pointer Low 0 DPH 83H 00H Data Pointer High 0 DPL1 84H 00H Data Pointer Low 1 DPH1 85H 00H Data Pointer High 1 WDTREL 86H 00H Watchdog Timer Reload register PCON 87H 00H Power Control TCON 88H 00H Timer Counter Control TMOD 89H 00H Timer Mode Control TLO 8AH 00H Timer 0 low byte TL1 8BH 00H Timer 1 high byte THO 8CH 00H Timer 0 low byte TH1 8DH 00H Timer 1 high byte CKCON 8bEH 01H Clock Control Stretch 1 P1 90H FFH Port 1 DPS 92H 00H Data Pointer select Register SOCON 98H 00H Serial Port 0 Control Register SOBUF 99H 00H Serial Port 0 Data Buffer IEN2 9AH 00H Interrupt Enable Register 2 S1CON 9BH 00H Serial Port 1 Control Register S1BUF 9CH 00H Serial Port 1 Data Buffer S1RELL 9DH 00H Serial Port 1 Reload Register low byte P2 AOH 00H Port 2 IENO A8H 00H Interrupt Enable Register 0 IPO A9H 00H Interrupt Priority Register 0 SORELL AAH D9H Serial Port 0 Reload Register low byte IEN1 B8H 00H Interrupt Enable Regist
113. erature c cc cce cescceeedessteeeceenedeedeneteendeeeedecdeesbdecdeesueeedeedseeteeedeenseeedecnivesdoees 80 Figure 5 25 Crystal CompensatlOn o ooi arte ae edocet gutes ra dee aec date kae eee dud ead tae eaae Roe ede c Ye ded 81 Figure 5 26 Operation Modes State Diagrarm c csccescececessceeedeseneeedeceeeeedeceedendeeesdeedeesenseseesesaedeedeensteedeeesteedenantenenes 97 Figure 6 1 Memory Map m comes Ga 103 Figure 6 2 80515 LC Block DiaQramml 0c sssseenseessseetseccnenseenenensncseeseectennuatsersnsenagasacoenedueseeeneeneessscornensaceennepeceeteess 118 Figure 6 3 Watchdog Block Diagram oooononcccnnnnccnnnoncncnanoncnononononononnnc canon eene nennen enne nnne inneren tenen enne nns 126 Figure 6 4 Interrupt Sources Diagram cnn nano rr rro enne inneren nennen nennen nene EAEE Eat 134 List of Tables Table 3 4 Memory Map ccs 2s feotsi a aia 19 Table 5 1 Internal Data Memory Map gege EENEG fc een chad ide atada ed 37 RI lut ER ECKE A0 Table 5 3 D mio Code Versions EE 41 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA Table 5 4 Current Sensing Options ee coire erant eret iex rare Ero denice ance MEL AEEEE RV 2 aA EE KE SORS Y EEE ETEEN EEEN AAN 42 Table 5 5 Compensation Features iicet iriiria ici 42 Table 5 6 Power Registers and Pulse Output Features ooonccccnnocccinoncccnnnonnncnnnnnnnn
114. erring 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 Licensed 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 contem
115. eset state WDTS is cleared either by the reset signal or changing the state of the WDT timer TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MERI DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Refreshing the WD Timer The watchdog timer must be refreshed regularly to prevent the reset request signal from becoming active This re quirement imposes an obligation on the programmer to issue two instructions The first instruction sets WDT and the second instruction sets SWDT The maximum delay allowed between setting WDT and SWDT is 12 clock cycles If this period has expired and SWDT has not been set WDT is automatically reset otherwise the watchdog timer is reloaded with the content of the WDTREL register and WDT is automatically reset Special Function Registers for the WD Timer Interrupt Enable 0 Register IENO MSB LSB EALI WDT ET2 ESO ET1 EX1 ETO EXO Table 6 33 The IENO Register Watchdog timer refresh flag Set to initiate a refresh of the watchdog timer Must be set directly before SWDT is set to prevent an unintentional refresh of the watchdog timer WDT is reset by hardware 12 clock cycles after it has been set Table 6 34 The IENO Bit Functions Note The remaining bits in the IENO register are not used for watchdog control Interrupt Enable 1 Register IEN1 MSB LSB EXEN2 SWDT EX6 EX5 EX4 EX3 EX2 T
116. esign Guide e Memory model programming test tools Design Reference e Demo code structure flow charts 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 1 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 features included in the 71M652X Demo Boards in terms of software and some hardware To get the most out of this document the reader should also have available other 71M652X publications such as the 71M652X Demo Board User s Manual respective data sheets errata list and application notes for additional details and recent developments TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation e 1 2 RELATED DOCUMENTATION Please refer to the following documents for further information e 71M6521 Demo Board User s Manual e 71M6521DE FE or 71M6521BE Data Sheet e Signum Systems ADM 51 In Circuit Emulator Manual 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
117. ess uwrdio c uwreep c2 Revision 1 7 TERIDIAN Proprietary O Copyright 2005 2007 TERIDIAN Semiconductor Corporation 94 of 138 71M652X Software User s Guide RA VAh Accumulate Calculates VAh void void vah c VARh Accumulate Calculates VARh void void varh c voltage phase lcd Display voltage phases on LCD uint8 t select void vphase c wd create Creates a software watchdog uint8 t wd void wd c wd destroy Destroys a software watchdog uint8 t wd void wd c wd reset Resets a software watch dog If all software watch dogs have been reset the hardware watchdog is reset uint8 t wd void wd c wh accumulate Calculate watt hours void void wh c wh brownout to lcd O Displays a precalculated 6 digit number uint32_t number void wh c wh lcd Displays a watt hour value on the LCD in milliwatt hours uint8 t val void wh c wh sum export Adds 0 w1 to s only if w1 is negative yielding a total of exported power in w uint8x t s int32i t wl void wh c wh sum import Adds w1 to s only if w1 is positive yielding a total of imported power in w uint8x t s int32i_t wl void wh c wh sum net Adds w1 to s yielding a net sum of watthours in s uint8x t s int32i t wl void wh c wh to long
118. est is DPH It can be loaded as a 2 byte register MOV DPTR data16 or as two registers e g MOV DPL data8 It is generally used to access external code or data space e g MOVC A A DPTR or MOVX A DPTR respectively Program Counter The program counter PC is 2 bytes wide initialized to OOOOH after reset This register is incremented during the fetching operation code or when operating on data from program memory Ports Port registers PO PT and P are Special Function Registers The contents of the SFR can be observed on corresponding pins on the chip Writing a 1 to any of the ports causes the corresponding pin to be at high level VCC and writing a 0 causes the corresponding pin to be held at low level GND All DIO ports on the chip are bi directional Each of them consists of a Latch SFR PO to P2 an output driver and an input buffer therefore the MPU can output or read data through any of these ports if they are not used for alternate purposes Timers 0 and 1 The 80515 has two 16 bit timer counter registers Timer O and Timer 1 These registers can be configured for counter or timer operations In timer mode the register is incremented every machine cycle meaning that it counts up after every 12 periods of the MPU clock signal In counter mode the register is incremented when the falling edge is observed at the corresponding input pin tO or t1 Since it takes 2 machine cycles to recogn
119. etermine Frequenc sag status and voltage F y thresholds to return 0 if the void void freq c voltages are off Sets status bits if voltages e currents or temperature are e Determine Peaks outside limits Sag tests are void void peak_alerts c in xfer_busy_int done exits control uint8_td c c cli c connects disconnects bool access uint16 t eeprom c EEProm Config bur ca Md to page size uint8_t Wr none eepromp3 c esO_isr serial port 0 service routine none none ser0 c esl isr serial port 1 service routine none none se1 c Input interrupt for FLAG flag0_in AMR module on SERO none none flag0 c3 eres Initialize the FLAG AMR flagO initialize module on SERO none none flag0 c3 Output interrupt for FLAG flag0_out AMR module on SERO none none flag0 c3 Run main loop logic for flag0 run FLAG AMR module on none none flag0 c3 SERO Input interrupt for FLAG flagl in AMR module on SER1 none none flag1 c3 TE Initialize the FLAG AMR flagl initialize module on SER1 none none flag1 c3 Revision 1 7 TERIDIAN Proprietary 84 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide EA Output interrupt for FLAG flagl out AMR module on SER1 none none flag1 c Run main loop logic for flag1_run FLAG AMR module on none none flag1 c SER1 Displays the frequency on frequency lcd the LCD
120. etion STARTUP A51 causes a jump to the label C_START which is contained in the second startup assembly program named init A51 Keil C51 LIB directory see Figure 5 2 Init A51 finally causes the jump to main The startup files are described in section 5 10 main v Reset Watchdog v Process WD Overflow flag BROWNOUT mode yes no PB pressed es v v Clear PB and WAKE flags Clear PB and WAKE flags v Set WAKE timer to 7s Y v Enter LCD mode Enter SLEEP mode ka Y v main init main run v Figure 5 3 main Program 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 Figure 5 4 expects regular interrupts from the CE If no interrupts occur the main program will cease to trigger the watchdog timer resulting in a reset condition if the watchdog timer is enabled The main program calls the main init Figure 5 4 and the main run Figure 5 5 routines main init is used for hardware and software initialization main run is the routine that is executed in an endless loop and that takes care of background and foreground processing TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN main_init y Initial
121. external interrupt 5 EX4 0 disable external interrupt A EX3 0 disable external interrupt 3 EX2 0 disable external interrupt 2 Table 6 44 The IEN1 Bit Functions Interrupt Enable 2 Register IEN2 MSB LSB E z E S z ES1 Table 6 45 The IEN2 Register IEN2 0 ES1 0 disable UART 1 interrupt Table 6 46 The IEN2 Bit Functions Revision 1 7 TERIDIAN Proprietary 129 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation ALERTAS SEMICONDUCTOR CORP 71M652X Software User s Guide Timer Counter Control Register TCON MSB LSB TF1 TR1 TFO TRO IE1 IT1 IEO ITO Table 6 47 The TCON Register Timer 1 overflow flag Not used for interrupt control Timer 0 overflow flag Not used for interrupt control External interrupt 1 flag External interrupt 1 type control bit External interrupt 0 flag External interrupt O type control bit Table 6 48 The TCON Bit Functions Interrupt Request Register IRCON MSB LSB IEX6 IEXS IEX4 IEX3 IEX2 Table 6 49 The IRCON Register IRCON 7 IRCON 6 IRCON 5 External interrupt 6 edge flag IRCON 4 External interrupt 5 edge flag IRCON 3 External interrupt 4 edge flag IRCON 2 External interrupt 3 edge flag IRCON 1 External interrupt 2 edge flag IRCON O Table 6 50 The IRC
122. for your PC O button The dialog box should look like shown below After making the necessary changes the project file 652X_demo UV2 should be stored Options for Target Target 1 Device Target Output Listing C5 A51 BL51 Locate BL51 Misc Debug Utiities Preprocessor Symbols Define Undefine Code Optimization Warnings Warninglevel 2 e Level 9 Common Block Subroutines M Bits to round for float compare 3 e Emphasis Favor size wel Global Register Coloring e nupt vectors at addens 00000 be h Don t use absolute register accesses Keep variables in order Iw Enable ANSI integer promotion rules Include main ESA cli 6513 Meter util sio Acli P Paths Misc Controls Compiler LARGE OPTIMIZE 9 SIZE BROWSE INCDIR main amp 513V cli 5513 Meter Autil io Seli control DEBUG OBJECTEXTEND string Cancel Defaults Revision 1 7 TERIDIAN Proprietary 31 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation EE SEMICONDUCTOR CORR 71M652X 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
123. fy 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 2007 TERIDIAN Semiconductor Corporation eA TER DIAN SEMICONDUCTOR CORR 71M652X Software User s Guide Revision 1 7 TERIDIAN Proprietary 12 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA 1 INTRODUCTION TERIDIAN Semiconductor Corporation s TSC 71M652X single chip Energy Meter Controllers are a family of Systems on Chip that supports all functionalities required to build a low cost power meter Demo Boards are available for each chip 71M6521DE FE 71M6521BE to allow development of embedded application in conjunction with an In Circuit Emulator Development of a 71M652X application can be started in either 80515 assembly language or more favorably in C using the Demo Boards TSC provides along with the 71M652X Demo Boards a development toolkit that includes a demonstration program Demo Code written in ANSI C that controls all features presen
124. g the Configure button Figure 3 1 as shown below Revision 1 7 TERIDIAN Proprietary 21 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN 3 5 2 CLI Commands The Demo Board User s Manual DBUM for the 71M6521 contains a complete list of the available commands Note Only the 71M6521FE chip has enough memory to support a serial command line interface in addition to its metering functions Communication with the 71M6521BE and 71M6521DE chips is implemented with a simpler interface based on Intel hex records This interface is also described in the Demo Board User s Manual 3 5 3 Command Macro Files Commands or series of commands may be stored in text ASCII files and sent to the 71M652X using the Transfer Send Text File command of Hyperterminal or any other terminal program 11 7 TERIDIAN Proprietary 22 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation ATER DIAN 71M652X 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
125. gister into normal form in which the major count of Wh is greater than or equal to zero and less than 1 000 000 000 The minor count of ce counts e g from wOsum is made to be less than 1 Wh and positive by transfering larger amounts into the major count uint8x_t register_ptr none math c operating lcd Displays the number of hours of operation void void rtc c OperatingHours Calculates hours of operation from the last valid mark none int32_t hours rtc c OSCOPE INIT Defines DIO 7 the VAR pulse output as a DIO n a n a oscope h OSCOPE ONE Set DIO 7 the same pin as the VARh pulse output to high n a n a oscope h OSCOPE TOGGLE Inverts DIO 7 the same pin as the VARh pulse output n a n a oscope h OSCOPE ZERO Set DIO 7 the same pin as the VARh pulse output to low n a n a oscope h pcnt accumulate Accumulates counts from the previous second void void pent c pent_init Initialize logic to count output pulses void void pent c pent lcd Display pulse count on LCD uint8 t select void pent c pent_start Starts plse counting for a fixed number of seconds int16_t seconds void pent c pent_update Synchronizes pulse counts with noninterrupting code void void pent c phase angle lcd Displays a V I phase angle uint8_t
126. gisters Secondary data pointer DPL1 DPH1 This register is a second 16 bit data pointer Note Check with the documentation on the compiler used for generating MPU code whether this pointer is utilized or not Data pointer select register DPS This register selects which data pointer is to be used for the current operation Port registers PO P1 P2 These registers hold bit patters that are written to or read from the DIO ports Serial data buffer SOBUF S1BUF These registers hold data received from the serial interfaces 0 and 1 Data to be transmitted via the serial interfaces is written to SOBUF or S1BUF Serial port reload registers SORELL SORELH S1RELL S1RELH These register pairs can be used to control the baud rate for the serial ports 0 and 1 Timer registers TLO TL1 THO TH1 These register pairs THO TLO and TH1 TL1 are the 16 bit counting registers for timers 0 1 and 2 Interrupt control registers IPO IP1 IEN IENO TMOD TCON T2CON SCON PCON IRCON These registers contain control and status bits pertaining to the interrupt system the timers counters and the serial port Clock control register CKCON The clock control configuration register It is used to implement stretch memory cycles for memory access Watchdog timer reload register WDTREL This register holds the reload count for the software watchdog timer Baud rate gen
127. i t typedef unsigned long idata uint32i t typedef signed char idata int8i t typedef signed short idata int16i t typedef signed long idata int32i t This is fairly fast not battery backed up memory slower than the data in the lower 128 bytes of internal memory Competes with data for space Type definitions 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 uint32p t typedef signed char pdata int8p t typedef signed short pdata int16p_t typedef signed long pdata int32p_t The upper byte of the XDATA address is supplied by the SFR OxBF ADRMSB on the 71M6521 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 are not battery backed up It can be used for everything possible On Keil s large model this is the default typedef unsigned char xdata uint8x t typedef unsigned short xdata uint16x t typedef unsigned long xdata uint32x t typedef signed char xdata int8x t typedef signed short xdata int16x t typedef signed long xdata int32x t Type definitions for external read only data loca
128. iliary routines for CLI load c upload and download profile c data collection for support of profile command serOcli c ser1cli c sercli c buffer serial I O for the CLI TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN When compiled without the on line help option help c CLI C takes about 14Kbytes of program space Adding the on line help will use another 5Kbytes When designing a real meter CLI C can easily be removed without major changes to the software FLAG flag0 c flag1 c flag c 10 cal_ldr c eep24C08 c eeprom c eepromp c eepromp3 c iiceep c iolite c Icd c Icd_VIM808 c rtc c ser c ser0 c ser1 c serial c tmr0 c tmr1 c uwrdio c uwreep c Main batmodes_20 c defaults c main c main c Meter calphased c ce c ce652X c error c freq c i0652X c meter c misc c pent c peak alerts c phase angle c psoft c pulse src c pwrfct c rms c vah c varh c vphase c wh c UnitTest eepromtest c Basic FLAG AMR Protocol implements a basic FLAG AMR protocol for SERO implements a basic FLAG AMR protocol for SER1 code shared shared by flag0 c and flag1 c Input Output load routines for calibration factors routines supporting the 2408 EEPROM interrupt driven serial EEPROM routines high speed polling EEPROM routines polling interface for uWire EEPROM I2C bus interface using the chip s I2C hardware IO subroutines for use by the calibration loader
129. im compensation using Y_Cals none int32_t ppb rtc c RTClk Write writes sets to RTC none none rtc c Converts seconds to clock seconds ticks usually for a software any number uint16 t stm h timer Selects pulse sources for 2 CE pulse outputs and optionally for two additional SelectPulses software pulse outputs void void pulse src c The controls are in MPU variables initialized from the default table sends passed result code to send a result UART uint8 tc none cli c send byte sends a 0 255 byte to S08n none io c DTE send char sends single character uint8 tc none io c sends lt CR gt lt LF gt out to send crlf UART none none io c sends single ASCII hex or send digit decimal digit out to uint8 tc none io c SERIALO Revision 1 7 TERIDIAN Proprietary 90 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation EA Function Routine Description Inp File Nam Name escriptio put Output e Name sends text in code at send help specified location to serial uint8 tr code s none cli c port send hex sends DVIS OUE SERIAL IN uint8_t n none io c HEX sends a 0 9 999 999 999 send long value to DTE int32 tn none io c sends a 0 FFFFFFFF a send long hex value to DTE U32n none io c send num sends a 0 9 999 999 999 int32_t n uint8_t size none io c value to DTE send_result l oks up TERUR code
130. imated 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 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MATERI DIAN SEMICONDUCTOR CORP 71M652X Software User s Guide CT and shunt 1KB to Y Configurations include one element one phase and resistors 2 5KB neutral current as well as two elements with two phases Rogowski coils 2 5KB N N N Needs special CE code Table 5 4 Current Sensing Options Chopping of 0 06KB Y Y Y Control of the chopping bit VREF Temperature 0 1KB Y 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 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 RTC constant 0 1KB Y N opt Y Constant rate compensation only compensation Full RTC 0 2KB N N opt N opt 2Md_order compensation of RTC to ppb using compensation temperature Correction does not occur when the ADC mux is off line Temperature 0 0K Y Y Y Provides difference from calibration temperature to measurement 0 1 C when calibrated Table 5 5 Compensation Features
131. inear 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 24 Crystal Frequency over Temperature TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation A a 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 from 1 a 10 T b 10 T2 c 109 When applying the inverted coefficients a curve see Figure 5 25 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 32767 9 32767 8 ii crystal 32767 7 8 curve fit 32767 6 9 inverse curve pop 50 25 0 25 50 32767 5 Figure 5 25 Crystal Compensation The MPU Demo Code supplied with the TERIDIAN Demo Kits has a direct interface for these coefficients and it directly controls the RTC DEC SEC or RTC INC SEC registers This interface is implemented by the MPU variables Y CAL Y CALC and Y CALC2 MPU addresses 0x04 0x05 0x06 For th
132. ing pu Vision2 Compiling the source code using the Keil compiler Modifying the source code and recompiling until all compiler error messages are resolved Using the assembler and linker to generate executable code Downloading the executable code to the ICE Executing the code and watching its effects on the target 2 3 SOFTWARE ARCHITECTURE The 71M652X 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 discrete 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 Revision 1 7 Hardware UARTO UART1 AFE Display Sensors Terminal AMR PC Figure 2 1 Software Structure TERIDIAN Proprietary 16 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation A
133. instruction in progress is not RETI or any write access to the registers IENO IEN1 IEN2 IPO or IP1 Interrupt response will require a varying amount of time depending on the state of the MPU when the interrupt occurs If the MPU is performing an interrupt service with equal or greater priority the new interrupt will not be invoked In other cases the response time depends on the current instruction The fastest possible response to an interrupt is 7 machine cycles This includes one machine cycle for detecting the interrupt and six cycles to perform the LCALL 6 3 5 2 Special Function Registers for Interrupts Interrupt Enable 0 Register IEO MSB LSB TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP EAL WDT ESO ET1 EX1 ETO EXO Table 6 41 The IENO Register EAL 0 disable all interrupts Not used for interrupt control ES0 0 disable UART 0 interrupt ET1 0 disable timer 1 overflow interrupt EX1 0 disable external interrupt 1 ETO0 0 disable timer O overflow interrupt EX0 0 disable external interrupt 0 Table 6 42 The IENO Bit Functions Interrupt Enable 1 Register IEN1 MSB LSB SWDT EX6 EX5 EX4 EX3 EX2 Table 6 43 The IEN1 Register Not used for interrupt control EX6 0 disable external interrupt 6 EX5 0 disable
134. issrrirnsriiresrinresrrnnrsens 106 Generic Special Function Registers Location and Reset Values ssssssnensssessrrrresesreee 107 Special Function Registers Specific to the 652X sss 108 6 2 2 The 80515 Instruction Set 109 Instructions Ordered by Function enm eene eren 110 Instructions Ordered by Opcode Hexadecimal eee 114 Instructions that Affect Flags eri te aang ve ten ata ep ua nerd ee 117 6 3 80515 Hardware description seeeeseeeeeeeieeeeeeeeeee eee rc 117 6 3 1 Block Diagram 118 6 3 2 80515 MPU 119 een TE it M 119 MIg doeceljcge C eee ee 119 Program Status Word PW iet en a a RR Rd een ended OD een bee 119 Stack Policiaca en 120 DO orm etus ert eese 120 Revision 1 7 TERIDIAN Proprietary 6 of 138 6 3 3 6 3 4 6 3 5 7 1 7 2 Program Counter AA Ports 120 Timers 0 and 1 Timer Counter Mode Control Register TMOD Timer Counter Control Register TCON 6 3 2 1 A Allowed Combinations of Operation Modes eem Serial Interface O and 1 Serial Interface O Modes s ciniiisiresriesiediteisstiiskiseteeeisi toi eirddededridiiatd e iddei dsideis titadi dedii dens aa Serial Interface 1 Modes 6 3 3 1 Baud Rate generator nennen nemen nnne enne Software Watchdog Timer structure 6 3 4 1 WD Timer
135. ith 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 8k 16k and 32k versions 2 4 UTILITIES Two 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 resulting 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 Both 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 Any changes to I O RAM Configuration RAM can be made permanent by merging them into the object file The first step for this is to create a maco file macro txt containing the commands adjusting the I O RAM such as the following commands affecting calibration 182416381 192416397 E4237 The d merge program updates the 6521 demo hex file with the values contained in the macro file The d merge program must be in the same directory as
136. ize a 1 to 0 event the maximum input count rate is 1 2 of the oscillator frequency There are no restrictions on the duty cycle however to ensure proper recognition of 0 or 1 state an input should be stable for at least 1 machine cycle Four operating modes can be selected for Timer 0 and Timer 1 Two Special Function Registers TMOD and TCON are used to select the appropriate mode TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation q ATER DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Timer Counter Mode Control Register TMOD MSB LSB GATE C T M1 MO GATE C T M1 MO Timer 1 Timer 0 Table 6 21 The TMOD Register Function If set enables external gate control pin intO or int1 for Counter O or 1 respectively When intO or int1 is high and trx bit is set see TCON register a counter is incremented every falling edge on tO or t1 input pin Selects Timer or Counter operation When set to 1 a Counter operation is performed When cleared to 0 the corresponding register will function as a Timer Selects the mode for Timer Counter 0 or Timer Counter 1 as shown in TMOD description Selects the mode for Timer Counter 0 or Timer Counter 1 as shown in TMOD description Table 6 22 The TMOD Register Bits Description 0 0 Mode 0 13 bit Counter Timer with 5 lower bits in the TLO or TL1 register and the remaining 8 bits in the THO or TH1
137. ize battery mode management v Remove software watchdogs Y Reset RTC y Set default values y Restore calibration values no restore OK Y Apply calibration defaults autocal request yes Perform autocal 8 v Initialize LCD v Display HELLO v meter initialize v Enable RTC interrupt v Initialize pulse counting v Enable CE v Create SW watchdog for main loop v Enable interrupts Figure 5 4 main init Function TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 00 TERIDIAN SEMICONDUCTOR CORP main run main background v main background v Reset SW watchdog for main loop v Neutralize potential flash Command pending erase from EMI yes v v Run software timers Process command 4 v Run metering Process flag protocol 0 y v Detect and manage battery modes Process flag protocol 1 Figure 5 5 main_run Function 5 4 BASIC CODE ARCHITECTURE The TERIDIAN 71M652X firmware can be divided into two code parts One is the Background task that is executed whenever there are no other higher priority exceptions such as the servicing of inte
138. kes probably because the push button was pressed in brownout mode it runs through the brief initialization needed by the C environment and in main it tests for brownout mode In the brownout mode s code it runs a very simple fast state machine that uses the wake button flag to decide whether to enter sleep mode or LCD mode and just depends on the LCD registers to remain unchanged An algorithm similar to this could be adapted to display several values setting the new value in the LCD as the last step after all other calculations were done in brownout mode After displaying the values in the LCD the code could enter LCD mode to save power and still display the value When the chip wakes from sleep or LCD mode the PC is cleared to zero and the I O bits that are not needed for the RTC or LCD are reset The experience of the firmware designers is that it is most convenient to treat transitions from LCD and sleep modes like resets This permits a relatively simple start up initialization to handle the state transitions as well as power up in mission mode That scheme proved so convenient that the Demo Code also used the same scheme to transition to and from brownout mode It s not clear at first how to distinguish hard resets from battery mode transitions The code can use the nonvolatile LCD control registers The trick is that after a reset the LCD registers are cleared In particular LCD NUM bits 0 4 of XDATA address 0x2020 are cleared
139. l stabilization delay measurement and adjustment phases are managed by separate routines that are activated by cal flag being YES and controlled by the variable cs which counts down accumulation intervals set calibration values to cal begin unity v Y set calibration values to unity populate table with unity values Y v record calibration copy table of starting values temperature to CE data area v v calculate PPMC and PPMC2 calculate PPMC and PPMC2 and write to CE and write to CE v start count down sequence ei v cal flag YES The processing of the calibration steps is performed by the routine calibration which is called in ce update when new data becomes available i e once per accumulation interval The auto calibration mechanism functions as a state machine sequenced by the variable cs which is used to count down accumulation intervals Figure 5 14 Auto Calibration 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 each cumulative voltage and current measurement are cleared TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation MYTERI DIAN SEMICONDUCTOR CORP 71M652X Software User s Guide 3 If 0 lt cs lt Scal For two accumulation intervals prorat
140. lculates watt hours Wh for each conductor and the meter WxSUM X 5 It calculates var hours VARh for each phase and the meter VARxSUM X 6 It calculates summed squares of currents for each phase IXSQSUM X 7 It calculates summed squares of voltages for each phase VxSQSUM X 8 It counts zero crossings on the same phase as the frequency MAINEDGE X The CE code see ce652x c for a C image 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 Each metering equation has a CE code written for that calculation so that the 6521 can calculate according to the most common metering methods Once per accumulation interval the MPU requests the CE code to make an alternative measurement alternate multiplexer cycle TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA At the end of each accumulation interval an MPU interrupt the xfer_interrupt occurs see ce c xfer_busy_isr occurs This is the signal for the MPU to copy the above data to stable storage for further use At this time the MPU performs creep detection meter c Apply_Creep If the measured voltage current and or power is below the minimum no results for volts current or watts are reported If the voltage
141. 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 ll write in the case of accumulation variables TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation A Name Purpose Function or LSB Value CLI Format Lin XDATA bits IThrshldA Starting current LSB 216 A TOSOSUM JO unsigned 32 0x0000 element A 0 in this position disables creep logic for both element A and B Config Configure meter bit 0 reserved 1 N A 8 0x0004 operation on the fly 0 VA Vrms Irms 1 VA AWh VARh bit1 1 Clears accumulators bit2 1 Calibration mode bit3 reserved 1 enable tamper detection VPThrshld error if exceeded LSB 2 6 IVOSOSUM D unsigned 32 0x0005 IPThrshld error if exceeded LSB 216 a TOSOSUM 3 unsigned 32 0x0009 Y Cal DegO RTC adjust 100ppb y signed 16 0x000D Y Cal Deg1 RTC adjust linear by 10ppb AT in 0 1 C JS signed 16 Ox000F temp Y_Cal_Deg2 RTC adjust squared 1ppb AT in 0 1 6 signed 16 0x001 1 by temp PulseWSource Wh Pulse source See table for PulseWSource and y7 unsigned 8 0x0013 PulseVSource VARh pulse source PulseVSource je 0x0014 selection Vmax Scaling Maximum 0 1V 9 unsigned 16 0x0015 Voltage for PCB equivalent to 176mV at the VA VB pins ImaxA
142. mpatibility Statement 112r erit cni reai n rau onion NEES SEENEN EEN 14 2 eus DESIGN GUIDE 15 2 1 Hardware Requirements R 15 2 2 Software Requirements 15 2 3 Software Architecture e 16 2 4 AAA 17 2 4 1 D_MERGE 17 2 4 2 CE_MERGE 17 guum DESIGN REFERENCE 19 3 1 Program MOMONY isis aiii EVA du anciana 19 3 2 IECH e Lu OT 19 3 3 Programming of the 71M652X Chips cocinar i 20 3 4 Debugging of the 71M652X Chips esee eseeeeeeee ee een nennen nnne cc 20 3 5 Test TOOS cionado aan ela M ana 20 3 5 1 Running the 652X_Demo hex Program 21 3 5 2 CLI Commands 22 3 5 3 Command Macro Files 22 Hos TOOL INSTALLATION GUIDE 23 4 1 Installing the Programs for the ADM51 Emwulator eese enne nnne nnne 23 4 2 Installing the Wemu Program Chameleon Debugger eene nennt 23 4 3 Installing the ADM51 USB Driver erret erret enero iaa 24 4 4 Installing Updates to the Emulator Program and Hardware eeeeeeeeeeeeeeeeeneeennnnne 25 4 5 GEARING a A A Eea A REE de Edaina 26 4 6 Installing the Keil Compiler 2 12 2 iice a ainaani 29 4 7 Creating a Project for the Keil Compiler 1eeeeeeeeeeeeeeeeeeeene eere enne nennen nnne rene nnne 30 4 7 1 Directory Structure 30 4 7 2 Adjusting the Keil Compiler Settings 31 4 7 3 Manually
143. n Compensation in meter c The gain calculations set a global gain parameter gain adj used by the CE code As a side effect the parameters PPMC and PPMC2 the coefficients that control the meter s linear and quadratic gain by temperature are now in MPU memory space rather than CE memory space This causes very little loss of accuracy because the temperature changes only slowly 5 18 TEST MODULES Various Test Modules are available from TERIDIAN These Test Modules are small Keil projects that can be used to test various functions of the 71M6521 IC The available Test Modules are described in this section 5 18 1 6513 CE Example Even though written for the 71M6513 this Test Module can be used for the 71M6521 It builds a simple test code that starts and runs the compute engine collects meter data in RAM and generates pulses for one accumulation interval The Keil project file is 6513 ce example uv2 5 18 2 Serial Port Tests These Test Modules build simple tests of the serial ports The tests start by sending the ASCII character E in a loop e g For testing with an oscilloscope As soon as a character is received the test code begins echoing typed characters using polling IO Sending the period character switches the I O to interrupting I O Note that serOtest c and seritest c use identical text except for the include file This is a very convenient technique for moving serial I O to a different port when requirements ch
144. nonnncnnnn nn nr nan cnn nan nennen enne nennen nennen 43 Table 5 7 Creep FUNCIONS iioii M 44 Table 5 8 Operating oo t dia 44 Table 5 9 Calibration and Various Services oooocccnoncconococccononcncnonannnnnnnncnnnno nn nn nono rca nan n rre rra nnne enne nennen nennen 46 Table 5 10 Interrupt Service ROUtirnies cuc irit biet ie dees t ecient det ag a p On EE Vo Rr a oe RR pane ed 50 Table 5 11 Interrupt Priority Assignment ceeceiiseeciee ese eene seis tiatia da denen de dar ires aa Rande inna 51 Table 5 12 MPU Memory Location eii trame eo EL eie bg ead ERR Ee He ERR E ERE lle lee 78 Table 5 13 Frequency over Temperature 80 Table 6 1 Speed Advantage Summary sss en nenne enne innen en nns n enne e eere 101 Table 6 2 Stretch Memory Cycle Wd 104 Table 6 3 Internal Data Memory Map 14 iieri e eaa annu uda 105 Table 6 4 Special Function Registers Locations mene nr 105 Table 6 5 Special Function Registers Reset Values ene ener nnne nnne emnes 107 Table 6 6 SFRs Specific to Bu 109 Table 6 7 Notes on Data Addressing Modes AA 109 Table 6 8 Notes on Program Addressing Modes AA 109 Table tandem t E 110 Table 6 10 Logic Operations viii es 111 Table 6 11 Data Transfer Operations 4 2 entenita aaa g nte e 112 Table 6 12 Program Elle iioii etd eta EU ae ROC a estes
145. of include files are special cases and provide global data or hardware definitions e Main 6521B options h selects the features used by the code that is less than 8K e Main 6521D options h selects the features used by the code that is less than 16K e Main 6521 CLloptions h selects the features used by the code that is less than 32K e mainloption gbl h defines global configuration values used in all meter versions e meter meter h defines the meter s configuration and power registers e meter ce652x h defines the CE memory used to communicate with the MPU e meter io652x h defines the memory mapped registers of the 652x chips e Utilreg652x h defines the special function registers of the 652x chips util stdint h defines a standard integer package for TSC meter chips using 8051s 5 11 1 OPTIONS H The file OPTIONS H is especially important because it controls entire features in a firmware build 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 can quickly tune the Demo Code to approximate the desired meter configuration 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
146. on aes Function Routine Name Description Input Output File Name ser xmit rdy Returns true if the serial port can send another byte void bool serO h ser1 h Receive a string up to a enum SERIAL PORT Serial CRx port uint8x t buffer uint16 tlength received sercli c3 maximum length i uint16_t len Transmit a string up to a Bn ce Serial CTx g up port uint8x_t buffer uint16_t length sent sercli c3 maximum length uint16 tlen ets additional bytes from enum ERE COM Serial CRx 9 y port uint8 tx buffer uint16 t secli c the receive buffer uint16 tlen uts additional bytes into ee Me Serial CTx p 8 y port uint8 tx buffer uint16 t sercli c the transmit buffer l uint16 tlen Receive a string of an Enum SERIAL FORT Serial_Rx g y port uint8x_t buffer none sercli c3 length uint16 tlen sets up receive buffer and gnum SERIAL PORT Serial_Rx Pe port uint8 tx buffer enum SERIAL RC data sercli c starts receiving uint16 tlen Serial RxFlowOff Force an XOFF to be sent enum SERIAL PORT na sercli c3 on the selected port port Serial RxFlow0n Force an XON to be sent on enum SERIAL PORT nons sercli c3 the selected port port Serial RxLen returns the number of bytes enum SERIAL_PORT uint16 t sercli c received port Transmit a string of any enum SERIAL PORT Serial_Tx port
147. ond element can be used to reduce the calibration steps during meter manufacturing The second element provides the data needed to calibrate the meter with both current sensors operating at the same time This permits more accurate realistic calibrations For two element three wire delta meters or dual non tamper detecting single phase meters use CE21A03 CE C and CE21A03 DAT C When the hardware field EQU is 02 this CE code provides two metering elements One has an equation of WhA VA IA The other is WhB VB IB This measures two legs of a delta configuration and therefore by Blondel s theorem when these are added together the total delivered power is metered Since the two channels are independent they can also be used as two single phase meters even if the meters are operating on different phases Teridian has a number of other CE codes for other sensors and needs including code for tamper resistant meters 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 5 13 CE21B CE C This file provides the image of the 6521 CE program in C notation CE21C DAT C This file provides the image of the 6521 CE default data in C notation COMMON MPU ADDRESSES In the Demo Code certain MPU XRAM parameters have been given fixed addresses in order to permit easy external access These variables can be read via the command
148. pSrc uint8 t len void ce Copies from the CE int32x_t pDst int32x t memepy eec n memory to XDATA pSrc uint8_t len void SER Reads a word of the CE e memget ce memory int32i t pDst int32 t ce c Sets a word of the CE int32i t pDst int32 t memset ce memory Sm void ce c Display the current quantity E meter lcd on the LCD void void meter c Performs meter data meter run processing void void meter c compares xdata to flash uint8 tr rsrc uint8_tx p EES code xsrc uint16_t len RUN Bra nie Revision 1 7 TERIDIAN Proprietary O Copyright 2005 2007 TERIDIAN Semiconductor Corporation 87 of 138 aes Function Routine interface Name Description Input Output File Name uint8_tx xsrc1 uint8_tx mememp xx compares xdata to xdata xsrc2 uint16_tlen S08 library c uint8 ti dst uint8 tx memcpy ix copies xdata to idata src uint8_t len none library c none x Copies data to serial U32 Dst uint8 tx pSrc enim GE Py_P EEPROM uint16_t len eee eepromp3 c memcpy rce reads from or writes to flash int32_tr dst into i none flash c src uint8_t len uint8 tr dst uint8 tx memcpy rx Copies xdata to code flash src uint16 t len bool flash c i SE uint8_tx det uint8_ti e memcpy xi Copies idata to xdata src uint8_t len none library c rene xe copies data from serial uint8 tx pDst U32 S
149. plated 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 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 certi
150. 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 Hyperterminal session at 9600 or 300 bps depending on the setting of jumper connected to DIO 08 see the 71M6521 Demo Board Users Manual 8N1 one stop bit with XON XOFF flow control enabled The setup dialog box is shown in Figure 3 1 e Power on the Demo Board and hit CR a few times on the PC keyboard until gt is displayed on the Hyperterminal screen e Typea command from the CLI Reference documented in the 71M6521 Demo Board User s Manual e Al 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 71M6521 Demo Board User s Manual contains instructions on how to connect the serial cable COM1 Properties Port Settings Bits per second Data bits la sl Parity None D Stop bits E y Flow control xon Xoff Restore Defaults Cancel Apply 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 pressin
151. pts and priorities code for counting output pulses detects out of range line values calculates and displays 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 Test and Verification not Shipped with standard Demo Code basic test of the EEPROM driver TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation Aa flagOtest c a test fora FLAG system modetest c a simple test of the 6520 s battery modes serOtest c tests the serial driver for SERO seritest c tests the serial driver for SER1 stmtest c tests the software timers tmrOtest c tests the driver for TMRO tmr test c tests the driver for TMR1 Util Utilities dead c defines unused flash space for the boot loader dio h defines high level access to DIO pins flash c flash memory read write erase compare and checksum calculation irq c securely disables and enables interrupts library c routines for memory copy compare CRC calculation string length math c contains routines for multiple precision math oscope h a utility to trigger oscilloscope loops using DIO7 priority h header file defining priorities for IPO and IP1 sfrs c access to SFRs startup a51 startup assembly code
152. r Corporation TERMINAN Description Baud Rate shift register Fclk 12 8 bit UART Variable 9 bit UART Fclk 32 or 64 9 bit UART Variable Table 6 29 Serial Port 0 Modes Note The speed in Mode 2 depends on the SMOD bit in the Special Function Register PCON when SMOD 1 Fclk 32 Serial Interface 1 Modes The Serial Interface 1 can operate in 2 modes Description Baud Rate 9 bit UART variable 8 bit UART variable Table 6 30 Serial 1 Modes Mode A This mode is similar to Mode 2 and 3 of serial interface 0 11 bits are transmitted or received a start bit 0 8 data bits LSB first a programmable 9 bit and a stop bit 1 The 9 bit can be used to control the parity of the serial interface at transmission bit tb81 in S1CON is output as the 9th bit and at receive the 9th bit affects rb81 in the Special Function Register S1CON The only difference between Mode 3 and A is that in Mode A only the internal baud rate generator can be use to specify baud rate Mode B This mode is similar to Mode 1 of serial interface 0 Pin rxd1 serves as an input and txd1 serves as a serial output No external shift clock is used 10 bits are transmitted a start bit always 0 8 data bits LSB first and a stop bit always 1 On receive a start bit synchronizes the transmission 8 data bits are available by reading S1BUF and the stop bit sets the flag rb81 in the Special
153. r more than one period A shorter undervoltage condition is called a dip see Figure Figure 5 22 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 RUE SR E RET A AEST Figure 5 22 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 23 SAG_THR 84 samples vi Ton SAG CNT Figure 5 23 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 652X Data Sheet for details It is up to the MPU firmware to decide what is to be done in case a sag is detected The Demo Code does not have any provisions for actions due to sags detected by the CE 5 14 2 Temperature Measurement The temperature output of the on chip temperature sensor TEMP RAW is provided by
154. rc enum GC PY_ P EEPROM uint16_t len PES eepromp3 c mem iti copies xdata from code uint8 tx dst uint8_tr none library c PY_ flash src uint16_t len y uint8 tx dst uint8 tx memcpy xx copies xdata to xdata src uint16 tlen none library c sets xdata to specified uint8 tx det uint8 t s memset x none library c value uint16 tlen meter initialize initializes most I O functions none none meter c thaty read line power meter totals Display a selected quantity uint8_t select uint8_t void meter on the LCD phase Er eee Converts to timer s count number uint16_t tmrO h tmr1 h Converts milliseconds to milliseconds clock ticks usually for a any number uint16 t stm h software timer i0 em Converts to timer s count number uint16 t tmrO h tmr1 h min dee uint16_t a uint16_t b uint16_t options_glib h MPU_Clk Select selects MPU clock speed enum MPU SPD speed bool serial c Describes the clock speed enum SERIAL_PORT MPU_Clk_Select of the MPU to a serial port enum eMPU_DIV bool sercli c3 interface speed Describes the clock speed MPU_C1k_Selecto of the MPU to the serial enum eMPU_DIV speed bool serOcli c3 interface Describes the clock speed MPU_Clk_Select1 of the MPU to the serial enum eMPU_DIV speed bool sertcli c3 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide MERI DIAN SEMICONDUCTOR CORP normalize puts a re
155. register VARh import 0 25KB N N opt Y pulse output VARh export 0 4KB N N opt Y register VARh export 0 25KB N N opt n pulse output Operating hours 0 36KB N N opt N opt 5 99999 9 Nonvolatile count of tenths of hours of register powered operation since first cold start RCT time register 0 18KB N opt Y RCT date register 0 21KB N opt Y Pulse source 0 4KB N N opt This is the ability to route most calculated energy selection values to a pulse output The 8K code provides only Wh pulses Dual IMAX 0 2KB Y Y Y 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 RMS current 0 2KB N N opt Y Implemented for two phases P 1 amp 2 1 P 000 000 register RMS voltage 0 2KB N N opt Y Implemented for two phases P 1 amp 2 1 P 000 000 register Power factor 0 3KB N N opt N opt Two phases are displayed with sign Reset at reset register and the start of each minute Volatile Table 5 6 Power Registers and Pulse Output Features Revision 1 7 TERIDIAN Proprietary 43 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERI DIAN SEMICONDUCTOR CORP 71M652X Software User s Guide Feature Creep mode 0 37KB Y Y Y Adjustable at calibration If abs W Creep threshold then creep mode Zero accumulator N A Y Y Y The pulse accumulation register in the CE is cleared of CE to prevent spurious p
156. rporation MERI DIAN 71M652X Software User s Guide SEMICONDUCTOR CORP Feature FLAG interface 2 5KB N N opt N opt Implements the FLAG protocol stack see the FLAG protocol specification The FLAG protocol reads and writes registers in the meter and responds to all ports Reception of 2 0KB Y Y Y Simple serial calibration system that supports reading calibration data and writing calibration values including CE data parameters via MPU calibration and RTC settings Meter operation is the serial interface not required when this feature is in use Intel hex records are used Count of 01 KB Y 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 N N opt Y Internal automatic calibration from command line interface if available or DIO state at start Calibration adjusts phase as in the fast calibration described in the DBUM Command Line 14KB N N Y Text based commands give access to CE data RAM Interface CLI IO registers No help profile or load features Versions without CLI can be controlled with IOMERGE The command line interface s space is to be counted as unused when calculating code space margin Optical FLAG 1 2KB N N opt N opt Implementation of the physical FLAG layer on UART 1 300 BAUD using pulse ou
157. rrupts The second part consists of the interrupt driven code Foreground tasks such as the CE_BUSY Interrupt Timer Interrupt and other Interrupt service routines The background code takes care of the non time critical functions starting with the system reset and this code is executed every time when there are CPU resources available after taking care of all interrupt driven tasks The background of the 71M652X firmware is implemented as a very simple state machine One state is serving the command inputs and the other is idle Display control 5 4 1 Initialization When the power applied for the first time or RESETZ is asserted the 71M652X device executes the code pointed to by the reset vector TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation TERIDAN 5 4 2 Foreground There are total 12 interrupts available for the 80515 and the revision 4 7a Demo Code uses a total of 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 Interrupt Source Interrupt Service External or In source file Vector Priority Routine Internal B Interrupt highest Pulse count pcnt w isr EXTO pent c 0x03 0 Pulse count pent_v_isr EXT1 pent c 0x13 3 Flash Write collision fwcol isr EXT2 flash c 0x4B 0
158. rupt 0 UART 1 interrupt Timer 0 interrupt External interrupt 2 TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation Level3 highest Polling sequence AA External interrupt 1 External interrupt 3 Timer 1 interrupt External interrupt 4 UART 0 interrupt External interrupt 5 External interrupt 6 Table 6 59 Polling Sequence 6 3 5 5 Interrupt Sources and Vectors The vectors associated with each interrupt source are displayed in Table 6 59 Interrupt Request Flags Interrupt Vector IL ____ Address IEO External interrupt 0 0003H TFO Timer 0 interrupt 000BH IE1 External interrupt 1 0013H TF1 Timer 1 interrupt 001BH RIO TIO UART 0 interrupt 0023H RI1 Tli1 UART 1 interrupt 0083H IEX2 External interrupt 2 004BH IEX3 External interrupt 3 0053H IEX4 External interrupt A 005BH IEX5 External interrupt 5 0063H IEX6 External interrupt 6 006BH Table 6 60 Interrupt Vectors External Interrupt Edge Detect The external interrupts 4 5 and 6 are activated by a positive transition The external source must hold the request pin low high for int2 and int3 if it is programmed to be negative transition active for at least one MPU clock period Afterwards it must be held high low for at least one MPU clock period to ensure the transition is recognized and the corresponding interr
159. s amp Prog Mem to from IRAM amp SFRs rxdOi MEMORY CONTROL pe dptr dptrl fetch instr cycle CONTROL_UNIT fetch instr RAM_SFR_CONTROL instr cycle ALU SERIAL_0 s con sOrell sOrelh sObuf txd0 lt rxdli txdl SERIAL_1 slrell slrelh CLOCK_CONTROL pcon ckcon internal sfrbus TIMER 0 1 tlO thO tll thl tf0 jet tfl iel ISR WATCHDOG_TIMER wdtrel Figure 6 2 80515 uC Block Diagram TERIDIAN Proprietary O Copyright 2005 2007 TERIDIAN Semiconductor Corporation DIO gating registers DIO_R external interrupts portOi portli port2i port3i port0o portlo port2o port3o DIO pins BA 6 3 2 80515 MPU The 80515 MPU is composed of four components 1 Control unit 2 Arithmetic logic unit 3 Memory control unit 4 RAM and SFR control unit The 80515 MPU allows instruction fetch from program memory and instruction execution using RAM or SFR The following chapter describes the main MPU registers Accumulator ACC is the accumulator register Most instructions use the accumulator to hold the operand The mnemonics for accumulator specific instructions refer to accumulator as A not ACC The B Register The B register is used
160. s a summary of the 80515 features Control Unit G bit instruction decoder Reduced instruction cycle time up to 12 times Arithmetic Logic Unit 8 bit arithmetic and logical operations Boolean manipulations 8x68 bit multiplication and 8 8 bit division 32 bit Input Output ports Four 8 bit I O ports Alternate port functions such as external interrupts and serial interfaces are separated providing extra port pins when compared with the standard 8051 Two 16 bit Timer Counters 4 Two Serial Peripheral Interfaces in full duplex mode capable of parity generation Synchronous mode fixed baud rate Serial 0 only 8 bit UART mode variable baud rate 9 bit UART mode fixed baud rate Serial O only 9 bit UART mode variable baud rate EI 701 7N2 7E2 702 8N1 8E1 801 8N2 ONT data formats supported Two Internal baud rate generators independent from timers Interrupt Controller Four priority levels with 11 interrupt sources 15 bit Programmable Watchdog Timer Internal Data Memory interface Can address up to 256B of internal data memory space 4 External Memory interface Can address up to 64kB of external program memory 32KB 16KB or 8KB provided on chip Can address up to 2kB of external data memory plus 512 bytes CE DRAM Separate address data bus to allow easy connection to memories Variable length code fetch and MOVC to access fast slow program memory Variable leng
161. s and subfolders where all project files will be stored Main project settings will be stored in the project configuration file Wemu51 CNF located in the project directory Other files stored in the project directory will be project command startup file Wemu5t INI program executable and source code files definitions of custom toolbar buttons various project related data files Note that project directory 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 lt Back Next gt J 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 E USPS In Circuit Emulator ES S Tag DoCD DCD on Chip Debug System Sim 8051 Simulator Nest Revision 1 7 TERIDIAN Proprietary 27 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation S EMRAN SEMICONDUCTOR CORP 71M652X 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 2 1 10 IceServer ho
162. sent gt N N N N Timer expired imer expir unction v execute Timer expired function Ne Figure 5 7 stm_run Process Software Timers non ISR TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA CE_BUSY Interrupt CE_BUSY interrupt is used for handling the outputs of the CE that are refreshed every 396us i e SAG detection ce busy isr Y Disable CE interrupts v Stretch clock 5 times v Read CE status v Normal clock v Execute Timer Expired function no ag data amp Ox l 0 yes v User code handling SAG goes here v sag data 0 Y EX CE BUSY 0 disable interrupt Figure 5 8 CE BUSY ISR XFER BUSY and RTC Interrupt The XFER Busy interrupt is requested by the CE at the conclusion of every accumulation cycle The interrupt service routine copies the CE output data to the MPU internal data RAM for further processing by the MPU which is performed by the background task The handling of data for the generation of pulses is also managed in this ISR Processing of CE data waits until the second interrupt after one second has elapsed since it takes roughly one second for the PLL in the CE to settle and therefore for the filtering to be reliable variable ce first pass Thus the first samples from the CE ar
163. set routine but this is followed by logic that calls four RTIs to reset the interrupt acknowledge logic for all four 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 are the PLL OK interrupt external interrupt 4 see Main batmodes_20 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 lo tmr1 c amp h though earlier versions used it to set the real time clock 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 O 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 0 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
164. st Name or IP address Back Next gt J Cancel When prompted for the processor to be used select either 71M6521 Click Next Project Creation Wizard Please select processor you want to use in your project from the following list of processors If you cannot find exact processor name please select processor manufactured by the same company which has features most alike to your processor or contact Signum Systems Technical Support for an assistance 116511 TDK 7 TDK 71M6513 Precision Voltage Reference CC Debug Click Finish Revision 1 7 TERIDIAN Proprietary 28 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 4 MONIO une 71M652X Software User s Guide E NE 4 6 INSTALLING THE KEIL COMPILER After inserting the Keil CD ROM into the CD drive of the PC the on screen instructions should be followed to install the Keil compiler Note For PCs that can only use one type of drive at a time CD ROM drive floppy drive such as certain laptops it is helpful to copy the contents of the floppy labeled Add On Disk to the hard drive of the PC That way drives do not have to be swapped out during the installation The installer will display the following screen y Keil Development Tools Release 04 2004 Ee Tools Ds PX Install Products amp Updates Thanks for taking the time to review this CD ROM Install Evaluation Software Here you will find the
165. t 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 652X ICs but should 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 guarantees implied Customers may use the Demo Code as 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 D
166. t 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 level 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 0xA9 Ox1A 0001 1010 e IP1 SFR 0xB9 0x2C 0000 1100 This results in the priority assignment shown in Table 5 11 Affected Interrupts 0 0 External interrupt 0 DIO UART 1 interrupt Timer 0 interrupt Ext 2 comparators External interrupt 1 DIO Ext 3 CE BUSY Timer 1 interrupt Ext 4 comparators UART O interrupt Ext 5 EEPROM s Ext 6 XFER BUSY RTC 1S Table 5 11 Interrupt Priority Assignment Timer Interrupt timerO of the MPU is the main system timer and it is used to generate a 10ms timer tick which is adjusted for MPU clock speed The timer tick variable tick count is used to control the software timers 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
167. ted in code space typedef unsigned char code uint8r_t typedef unsigned short code uint16r t typedef unsigned long code uint32r t typedef signed char code int8r t typedef signed short code int16r t typedef signed long code int32r t Access is indirect via a 16 bit register This is the slowest but largest space nonvolatile programmable flash memory It should be used for constants and tables TERIDIAN Proprietary Copyright 2005 2007 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 Bytes Comments Bit Bbool Unique to 8051 Sbit Unique to 8051 SFR Unique to 8051 SFR16 Unique to 8051 signed unsigned char ANSI C ANSI C ANSI C ANSI C ANSI C ANSI C ANSI C ANSI C o N enum unsigned short signed short signed unsigned int signed int Sibilla lich unsigned long Float S 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 overl
168. th MOVX to access fast slow RAM or peripherals Dual data pointer for fast data block transfer 4 Special Function Registers interface Services up to 74 external special function registers TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation AA 6 2 80515 ARCHITECTURAL OVERVIEW 6 2 1 Memory organization The 80515 MPU core incorporates the Harvard architecture with separate code and data spaces Memory organization in the 80515 is similar to that of the industry standard 8051 There are three memory areas program memory External Flash external data memory External RAM and internal data memory Internal RAM FFFFH FFFFH C000H C000H 8000H 8000H 4000H 4000H FFH Program memory External data memory Internal data memory Figure 6 1 Memory Map Program Memory The 80515 can address up to 64kB of program memory space from 0000H to FFFFH Program memory is read when the MPU fetches instructions or performs a MOVC After reset the MPU starts program execution from location 0000H The lower part of the program memory includes a reset and interrupt vectors The interrupt vectors are spaced at 8 byte intervals starting from 0003H External Data Memory The 80515 can address up to 64kB of external data memory in the space from 0000H to FFFFH The 80515 writes into external data memory when the MPU executes a MOVX Ri A or MOVX QDPTRAA instruction The external data memory is read when the MPU executes a
169. thin the 71M652X has separate program 32K 16K or 8K bytes and data memory 2K 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 segmented in 512 byte pages 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 71M652X has 2K bytes of Data Memory for exclusive use of the embedded 80C515 MPU In addition there are 512 bytes for the Compute Engine See Table 3 1 for a summary 0000 7FFF 0000 4FFF Flash Memory Non volatile Program and non volatile 0000 2FFF data 0000 07FF Static RAM Volatile MPU data XRAM 1000 11FF Static RAM Volatile CE data Miscellaneous I O RAM 2000 20FF Static RAM Volatile configuration RAM Table 3 1 Memory Map Revision 1 7 TERIDIAN Proprietary 19 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation d jTERIDIAN 3 3 PROGRAMMING OF THE 71M652X CHIPS There are two ways to download a hex file to the 71M652X Flash Memory e Using a Signum Systems ADM 51 ICE e Using the TERIDIAN Semiconductor Flash Programmer Module FDBM or the TERIDIAN Semiconductor Flash Download FDBM TFP1 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
170. to start the Chameleon debugger Signum Systems Wemus51 ADM51 Emulator 6513 File Edit View Debug Project Options Window Help 1 AHHH HHH HIE HH X HEHEHE HEHE HEHE HEHE c c JE HEHE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE JE c X c X c HEH 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 e implied warranties of merchantability and or fitness for a particular 5 purpose 5 e 7 Copyright C 2003 TDK SemiConductor Corporation All Rights Reserved 8 9 gt 3 3 3 C CC HHH JC 3 9 HHH 3 9 3 JE 3 3 9 3 9 3 JE 3 3 3 3 3 3 3 JE 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 EE E E EE EEN 1 Bo LL RHEE CC CC CC CC CC C JC C C C C C EC E 9 9 JC JC JC 3 JE 3 9 9 9 9 3 ERE li 7 12 DESCRIPTION 71M651x POWER METER API Exerciser Routines 135 w 14 AUTHOR MTF 15 7 16 HISTORY 2003 OCTOBER 30 First Version 17 1 8 bo A Lf RHEE HE HK HH KH HEHEHE HK CE 3 9 3 3 9 9 9 3 3 JE 3 3
171. tput Wired FLAG 1 2KB N N opt N opt Implementation of the physical FLAG layer on UART 0 9600 BAUD Save registers 0 75KB Y Y Y Saves power and error registers on sag detection when sag occurs Save to flash 0 9KB N opt 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 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 Y Each revenue affecting data area is protected by a simple checksum Revision 1 7 TERIDIAN Proprietary 45 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation E SEMICONDUCTOR CORP 71M652X Software User s Guide Error recording 0 4KB N opt N opt N opt Errors are recorded in 16 bit words one bit per error and saving All error collection is reset when the magnetic tamper DIO is asserted for 1 second Error data is protected by a checksum The time stamp 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 N opt EEPR
172. uilding 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 LINK6521 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 10 ALTERNATIVE EDITORS Many modern text editors have a feature called tag jumping 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 conv
173. ulse t 2 PulseWidth 1 397us 13 signed 16 0x0029 is on OxFF disables this feature Takes effect only at start up temp_nom Nominal tempera Units of TEMP_RAW from CE 14 unsigned 32 0x002B ture the temperature The value read from the CE must at which calibration be entered at this address occurs ImaxB Scaling maximum 0 1A 15 unsigned 16 0x002F current for PCB ele ment B equivalent to 176mV at the IA pin IThrshldB Starting current 2 5 IISOSUM 16 unsigned 32 0x0031 element B VBatMin Minimum battery Same as VBAT below 17 unsigned 32 0x0035 voltage CalCount Count of calibrations Counts the number of times 18 unsigned 8 0x0039 calibration is saved toa maximum of 255 RTC copy Nonvolatile copy of Sec Min Hr Day Date Month 119 unsigned 8 0x163 the most recent time Year 1A 8 the RTC was read 1B 8 1C 8 1D 8 1E 8 1F 8 deltaT Difference between Same units as TEMP RAW 320 signed 32 0x003B raw temperature and temp_nom Frequency Frequency Units from CE 21 unsigned 32 0x003F VBAT Last measured n 322 unsigned 32 0x0043 battery voltage VBAT ES ADC counts logically shifted right by 9 bits Note battery voltage is measured once per day except when it is being displayed or requested with the BT command Revision 1 7 TERIDIAN Proprietary 76 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation d J TERIDIAN Purpose CLI
174. ulses from low current noise Current threshold N A Y Y Y Adjustable at calibration Set If max abs IA2 abs IB2 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 N Y Y Adjustable at calibration If max abs VA2 abs VB2 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 Brownout mode 0 1KB Y 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 Y Is entered automatically when a sag event occurs Displays the Wh register waits 7 sec using wakeup timer then initiates sleep mode Wake button 0 5KB Y Y Y When in sleep mode enters LCD mode Wake timer 0 5KB Y 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 is represented by the sum of the other code features Revision 1 7 TERIDIAN Proprietary 44 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Co
175. umulator 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 QRi 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 accumulator e aja a N ajaj gt 9 PO gt PM dM dM dM dM PD eJ Al oO ow ws ms a gt oO oO M MIMI M gt MLM MO _ MO NM DM Table 6 9 Arithmetic Operations TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation 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
176. upt request flag is set TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation d J TERIDIAN External Internal Logicand Interrupt Interrupt Source Interrupt Interrupt Polarity Control Es Flags Flags Selection Register Eo j UART1 gt RI al gt optical Sr LT Timer 0 El gt TFO E Priority Assignment D Z e S i es Z o o tr ti tri tr Z 3 Z Z Ss gt n bo Wi N e ul co o c o 2 o o e D lo a d I FR Bis IEN1 1 INT2 E ot IRCON 1 m Ei L Compar ators ri I3FR 4 INT3 CE BUSY m diem IRCON 2 17 IENO Timer 1 M TFI ators Wi u S nu RIO a pu IEEE S SS i TIO H IENI IRCON 3 H E tri z o EN D Le P m T BO A oso Z Z CA Do 5 zi a a o o z z un TEN 1 un Figure 6 4 Interrupt Sources Diagram TERIDIAN Proprietary O Copyright 2005 2007 TERIDIAN Semiconductor Corporation Interrupt Vector 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 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
177. ve 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 R AM 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 constan t included as bytes 2 and 3 of instruction bit 256 software flags any bit addressable I O pin control or status bit A addr16 Accumulator address space Table 6 7 Notes on Data Addressing Modes Destination address for LCALL and LJMP may be anywhere within the 64 kB of program memory addr1 1 Destination address for ACALL and AJMP will be within the same 2 kB page of program memory as the first byte of the following instruction rel the first byte of SJMP and all conditional jumps include an 8 bit offset byte Range is 127 128 bytes relative to the following instruction Table 6 8 Notes on Program Addressing Modes TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation d jTERIDIAN Instructions Ordered by Function Mnemonic Description ADD A Rn Add register to acc
178. verflow 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 Note The bits of the WDI register SFR OxE8 should not be individually set or reset Instead byte operations should be used The following macro code should be used for resetting clearing the watchdog IE RTC or IE XFER bits define WD RST OxFF WatchDog bit define IE BIC 0x02 RTC ticked define IE XFER 0x01 XFER data available define RESET WD IFLAGS WD RST define CLR IE XFER IFLAGS IE XFER amp Ox7F 0x7E define CLR IE RTC IFLAGS IE BIC Ox7F 0x7D 5 4 5 Real Time Clock RTC The RTC is accessible through the I O RAM Configuration RAM registers RTC SEC through RTC YR addresses 0x2015 through 0x201B as described in the data sheets Since the RTC runs on a much slower clock than the MPU only one write operation can be performed per RTC clock cycle This means that write operations to set the RTC must be separated by at least 396us The sample code uses a software timer to perform this delay so any code modification must make sure that hardware timer 1 is still useable for the RTC functions TERIDIAN Proprietary Copyright 2005 2007 TERIDIAN Semiconductor Corporation SA 5 5 MANAGING MISSION AND BATTERY MODES
179. void void freq c Copies CE configuration constants to a data a get ce constants structure so they can be void void ce c viewed in the emulator gets next character from get char CLI buffer none uint8_t io c gets next character from e get char d CLI buffer uint8 t idata d uint8 t io c TENE gets next decimal or hex F x get digit digit from CLI buffer uint8 t idata d uint8 t io c converts ascii decimal or get long hex long to binary number none int32 t io c i converts ascii decimal long get long decimal to binary number uint8 tc int32 t io c converts ASCII get long hex hexadecimal number to none U32 io c binary number converts ascii decimal or get num hex number to binary none S08 io c number i converts ascii decimal get num decimal number to binary number none S08 io c converts ascii hexdecimal get num hex byte to binary number none uint8 t io c converts ascii decimal or e get_short hex short to binary number none int16_t io c get short decimal converts ascii decimal short none int16 t iam to binary number converts ascii hexdecimal ge _short_hex short to binary number nong SET SC htoc converts hexadecimal digit Yintg tc uint t load c to ascii hex character gets a bit used to reset e IICGetBit some parts none bit iiceep c i initializes DIO4 5 as IICInit EEPROM interface none none iiceep c Revision 1 7 TERIDIAN Proprietary 85 of 138
180. w 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 11 ALTERNATIVE LINKERS Compiled and linked code can be significantly compacted by using the linker available with the Professional Compiler Kit PK51 from Keil www kel com The LX51 Enhanced Linker supplied 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 conventional linker can pack into a given code space the LX51 Enhanced Linker should be considered TERIDIAN Proprietary 36 of 138 Copyright 2005 2007 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
181. ys HELLO on LCD none none Icd c i clears LCD enables LCD LCD Init segment drivers none none Icd c LCD Mode Display a mode number uint8 t mode none Icd c Revision 1 7 TERIDIAN Proprietary 86 of 138 Copyright 2005 2007 TERIDIAN Semiconductor Corporation 71M652X Software User s Guide EA int32_t number uint8_t num_digits_before_deci LCD_Number Displays a number onthe mal_point uint8_t none Icd c LCD eu num digits after decim al point returns maximum of lmax unsigned long a and b U32 a U32b U32 math c returns minimum of lmin unsigned long a and b U32 a U32 b U32 math c log2 returns binary logarithm uint16 tk uint8 t math c main background Penes background none none main c processing Displays either the main edge cnt lcd instantaneous edge count Q or the cumulative edge a void freq c count main soft reset initiates soft reset none none main c returns maximum of t max unsigned int a and b uint16 ta uint16 tb uint16 t options glib h A Copies from IDATA to the int32x_t pDst int32i_t memepy esiis CE memory pSrc uint8_t len ZER e Copies from flash to the CE int32x t pDst int32r t mene ry eet memory pSrc uint8_t len EE Ke Copies from XDATA to the int32x_t pDst int32x t ie cM CE memory pSrc uint8_t len van Ke Copies from the CE int32i_t pDst int32x_t MEMEDY MCN 1j memory to IDATA

Download Pdf Manuals

image

Related Search

Related Contents

Blackwire® C710™/C720™  GUÍA DEL USUARIO LISTA DE TRIPULANTES/PASAJEROS  Notice d`installation TABLE DES MATIÈRES  Fichas CBB AR SIDERURGICO  Visualizza/apri - POLITesi  Euromac Golden 1500  - NEC Display Solutions Europe  Philips TL-D Colored 18W  Le Système Trind  Alarm Handling Manual  

Copyright © All rights reserved.
Failed to retrieve file