Application Note EEPROM Emulation on the Z51F3220 MCU

AN036501-1013

Abstract

This application note provides a method for utilizing a segment of the Z51F3220 MCU’s to emulate the functionality of an EEPROM device. The written to Flash remains protected from power loss and inadvertent writes, because special instruc- tion sequences are required to write or erase Flash memory.

Note: The source code file associated with this application note, AN0365-SC01.zip, is available free for download from the Zilog website. This source code was compiled using the Keil μVision4 and Small Device C Compiler (SDCC) v 3.1.0 tools. The Keil μVision4 develop- ment tool is available from Keil; the SDCC v3.1.0 tool is included in version 2.1 of the Z8051 Software and Documentation set, which is available free for download from the Zilog Store. For this source code to work properly with other Z8051 MCUs, minor modifi- cations to the source code may be required.

Discussion

This section describes the Flash memory spaces of the Z8051 MCU, including a virtual EEPROM emulation technique. Z8051 Internal Flash Memory The on-chip program Flash memory in Zilog’s Z8051 MCUs feature nonvolatile, linearly- addressable, Flash memory with in-circuit write/erase capability. This Flash memory can be read with a MOVC instruction and can be programmed in the On-Chip-Debugger (OCD), Serial In-System Programming (ISP), or User Program modes. The contents of Flash memory are divided into sectors, which are blocks of consecutive Flash addresses. The Z51F3220 MCU contains 512 sectors with 64 on each sector. A Flash loca- tion comprises eight Flash cells, with each cell representing one bit. In a typical Flash cell, a logic 0 represents an erased state, and a logic 1 represents a programming state. There- fore, a byte location in the erased state reads as 0x00 and can be programmed to any other value by flipping its 0s to 1s. Changing the state of a cell from 1 to 0 can be accomplished only by erasing an entire sec- tor. A sector erase occurs when all of the bytes in a sector are erased at the same time. In an erase cycle, a sector, or several sectors, are erased. Each cell of Flash memory can per- form a specified number of erase cycles; this number is termed endurance. In the Z51F3220 MCU, the endurance of each Flash cell is at least 100,000 write/erase cycles. The primary purpose of the Z8051 MCU’s on-chip Flash memory is to store software pro-

AN036501-1013 Page 1 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

gramming instructions. When code is programmed, some portions of Flash are not uti- lized, and remain free. These unused portions can be earmarked for virtual EEPROM memory. EEPROM Emulation Technique Generally, an EEPROM chip stores and retains data in the event of a power failure. The data is retrieved when required and updated in the same location (up to the maximum device rating). A virtual software version of an EEPROM can be used instead of a traditional EEPROM chip, and can emulate generic EEPROM functionality in Zilog’s Z8051 on-chip Flash memory. This emulation is performed in various ways by considering Flash limitations and product requirements. At a minimum, all EEPROM emulation implementations require data and address pairs to be stored in Flash locations for subsequent retrieval or update. When data is modified, the modified data associated with an earlier virtual address is stored in a new Flash location. During data retrieval, this modified data is returned. If a new (blank) Flash location on the appropriate page is not available, that page is erased after its valid contents are copied to a new page. The modified data is then written to the new page. Consequently, virtual EEPROM is useful in products requiring frequent updates to data items in the field or during run time. Example. A remotely-located weather data logger that is required to record ambient tem- perature values at regular intervals can utilize virtual EEPROM to store the latest time and temperature values in the Z8051 MCU’s on-chip Flash. The only working limitation is that this Flash memory contains a finite number of erase cycles and a finite amount of memory. As data is being written to Flash in an emulated EEPROM, it is prone to corruption or ambiguity due to power failure, fluctuations in voltage supply, or loss of voltage. These conditions must be considered carefully when designing an application. Developing an EEPROM Emulation This section describes variable structures in EEPROM memory.

Variable Structure A tag byte and its associated data byte combine to create a variable that requires two bytes of storage space. Figure 1 shows the structure of this variable.

AN036501-1013 Page 2 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 1. Structure of a Variable

The tag byte is configured as follows: • The most significant bit (msb) is used as a dedicated bit to indicate whether the associ- ated data byte is the latest (msb = 1) or old (msb = 0) • The remaining seven bits are used to store a 7 bit virtual address value (ranging from 0x01 to 0x7F)

The virtual address value on a page is calculated as follows: Virtual Address Value = ( Virtual EEPROM Address - ( PAGE_VARIABLES * ( PAGE_NUMBER - 1 ) ) ) + 1

