using microchip i2c eeproms with mplab x and mplab code
TRANSCRIPT
AN3318Using Microchip I2C EEPROMs with MPLAB® X and
MPLAB® Code Configurator
INTRODUCTION
Most embedded control systems require nonvolatilememory and serial EEPROMs are a popular choice fornonvolatile storage due to their flexibility, low pin count,power consumption and cost. Microchip Technologyoffers a full line of serial EEPROMs covering industrystandard serial communication protocols from two-wire(I2C) to single-wire and UNI/O®, three-wire (Microwire)and SPI. Serial EEPROM devices are available in avariety of densities, operational voltage ranges andpackaging options.
Many times, when designing an application whichutilizes a serial EEPROM device, it may be beneficial touse a microcontroller which does not feature adedicated protocol-specific serial port, due to severalpossible reasons, including size restrictions or costs. Inthese instances, it is required of the designer to writesoftware routines capable of generating the propersignals for communicating with the EEPROM device.Other times, the microcontroller in use has a dedicatedprotocol-specific peripheral, but even in this case theperipheral must be properly configured and somesoftware routines must be implemented.
THE I2C PROTOCOL
The Inter-Integrated Circuit (I2C) bus is a widely usedindustry standard bus used in the transfer of databetween integrated circuits, such as between serialEEPROMS and microcontrollers. Devices communi-cate in a master/slave environment in which the masteralways initiates the communication and the slavedevice is controlled through addressing. For a broaderoverview of the I2C protocol, see Appendix B: “I2COverview” at the end of this document.
I2C EEPROMSTo correctly use and deploy I2C EEPROMs in a robustproject, understanding the following topics is recom-mended:
• Chip Address Inputs
• Write-Protect Feature
• Power Supply
• Checking for Acknowledge
• Acknowledge Polling
• Bus Pull-up Resistors
If you are not already familiar with these topics, refer toAppendix D: “EEPROM Characteristics” thatexplains how they impact your project.
MICROCHIP EEPROMS
Memory products are at the heart of electronic devicesand systems we use every day. Virtually all consumerelectronics, communication, computing, automotiveand medical devices require certain types of memory tostore software code, data and parametric data. To learnmore about Microchip quality standards in EEPROMmemories, see Appendix C: “Microchip EEPROMs”at the end of this document.
MPLAB® CODE CONFIGURATOR
The MPLAB® Code Configurator (MCC) is a free,graphical programming environment that generatesseamless, easy-to-understand C code that can easilybe integrated into a project. Using an intuitive interface,it enables and configures a rich set of peripherals andfunctions specific to the user’s application. It supportsAVR microcontrollers and 8-bit, 16-bit and 32-bit PIC®
microcontrollers. MCC is incorporated into both thedownloadable MPLAB® X IDE and the cloud-basedMPLAB® Xpress IDE.
This application note intends to demonstrate how tointerface I2C EEPROM devices using MPLAB X 5.05 orlater, the XC series of compilers and the MPLAB CodeConfigurator plugin for the MPLAB X IDE. TheMicrochip Explorer 8 and Explorer16/32 DevelopmentBoards are used as the hardware developmentplatforms. The choice of platform or MCU target is notmeant as definite requirement; however, its adoptionwill lead to a faster time to the completion of the project,using tested and verified code that can fit most applica-tions.
Author: Dragos CiofuMicrochip Technology Inc.
2019 Microchip Technology Inc. DS00003318A-page 1
AN3318
This application note is intended to be a reference forcommunicating with Microchip’s I2C serial EEPROMdevices using most of the PIC microcontrollers, inconjunction with MCC, without the need of extensiveknowledge in software writing, peripheral programmingor firmware in general. Almost everything related to thetopic can be accomplished due to the capabilities of theMPLAB Code Configurator plugin.
MCC OVERVIEW
When starting a new project using PIC16, PIC24 orPIC32 microcontrollers, setup of the configuration andall the peripherals can be time consuming, especiallyfor new projects. The MPLAB Code Configurator is aplugin for MPLAB X IDE that simplifies this down to aseries of simple selections from the menus within theMCC. The MCC generates driver code using a Graph-ical User Interface (GUI). The generated drivers controlthe peripherals on PIC microcontrollers. The GUI pro-vides an easy means for setting up the configuration ofthe peripherals.
Additionally, the MCC is used to configure and gener-ate libraries, which allows the user to configure andgenerate code for software libraries and off-chipperipherals. The generated drivers or libraries can beused in any PIC device application program.
The MCC requires an MPLAB X IDE project to be cre-ated or an existing project to be opened before launch-ing the MCC plugin. This is required as MCC needs toknow the device used in the project to have access todevice-specific information like: registers, bits and con-figurations and to set up the MCC GUI.
The MCC generates source and header files based onselections made in the GUI. The generated files areadded to the active project of MPLAB X IDE.
Prerequisites and Installation of the MCC Plugin
Consult the “MPLAB® Code Configurator User’sGuide” (DS40001725) for installation instructions, pre-requisites and getting familiar with the User Interface.
To automatically install the MPLAB Code ConfiguratorPlugin, consider the steps below:
1. In the MPLAB X IDE, select Plugins from theTools menu
2. Select the Available Plugins tab
3. Check the box for the MPLAB Code Configura-tor v3, and click on Install
To manually install the latest available plugin:
1. Access the address https://www.micro-chip.com/mplab/mplab-code-configurator andclick on the Current Download tab, then down-load the.zip file that contains a .nbm file.
2. In the MPLAB X IDE, select Plugins from theTools menu
3. Click on the Downloaded tab, then on AddPlugins and browse to a location where the .zipfile has been extracted, then select the .nbm file
4. Click Install, which will lead you through the restof the procedure
CONFIGURING YOUR PROJECT
Create a new MPLAB X IDE project or open an existingproject. Steps are shown below for creating a projectfor the PIC16F1719 device.
FIGURE 1: CREATE A PROJECT
Create a normal stand-alone project.
Select the target device. The MPLAB Code Configura-tor will only load the supported libraries matching thetarget device. Internally, the MCC plugin has access toevery resource that a particular target has, from pins,system peripherals such as clock and integratedperipherals like MSSP, I2C, UART, etc. Refer to eachtarget’s data sheet to see what capabilities areenabled. In this particular example the PIC16F1719has an MSSP peripheral that can be configured to com-municate on the I2C bus specification.
Choose an available debugger, for example PICkit™,an In-Circuit Debugger (ICD) or run the project inSimulator mode.
Having the latest compiler installed ensures the mostoptimized output for your code if you are looking forsize or speed.
Name the project and finish the process.
2019 Microchip Technology Inc. DS00003318A-page 2
AN3318
FIGURE 2: PROJECT STRUCTURE
This creates an empty project that contains no files.Clicking the blue MCC icon in the toolbar will launch theMCC plugin within MPLAB X IDE.
SELECTING A PERIPHERAL OR RESOURCE
The MCC Graphical User Interface (GUI) is comprisedof multiple panels, out of which the focus is brought tothe Project Resources and Device Resources panels.
The Device Resources panel lists all the availableresources for the selected target. Historically, this panelmainly contained the target microcontroller’s peripher-als, but has evolved to accommodate other usefulresources. Users can take advantage of documenta-tion, libraries for various stack implementations such asCAN and LIN, compatible external products like theMikro-E line of Click boards™ and, as required for thisapplication note, Memory Products with I2C EEPROM.
FIGURE 3: MCC RESOURCES
When selecting and double-clicking a peripheral, forinstance, an ADC, the selected resources will pop outof the Device Resources panel and into the ProjectResources panel. This means that the respectiveperipheral has been selected and prepared for config-uration and later code generation.
If selecting one of the newer resources, like I2CEEPROM in this case, the MCC plugin will automati-cally load the required compatible peripheral (in thiscase MSSP) into the Project Resources panel.
In other cases, for other types of libraries, manualselection of the peripheral to be used may be neces-sary.
FIGURE 4: LOADING A LIBRARY
The figure above shows that MSSP has been loadedalongside with the I2C EEPROM library.
FIGURE 5: EEPROM LIBRARY GUI
2019 Microchip Technology Inc. DS00003318A-page 3
AN3318
When a resource is selected from the ProjectResources panel, the Graphical User Interface corre-sponding to that resource will be rendered within themain display area of the MCC window. In this case,after loading and selecting the I2C EEPROM, the userhas access to three tabs: Information, Configurationand Advanced Settings.
CHOOSING AND CONFIGURING AN EEPROM
The Configuration tab contains four drop-down/edit-able controls:
1. Select Device
2. Filter by Density
3. Select Address Bits
4. Select Buffer Size (bytes)
FIGURE 6: EEPROM CONFIGURATION TAB
The user can directly select an EEPROM device fromthe drop-down list. Alternatively, a filter by density canbe applied and the available device list will narrowaccordingly.
The options for the Address bits drop-down list willadjust as well to the device selection and the availablephysical address pins on the device.
The GUI provides a check box for generating an exam-ple. This code example can be ported directly into themain file to quickly test the functionality of the device inreal bench top conditions.
FIGURE 7: EEPROM ADVANCED SETTINGS TAB
The Advanced Settings tab allows for simple configu-ration of the I2C bus speed, and the changes appliedhere will manifest in the automatic altering of the MSSPregisters to the correct values. This process is trans-parent to the user, which makes it far easier to use thanmanually configuring the registers.
CODE GENERATION
After all changes have been made and the user is sat-isfied with the selected configuration, by clicking theGenerate button in the Project Resources panel, MCCwill generate all the required files, both headers and .cfiles.
FIGURE 8: CORE GENERATION REPORT
A report will be generated in the Output section, usuallyon the bottom of the interface. The user will beprompted to save the current MCC configuration into a.m3c file within the project folder, that can be sharedbetween projects or machines for easier portability.
2019 Microchip Technology Inc. DS00003318A-page 4
AN3318
FIGURE 9: PROJECT STRUCTURE AFTER MCC CODE GENERATION
After all of the steps above have been taken, the usercan close the MCC plugin by clicking on the blue MCCicon and can return to the classic project view inMPLAB X.
The project structure can be consulted, and one canobserve the presence of several header and sourcefiles grouped under the “MCC Generated Files” nodes.
At this point the project can be successfully built.
MCC PROVIDED LAYERS
MCC provides a two-layer implementation to I2C usingMSSP. A third layer is visible to the user and is gener-ated by the EEPROM library that was loaded before.For the final user, a final API layer is exposed throughthe EEPROM_driver.* files. In this stack-up, the imple-mentation is comprised of:
• The bottom layer is the driver layer that consists of the i2c_driver.c file and dependences. This layer operates on the register level and manipu-lates the MSSP peripheral so that is behaves in accordance to the I2C bus specification.
• The middle layer is the logical layer, consisting of the i2c_master.c source file and dependences. This is where a finite state machine operates on an Interrupt Service Routine (ISR).
• This ISR iterates through the state machine and calls the bottom layer whenever register-level operations are required (i.e., setting buffers, alter-ing flags).
• The upper layer is the user-accessible layer that uses the middle layer for logical operations, directly calling exposed methods. This ensures consistency when propagating calls to the driver layer, as the code becomes very deterministic.
• The user is exposed to an API-like layer, that through the EEPROM_driver.* files provides prototypes for single-function call operations.
USING THE GENERATED CODE
If the code generation was successful and the checkbox for generating an example was enabled, theexample main function would have also beengenerated. Its purpose is to showcase the correctusage of a several generated functions.
FIGURE 10: GENERATED MAIN FILE
FIGURE 11: GENERATED EXAMPLE FILE
2019 Microchip Technology Inc. DS00003318A-page 5
AN3318
The EEPROM_example() function can be directlycalled from the main loop, and contains the followingbasic function calls:
• Byte read
• Sequential write
• Page write
• Current address read
• Sequential (or random address) read
Documentation for these functions can be obtained byconsulting the generated documentation or the functionprototypes in the corresponding header.
FUNCTION USAGE
The example that was generated (shown in the previ-ous section) contains the basic functions that anEEPROM can be used with. Going further, here is howone can employ these functions and how they work.
Byte Read
The most basic function provided by the generated APIis the Byte Read function:
Since the function call will only return one byte, thereturn is not done via reference, but rather by value. SodataByte will store the result of the function call. The0x0010 parameter represents the address within thearray at which the read is executed. There is no needfor manipulating the control byte at the protocol level,as this is handled in lower layers of the API.
FIGURE 12: BYTE READ
Here is the oscilloscope plot of the Byte Read function.Notice the control byte that has been generated by theMCC code and the 0x0010 address byte filled in by theuser.
Sequential Write
The Sequential Write function deploys the continuouswrite mechanism, where after sending the control byteand the address to be written, the master clocks inmore than one byte of data:
The first parameter is the address to be written at, thesecond parameter is a buffer containing the bytes to bewritten and the last parameter is the number of bytes tobe written. In this case, the return value is not validated,but when taking a look at the call tree one can observethat a return value is indeed passed upwards to thecaller, for further use.
The example code declares an array of unsigned chars- dataBuffer - and defines it as several actual bytevalues (0x55, 0xFF, etc.).
FIGURE 13: MULTIPLE BYTE WRITE
The oscilloscope plot and the serial decode show thecontrol byte, the address and the four bytes that havebeen sent over.
Page Write
The Page Write function is similar to the sequentialwrite function, with the difference being that it onlywrites a number of bytes equal to the target device’spage size. This parameter is stored as a #define inthe header files and is automatically generated by theMCC after selecting a device.
dataByte = EEPROM_ReadOneByte (0x0010);
Note: An in-depth analysis of the call tree can befound in Appendix E: “Underlying CodeAnalysis”. There one can find how theMCC provided layers that were mentionedabove work, and can prove useful inunderstanding the API as a whole.
EEPROM_SequentialWrite (0x0020, dataBuffer, 4)
EEPROM_PageWrite (0x0020, dataBuffer);
2019 Microchip Technology Inc. DS00003318A-page 6
AN3318
FIGURE 14: PAGE WRITE
The condensed oscilloscope plot shows 8 bytes of databeing written, corresponding to a page size of 8 of asmaller 24AA01 device. If the page size were larger butthe dataBuffer variable contained only 8 bytes, thecode would continue to send out “garbage” valueswhose addresses are contiguous with the boundary ofthe buffer variable.
Sequential Read (Random Address Read)
A random read is performed at a given address. Theword “random” signifies that the user is not relying onthe previous read pointer value when executing theread, but rather a new address is provided to theEEPROM. In this case, the function reads 8 bytes ofdata starting from address 0x0020 and stores them inthe dataBuffer unsigned char array.
FIGURE 15: SEQUENTIAL READ
The oscilloscope plot shows the two control bytesbeing sent, one for writing the address and another onefor switching the direction of the data on the bus,followed by the 8 bytes of data required.
COMPARING MCC WITH STANDARD MSSP PERIPHERAL HANDLING
Mid-range Microchip PIC microcontrollers, like thePIC16, might have a generic MSSP peripheral that canbe used to implement various serial protocols includingthe I2C specification, while PIC24 devices (and PIC32devices) have dedicated I2C peripherals and they donot rely on a MSSP peripheral for serial communica-tions.
USING MSSP AS I2C ON A PIC16 WITHOUT MCC
Several of the Mid-Range Enhanced Core PIC16microcontroller devices have a Master SynchronousSerial Port (MSSP). The MSSP module can be used toimplement either the I2C or the SPI communicationsprotocol. The following is an overview of the registersinvolved in the configuration of MSSP to function as anI2C peripheral and is meant to showcase the breadthand complexity of bit-level manipulation required forcorrect use. For more information, see AN735 – “Usingthe PICmicro MSSP Module for I2C Communications”(DS00735).
MSSP Registers and Functionality
Some key Special Function Registers (SFRs) utilizedby the MSSP module are:
• SSP Control Register 1 (SSPCON1)
• SSP Control Register 2 (SSPCON2)
• SSP STATUS Register (SSPSTAT)
• Pin Direction Control Register (TRISC)
• Serial Receive/Transmit Buffer (SSPBUF)
• SSP Shift Register (SSPSR) - Not directly acces-sible
• SSP Address Register (SSPADD)
• SSP Hardware Event Status (PIR1)
• SSP Interrupt Enable (PIE1)
• SSP Bus Collision Status (PIR2)
• SSP Bus Collision Interrupt Enable (PIE2)
To configure the MSSP module for Master I2C mode,key SFR registers must be initialized in order to config-ure the MSSP module for Master I2C mode.
• SSP Control Register 1 (SSPCON1)
- I2C Mode Configuration
• SSP Address Register (SSPADD)
- I2C Bit Rate
• SSP STATUS Register (SSPSTAT)
- Slew Rate Control
- Input Pin Threshold Levels
• Pin Direction Control (TRISC)
- SCL/SDA Direction
EEPROM_SequentialRead( 0x0020, dataBuffer, 8);
2019 Microchip Technology Inc. DS00003318A-page 7
AN3318
Once the basic functionality of the MSSP module isconfigured for Master I2C mode, the remaining stepsrelate to the implementation and control of I2C events.The master can initiate any of the following I2C busevents:
• Start
• Restart
• Stop
• Read (Receive)
• Acknowledge (after a read)
- Acknowledge
- Not Acknowledge (NACK)
• Write
The first four events are initiated by asserting high theappropriate control bit in the SSPCON2 register. TheAcknowledge bit event consists of first setting theAcknowledge state, ACKDT (SSPCON2) and thenasserting high the event control bit, ACKEN(SSPCON2).
Data transfer with Acknowledge is obligatory. TheAcknowledge-related clock is generated by the master.The transmitter releases the SDA line (HIGH) duringthe Acknowledge clock pulse. The receiver must pulldown the SDA line during the Acknowledge clock pulseso that it remains stable LOW during the HIGH periodof this clock pulse.
When the slave does not acknowledge the masterduring this Acknowledge clock pulse (for any reason),the data line must be left HIGH by the slave. Thissequence is termed “Not Acknowledge” or “NACK”.
For actual data to be transferred, the SSPBUF registermust be written with the control byte and the data to besent. Once the SSPBUF is loaded with data, the MSSPperipheral will clock out the data at the configured rate.
Pin Assignment
Another aspect involved in the functioning of MSSP asI2C (or any type of supported bus) is the correct pinassignment. After the MSSP configuration has beenset, the data sheet must be consulted in order to deter-mine the correct I/O pins that map to the MSSP periph-eral.
Depending on the peripheral configuration of the PICdevice in use (i.e., number of MSSP peripherals), themost common ports used are RC3 and RC4. Theseneed to be configured as well by setting the correctdata direction according to the role the MSSP plays inthe I2C implementation (master or slave).
2019 Microchip Technology Inc. DS00003318A-page 8
AN3318
Byte Write Routine as Master
The main takeaway of the example with PIC16 is thateven the simplest bit level implementation of theperipheral requires a certain expertise with using theactual MSSP peripheral. Certain bits and flags must beprecisely manipulated for correct operation, which canbe time consuming.
The advantage of this approach is that developinglow-level code leads to a better understanding of thedevice in use and makes debugging easier and moredeterministic. The disadvantage is the amount of timespent in order to get a coherent and working example.
CONCLUSION
When deciding between a bare-bones versus a com-plete implementation, MCC helps with providing the lat-ter. By using MCC instantiated code, a predictable anddeterministic implementation can be achieved.
Microchip Technology is continuously addingsupported device libraries and is improving the capabil-ities of MCC to serve both prototyping and indus-trial-grade code generation. Its ease of use is matchedwith consistent code, that can be deployed in real-life
applications. The generated code is documented andvisible, and other implementations can be easilyderived from it to fit every need. For a robust implemen-tation in embedded systems and peripherals, theMPLAB Code Configurator is a great starting point.
REFERENCES
1. AN 734 – “Using the Mid-Range Enhanced CorePIC16 Devices’ MSSP Module for Slave I2CCommunication” (DS00000734)
2. AN735 – “Using the PICmicro MSSP Module forI2C Communications” (DS00735)
3. AN 2045 – “Interfacing Serial EEPROMs with8-Bit PIC® Microcontrollers” (DS00002045)
4. AN1028 – “Recommended Usage of MicrochipI2C Serial EEPROM Devices” (DS01028)
5. “1024K I2C Serial EEPROM” Data Sheet(DS20001941)
6. “Inter-Integrated Circuit (I2C)” ReferenceManual (DS70000195)
void wait(){while ((SSPSTAT & 0x04) || (SSPCON2 & 0x1F));return ;
}
void main(void){
SSPCON = 0X28 ;// I2C Master, enable SCL and SDA
SSPCON2 = 0 ;//
SSPADD = 99 ;// calculated using FOSC/(4*speed)–1 where speed is 10000
SSPSTAT = 0 ;
TRISC = 0x18 ;// using RC3 (SCL) and RC4 (SDA)
char data = 0 ;
while(1)
{
wait() ;
SEN = 1 ;// I2C start
wait() ;
SSPBUF = 0x30 ;// control byte (7-bit address + r/nw bit)
wait() ;
SSPBUF = 0x30 ;// send and increment data char
wait() ;
PEN = 1 ;// I2C stop
_delay_ms(100) ;
}
}
2019 Microchip Technology Inc. DS00003318A-page 9
AN3318
APPENDIX A: REVISION HISTORY
Revision A (December 2019)
Initial release of this document.
2019 Microchip Technology Inc. DS00003318A-page 10
AN3318
APPENDIX B: I2C OVERVIEW
An I2C bus can have one or more master devices andone or more slave devices. The master device is thedevice that initiates a data transfer on the bus and isresponsible for generating the serial clock used on thebus. Any addressed device is then considered a slave.Data transfers are performed eight bits at a time, start-ing with the Most Significant bit (MSb). Each device isrecognized by a unique address and can operate aseither a transmitter or receiver.
The physical interface of the bus consists of two bidi-rectional open-drain lines, one line used for the serialclock (SCL) and the other used for serial data (SDA).Each line will require a pull-up resistor to supply voltageto the lines. Pulling the line to ground is considered alogical Low, while letting the line float high is consid-ered a logical High. When the bus is free, both SDA andSCL are logical High.
Data can be transferred at a rate up to 100 Kbits/s inthe Standard mode, up to 400 Kbits/s in Fast mode, upto 1 Mbits/s in Fast mode Plus or up to 3.4 Mbits/s inHigh-Speed mode. Data on the SDA line must be stableduring the high period of the clock. Any changes on theSDA line can only occur when the clock signal on theSCL line is low. One clock pulse is generated for eachtransferred data bit.
The I2C specification defines a Start condition as atransition of the SDA line from a high-to-low state, whilethe SCL line is high. A Start condition is always gener-ated by the master and signifies the transition of thebus from an Idle to an Active state. The I2C specifica-tion states that no bus collision can occur on a Start.
A Stop condition is a transition of the SDA line fromlow-to-high state while the SCL line is high. At least oneSCL low time must appear before a Stop is valid. ARestart, or Repeated Start, is valid any time that a Stopwould be valid. A master can issue a Restart if it wishesto hold the bus after terminating the current transfer. ARestart has the same effect on the slave that a Startwould, resetting all slave logic and preparing it to clockin an address. The master may want to address thesame or another slave. This can be useful for many I2Cperipherals, such as nonvolatile EEPROM memory, inwhich an I2C write operation and a read operation aredone in succession. In this case, the write operationspecifies the address to be read and the read operationgets the byte of data. Since the master device does notrelease the bus after the memory address is written tothe device, a Restart sequence is performed to readthe contents of the memory address.
The ninth SCL pulse for any transferred byte in I2C isdedicated as an Acknowledge (ACK). It allowsreceiving devices to respond back to the transmitter bypulling the SDA line low. The transmitter must releasecontrol of the line during this time to shift in theresponse. The ACK is an active-low signal, pulling theSDA line low, indicating to the transmitter that thedevice has received the transmitted data and is readyto receive more.
2019 Microchip Technology Inc. DS00003318A-page 11
AN3318
APPENDIX C: MICROCHIP EEPROMS
Microchip offers the broadest range of Serial EEPROMdevices. Our Serial EEPROMs are low-power,nonvolatile memory devices with wide operatingranges, small-size and byte-alterability, making themideal for data and program storage. Serial EEPROMscan be written more than one million times and retaindata for over 200 years. Innovative low-power designsand extensive testing have ensured industry-leadingendurance and best-in-class quality.
Microchip’s best-in-class field performance is the com-bined result of world-class manufacturing, wafer-levelburn-in and wafer probe quality screens. Microchip’sTriple-Test Flow is currently the most robust testing pro-cedure for Serial EEPROM devices in the industry. Ittests each cell of each die three times and performsextensive endurance and data retention tests to ensurequality and reliability. Infant mortality of MicrochipSerial EEPROMs is among the lowest in the industrydue to this extensive testing, excellent fabrication andhighly-reliable memory cell design.
2019 Microchip Technology Inc. DS00003318A-page 12
AN3318
APPENDIX D: EEPROM CHARACTERISTICS
Chip Address Inputs
The Chip Address input pins (A0, A1 and A2 or combi-nations) are used on several devices to support multi-ple device operation. On devices with this feature, thelevels on these inputs are compared with the corre-sponding bits in the slave address, and the device isselected if the comparison is true. Note that the ChipAddress pins are not internally connected on somedevices. Refer to the appropriate device data sheet formore details. For devices with internally connectedChip Address pins, these inputs must be hard-wired toeither logic ‘0’ or logic ‘1’. That is, they cannot be leftfloating, otherwise the device will not operate correctly.
Write-Protect Feature
For devices with write-protect functionality, the WP pinprovides a hardware write-protect feature which allowsthe user to protect the entire array when the pin is tiedto VCC. If tied to VSS, the write protection is disabled. Apull-up resistor connected to the WP pin can be used toensure the device remains write-protected duringpower-up/power-down and any other time the pin is notbeing driven explicitly. This helps to guard againstunwanted writes which may occur due to noise on theSDA/SCL lines or for other reasons. For a write cycle tobe initiated, the WP pin must be driven to logic ‘0’, oth-erwise the write cycle will not execute. If the designerchooses not to control the WP pin, but rather to alwaysdisable write protection, the pin must be hard-wired tologic ‘0’. As with the Chip Address inputs, this pin can-not be left floating, otherwise the device will not operatecorrectly. Note that some devices do not supportwrite-protect functionality.
Power Supply
Microchip serial EEPROMs feature a high amount ofprotection from unintentional writes and data corruptionwhile power is within normal operating levels. But cer-tain considerations should be made regardingpower-up and power-down conditions to ensure thesame level of protection during those times whenpower is not within normal operating levels. A decou-pling capacitor (typically 0.1 µF) should be used to helpfilter out small ripples on VCC.
Checking for Acknowledge
One of the many benefits of I2C communication is theAcknowledge bit transmitted after every byte isreceived. Except during write cycles, Microchip serialEEPROMs will always transmit this bit low after receiv-ing each byte, assuming a valid Start bit and controlbyte were already received.
Due to this, the master can monitor the ACK bitreceived throughout an operation to detect any errorsthat may occur. It is always good practice to check if alogic ‘1’ is received for the ACK during transmission,which would indicate that the EEPROM did notrespond. At that point, an error-handling routine wouldbe required to determine why the device did notrespond and, if necessary, to perform a software Resetsequence
Acknowledge Polling
Write operations on serial EEPROMs require that awrite cycle time be observed after initiating the write,allowing the device time to store the data. During thistime, normal device operation is disabled, and anyattempts by the master to access the device will beignored. Therefore, it is important that the master waitfor the write cycle to end before attempting to accessthe EEPROM again. Each device has a specifiedworst-case write cycle time, typically listed as TWC. Asimple method for ensuring that the write cycle time isobserved is to perform a delay for the amount of timespecified before accessing the EEPROM again. How-ever, it is not uncommon for a device to complete awrite cycle in less than the maximum specified time. Assuch, using the previously shown delay method resultsin a period of time in which the EEPROM has finishedwriting, but the master is still waiting. To eliminate thisextra period of time, and therefore operate more effi-ciently, it is highly recommended to take advantage ofthe Acknowledge Polling feature. Since Microchip’s I2Cserial EEPROM devices will not acknowledge during awrite cycle, the device can continuously be polled untilan ACK bit is received, thus indicating that the write iscomplete. This is done after the Stop condition takesplace to initiate the internal write cycle of the device.
Bus Pull-Up Resistors
For proper operation, pull-up resistors are required forboth SCL and SDA buses. However, the resistor valuechosen can have a vast impact on the performance ofthe system.
Specifically, three limiting actors must be consideredwhen selecting pull-up resistor (RP)
• Supply Voltage (VCC)
• Total Bus Capacitance (CBUS)
• Total High-Level Input Current (IIH)
For an in-depth computation of these factors, consultAN1028 – “Recommended Usage of Microchip I2CSerial EEPROM Devices” (DS01028). Most applica-tions will require the pull-up resistor value to be2.2 kOhm but this may vary depending on require-ments.
2019 Microchip Technology Inc. DS00003318A-page 13
AN3318
APPENDIX E: UNDERLYING CODE ANALYSIS
This annex helps the reader understand both the func-tionality of the generated code and the complexity of arobust I2C implementation.
The entry point for analyzing the code will be the ByteRead function.
The function implementation is:
The first important call is:
This function operates on a structure that maps a num-ber of flags and data pointers specific to the I2C imple-mentation on the MSSP peripheral.
Software License Agreement
The software supplied herewith by Microchip Technology Incorporated (the “Company”) is intended and supplied to you, theCompany’s customer, for use solely and exclusively with products manufactured by the Company.The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights are reserved.Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under applicable laws, as well as to civilliability for the breach of the terms and conditions of this license.THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATU-TORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICU-LAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FORSPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
EEPROM_ReadOneByte ; (0x0010);
uint8_t EEPROM_ReadOneByte(uint32_t address){uint8_t data ;
while (!I2C_open(EEPROM_DEVICE_ADDRESS)) ; //sit here until we get the bus...
I2C_setDataCompleteCallback(readOneByteHandler & data) ;
I2C_setBuffer(& address,2) ;
I2C_setAddressNACKCallback(I2C_restart_write,NULL) ; //NACK polling
I2C_masterWrite() ;
while (I2C_BUSY==I2C_close()) ; //sit here until finished
return data ;
}
I2C_open(EEPROM_DEVICE_ADDRESS)
2019 Microchip Technology Inc. DS00003318A-page 14
AN3318
This type definition resides in the I2C_master.c filewhich is generated by MCC.
The I2C_open() function resets the flags and sets thedevice address within this structure. It also callsI2C_driver_open(). This is also the point where thecode eventually reaches the register level:
Going upwards to the user-available API, theEEPROM_ReadOneByte() function, after the call toI2C_open() one can observe the assignment of a datacomplete callback by sending a function pointer as aparameter:
typedef struct{unsigned busy:1 ;
unsigned inUse:1 ;
unsigned bufferFree:1 ;
unsigned addressNACKCheck:1 ;
I2C_address_t address ; /// The I2C Address
uint8_t *data_ptr ; /// pointer to a data buffer
size_t data_length ; /// Bytes in the data buffer
uint16_t time_out ; /// I2C Timeout Counter between I2C events
uint16_t time_out_value ; /// Reload value for the timeouts
I2C_fsm_states_t state ; /// Driver State
I2C_error_t error
I2C_callback callbackTable[6] ;
void *callbackPayload[6] ; /// each callback can have a payload
} I2C_status_t ;
_bit I2C_driver_open(void)
if(!SSP1CON1bits.SSPEN){SSP1STAT = 0x00 ;
SSP1CON1 = 0x28 ;
SSP1CON2 = 0x00 ;
SSP1ADD = 0x3 ;
return true ;
}
else
return false ;
}
I2C_setDataCompleteCallback(readOneByteHandler & data);
2019 Microchip Technology Inc. DS00003318A-page 15
AN3318
The readOneByteHandler function is already imple-mented, and basically maps a pointer to the I2Cspecific (I2C_status) structure’s data pointer.
After the callback has been registered and thus thepointer remapped, the EEPROM_ReadOneByte()function calls:
In case the slave device (EEPROM) does not acknowl-edge, a restart write is callback is registered through
The next call is I2C_masterWrite(); which in term altersthe I2C_status structure by setting a write flag. Basedon these flags, the code eventually iterates through afinite state machine that correctly operates the MSSPperipheral.
I2C_setBuffer(&address,2) ;
I2C_setAddressNACKCallback(I2C_restart_write,NULL); //NACK polling
2019 Microchip Technology Inc. DS00003318A-page 16
AN3318
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights unless otherwise stated.
2019 Microchip Technology Inc.
For information regarding Microchip’s Quality Management Systems, please visit www.microchip.com/quality.
TrademarksThe Microchip name and logo, the Microchip logo, Adaptec, AnyRate, AVR, AVR logo, AVR Freaks, BesTime, BitCloud, chipKIT, chipKIT logo, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, HELDO, IGLOO, JukeBlox, KeeLoq, Kleer, LANCheck, LinkMD, maXStylus, maXTouch, MediaLB, megaAVR, Microsemi, Microsemi logo, MOST, MOST logo, MPLAB, OptoLyzer, PackeTime, PIC, picoPower, PICSTART, PIC32 logo, PolarFire, Prochip Designer, QTouch, SAM-BA, SenGenuity, SpyNIC, SST, SST Logo, SuperFlash, Symmetricom, SyncServer, Tachyon, TempTrackr, TimeSource, tinyAVR, UNI/O, Vectron, and XMEGA are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
APT, ClockWorks, The Embedded Control Solutions Company, EtherSynch, FlashTec, Hyper Speed Control, HyperLight Load, IntelliMOS, Libero, motorBench, mTouch, Powermite 3, Precision Edge, ProASIC, ProASIC Plus, ProASIC Plus logo, Quiet-Wire, SmartFusion, SyncWorld, Temux, TimeCesium, TimeHub, TimePictra, TimeProvider, Vite, WinPath, and ZL are registered trademarks of Microchip Technology Incorporated in the U.S.A.
Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BlueSky, BodyCom, CodeGuard, CryptoAuthentication, CryptoAutomotive, CryptoCompanion, CryptoController, dsPICDEM, dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial Programming, ICSP, INICnet, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, memBrain, Mindi, MiWi, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PowerSmart, PureSilicon, QMatrix, REAL ICE, Ripple Blocker, SAM-ICE, Serial Quad I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, Total Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.The Adaptec logo, Frequency on Demand, Silicon Storage Technology, and Symmcom are registered trademarks of Microchip Technology Inc. in other countries.GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries. All other trademarks mentioned herein are property of their respective companies.
© 2019, Microchip Technology Incorporated, All Rights Reserved.
ISBN: 978-1-5224-5369-7
DS00003318A-page 17
2019 Microchip Technology Inc. DS00003318A-page 18
AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://www.micro-chip.com/supportWeb Address: www.microchip.com
AtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455
Austin, TXTel: 512-257-3370
BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088
ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075
DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924
DetroitNovi, MI Tel: 248-848-4000
Houston, TX Tel: 281-894-5983
IndianapolisNoblesville, IN Tel: 317-773-8323Fax: 317-773-5453Tel: 317-536-2380
Los AngelesMission Viejo, CA Tel: 949-462-9523Fax: 949-462-9608Tel: 951-273-7800
Raleigh, NC Tel: 919-844-7510
New York, NY Tel: 631-435-6000
San Jose, CA Tel: 408-735-9110Tel: 408-436-4270
Canada - TorontoTel: 905-695-1980 Fax: 905-695-2078
ASIA/PACIFICAustralia - SydneyTel: 61-2-9868-6733
China - BeijingTel: 86-10-8569-7000
China - ChengduTel: 86-28-8665-5511
China - ChongqingTel: 86-23-8980-9588
China - DongguanTel: 86-769-8702-9880
China - GuangzhouTel: 86-20-8755-8029
China - HangzhouTel: 86-571-8792-8115
China - Hong Kong SARTel: 852-2943-5100
China - NanjingTel: 86-25-8473-2460
China - QingdaoTel: 86-532-8502-7355
China - ShanghaiTel: 86-21-3326-8000
China - ShenyangTel: 86-24-2334-2829
China - ShenzhenTel: 86-755-8864-2200
China - SuzhouTel: 86-186-6233-1526
China - WuhanTel: 86-27-5980-5300
China - XianTel: 86-29-8833-7252
China - XiamenTel: 86-592-2388138
China - ZhuhaiTel: 86-756-3210040
ASIA/PACIFICIndia - BangaloreTel: 91-80-3090-4444
India - New DelhiTel: 91-11-4160-8631
India - PuneTel: 91-20-4121-0141
Japan - OsakaTel: 81-6-6152-7160
Japan - TokyoTel: 81-3-6880- 3770
Korea - DaeguTel: 82-53-744-4301
Korea - SeoulTel: 82-2-554-7200
Malaysia - Kuala LumpurTel: 60-3-7651-7906
Malaysia - PenangTel: 60-4-227-8870
Philippines - ManilaTel: 63-2-634-9065
SingaporeTel: 65-6334-8870
Taiwan - Hsin ChuTel: 886-3-577-8366
Taiwan - KaohsiungTel: 886-7-213-7830
Taiwan - TaipeiTel: 886-2-2508-8600
Thailand - BangkokTel: 66-2-694-1351
Vietnam - Ho Chi MinhTel: 84-28-5448-2100
EUROPEAustria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393
Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829
Finland - EspooTel: 358-9-4520-820
France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79
Germany - GarchingTel: 49-8931-9700
Germany - HaanTel: 49-2129-3766400
Germany - HeilbronnTel: 49-7131-72400
Germany - KarlsruheTel: 49-721-625370
Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44
Germany - RosenheimTel: 49-8031-354-560
Israel - Ra’anana Tel: 972-9-744-7705
Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781
Italy - PadovaTel: 39-049-7625286
Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340
Norway - TrondheimTel: 47-7288-4388
Poland - WarsawTel: 48-22-3325737
Romania - BucharestTel: 40-21-407-87-50
Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91
Sweden - GothenbergTel: 46-31-704-60-40
Sweden - StockholmTel: 46-8-5090-4654
UK - WokinghamTel: 44-118-921-5800Fax: 44-118-921-5820
Worldwide Sales and Service
05/14/19