Infineon-AN50987 Getting Started With I2C in PSoC 1-ApplicationNotes-V07 00-En
Infineon-AN50987 Getting Started With I2C in PSoC 1-ApplicationNotes-V07 00-En
AN50987 gives an overview of the I2C standard and explains how a PSoC® 1 device handles I2C communications.
After reading this application note, you should have an understanding of how I2C works, how to implement it in
PSoC 1, and how to choose the correct user module for a design. Example projects demonstrate how to configure
PSoC 1 as an I2C master/slave to communicate with other I2C devices on the bus.
Contents
Introduction ....................................................................... 2 Appendix A ...................................................................... 17
I2C Basics .......................................................................... 2 Hardware Registers.................................................... 17
The Physical Layer ....................................................... 2 Firmware Requirements ............................................. 17
The Protocol Layer ....................................................... 2 Arbitration ................................................................... 18
I2C in PSoC 1 .................................................................... 4 Appendix B ...................................................................... 20
Hardware ...................................................................... 5 EzI2Cs_ADC_LED_DAC Example Project ................. 20
I2C User Modules ......................................................... 6 I2CHW Slave Example Project ................................... 24
Firmware ........................................................................... 8 I2CHW Master Example Project ................................. 25
Slave Operation ............................................................ 8 Migrating Example Project ......................................... 26
Master Operation .......................................................... 9 Worldwide Sales and Design Support ............................. 28
Multimaster Slave Operation ...................................... 10
I2Cm ........................................................................... 11
Special I2C Considerations .............................................. 12
I2C Addressing ........................................................... 12
Pull-up Resistors ........................................................ 12
I2C and ISSP Programming Conflicts ......................... 12
Pin Glitches at Power-up ............................................ 13
Clock Speeds ............................................................. 13
Clock Stretching and Interrupt Latency ...................... 14
Hot Swapping ............................................................. 14
Glitch Filtering ............................................................ 14
I2C and Sleep ............................................................. 14
I2C and Dynamic Reconfiguration............................... 15
Dynamic Slave Addressing in I2CHW UM .................. 15
The SCL Line Gets Stuck LOW .................................. 15
Summary ......................................................................... 16
The Physical Layer The I2C bus operates at different voltage levels depending
2 2 on the individual devices themselves. To determine if two
Figure 1 shows how I C devices connect to the I C bus. devices can successfully communicate, review their
The I2C bus consists of two physical lines: serial data respective datasheets to ensure that the logic levels are
(SDA) and serial clock (SCL). All devices on the bus must compatible.
connect to these two physical lines. The only external
hardware required are pull-up resistors to VDD (high rail) The I2C specification offers a solution for bridging between
on SDA and SCL. For more information, see the Pull-up buses of different voltage levels, in the event that the
Resistors section. voltage and logic levels of two devices are not compatible.
SCL Data
After the master has sent the address and the slave has
A repeated start condition is physically identical to a start acknowledged it, data can be transferred eight bits at a
condition. It gives a signal that the master has maintained time. Both the master and the slave can transmit and
control of the bus and that the bus is not free. receive, so together they control the SDA line.
1 0 - B i t Ad d r e s s
The I2C specification also allows for 10-bit addressing; see Stop
Figure 5. To accomplish this, the master must send two After all bytes are sent, the master sends a stop condition.
address bytes to the slave. The first byte, which the slave A stop indicates that the current transaction is complete
must acknowledge, contains the sequence 11110 followed and the bus is free; see Figure 8.
by the two MSBs of the address followed by the R/W bit.
Stop = LOW to HIGH transition on SDA when SCL is
Next, the master sends the remaining eight bits of the
HIGH
address. Finally, the slave sends an ACK/NAK.
Figure 8. Stop Condition stop driving the SDA line and must wait until the bus is
free before sending data again.
Stop As Figure 10 shows, the first master that leaves SDA
HIGH while another tries to drive it LOW loses arbitration
SDA and must wait.
Ar b i t r a t i o n
The I2C protocol allows multiple masters to communicate
on the same bus. Both masters may start communicating
at the same time. To prevent loss of data, each I2C master
2
must check the I C bus to ensure that the data on the bus
matches what it intended to put on the bus. If the data
does not match, the I2C master that loses arbitration must
Figure 11. I2C Hardware Block Receiver After 8 bits of data After 8 bits of data
+ ACK/NAK
SDA_OUT SDO SDA
SDA_IN SDI
GPIO Port1[5] For more information on the functionality of the I2C
SDE
or
Port1[0]
hardware block, see Appendix A and the I2C sections of
I2CBLK the PSoC Technical Reference Manual.
I2C Bus
Hardw are Blocks in CY8C28xxx
SCL_OUT SDO
Part family CY8C28xxx offers two separate I2C hardware
SCL
SCL_IN SDI
GPIO Port1[7]
or
blocks, allowing hardware connections to more than one
I2CEN SDE Port1[1] I2C bus at a time. In addition, each block provides
hardware address matching. The hardware interrupts the
The hardware block is a simple block that handles all of CPU only on an address match. However, it does not
the status and timing requirements of the I2C transaction. wake PSoC 1 out of a sleep state. After the address, the
This block generates the I2C clock when it is in master hardware interrupts the CPU according to the conditions in
mode. It also shifts I2C data in and out of PSoC 1 and Table 2.
reports the status of I2C transactions and errors. Each of the hardware blocks in part family CY8C28xxx
Interrupts and Transaction Queuing allows for additional I2C pin connections either on Ports
1.2 and 1.6 or on Ports 3.0 and 3.2.
The block is capable of receiving or transmitting only one
byte of data at a time. At each byte boundary, the block Having two I2C hardware blocks allows for many powerful
will generate an interrupt. The CPU must service the applications. Table 3 lists some of the unique applications
interrupt and provide more data to the block, or it must that can be achieved.
read the data that the block received. The CPU need not
service the block immediately, because the block holds Table 3. Two I2C Configurations with Common Use Cases
the SCL LOW until the CPU releases it; this process is
Configuration Common Uses
referred to as clock stretching. For more information, see
the Clock Stretching and Interrupt Latency section. 2
Two I C slaves
2
Multi-I C bus systems
2
The block is capable of queuing only one transaction at a I C shared memory device
time. Multiple starts cannot be queued in the block. 2 2
One I C slave, one I C
2
I C bus switch
Therefore, user code must ensure that the current I2C master or multimaster 2
I C hot-swap controller
transaction is complete before another transaction can be 2
I C buffer
initiated.
Debugging
The block automatically detects and reports arbitration 2
conditions in multimaster environments. In the case of an Two I C masters or Increase bandwidth
multimasters
arbitration event, the block reports to the CPU that it has
lost arbitration. User code checks to see if arbitration has
been lost. If so, then the code retries the transfer.
The I2C hardware block will generate an interrupt on three
conditions: a bus error, a stop, or a byte complete.
Bus errors occur when there is a misplaced start or stop
on the bus. When this occurs, all devices on the bus must
stop their current transfer and return to an idle state.
If enabled, the stop interrupt occurs every time there is a
stop condition on the bus.
The byte complete interrupt is triggered at different points
depending on the direction of data flow; see Table 2. This
table applies for both address and data transfers.
I2C User Modules This UM is best suited for situations when PSoC needs to
2 stream data continuously to a master device and when
Cypress provides a set of preconfigured and precoded I C
you want to write minimal I2C code. For example, the UM
user modules (UMs), located in PSoC Designer in the UM
is popular in CapSense® applications. PSoC reads the
Catalog; see Figure 12.
state of CapSense buttons and the master device
Figure 12. I2C UMs in PSoC Designer communicates continuously with PSoC to see if a button
has been pressed. In this situation, expose the CapSense
variables to the EzI2Cs and the master can easily read the
state of the CapSense buttons.
EzI2Cs is patterned after an I2C-based memory such as
EEPROM. It uses subaddressing to write or read to
specific data locations within the exposed I2C data
structure. For example, consider an I2C data structure that
appears as follows:
struct MyI2C_Regs {
BYTE bStat;
BYTE bCmd;
int iVolts;
char cStr[6];
When these UMs are placed in a design, you will not see } MyI2C_Regs
them appear in the chip view within PSoC Designer,
because the UMs either use the dedicated hardware block The above data will be exposed to the master with the
or are a software master. They use digital blocks only with following memory map:
the 28xxx family; in that case, the chip view shows both
I2C hardware blocks visually so you know which block you 0x00 MyI2C_Regs.bStat
have used and how many remain; see Figure 13.
0x01 MyI2C_Regs.bCmd
Figure 13. Two I2C Blocks in 28xxx
0x02 MyI2C_Regs.iVolts(MSB)
0x03 MyI2C_Regs.iVolts(LSB)
0x04 MyI2C_Regs.cStr[0]
0x05 MyI2C_Regs.cStr[1]
0x06 MyI2C_Regs.cStr[2]
I2C UMs, which include EzI2Cs and I2CHW, provide a 0x07 MyI2C_Regs.cStr[3]
level of abstraction over the I2C hardware block. This 0x08 MyI2C_Regs.cStr[4]
section briefly describes each UM and explains when it will
be needed in a design. For more information, see the 0x09 MyI2C_Regs.cStr[5]
specific UM datasheet.
EzI2Cs If the master wants to write to iVolts, it first sends the slave
address, followed by a subaddress (0x02), which indicates
Ezl2Cs operates exclusively as a slave; there is no master the offset of iVolts in the structure. To calculate the offset,
version. If a design requires master operation, use I2CHW count the number of bytes before iVolts; in this example,
or I2Cm. the subaddress is „2.‟ To extend the example, a
EzI2Cs, as the name implies, is an easy-to-implement I2C subaddress of „0‟ will write to bStat, a subaddress of „1‟ will
slave interface. It is a firmware layer on top of the I2C write to bCmd, and a subaddress of „4‟ will write to the first
hardware block. It implements many of the firmware element of the cStr array. Figure 14 shows an example of
requirements mentioned in the hardware block description a master writing data to iVolts in an EzI2Cs UM with a
found in Appendix A. slave address of 0x04.
EzI2Cs is unique; it requires minimal user knowledge of Figure 14. EzI2Cs Example: Write to iVolts
how the I2C bus works. It allows you to set up a data
Slave Addr Subaddr Data to iVolts
structure in user code and expose that structure to the I2C S 0x04 WA 0x02 A 0x55 A 0xAA A P
master. All I2C transactions happen in the background
through interrupts. You need not worry about any of the
2
I C functionality after the UM is started. The application
If the master wants to read iVolts, it first needs to address
code just needs to update the data structure with data for
the PSoC slave and write the subaddress of „2.‟ It should
the master to read and then check and process data that
then address the slave again and read out two bytes.
the master writes.
Each subsequent read will start at iVolts until a new 6 MHz, the actual speed of the slave will be 100 kHz. See
subaddress is written. Figure 15 shows an example of a the Clock Speeds section for more details.
master reading the data in iVolts.
I2C_Pins: This parameter selects the pins used for the I2C
Figure 15. EzI2Cs Example: Read from iVolts clock and data.
Slave Addr Subaddr After the UM parameters are configured, follow these
S 0x04 WA 0x02 A P steps to make the EzI2Cs work in firmware.
Slave Addr Data from iVolts 1. Create a data structure to expose to the master. For
S 0x04 R A 0x55 A 0xAA A P example:
structMyI2C_Regs {
Let‟s take a look at how EzI2Cs can be implemented in a BYTE bStat;
project. Figure 16 shows the parameters for the project. BYTE bCmd;
Figure 16. EzI2Cs UM Parameters int iVolts;
char cStr[6];
} MyI2C_Regs
more details on other ways to ensure that the data is In the master operation, three parameters are available:
coherent. Read_Buffer_Type, I2C_Clock, and I2C_Pin.
Configuration of these parameters is the same as that
This application note includes a simple project that described for the slave operation below.
demonstrates how to use the EzI2Cs UM. For details on
how to use the project, see Appendix B. Multimaster and Slave Operation: Select this option if
you need the I2CHW as a master and slave in a
For a detailed description of how this UM works and how multimaster environment.
to use it, see the EzI2Cs datasheet.
Depending on the option you select, the UM parameter
EzI2Cs Summary and Important Notes window will populate.
EzI2Cs is an easy-to-implement slave-only UM. Slave_Addr: This is the 7-bit slave address. Unlike
EzI2Cs, I2CHW does not offer dynamic addressing or
EzI2Cs exposes a register structure to a master with separate address for ROM buffers. In multimaster and
clearly defined read/write permissions. slave operation, Slave_Addr is the address of the device
when it is addressed as a slave by another master on the
When ROM registers are enabled, the slave will have
bus.
two addresses, one for RAM space (seventh bit cleared)
and one for ROM space (seventh bit set). For this Read_Buffer_Type: When you select “RAM only,” the
reason, the slave address is limited to a 6-bit value when application will set up the read buffer only in RAM. When
ROM registers are enabled. you select ”RAM or flash,” the application exposes either a
RAM buffer or a flash buffer to the master.
When dealing with multiple byte values in EzI2Cs, take
care to ensure data coherency by using flags or Communication Service Type: When you select
semaphores between the master and slave. “Interrupt,” all I2C transactions are automatically handled
inside the interrupt. When you select “Polled,” I2C
I2CHW transactions are handled only when the foreground
application calls the I2CHW_Poll function. The hardware
This UM is a firmware layer on top of the I2C hardware
keeps the I2C clock stretched until the application calls
block and implements all the firmware tasks described in
I2CHW_Poll. Cypress recommends the “Interrupt” option.
Appendix A. You can use this flexible UM as a slave, a
master, or a multimaster slave. I2C_Clock: This parameter selects the speed of the slave.
2 As explained in the clock parameter of the EzI2Cs slave,
I CHW, unlike EzI2Cs, requires more code interaction.
the speed is based on a SYSCLK of 24 MHz.
Check status bits to see if an I2C transaction occurred,
reinitialize buffers when a transaction is complete, and I2C_Pin: This parameter selects the pins for the I2C.
clear status bits. Also, check the firmware for error Options are P1[0]-P1[1] and P1[5]-P1[7] for all devices
conditions on a transaction. except for CY8C28xxx. For CY8C28xxx, P1[2]-P1[6] and
P3[0]-P3[2] options are also available.
Here‟s how to implement I2CHW in a project. When you
double-click, the I2CHW topology selection window opens.
See Figure 17. Firmware
Figure 17. I2CHW Topology Window After the topology and parameters are configured, follow
these steps to get the I2CHW working in firmware.
Slave Operation
1. Declare a read buffer in RAM (or flash) for the master
to read from. For example:
BYTE ReadBuffer[16];
Slave Operation: Select this option if you need slave 2. Declare a write buffer in RAM for the master to write
operation. to. For example:
Single Master Operation: Select this option if you need a BYTE WriteBuffer[16];
simple operation in a single master environment.
The buffer can also be a structure such as:
3. Enable global interrupts by calling the 8. Call the function I2CHW_bReadI2CStatus and check
M8C_EnableGInt macro. for the I2CHW_WR_COMPLETE flag. If this flag is
set, it means that the master has completed a write
M8C_EnableGInt ; transaction. Process the data, clear the flag, and
reinitialize the write buffer.
It is important to enable global interrupts, because all
of the I2C operations take place in the background // Check if a write operation is over
inside the I2C ISR. if (I2CHW_bReadI2CStatus() &
I2CHW_WR_COMPLETE)
4. Call the I2CHW_Start, I2CHW_EnableSlave, and {
I2CHW_EnableInt functions to start the slave. // Process data from Master
I2CHW_Start(); // Clear the flag
I2CHW_EnableSlave(); I2CHW_ClrWrStatus();
I2CHW_EnableInt();
// Re-initialize the buffer
5. Initialize the read buffer using I2CHW_InitRamRead. I2CHW_InitWrite(WriteBuffer,
I2CHW_InitRamRead(ReadBuffer, sizeof(WriteBuffer));
sizeof(ReadBuffer)); }
This function initializes a pointer to the read buffer It is important to reinitialize the write buffer; otherwise,
and sets the size of the buffer. Whenever the master the slave will not acknowledge any further data from
tries to read from the slave, data from the buffer is the master.
transmitted to the master automatically. If the master A simple project in this application note demonstrates how
tries to read more bytes than the size of the buffer, to use I2CHW as a slave that echoes the data written by
the last byte of the buffer is transmitted repeatedly. an I2C master. For details on the project, see Appendix B.
6. Initialize the write buffer using the I2CHW_InitWrite
function. Master Operation
I2CHW_InitWrite(WriteBuffer, 1. Declare a read buffer in RAM (or flash) where data
sizeof(WriteBuffer)); read from the slave will be stored. For example:
BYTE ReadBuffer[16];
This initializes a pointer to the write buffer and the The buffer can also be a structure similar to the one
buffer size. When the master writes data to the slave, discussed in the slave operation section above.
the data is automatically deposited in the buffer. If the
master tries to write a greater number of bytes than 2. Declare a write buffer in RAM for data that will be
the buffer size, the slave will not acknowledge the written to the I2C slave. For example:
extra bytes and those extra bytes will be discarded. BYTE WriteBuffer[16];
7. Call the function I2CHW_bReadI2CStatus and check
for the I2CHW_RD_COMPLETE flag. If this flag is 3. Enable global interrupts by calling the
set, it means that the master has completed a read M8C_EnableGInt macro.
transaction. Clear the status flag and reinitialize the M8C_EnableGInt;
read buffer.
// Check if a read operation is over It is important to enable global interrupts, because all
if (I2CHW_bReadI2CStatus() of the I2C operations take place in the background
I2CHW_RD_COMPLETE) inside the I2C ISR.
{
4. Call the I2CHW_Start, I2CHW_EnableMstr, and
// Prepare fresh data for Master
I2CHW_EnableInt functions to start the master.
// Clear the flag I2CHW_Start();
I2CHW_ClrRdStatus();
I2CHW_EnableMstr();
// Re-initialize the buffer I2CHW_EnableInt();
I2CHW_InitRamRead(ReadBuffer,
sizeof(ReadBuffer)); 5. To write to a slave, use the I2CHW_bWriteBytes
} function.
operation is completed or if the master lost arbitration. overhead and does not support multimaster operation. It
Following is an example code that does this. requires 100 percent of CPU during I2C transactions. A
while((!(I2CHW_bReadMasterStatus() & second disadvantage is that it is limited to bus frequencies
I2CHW_WR_COMPLETE)) && of 100kHz.
(!(I2CHW_bReadBusStatus() & I2Cm is best for applications in which multiple masters are
I2CHW_LOST_ARB))); needed in a single chip or when the pins that connect to
if (I2CHW_bReadMasterStatus() & the I2C hardware are not available. Cypress recommends
I2CHW_WR_COMPLETE) using I2CHW for master operations if only one master is
{ needed and if P1.5, P1.7 or P1.0, P1.1 are available.
// Write is completed successfully.
// Clear flag Following are the steps to get this UM running in a project.
I2CHW_ClrMasterWrStatus();
} 1. Start the UM using the I2Cm_Start function.
if (I2CHW_bReadBusStatus() & 2. To write data from a RAM buffer (or a ROM buffer) to
I2CHW_LOST_ARB) a slave, use the I2Cm_bWriteBytes function. This
{ function accepts the slave address, pointer to the
// Master lost arbitration. Retry source data in RAM (or ROM), and the number of
later bytes to be transferred.
}
3. To read data from a slave, use the I2Cm_fReadBytes
The first line loops until either the write is completed function. This function accepts the address of the
or the LOST_ARB error flag is set. If the “while” loop slave, pointer to destination buffer where the read
terminates, the code checks to determine which data must be saved, and the number of bytes to be
condition caused the loop to terminate. If the read.
WR_COMPLETE flag is set, then clear the flag. If the This UM works by manipulating the drive mode
LOST_ARB flag is set, then retry the transaction later. (PRTxDMx) and data registers (PRTxDR) of the port on
This application note includes a simple project that which it is operating. For this reason, take care when
demonstrates how to use the I2CHW UM to read a manipulating data registers in user code; otherwise, I2C
standard EEPROM. For details, see Appendix B. traffic is affected adversely. The best way to avoid issues
is to use shadow registers when writing to the drive mode
For more information, see the I2CHW UM datasheet and 2
and data registers associated with the I Cm pins.
the I2C section of the Technical Reference Manual.
When I2Cm is placed in the project, PSoC Designer
2
I CHW Summary and Important Notes automatically creates shadow registers for the data
register and the two drive mode registers PRTxDM0 and
I2CHW can operate in single master, single slave, or PRTxDM1. Because the UM does not affect PRTxDM2, a
multimaster slave modes. shadow register is not created for this register.
In slave mode, when a master completes a read or write, These shadow registers are defined in psocconfig.asm
the buffers must be reinitialized for the next transaction and psocgpioint.h files. For example, if I2Cm is placed in
to take place. Port0, the following variables are defined in the
psocconfig.asm file.
In the master mode in a multimaster environment, the
firmware must check the return value of the ; write only register shadows
bWriteBytesNoStall and fReadBytesNoStall functions to _Port_0_Data_SHADE:
know if the bus is busy, and must retry the transaction. Port_0_Data_SHADE: BLK 1
_Port_0_DriveMode_0_SHADE:
In the master mode in a multimaster environment: When Port_0_DriveMode_0_SHADE: BLK 1
a read or write transaction is initiated, the firmware _Port_0_DriveMode_1_SHADE:
checks if the transaction has completed successfully or Port_0_DriveMode_1_SHADE: BLK 1
the master has lost arbitration to another master. If the
master lost arbitration, the transaction must be retried. The following definitions are placed in psocgpioint.h.
extern BYTE Port_0_Data_SHADE;
I2Cm extern BYTE Port_0_DriveMode_0_SHADE;
extern BYTE Port_0_DriveMode_1_SHADE;
I2Cm, another UM in PSoC 1, implements an I2C master
through software manipulation of GPIO port pins. This UM The application code uses these shadow registers to write
does not use the I2C hardware block. There is no I2C to the data and drive mode registers. For example, if the
software slave user module. application wants to set P0[0], use the following code:
The advantage of this UM over I2CHW is that it can be // Write to PRT0DR through shadow register
used on any pair of pins instead of just P1.5, P1.7 or P1.0, Port_0_Data_SHADE |= 0x01;
P1.1. One drawback is that it requires more CPU
For more information on the need to use shadow registers, Pull-up Resistors
refer to the Shadow Registers Database. For more
Another common design consideration with I2C is the
information on this user module, see the I2Cm datasheet.
value of the pull-up resistors. The selected value of the
resistors depends on the communication frequency and
I2Cm Summary and Important Notes
the bus capacitance. A larger bus capacitance and pull-up
resistor size causes longer rise time on the clock and data
I2Cm is a software implementation of I2C master and
lines. The I2C specification provides a maximum rise time.
does not occupy the I2C hardware resource.
If the rise time on the bus exceeds the maximum, I2C
I2Cm uses all the CPU resources while reading or writing
communication does not occur properly. The I2C
to a slave.
specification offers the graph shown in Figure 18 to
If the application code has to write to the data or drive determine the value of the pull-up resistors. RS is a series
mode registers of the port in which I2Cm is placed, take resistor; the I2C specification defines the maximum RS.
care to use the shadow registers to avoid problems with
Pull-up resistors between 2.2 k and 4 k work for most
the I2C interface.
systems.
Clock stretching and interrupt latency I2C and ISSP Programming Conflicts
One common consideration when using I2C with PSoC is
Hot swapping
the choice of which pins to use. When using the hardware
Glitch filtering block, there are two pairs of fixed pins available for I2C:
P1.5, P1.7 and P1.0, P1.1. (In the 28xxx family, you can
I2C and sleep also use P1.2 and P1.6 or P3.0 and P3.2.) You can also
use pins P1.0, P1.1 to program PSoC. Pull-up resistors on
I2C and dynamic reconfiguration these lines can cause in-system programming failures.
Dynamic addressing in I2CHW During programming, P1.0 uses the resistive pull-down
drive mode to force a logic level LOW on the line. The pull-
down resistor is approximately 5.6k. This internal pull-
down resistor and the external I2C pull-up resistor create a
The frequency of SYSCLK depends on the supply voltage Figure 21. Byte Complete Interrupt Timing
for PSoC. If the supply voltage is above 3 V, then most
Max
devices have a 24-MHz SYSCLK. If the supply voltage is
4 Cycles
below 3 V, then many devices have a 6-MHz SYSCLK. Internal
Several devices have a 12-MHz SYSCLK option. Further, Sampling
the value of SYSCLK can be changed within PSoC Clock
Designer. When using I2C, do not change the frequency of SCL
SYSCLK or the CPU_CLK; this can cause glitches on the
I2C lines. For more information on clocks, see the clock Interrupt
section of the Technical Reference Manual.
Transmit: Ninth positive edge SCL
When using an external clock, be sure to use the correct Receive: Eighth positive edge SCL
I2C clock speed.
Using this information, you can determine if the clock will
Clock Stretching and Interrupt Latency be stretched and for how long. However, if there are other
Clock stretching is the process in which a slave device interrupts in the system, the time spent in those interrupts
holds the clock line LOW, thus stalling further must be considered.
communication on the bus by the master. The slave To minimize clock stretching in PSoC, the first step is to
device typically stretches the clock so it can process run the CPU at 24 MHz. Next, the I2C clock speed must be
information it is receiving from the master or prepare more 100 kHz or lower. Last, having minimal interrupts reduces
data to send to the master. This stretching can be done at clock stretching.
any point of the transaction. PSoC stretches the clock
after the byte complete interrupt. See Figure 20. Hot Swapping
2
The I C specification indicates that this is an optional Hot swapping is the process of attaching powered devices
feature; not all I2C devices need to support clock to an unpowered PSoC. I2C in PSoC is not designed to be
stretching. However, all Cypress PSoC 1 I2C slave UMs hot swappable. There are several factors to consider when
stretch the clock. If you use a master that does not support hot swapping PSoC. The first issue is back powering. If
clock stretching, the bus can lock up and fail to reset. PSoC is not powered but one of the external pins is at a
high voltage level, then there is a possibility of back
Figure 20. Clock Stretching Example powering the PSoC device. This is not a desirable
START 7-Bit Address R/W situation, because PSoC may execute in unexpected ways
ACK and the I2C lines may be adversely affected.
1 7 8 9 Glitch Filtering
The input of the SCL has a glitch filter, which Figure 22
Clock Stretching
shows.
The time the PSoC slave spends stretching the clock Figure 22. SCL Glitch Filter
depends on whether the master is reading or writing to the
slave and whether other interrupts occur in the system. It SCL Pin INPUT
also depends on the CPU speed.
0
PSoC 1 devices will stretch the clock a majority of the time 1
for I2C bus speeds of 100 kHz or greater. The ISR code in
SAMPLE
the EzI2Cs and I2CHW UMs contain 150 to 300 CPU
CLK
instruction cycles. With a 24-MHz CPU clock, the ISR
takes approximately 6 to 13 µs to execute. The SCL line is
The input is double-synchronized to the sample clock, and
released at the end of the ISR code.
then it is glitch-filtered. The raw input and the delayed
The ISR is triggered three or four internal sample clock input must match for a signal to pass through. Because
periods after the rising edge of SCL; see Figure 21. This is the sample clock is either 1.5 MHz or 6 MHz, glitches less
due to an internal glitch filter on SCL; see Figure 22. Refer than 666 ns and 166 ns are suppressed.
to Table 4 for the frequency of the sampling clock. For
100 kHz, the sample clock is 1.6 MHz, which means that I2C and Sleep
the ISR will fire ~2.5 µs after the rising edge of SCL. The When using I2C in designs that enter and exit sleep mode,
nominal period of a 100-kHz clock is 10 µs. If it takes 2.5 you need to take special design considerations into
µs for the ISR to be triggered and the ISR takes 6 to account.
13 µs, the clock will be stretched in most cases.
First, it is important that all I2C transactions are complete
before the I2C enters sleep mode. Otherwise, when the
part wakes up, the I2C block can erroneously interpret data
as an address or vice-versa. After confirming that all I2C Figure 23. I2CHW UM Slave Address
traffic has stopped, follow these steps:
Ensure that no I2C activity is occurring on the bus. Follow these steps to replace the constant with a RAM
variable:
Call the appropriate start API.
1. Create a RAM variable to hold the dynamic slave
Configure I2C pins for open-drain drives LOW. address. In the I2CHW_1int.asm file, just below the
variable allocations, is a custom user code area.
Enable interrupts. Under the custom declaration area, add this code:
If you follow these steps, you can avoid most errors when export _I2CSlaveAddress
using I2C in conjunction with sleep. export I2CSlaveAddress
I2C and Dynamic Reconfiguration Under the variable allocation area, add the following:
I2C UMs should never be loaded or unloaded through
dynamic reconfiguration. They should always be present. Area InterruptRAM(ram)
If they are loaded and unloaded, I2C errors will occur. _I2CSlaveAddress:
I2CSlaveAddress: BLK 1
The I2C UMs should be located either in the base
configuration or in a separate overlay that is always The variable with the „_‟ allows you to modify this in C
loaded. code.
Dynamic Slave Addressing in I2CHW UM 2. Modify the code that does the address comparison.
The EzI2Cs UM allows you to programmatically change mov A, reg[I2CHW_1_DR]
the I2C slave address on the fly. However, this functionality and F, 0xF9
is not available in the I2CHW UM; to achieve the same rrc A
functionality, do the following: xor A, [I2CSlaveAddress]
In the I2CHW UM, the address from the master is Because this code is inside a custom user code area,
processed inside the I2CHW_1int.asm file. The following changes to the UM library file are preserved during
code does the address matching. application generation. Note that if you rename the
UM, changes will be lost and must be made again.
mov A, reg[I2CHW_1_DR]
and F, 0xF9 3. Add a reference to the I2C slave address variable that
rrc A is defined in the I2CHW_1int.asm file by adding the
xor A, I2CHW_1_SLAVE_ADDR following code in main.c (or any other C file).
extern BYTE I2CSlaveAddress;
When the address is received from the master, it has a
7-bit address and the read/write bit. The „rrc A‟ drops the
read/write bit and compares the 7-bit address with the
The SCL Line Gets Stuck LOW
constant I2CHW_1_SLAVE_ADDR, which the device A common issue with I2C is the SCL getting stuck LOW.
editor creates according to the Slave_Addr set in the UM Follow these guidelines for debugging and fixing this issue
parameters for the I2CHW. This constant is located in the with PSoC 1 devices:
I2CHW_1.inc file.
1. Are you using EzI2Cs with PSoC Designer 5.0 SP5?
If yes, there is a known bug with this version of the
UM that causes the SCL to be stuck LOW. Update to
the latest version of PSoC Designer to fix this issue.
See the article I2C Clock Permanently Stuck to
Logical LOW.
2. Are you using PSoC Designer version prior to PD5.0?
If yes, then there are glitches on P1.5, P1.7 at startup.
Appendix A
This appendix is for users who are curious about the I2C_SCR register. If the bit is a zero, then the slave has
2
detailed operation of the I C hardware block in PSoC. acknowledged; if the bit is a one, then the slave has not
acknowledged. Take appropriate action depending on this
Hardware Registers condition.
Several registers control the I2C hardware block and report Firmware is also responsible for setting the direction of
its status. communication. This is done by setting the transmit bit in
I2C_CFG Register: Controls the configuration of the I2C the SCR register. If a zero is written to the bit, the block is
hardware block. It controls the clock speed and the pins placed in receive mode. In this mode, the hardware
being used, and it indicates if the slave or master interrupts the CPU when it receives eight data bits. After
functionality is enabled. It also enables support for this interrupt, the firmware must determine if an ACK/NAK
interrupts on stop conditions and bus errors. needs to be sent.
I2C_SCR Register: Returns status flags from the I2C If a „1‟ is written to the transmit bit, the block is placed in
hardware block. It reports if a full byte (byte complete) is transmit mode. In this mode, the hardware interrupts after
sent or received. This register indicates if a bus error has the ACK/NAK is received from the slave device. The
occurred or if arbitration is lost. It also determines if the firmware again handles these cases.
last transaction was an address. When the SCR register is written, the master will start to
I2C_DR Register: This register holds the value of data generate clocks to either send or receive more data.
sent or received. It shifts data in only if the data is an S l a ve O p e r a t i o n
address, if the hardware block is configured as a slave
When the hardware detects a start condition in slave
and is addressed, or if the master has initiated a read.
mode, it shifts the next eight bits of data into the I2C_DR
I2C_MSCR Register: This register controls the master register. On receipt of the eighth bit, the hardware block
portion of the I2C transaction. It holds the bit that allows interrupts the CPU and causes the address bit in the
generating a start. The enable master bit in the I2C_CFG I2C_SCR register to go HIGH.
register must be set for this register to be available;
When the interrupt is posted, the hardware holds the clock
otherwise, this register is held in reset.
line LOW. It is then the firmware‟s responsibility to read
the incoming address and acknowledge whether the
Firmware Requirements address is its own. The firmware must set the ACK bit in
This section describes the operation of the hardware block the SCR register appropriately. The firmware should also
for different configurations. Note that wherever the text read the read/write bit of the address. If the bit is a „1,‟
mentions a requirement of firmware, all PSoC I2C user then the transmit bit in the SCR register is changed to a
modules run this code. „1.‟ After the CPU writes to the SCR register, the hardware
releases the clock line, which allows the transaction to
Start Generation continue.
If the start gen bit is set in the master status and control
register, the hardware block generates a start condition If the slave is configured as a transmitter, firmware must
and sends out the address in the data register. However, load valid data into the DR register before writing to the
the hardware recognizes if another device has taken SCR register and releasing the bus. After the bus is
control of the bus. If an external start condition is detected, released, the hardware shifts data out to the SDA line on
the hardware queues the current start until the bus is free. the clock edges provided by the master. The hardware
The start bit is not cleared until the hardware has waits until it receives an ACK/NAK from the master and
successfully sent out a start condition or the firmware has then interrupts the CPU. The firmware then must load new
cleared it. data or do nothing.
Only one start can be queued at a time. If the master If the slave is configured as a receiver, the hardware
attempts to send two starts while the bus is busy, the interrupts after the eighth bit of data is received. The
hardware sends only the last address. As stated earlier, firmware then decides if it can receive more data. It must
the user code must ensure that this situation does not then set the ACK bit appropriately.
occur.
Stop Condition
Master Operation When a transaction is completed in master mode, the
In master mode, after the start and address are sent, the hardware block generates a stop condition to indicate that
hardware waits until the ACK/NAK bit from the slave is the bus is free.
received. On receiving the ACK/NAK bit, the hardware In slave mode, the reception of a stop puts the hardware
interrupts the CPU. Firmware then determines if the slave block into an idle mode until it receives a new start
acknowledged or did not acknowledge the address. It condition.
does so by reading the last received bit (LRB) in the
Master transmits
another byte
9 1 7 8 9
ACK = Master
wants to read
another byte.
Read (RX)
data.
CPU reads the
START 7-Bit Address R/W received byte from
I2C_D register.
ACK
CPU checks Read/
Write Bit
1 7 8 9
1 7 8 9
ACK = Slave
says OK to
receive more.
Master can
send more or
Stop.
Master wants to
send more bytes.
Appendix B
This appendix describes various example projects that written to the variable ADCValue. A master device can
demonstrate the use of the I2C UMs. read this variable.
In firmware, a local copy for LEDValue and DACValue are
EzI2Cs_ADC_LED_DAC Example Project created. The values of LEDVAlue and DACValue in the
This project demonstrates how to configure the EzI2Cs I2C register structure are continuously compared with the
UM. The project configures PSoC as an I2C slave and may local copies of these parameters. When the master writes
be considered as an implementation of an I2C-controlled a different DAC value or LED value, then the LED ports
analog peripheral device and port expander. (P0[0] to P0[3]) and DAC are updated with the new values.
This project creates the following data structure: The DAC output is available on P0[5].
Figure 28. Test Setup for EzI2Cs Example Project Figure 29. Bridge Control Panel
Command Window
Status/Response
Window
There are two methods for testing the project. You can
use Bridge Control Panel software or an external MCU.
Using Bridge Control Panel Software to Test Power Button Connect Button
Figure 30. Write LED and DAC Values This write command sets the subaddress in the
EzI2Cs. Any further read operation will take place on
subaddress 0x0, which is the ADC value.
Next, type the following command and select the
Repeat button. Observe only the ADC value being
read.
r 04 x p
r 04 x x x x x x x x x x p
w 04 0a 0b 0c 0d 0e 0f 10 11 12 13
r 04 x x x x x x x x x x p
2. Select the “Send all strings” option and click the Send
button to execute all of the commands in sequence.
Observe in the results window that the same values
written using the write command are being read back
while executing the read command.
Figure 37. Writing and Reading the I2CHW Slave When the slave generates an ACK, the master exits the
while loop.
Next, the master reads the data that it just wrote to the
EEPROM. This is done by first writing the two subaddress
bytes and then reading out 64 bytes of data from the
EEPROM. The master then compares the read data with
the written data. When all 64 bytes match, an LED is
turned on.
To test this project, connect P1.5 and P1.7 to the SDA and
SCL of an external I2C EEPROM. Make sure that you
have external pull-up resistors on those lines. Connect an
LED with a series resistor to P0_7. You can test the
project using a CY3210 PSoC evaluation board. (See
Table 9.)
Table 9. Connections for Project Testing
Document History
Document Title: Getting Started with I2C in PSoC® 1 – AN50987
Document Number: 001-50987
All other trademarks or registered trademarks referenced herein are the property of their respective owners..
Cypress Semiconductor
198 Champion Court
San Jose, CA 95134-1709
© Cypress Semiconductor Corporation, 2009-2017. This document is the property of Cypress Semiconductor Corporation and its subsidiaries, including
Spansion LLC (“Cypress”). This document, including any software or firmware included or referenced in this document (“Software”), is owned by
Cypress under the intellectual property laws and treaties of the United States and other countries worldwide. Cypress reserves all rights under such
laws and treaties and does not, except as specifically stated in this paragraph, grant any license under its patents, copyrights, trademarks, or other
intellectual property rights. If the Software is not accompanied by a license agreement and you do not otherwise have a written agreement with
Cypress governing the use of the Software, then Cypress hereby grants you a personal, non-exclusive, nontransferable license (without the right to
sublicense) (1) under its copyright rights in the Software (a) for Software provided in source code form, to modify and reproduce the Software solely for
use with Cypress hardware products, only internally within your organization, and (b) to distribute the Software in binary code form externally to end
users (either directly or indirectly through resellers and distributors), solely for use on Cypress hardware product units, and (2) under those claims of
Cypress‟s patents that are infringed by the Software (as provided by Cypress, unmodified) to make, use, distribute, and import the Software solely for
use with Cypress hardware products. Any other use, reproduction, modification, translation, or compilation of the Software is prohibited.
TO THE EXTENT PERMITTED BY APPLICABLE LAW, CYPRESS MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD
TO THIS DOCUMENT OR ANY SOFTWARE OR ACCOMPANYING HARDWARE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. To the extent permitted by applicable law, Cypress reserves the right to
make changes to this document without further notice. Cypress does not assume any liability arising out of the application or use of any product or
circuit described in this document. Any information provided in this document, including any sample design information or programming code, is
provided only for reference purposes. It is the responsibility of the user of this document to properly design, program, and test the functionality and
safety of any application made of this information and any resulting product. Cypress products are not designed, intended, or authorized for use as
critical components in systems designed or intended for the operation of weapons, weapons systems, nuclear installations, life-support devices or
systems, other medical devices or systems (including resuscitation equipment and surgical implants), pollution control or hazardous substances
management, or other uses where the failure of the device or system could cause personal injury, death, or property damage (“Unintended Uses”). A
critical component is any component of a device or system whose failure to perform can be reasonably expected to cause the failure of the device or
system, or to affect its safety or effectiveness. Cypress is not liable, in whole or in part, and you shall and hereby do release Cypress from any claim,
damage, or other liability arising from or related to all Unintended Uses of Cypress products. You shall indemnify and hold Cypress harmless from and
against all claims, costs, damages, and other liabilities, including claims for personal injury or death, arising from or related to any Unintended Uses of
Cypress products.
Cypress, the Cypress logo, Spansion, the Spansion logo, and combinations thereof, WICED, PSoC, CapSense, EZ-USB, F-RAM, and Traveo are
trademarks or registered trademarks of Cypress in the United States and other countries. For a more complete list of Cypress trademarks, visit
cypress.com. Other names and brands may be claimed as property of their respective owners.