In this equation, the following statements are true: • A virtual EEPROM address is a user-specified address • PAGE_VARIABLES is the total number of bytes that can be stored on a single virtual EEPROM page • PAGE_NUMBER is the virtual page number; it is always an integer

A virtual page number is calculated as follows: Virtual page number = (virtual EEPROM address ÷ PAGE_VARIABLES) + 1

Virtual Page Number Byte and Page Integrity Byte The last two physical addresses in every four Flash sectors are reserved as a virtual page number byte and a page integrity byte, respectively. Figure 2 shows a representation of these virtual page number and page integrity bytes.

AN036501-1013 Page 3 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 2. Emulated EEPROM in Z51F3220 Flash

A virtual page number byte indicates the page number of a virtual page in the emulated EEPROM. For newly-erased Flash memory, the final four sectors of the device are main- tained as a transfer page. Each group of four consecutive sectors that precede the transfer page act as virtual page number 1, virtual page number 2, etc. This sequence continues until the allotted number of pages is reached, and changes when the data is modified and stored as a result of page erasures. A page integrity byte indicates the validity of data on a page. Values for these page integ- rity bytes – and interpretations of these values – are listed below. • 0xFF: indicates that the page is valid • 0xCC: indicates that data on this page is invalid (i.e., an incomplete transfer) • 0x00: indicates that the page is blank (i.e., contains no data)

Specifications The EEPROM emulation implemented in this application is based on the following specifications: • Virtual EEPROM is accessible as a linearly-addressable range (i.e., 0000h–1FBFh). • The size of the data to be stored is one byte long (i.e., ranging from 00h to FFh).

AN036501-1013 Page 4 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

• Four Flash sectors form a virtual EEPROM page, which contains 127 bytes of data. • A minimum of two (2) virtual EEPROM pages are required for storing variables as tag- data pairs: one to store tag-data pairs, and the other to be used as a transfer page when the first page is erased. The erased page is then used as a transfer page. • The first virtual EEPROM page should be located at the last sector of Flash memory to avoid the overlapping of the program code and virtual EEPROM (4 KB).

Hardware Implementation

The Z51F3220 Development Board used in this application is connected to a PC using an USB A (male) to Mini-B cable. An on-chip debugger is connected to the Z51F3220 Development Board when downloading the application software to the MCU. Figure 3 shows an example of this hardware setup.

Figure 3. Hardware Setup

The USB cable provides two functions: it powers the Development Board and serves as the communication line between the PC and the MCU. On the Development Board, the cable is connected to the FTDI UART-to-USB chip, which is connected to the UART pins.

AN036501-1013 Page 5 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Software Implementation

The software for this application can be compiled using Keil μVision v4.53.0.6 or SDCC v3.1.0. The primary source code files for this application are the flash.c and .c files. The flash.c file contains the routines that manage the writing, reading, and erasing of Flash memory, while the eeprom.c file contains routines for EEPROM emulation. Flash Memory Operations In this application, Flash memory is read, written, and erased in User Program Mode; these routines are listed below, and described in this section. • FLASH_Write • FLASH_Read • FLASH_SectorErase • FLASH_ByteErase

FLASH_Write The FLASH_Write routine writes a byte to a specific location in Flash memory. This rou- tine begins by setting the Flash Mode Control (FMCR) Register to 01h to clear the page buffer, then sends three NOP instructions. The routine then writes the data to the page buf- fer. The following code segment shows how to write this data in the page buffer.

#pragma asm MOV A, ucData MOV DPH, #0x80 MOV DPL, ucPgBffrAddLwRg MOVX @DPTR, A #pragma endasm

Next, the Flash Sector Address High (FSADRH), Mid (FSADRM), and Low (FSADRL) registers are set, as indicated in the following code segment.

FSADRH = 0; // High Address Register FSADRM = (UINT8) (uiSctrAddrss >> 8); // Mid Address Register FSADRL = (UINT8) (uiSctrAddrss); // Low Address Register

Finally, the Flash Identification (FIDR) and Flash Mode Control (FMCR) registers are set to A5h (i.e., the identification value for Flash Mode) and 03h (i.e., the Flash sector write value), respectively. The three NOP instructions follow.

FLASH_Read The FLASH_Read routine reads a byte from a specific memory location in Flash memory using a MOVC instruction. The following code shows how to perform a byte read.

ucData = 0;

AN036501-1013 Page 6 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

ucFlshAddrssLw = (UINT8) (uiFlshAddrss); ucFlshAddrssHgh = (UINT8) (uiFlshAddrss >> 8); #pragma asm MOV A, #0 MOV DPH, ucFlshAddrssHgh // Flash Address High Byte MOV DPL, ucFlshAddrssLw // Flash Address Low Byte MOVC A,@A+DPTR MOV ucData, A #pragma endasm _nop_ (); // No operation _nop_ (); // No operation _nop_ (); // No operation while ((FMCR & BUSY) == BUSY); // Check if Flash is busy return (ucData);

FLASH_ByteErase The FLASH_ByteErase routine sets a specific memory location in the Flash to 00h. This routine is nearly identical to the FLASH_Write routine, with the exception that with the FLASH_ByteErase routine, the data written to the page buffer will always be 00h and that the Flash Mode Control (FMCR) Register is set to 02h (which sets Flash sector erase mode).

FLASH_SectorErase The FLASH_SectorErase routine erases an entire Flash sector. This routine is similar to the FLASH_ByteErase routine except that, instead of writing 00h to a specific location in the page buffer, 00h is written to the entire page buffer (64 bytes). Protection Against Power Loss The software overhead associated with writing a byte in Flash memory can cause data to be prone to corruption or ambiguity (i.e., address information can become corrupted) due to a power failure. Data corruption can also occur due to fluctuations in voltage supply or a total loss of voltage when writing a byte to Flash. These types of errors must be consid- ered carefully when designing an application. In the software that accompanies this application note, the EEPROM_Initialize routine in the eeprom.c file contains code to eliminate errors due to power loss. A check is conducted at the time of initialization, after a Power-on Reset (POR), using the EEPROM_Initialize API. If more than one location containing the same valid EEPROM address is found, then the latest address byte is invalidated by flipping the msb to 0. Performing this task preserves the last data byte associated with the address and ensures that the old data is retained. The latest address byte is invalidated because the data byte associated with it can potentially be corrupted, for various reasons. EEPROM Emulation APIs To emulate an EEPROM in the Z8051 Flash memory, the following three APIs are cre- ated: EEPROM_Initialize, EEPROM_ReadDataByte, and EEPROM_WriteDataByte.

AN036501-1013 Page 7 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

EEPROM_Initialize The EEPROM_Initialize API sets up and initializes the emulated EEPROM upon power-up. This API must be called prior to other EEPROM emulation APIs. Subsequent calls to this API cause it to function as a clean-up routine to check the of the emulated EEPROM space. The EEPROM_Initialize API returns an error upon failure. Figure 7 on page 15 shows the steps required to initialize virtual EEPROM.

EEPROM_ReadDataByte The EEPROM_ReadDataByte API reads the data byte corresponding to the virtual EEPROM address. If this virtual address is not found, this API returns an error. The pro- cess of reading a data byte from a virtual EEPROM address is shown in Figure 8 on page 16.

EEPROM_WriteDataByte The EEPROM_WriteDataByte API writes a data byte to the virtual EEPROM address. Figure 9 on page 17 shows the process of writing a data byte to a virtual EEPROM address.

Equipment Used

This section provides a list of the hardware and software requirements for this application. Hardware The hardware tools required for this application are: • Z51F3220 Development Kit • Desktop or laptop PC with minimum of three USB ports Software The software tools used to develop this application are: • Keil μVision 4 • SDCC v3.1.0 • AN0365-SC01.zip file containing the project and source code files • HyperTerminal or equivalent terminal emulation program

Testing the Application

This section lists the steps for demonstrating this application and testing the software. Hardware Setup To build and configure the hardware for this application, observe the following procedure.

AN036501-1013 Page 8 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

1. Connect the On-Chip-Debugger (OCD) to the PC’s USB port, and connect the 10-pin connector of the OCD to the Z51F3220 Development Board. 2. Connect one end of the USB A (male) to Mini-B cable to the Z51F3220 Development Board, and connect the other end to the PC’s USB port. The power LED on the Board should illuminate, indicating that the Board is powered up. 3. On the Development Board, check the header to determine if the J16 jumpers are in place on pins 1-2 and 3-4. These jumpers will connect the UART0 TXD and RXD pins to the FTDI UART-to-USB chip. Software Setup To install, configure, and test the software for this application, observe the following pro- cedure. 1. Download and install the Z8051 Software and Documentation files. These files are available free for download from the Downloadable Software category of the Zilog Store. 2. After the Z8051 software is installed, download the AN0365-SC01.zip file from the Zilog website and unzip it into the following path, which you created during the instal- lation process in Step 1. \samples

Example: C:\Program Files\Zilog\Z8051_2.1\samples

3. The software created for this application is designed in a manner such that the source code must be compiled using either the Keil μVision4 tool or the Small Device C Compiler (SDCC) tool. Select one of these two tools as your compiler, and compile the application software. 4. If the preferred compiler is SDCC, run the AN0365_build_sdcc.bat file, which is located in C:\Program Files\Zilog\Z8051_2.1\samples\AN0365- SC01\sdcc. Ensure that the INSTALL_FOLDER variable in the AN0365_build_sdcc.bat file contains the correct installation path for Z8051_2.1 on your computer. 5. A hex file named eeprom_emulation.hex will be created at the conclusion of the build. If the Keil μVision4 tool is used, the hex file will be located in the following path: C:\Program Files\Zilog\Z8051_2.1\samples\AN0365-SC01\keil\obj

However, if the SDCC tool is used, the hex file will be located in the following path: C:\Program Files\Zilog\Z8051_2.1\samples\AN0365-SC01\sdcc

AN036501-1013 Page 9 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

6. Load this hex file to the Z8051 MCU using Zilog’s Z8051 OCD 1.147 software tool. To learn more about compiling and loading a hex file to a Z8051 MCU, please refer to the Z8051 Tools Product User Guide (PUG0033). Demonstration To demonstrate how the application works, observe the following procedure. 1. Load the eeprom_emulation.hex file to the MCU by using either the Keil μVision4 tool or the Z8051 OCD 1.147 tool. 2. After loading the software to the MCU, disconnect the USB A (male) to Mini-B cable first, then disconnect the 10-pin connector of the OCD from the Development Board.. 3. Power up the Development Board by reconnecting the USB A (male) to Mini-B cable to the Development Board. 4. Configure the HyperTerminal (or equivalent) emulation program. In the application software, the MCU is set to communicate with 9600 baud, 8 bits data frame, no parity bits, and 1 stop bit. 5. Reset the MCU by pressing the reset switch on the Development Board.

Note: For the reset pin to work, the Enable/Reset Input option in both the OCD and Keil config- uration dialogs must be selected during the loading of the hex file to the MCU.

6. After the reset, HyperTerminal will display the message shown in Figure 4. This mes- sage indicates that the MCU is initialized. Be advised that after the Pls. Wait. prompt appears, it may take approximately 25 seconds before the -OK prompt will appear.

AN036501-1013 Page 10 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 4. Terminal Display after Reset

7. To begin writing a byte to a specific address in the emulated EEPROM, press the W key on your keyboard. Next, enter the required 16-bit EEPROM address and 8-bit data. After keying in these addresses, the 8-bit data will be automatically written to the emulated EEPROM. Figure 5 shows the HyperTerminal display during this EEPROM write operation.

AN036501-1013 Page 11 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 5. Writing Data to the Emulated EEPROM

8. Press the R key on your keyboard to read from a specific address in the emulated EEPROM. Next, enter the required 16-bit EEPROM address. After you key in this address, the 8-bit data stored in the corresponding EEPROM address will be displayed in HyperTerminal, as shown in Figure 6.

AN036501-1013 Page 12 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 6. Reading Data from the Emulated EEPROM

9. To check , perform a simple power cycle by disconnecting the USB A (male) to Mini-B cable from the Development Board, then reconnecting it; the power LED on the Development Board should illuminate. Wait for the MCU to be initialized, then repeat Step 8 by keying in a virtual EEPROM address. HyperTerminal should return the same data that it displayed before the power cycle. 10. To overwrite the data in a specific virtual EEPROM address, repeat Step 7. To verify that the operation is successful, read the virtual EEPROM address overwritten earlier by repeating Step 8. Check to determine if this address contains the necessary data.

Results

This application shows that data can be written to and read from an emulated EEPROM memory space. Data in this virtual EEPROM can also be overwritten. Data is retained in this emulated EEPROM memory even when power is removed from the MCU.

AN036501-1013 Page 13 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Summary

This document discusses how to virtually emulate EEPROM memory in the Flash mem- ory space of a Z51F3220 MCU; a terminal emulation program is used to demonstrate this EEPROM emulation. The application shows that data in an emulated EEPROM space can be read, written, and overwritten. Data is retained in this section of Flash memory in the event of a power loss, and the size of the emulated EEPROM space can be adjusted to suit design requirements.

References

The following documents are each associated to the Z8051 MCU, and are available free for download from the Zilog website. • Z51F3220 Product Specification (PS0299) • Z51F3220 Development Kit User Manual (UM0243) • Z8051 Tools Product User Guide (PUG0033)

AN036501-1013 Page 14 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Appendix A. Flowcharts

Figure 7 shows the flow of the routine for initializing virtual EEPROM memory.

Figure 7. Virtual EEPROM Initialization

AN036501-1013 Page 15 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 8 shows the flow of the routine for reading a data byte from a virtual EEPROM address.

Figure 8. Reading from the Virtual EEPROM

AN036501-1013 Page 16 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Figure 9 shows the flow of the routine for writing a data byte to a virtual EEPROM address.

Figure 9. Writing to the Virtual EEPROM

AN036501-1013 Page 17 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Appendix B. EEPROM Emulation APIs

Table 1 describes the APIs used in this application.

Table 1. EEPROM Emulation APIs

Function Description Parameter Returns Usage FLASH_Write Writes a byte to a unsigned void FLASH_Write(0xAA, 0x7FFF); specific Flash char location. unsigned int FLASH_SectorErase Erases a specific unsigned int void FLASH_SectorErase(13); sector in Flash. FLASH_ByteErase Erases a specific unsigned int void FLASH_ByteErase(0x7FFF); Flash memory location. FLASH_Read Reads data from a unsigned int unsigned Data = FLASH_Read(0x1000); specific Flash char memory location. EEPROM_Initialize Initializes the void unsigned Result = EEPROM_Initialize( ); emulated EEPROM char EEPROM_ReadDataByte Reads data from the unsigned int unsigned Data = EEPROM_ emulated EEPROM. int ReadDataByte(0x1000); EEPROM_WriteDataByte Writes data to the unsigned int unsigned Result = EEPROM_ emulated EEPROM. unsigned int WriteDataByte(0x1000,0xAA); char

AN036501-1013 Page 18 of 19 EEPROM Emulation on the Z51F3220 MCU Application Note

Customer Support

To share comments, get your technical questions answered, or report issues you may be experiencing with our products, please visit Zilog’s Technical Support page at  http://support.zilog.com. To learn more about this product, find additional documentation, or to discover other fac- ets about Zilog product offerings, please visit the Zilog Knowledge Base at http:// zilog.com/kb or consider participating in the Zilog Forum at http://zilog.com/forum. This publication is subject to replacement by a later edition. To determine whether a later edition exists, please visit the Zilog website at http://www.zilog.com.

Warning: DO NOT USE THIS PRODUCT IN LIFE SUPPORT SYSTEMS.

LIFE SUPPORT POLICY ZILOG’S PRODUCTS ARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN LIFE SUPPORT DEVICES OR SYSTEMS WITHOUT THE EXPRESS PRIOR WRITTEN APPROVAL OF THE PRESIDENT AND GENERAL COUNSEL OF ZILOG CORPORATION.

As used herein Life support devices or systems are devices which (a) are intended for surgical implant into the body, or (b) support or sustain life and whose failure to perform when properly used in accordance with instructions for use provided in the labeling can be reasonably expected to result in a significant injury to the user. A critical component is any component in a life support device or system whose failure to perform can be reasonably expected to cause the failure of the life support device or system or to affect its safety or effectiveness.

Document Disclaimer ©2013 Zilog, Inc. All rights reserved. Information in this publication concerning the devices, applications, or technology described is intended to suggest possible uses and may be superseded. ZILOG, INC. DOES NOT ASSUME LIABILITY FOR OR PROVIDE A REPRESENTATION OF ACCURACY OF THE INFORMATION, DEVICES, OR TECHNOLOGY DESCRIBED IN THIS DOCUMENT. ZILOG ALSO DOES NOT ASSUME LIABILITY FOR INTELLECTUAL PROPERTY INFRINGEMENT RELATED IN ANY MANNER TO USE OF INFORMATION, DEVICES, OR TECHNOLOGY DESCRIBED HEREIN OR OTHERWISE. The information contained within this document has been verified according to the general principles of electrical and mechanical engineering. Z8051 is a trademark or registered trademark of Zilog, Inc. All other product or service names are the property of their respective owners.

AN036501-1013 Page 19 of 19