I2C Communication
1. Definition and Purpose of I2C
Definition and Purpose of I2C
The Inter-Integrated Circuit (I2C) protocol is a synchronous, multi-master, multi-slave serial communication bus designed by Philips Semiconductor (now NXP) in 1982. It uses a two-wire architecture consisting of a bidirectional serial data line (SDA) and a serial clock line (SCL), enabling half-duplex communication between integrated circuits at speeds up to 5 MHz in Ultra Fast-mode.
Electrical Characteristics
I2C operates on an open-drain topology with pull-up resistors, requiring voltage levels to satisfy:
where VDD is the supply voltage. The bus capacitance limit (typically 400 pF for Standard-mode) constrains maximum wire length and device count.
Protocol Fundamentals
Each transaction contains:
- Start condition (S): SDA falls while SCL remains high
- 7/10-bit slave address + R/W bit
- ACK/NACK handshake after each byte
- Stop condition (P): SDA rises while SCL is high
Clock Synchronization
Multi-master systems employ clock stretching where:
with tBUF as bus-free time between stop and start conditions, ensuring proper arbitration.
Practical Applications
I2C dominates in sensor networks (e.g., MEMS accelerometers), EEPROM access, and display control (OLED, LCD) due to its:
- Minimal pin count (2-wire vs SPI's 4+)
- Built-in addressing (128–1024 unique addresses)
- Hardware-level collision detection
Performance Considerations
The maximum theoretical throughput R follows:
yielding 400 kbit/s in Fast-mode with 400 kHz clock. Actual throughput reduces by 20-30% due to protocol overhead.
1.2 Key Features and Advantages
Two-Wire Serial Interface
The Inter-Integrated Circuit (I2C) protocol utilizes only two bidirectional open-drain lines: Serial Data Line (SDA) and Serial Clock Line (SCL). This minimal wiring requirement enables efficient communication between multiple devices while significantly reducing PCB complexity. The open-drain configuration allows for flexible voltage level matching between devices operating at different logic levels.
Multi-Master and Multi-Slave Architecture
I2C supports a true multi-master bus configuration where multiple controllers can initiate communication. Collision detection and arbitration are handled at the protocol level through:
Each slave device has a unique 7-bit or 10-bit address, allowing up to 112 (7-bit) or 1024 (10-bit) devices on the same bus. The address space includes reserved addresses for special functions like general call and HS-mode masters.
Variable Speed Modes
The protocol defines several speed grades with distinct timing characteristics:
- Standard Mode (100 kbit/s): Original specification with 4.7μS clock low period
- Fast Mode (400 kbit/s): 1.3μS clock low period, mandatory Schmitt triggers
- Fast Mode Plus (1 Mbit/s): Requires reduced bus capacitance (<400pF)
- High-Speed Mode (3.4 Mbit/s): Uses current-source pull-ups during HS bursts
- Ultra Fast Mode (5 Mbit/s): Unidirectional communication only
Clock Synchronization and Stretching
The I2C protocol implements sophisticated clock management through SCL synchronization and stretching. When multiple masters operate at different frequencies, the slowest device determines the bus frequency through:
Slave devices can extend the low period of SCL (clock stretching) to accommodate processing delays, ensuring reliable data transfer without additional handshaking lines.
Advanced Error Handling
I2C incorporates multiple error detection mechanisms:
- Acknowledge (ACK) Bit Verification: Each byte transfer requires receiver confirmation
- Bus Timeout Detection: Automatic reset if SCL remains low for >25ms
- Clock Low Timeout: Maximum 35ms SCL low period in Standard Mode
- Arbitration Loss Detection: Hardware flag for multi-master conflicts
Power Efficiency
The protocol's quiescent current is exceptionally low due to:
- Open-drain outputs with passive pull-ups
- No continuous clock requirement
- Address-based device wakeup (no polling)
Current consumption follows:
Typical implementations achieve <1μA standby current in sleep modes.
Integrated Hardware Support
Modern microcontrollers incorporate dedicated I2C peripherals that handle:
- Automatic address recognition
- Clock generation and synchronization
- DMA-compatible data buffering
- Interrupt-driven operation
These hardware accelerators reduce CPU overhead to <5% even at 3.4Mbit/s speeds.
1.3 Common Applications in Electronics
The Inter-Integrated Circuit (I2C) protocol is widely adopted in embedded systems and consumer electronics due to its simplicity, multi-master capability, and moderate speed. Its two-wire design (SDA for data and SCL for clock) minimizes pin count while enabling communication between multiple devices on the same bus. Below are key applications where I2C excels.
Sensor Interfacing
I2C is the de facto standard for connecting environmental sensors (temperature, humidity, pressure) and inertial measurement units (IMUs) in IoT devices. For example, the BME280 environmental sensor and MPU6050 accelerometer/gyroscope use I2C for low-power data transfer. The protocol's addressing scheme (7-bit or 10-bit) allows up to 112 devices on a single bus, making it ideal for sensor arrays in industrial monitoring systems.
Real-Time Clocks (RTCs)
Devices like the DS3231 precision RTC rely on I2C for timekeeping in embedded systems. The bus's low-speed modes (100 kHz standard, 400 kHz fast-mode) suffice for RTC communications, while clock stretching ensures synchronization. RTCs often pair with non-volatile memory (e.g., 24LC256 EEPROM) on the same bus for timestamp logging.
Display Controllers
I2C reduces wiring complexity for small displays (OLED, LCD) via serial interface adapters like the SSD1306 driver. The protocol's acknowledgment mechanism ensures reliable frame buffer updates. For example, a 128x64 OLED display can be controlled with just two wires, freeing GPIO pins for other tasks.
Digital-to-Analog Converters (DACs)
High-resolution DACs (e.g., MCP4725) use I2C for configuring output voltages in precision instrumentation. The bus supports write modes that combine command and data bytes, enabling single-transaction updates. A typical voltage set operation follows:
where D is the digital value written via I2C and n is the DAC resolution (e.g., 12 bits).
System Management
I2C is integral to System Management Bus (SMBus), a derivative protocol for power management in PCs and servers. Applications include:
- Battery charge controllers (e.g., monitoring Li-ion cells)
- Fan speed regulation via PWM controllers
- Voltage rail monitoring using ADCs like the INA219
Multi-Chip Modules
System-on-Chip (SoC) designs leverage I2C for inter-IC communication, such as between microcontrollers and co-processors. For instance, Raspberry Pi's Broadcom SoC uses I2C to interface with HAT (Hardware Attached on Top) peripherals. The protocol's clock synchronization handles timing variations across silicon dies.
Automotive Electronics
I2C appears in vehicle subsystems for non-critical functions due to its cost-effectiveness. Typical uses include:
- Seat/mirror position memory in infotainment systems
- Climate control sensor networks
- LED driver control (e.g., TLC59116) for interior lighting
2. Physical Layer: Hardware Connections
2.1 Physical Layer: Hardware Connections
Signal Lines and Electrical Characteristics
The I2C bus consists of two bidirectional open-drain lines: Serial Data Line (SDA) and Serial Clock Line (SCL). Both require pull-up resistors to VDD, with values determined by the bus capacitance (Cbus) and desired rise time (tr). The RC time constant must satisfy:
where Rp is the equivalent pull-up resistance. For standard-mode (100 kHz), tr must be ≤ 1 μs, while fast-mode (400 kHz) requires ≤ 300 ns. The maximum bus capacitance is 400 pF.
Multi-Master Bus Arbitration
I2C supports multi-master configurations through clock synchronization and arbitration. SCL is stretched by masters holding it low, while SDA arbitration occurs when multiple masters transmit simultaneously. The first master to detect a mismatch between its output and SDA loses arbitration.
Power Supply and Noise Immunity
I2C operates at voltages from 1.8V to 5V, with noise margins defined by:
Schmitt triggers on SDA/SCL inputs improve noise rejection. For long-distance communication (>1 m), shielded twisted-pair cables or active terminators are recommended to mitigate crosstalk and reflections.
Bus Topology and Layout Guidelines
- Star vs. Linear Topology: Linear buses simplify routing but limit speed due to stub effects. Star topologies require buffers for signal integrity.
- PCB Layout: Minimize trace length asymmetry (ΔL ≤ 10 mm). Route SDA/SCL as a differential pair if edge rates exceed 10 ns.
- Pull-Up Resistor Calculation: For VDD = 3.3V and IOL = 3 mA:
Fail-Safe Mechanisms
Open-drain outputs prevent bus contention during power-up or faults. Timeout detectors (≥ 35 ms) reset stuck buses. Bidirectional level shifters (e.g., TXS0108E) enable mixed-voltage operation.
2.2 Data Frame Structure
The I2C data frame consists of well-defined fields that ensure reliable communication between master and slave devices. Each frame begins with a Start Condition (S), followed by an address frame, read/write control bit, data frames, and ends with a Stop Condition (P). The timing and structure adhere strictly to the I2C specification, with clock synchronization and arbitration mechanisms ensuring data integrity in multi-master environments.
Start and Stop Conditions
A Start Condition is signaled when the master pulls SDA low while SCL remains high. Conversely, a Stop Condition occurs when SDA transitions from low to high while SCL is high. These conditions are unique in that they are the only times SDA changes while SCL is high, making them easily distinguishable from normal data transitions.
Address Frame Structure
The 7-bit or 10-bit address frame immediately follows the Start Condition. For 7-bit addressing:
where A6:0 represents the slave address and R/Ŵ determines the transfer direction (1 for read, 0 for write). The 10-bit addressing scheme uses two bytes:
Data Frame Validation
Each data byte (8 bits) is followed by a 9th clock pulse during which the receiver must pull SDA low as an Acknowledge (ACK). The transmitter releases SDA during this cycle. If SDA remains high (NACK), it indicates either:
- The receiver cannot accept more data
- An invalid address was specified
- The transfer should terminate
Clock Stretching Mechanism
Slave devices may hold SCL low after detecting their address (clock stretching) to force the master into a wait state. This flow control mechanism allows slower slaves to synchronize with higher-speed masters. The maximum stretch duration is specified by the device's tTIMEOUT parameter in the I2C bus specification.
Bus Arbitration
In multi-master systems, arbitration occurs when masters simultaneously transmit Start conditions. The master transmitting a '1' while another transmits '0' will detect the bus state mismatch and withdraw. Arbitration is lost without corruption because the competing masters monitor SDA throughout the entire process.
where M1 and M2 represent competing masters' output states.
Real-World Frame Example
A complete I2C write transaction to device address 0x4A with data byte 0x75 appears as:
2.3 Addressing Modes and Device Identification
I2C Address Structure
The I2C protocol uses a 7-bit or 10-bit addressing scheme to uniquely identify slave devices on the bus. The 7-bit address is the most common, providing up to 112 unique addresses (16 reserved addresses are excluded for special purposes). The address is transmitted as the first byte after the start condition, with the most significant bit (MSB) first.
Here, A6–A0 represent the 7-bit address, and R/Ŵ is the read/write bit (1 for read, 0 for write). The 10-bit addressing extends this by using two bytes: the first byte starts with the sequence 11110XX, where XX are the two most significant bits of the 10-bit address.
7-Bit vs. 10-Bit Addressing
7-bit addressing is sufficient for most applications, but 10-bit addressing (introduced in I2C v2.1) allows up to 1024 unique addresses. The trade-off is increased complexity in address decoding:
- 7-bit: Single-byte transmission, 112 usable addresses.
- 10-bit: Two-byte transmission, first byte contains 11110XX prefix.
10-bit addressing is backward-compatible; a 7-bit master can ignore 10-bit slaves by treating the first byte as a reserved address.
Device Identification and Conflicts
Manufacturers assign fixed addresses to I2C devices, but conflicts arise when multiple identical ICs share a bus. Solutions include:
- Hardware-configurable pins: Some devices (e.g., EEPROMs) allow address bits to be set via external pull-up/pull-down resistors.
- Software reconfiguration: Certain sensors permit dynamic address changes via register writes.
- I2C multiplexers: Devices like the TCA9548A split the bus into multiple channels, isolating identical slaves.
General Call and Reserved Addresses
The I2C standard reserves specific addresses for special functions:
- General Call Address (0x00): Broadcasts a command to all slaves.
- START Byte (0x01): Used for bus synchronization in slow microcontrollers.
- CBUS Addresses (0x02–0x07): Legacy compatibility with CBUS protocol.
- 10-bit Addressing Prefix (0x78–0x7F): Indicates a 10-bit address follows.
Practical Considerations
In real-world designs, address conflicts are mitigated by:
- Checking manufacturer datasheets for fixed addresses.
- Using I2C scanners to detect active devices.
- Employing multiplexers or GPIO expanders to manage bus segmentation.
For example, a system with four identical 0x68-address IMUs might use a TCA9548A multiplexer, assigning each IMU to a separate channel.
3. Start and Stop Conditions
3.1 Start and Stop Conditions
In I2C communication, the Start (S) and Stop (P) conditions are fundamental signaling events that frame every transaction on the bus. These conditions are generated by the master device to initiate or terminate communication with a slave device. Both conditions are defined by unique transitions of the Serial Data Line (SDA) while the Serial Clock Line (SCL) remains at a high logic level.
Start Condition (S)
A Start condition occurs when SDA transitions from HIGH to LOW while SCL is HIGH. This transition alerts all connected slave devices that a new transaction is beginning. The timing constraints for a valid Start condition are critical:
These parameters ensure reliable detection across all devices on the bus, accounting for propagation delays and capacitive loading effects. Violating these timing constraints may lead to missed Start conditions or bus contention.
Repeated Start Condition (Sr)
A Repeated Start condition has identical electrical characteristics to a standard Start but occurs without an intervening Stop condition. This allows the master to:
- Switch between read/write modes without releasing the bus
- Address multiple slaves in a single composite transaction
- Maintain atomicity in multi-part operations
Stop Condition (P)
The Stop condition is signaled by a LOW to HIGH transition on SDA while SCL remains HIGH. This indicates the end of a transaction and releases the bus. The timing requirements are:
These constraints prevent overlapping transactions and ensure proper bus arbitration. The rising edge of SDA during a Stop condition must be sufficiently sharp to avoid intermediate voltage levels that could be misinterpreted by some devices.
Electrical Characteristics
The Start/Stop conditions leverage the wired-AND nature of the I2C bus:
- All devices monitor SDA transitions during SCL HIGH
- Open-drain outputs require pull-up resistors (typically 1kΩ-10kΩ)
- Bus capacitance (generally < 400pF) affects rise times
The voltage thresholds for recognizing these conditions vary by logic level:
Standard | VIL (max) | VIH (min) |
---|---|---|
I2C (5V) | 1.5V | 3.0V |
I2C (3.3V) | 0.99V | 2.31V |
Practical Implementation Considerations
In hardware implementations, Start/Stop detection typically uses edge-triggered interrupts or dedicated hardware state machines. Modern microcontrollers often include specialized I2C peripherals that automatically:
- Generate and detect S/P conditions
- Handle timing requirements
- Manage bus arbitration
For custom implementations in FPGAs or discrete logic, designers must account for metastability risks when sampling asynchronous SDA transitions against the local clock domain.
3.2 Data Transfer Mechanism
The I2C protocol employs a synchronous, half-duplex communication scheme where data is transferred in 8-bit segments (bytes) between a master and slave device. Each byte is followed by an acknowledgment (ACK) or non-acknowledgment (NACK) bit, ensuring robust error detection. The mechanism is governed by precise timing constraints and signal transitions on the serial data line (SDA) and serial clock line (SCL).
Signal Timing and Data Validity
Data on SDA must remain stable during the high phase of SCL, adhering to setup (tSU;DAT) and hold (tHD;DAT) times specified in the I2C standard. Changes are only permitted when SCL is low. The clock frequency ranges from 100 kHz (Standard Mode) to 5 MHz (Ultra Fast-mode), with rise/fall times constrained by capacitive loading:
where Rp is the pull-up resistance and Cb is the bus capacitance. Violating these timings risks metastability or arbitration failures.
Byte Transfer Sequence
Each data transfer follows this sequence:
- Start Condition (S): SDA transitions low while SCL remains high.
- 7-bit Address + R/W Bit: The master transmits the slave address (MSB first) and a read/write flag.
- ACK/NACK: The addressed slave pulls SDA low during the 9th clock cycle.
- Data Byte(s): 8-bit payloads with interleaved ACK/NACK.
- Stop Condition (P): SDA transitions high while SCL is high.
Clock Stretching and Arbitration
Slaves may stretch SCL low to throttle data rates during critical operations. Multi-master systems rely on arbitration: if two masters transmit simultaneously, the one sending a '1' while the other sends '0' loses control (SDA is wired-AND). The losing master switches to slave mode.
Error Handling
NACK triggers retransmission or bus reset. Common failure modes include:
- Bus contention: Undefined states from improper pull-up configuration.
- Clock skew: Exceeding tSU;STO between repeated start conditions.
- Slave timeout: Missing ACK within tTIMEOUT (typically 25–35 ms).
3.3 Acknowledgment and Error Handling
In I2C communication, acknowledgment (ACK) and negative acknowledgment (NACK) are critical for ensuring reliable data transfer between the master and slave devices. Each byte transmitted over the I2C bus is followed by an ACK or NACK bit, generated by the receiver to confirm successful reception or indicate an error condition.
ACK/NACK Signaling Mechanism
The ninth clock pulse in a data frame is reserved for the ACK/NACK bit. After transmitting 8 bits of data, the sender releases the SDA line, allowing the receiver to pull it low (ACK) or leave it high (NACK). The timing constraints are strict:
- ACK: SDA is pulled low during the high phase of the ninth SCL pulse.
- NACK: SDA remains high during the ninth SCL pulse.
If a slave device is unable to process the received byte (e.g., due to buffer overflow or internal errors), it must issue a NACK, prompting the master to retry or terminate the transaction.
Error Conditions and Recovery
Several failure scenarios can disrupt I2C communication, each requiring specific handling:
- Bus Contention: Occurs when multiple devices attempt to drive SDA simultaneously. Modern I2C implementations use open-drain outputs to mitigate this.
- Clock Stretching: Slaves may hold SCL low to delay communication, but excessive stretching can trigger timeouts.
- Arbitration Loss: If two masters transmit simultaneously, the one sending a '1' while the other sends '0' loses arbitration and must retry.
The probability of arbitration failure in a multi-master system can be modeled as:
where N is the number of contending bits and M is the number of competing masters.
Advanced Error Detection Techniques
Beyond basic ACK/NACK, sophisticated I2C systems implement additional error checking:
- Packet Checksums: CRC-8 is commonly used for multi-byte transmissions.
- Watchdog Timers: Reset the bus if SCL remains low beyond a threshold (typically 25-35 ms).
- Bus Reset Sequences: Some controllers implement a special 9-pulse pattern to recover stuck devices.
For mission-critical applications, the mean time between failures (MTBF) can be estimated by analyzing the error correction mechanisms:
where λc is the rate of correctable errors and λu is the rate of uncorrectable errors.
Practical Implementation Considerations
When designing I2C systems with robust error handling:
- Always verify ACK bits in firmware before proceeding to subsequent operations.
- Implement timeout counters for clock stretching and bus idle conditions.
- Use pull-up resistors sized appropriately for the bus capacitance to ensure clean signal edges.
4. Configuring I2C Registers
4.1 Configuring I2C Registers
Register Map Structure
I2C peripherals use memory-mapped registers to control device behavior, each occupying a unique address space. A typical register map includes:
- Control Registers (CRx): Configure operational modes (e.g., master/slave, clock stretching).
- Status Registers (SRx): Indicate bus state (e.g., arbitration loss, acknowledge failure).
- Data Registers (DRx): Hold transmitted/received bytes.
- Clock Control Registers (CCRx): Set SCL frequency via prescalers.
For example, the STM32 I2C_CR2 register configures slave addressing (7/10-bit) and interrupt enable flags.
Clock Configuration
The I2C bus frequency is derived from the peripheral clock (PCLK) using:
where SCLL (SCL low period) and SCLH (SCL high period) are values programmed into the timing register. For a 100 kHz bus with PCLK = 48 MHz:
Empirical tuning is often required due to bus capacitance.
Addressing and Data Handling
Slave devices respond to addresses written to the I2C_OAR (Own Address Register). A 7-bit address 0x3C is stored as:
Data transmission involves:
- Writing the target address to I2C_DR with the R/W bit.
- Polling I2C_SR1.TXE (Transmit Empty) before sending subsequent bytes.
Error Handling
Critical flags in I2C_SR1 include:
- BERR: Bus error (illegal start/stop condition).
- ARLO: Arbitration lost during multi-master contention.
- AF: Acknowledge failure (no slave response).
Clearing these flags requires writing 0 to the corresponding bit in I2C_SR1.
Practical Example: STM32 Configuration
To initialize an STM32F4 as an I2C master at 400 kHz:
// Enable I2C1 clock
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
// Configure GPIO pins (SCL: PB6, SDA: PB7 in AF4)
GPIOB->MODER |= (2 << 12) | (2 << 14); // Alternate function mode
GPIOB->AFR[0] |= (4 << 24) | (4 << 28); // AF4 for I2C
// Set timing for 400 kHz (PCLK1 = 42 MHz)
I2C1->TIMINGR = (0x1 << 28) | (0x9 << 0) | (0x3 << 8) | (0x1 << 16);
// Enable I2C peripheral
I2C1->CR1 |= I2C_CR1_PE;
Advanced Techniques
For high-speed (3.4 MHz) or multi-master systems:
- Use I2C_CR2.FREQ to synchronize clock domains across devices.
- Leverage I2C_CR1.SMBUS for packet error checking (PEC).
4.2 Writing and Reading Data
I2C data transactions follow a strict protocol where the master initiates communication by generating a start condition (S) and terminates it with a stop condition (P). Each transaction consists of an address frame followed by one or more data frames. The address frame includes a 7-bit or 10-bit slave address and a read/write (R/W) bit, while data frames contain 8-bit payloads.
Data Frame Structure
Every data frame is composed of 8 bits transmitted MSB-first, followed by an acknowledgment (ACK) or not-acknowledge (NACK) bit from the receiver. The ACK/NACK mechanism ensures reliable data transfer:
- ACK (Acknowledgment): The receiver pulls SDA low during the 9th clock pulse.
- NACK (Not Acknowledged): The receiver leaves SDA high during the 9th clock pulse.
Write Operation
To write data to a slave device, the master:
- Transmits a start condition (S).
- Sends the slave address with R/W bit set to 0 (write).
- Waits for an ACK from the slave.
- Transmits one or more data bytes, each followed by an ACK.
- Ends the transaction with a stop condition (P).
Read Operation
Reading data requires a two-phase transaction:
- The master sends the slave address with R/W=0 (write) to set the internal register pointer.
- Issues a repeated start (Sr).
- Sends the same slave address with R/W=1 (read).
- Receives data bytes, sending ACK after each byte except the last one.
- Terminates with a stop condition.
Clock Stretching and Arbitration
Slave devices may implement clock stretching by holding SCL low after detecting their address. In multi-master systems, arbitration occurs when two masters transmit simultaneously - the master transmitting a '1' while another transmits '0' loses arbitration and becomes a slave.
Error Handling
Common error conditions include:
- Bus busy timeout: Recovery after 50+ clock pulses with SDA high
- Invalid ACK position: Occurs when SDA changes during SCL high periods
- Clock synchronization: Masters must synchronize clocks during contention
Modern I2C controllers implement automatic error detection with status registers indicating:
4.3 Troubleshooting Common Issues
Signal Integrity Problems
I2C communication failures often stem from signal integrity issues, particularly in high-speed or long-distance applications. The primary concerns are:
- Rise time degradation due to excessive bus capacitance
- Reflections from impedance mismatches
- Crosstalk in parallel bus configurations
The maximum allowable bus capacitance for standard-mode (100 kHz) I2C is 400 pF. For fast-mode (400 kHz), this reduces to approximately 200 pF. The rise time (tr) can be calculated from the RC time constant:
where Rp is the pull-up resistance and Cb is the total bus capacitance. When tr exceeds 300 ns for standard mode or 120 ns for fast mode, signal integrity degrades.
Address Conflicts
Address conflicts occur when multiple devices share the same I2C address. Advanced troubleshooting techniques include:
- Using an I2C bus scanner to detect all connected devices
- Checking manufacturer documentation for alternate address options
- Implementing I2C multiplexers (e.g., PCA954x series) when address conflicts are unavoidable
Clock Stretching Issues
Clock stretching, when a slave device holds SCL low to delay communication, can cause system lockups if not properly handled. Debugging steps:
- Verify the master supports clock stretching (not all microcontroller I2C peripherals do)
- Measure SCL with an oscilloscope to detect excessive stretching durations
- Check for slave devices that may stretch the clock indefinitely during error conditions
Power Supply Considerations
Mixed-voltage I2C systems often fail due to:
- Inadequate level shifting between voltage domains
- Power sequencing problems causing bus contention
- Ground potential differences exceeding 0.4V
The minimum high-level input voltage (VIH) must satisfy:
where VDD is the supply voltage of the receiving device. For 3.3V systems, this means signals below 2.31V may not be reliably detected.
Bus Lockup Conditions
I2C bus lockups typically occur when:
- A slave device fails to release the SDA line
- Noise triggers false start/stop conditions
- The master resets during a transaction
Recovery procedures involve:
- Sending 9 clock pulses while holding SDA high
- Implementing a hardware watchdog timer
- Using bus buffers with lockup recovery circuits
Timing Violations
Advanced debugging of timing issues requires examining:
- Setup and hold times for SDA relative to SCL
- Bus free time between stop and start conditions
- Clock low period violations
The I2C specification defines critical timing parameters:
5. Multi-Master Communication
5.1 Multi-Master Communication
Multi-master I2C systems allow multiple controllers to share the same bus, enabling complex distributed architectures. Unlike single-master configurations, arbitration and synchronization mechanisms are critical to prevent data corruption during concurrent access attempts.
Arbitration Mechanism
When two or more masters initiate a transmission simultaneously, arbitration is resolved by monitoring the SDA line while SCL remains high. The master driving a logic low overrides others transmitting a high, as per wired-AND bus behavior. The losing master(s) withdraw and retry later.
Clock Synchronization
Masters with varying clock speeds synchronize by stretching the SCL low phase. The slowest device dictates the effective clock frequency through a handshake mechanism:
- Each master monitors SCL and holds it low until ready.
- The combined low period becomes the maximum of all individual low periods.
Practical Implementation Challenges
Real-world multi-master systems face:
- Bus capacitance limits: Excessive masters increase parasitic capacitance, degrading signal integrity. The total capacitance must satisfy:
- Priority handling: No inherent priority scheme exists—designers must implement application-layer protocols.
- Clock stretching timeout: Requires watchdog timers to prevent indefinite bus locks.
Case Study: Automotive Sensor Networks
Modern vehicles employ multi-master I2C for ECU communication, where:
- Critical sensors (e.g., accelerometers) act as masters during emergency events.
- Typical implementations use 10 kΩ pull-ups and 3.4 MHz clock speeds (I2C Fast-mode Plus).
5.2 Clock Stretching
Clock stretching is a mechanism in I2C communication where a slave device temporarily holds the SCL line low to delay the master's clock signal. This allows the slave to control the pace of data transfer, ensuring it has sufficient time to process received data or prepare a response. Unlike standard I2C operation, where the master exclusively controls the clock, clock stretching introduces a bidirectional dependency on SCL.
Mechanism and Timing Constraints
When a slave device needs additional time, it pulls SCL low after the master releases it (post-clock edge). The master must detect this and wait until the slave releases SCL before proceeding. The timing is governed by two critical parameters:
- Hold time (tHOLD): Minimum duration the slave must stretch SCL.
- Timeout (tTIMEOUT): Maximum allowable stretch duration before the master aborts the transaction.
Violating these constraints risks synchronization failures. For example, if tSTRETCH exceeds tTIMEOUT, the master may interpret it as a bus fault and reset the communication.
Practical Implementation
In hardware, clock stretching is typically implemented using open-drain buffers and pull-up resistors. The slave's SCL driver must:
- Monitor SCL for the master's release (rising edge).
- Assert SCL low within the I2C standard's tLOW period.
- Release SCL only after completing its internal operation (e.g., fetching data from memory).
Microcontrollers like ARM Cortex-M series handle this via hardware I2C peripherals with configurable clock stretching timeouts. For instance, the STM32 HAL library provides a parameter I2C_TIMEOUT
to enforce tTIMEOUT.
Applications and Limitations
Clock stretching is indispensable in scenarios where slave devices operate at variable speeds, such as:
- Sensor nodes with long analog-to-digital conversion times.
- EEPROMs during write cycles.
- Multi-master arbitration where slaves must synchronize conflicting requests.
However, excessive stretching degrades bus throughput. In high-speed modes (e.g., I2C at 3.4 MHz), stretching is often disabled to meet timing requirements. The I2C specification mandates that slaves must not stretch the clock during:
- Start/stop conditions.
- ACK/NACK phases.
Case Study: Clock Stretching in NXP PCA9548A
The NXP PCA9548A I2C multiplexer uses clock stretching to manage bus switching latency. When switching channels, it stretches SCL for up to 300 µs to prevent data corruption. This behavior is documented in its datasheet under tSWITCH, with a maximum stretch duration of:
Designers must account for this delay in systems with strict real-time constraints.
5.3 I2C with Interrupts and DMA
Interrupt-Driven I2C Communication
Interrupt-driven I2C communication enhances efficiency by allowing the microcontroller to perform other tasks while waiting for I2C events. Instead of polling status flags, the processor responds to interrupts triggered by events such as:
- Transmit buffer empty (TXE)
- Receive buffer not empty (RXNE)
- Stop condition detection (STOPF)
- Address match (ADDR)
- Bus error (BERR)
The interrupt service routine (ISR) must handle these events efficiently to prevent bus timeouts or missed acknowledgments. For example, in STM32 microcontrollers, enabling the I2C interrupt involves configuring the CR2 register and implementing the corresponding ISR:
// Enable I2C event and error interrupts
I2C1->CR2 |= I2C_CR2_ITEVTEN | I2C_CR2_ITERREN;
// NVIC configuration for I2C1
NVIC_EnableIRQ(I2C1_EV_IRQn);
NVIC_EnableIRQ(I2C1_ER_IRQn);
void I2C1_EV_IRQHandler(void) {
if (I2C1->SR1 & I2C_SR1_ADDR) {
// Address matched, clear ADDR flag
uint32_t temp = I2C1->SR1 | I2C1->SR2;
}
if (I2C1->SR1 & I2C_SR1_TXE) {
// Transmit buffer empty, load next byte
I2C1->DR = next_byte;
}
}
DMA-Enhanced I2C Transfers
Direct Memory Access (DMA) further optimizes I2C communication by offloading data transfers from the CPU. DMA controllers handle bulk data movement between memory and the I2C peripheral, reducing interrupt overhead and improving throughput. Key considerations include:
- DMA channel configuration for I2C TX/RX
- Circular vs. single-shot DMA modes
- Handling DMA completion interrupts
- Buffer alignment and size constraints
The following example demonstrates DMA configuration for I2C transmit operations on an STM32 platform:
// Configure DMA for I2C TX
DMA1_Channel6->CCR &= ~DMA_CCR_EN; // Disable DMA first
DMA1_Channel6->CPAR = (uint32_t)&(I2C1->DR); // Peripheral address
DMA1_Channel6->CMAR = (uint32_t)tx_buffer; // Memory address
DMA1_Channel6->CNDTR = tx_len; // Transfer count
DMA1_Channel6->CCR = DMA_CCR_DIR // Memory to peripheral
| DMA_CCR_MINC // Memory increment
| DMA_CCR_TCIE; // Transfer complete interrupt
// Enable DMA and I2C DMA requests
DMA1_Channel6->CCR |= DMA_CCR_EN;
I2C1->CR2 |= I2C_CR2_DMAEN;
Latency and Throughput Analysis
The performance improvement from interrupts and DMA can be quantified by comparing the effective data rate against polling-based implementations. The theoretical maximum throughput R for an I2C bus with clock frequency fSCL is given by:
where Nbytes is the number of bytes per transaction. However, practical implementations face additional constraints:
where τpoll represents polling overhead and τsetup includes interrupt/DMA initialization time. For a 400 kHz I2C bus transferring 64-byte packets:
Method | Throughput (kB/s) | CPU Load (%) |
---|---|---|
Polling | 28.4 | 92 |
Interrupts | 32.7 | 45 |
DMA | 38.1 | 12 |
Error Handling and Robustness
Interrupt and DMA-based I2C implementations require careful error recovery strategies. Common failure modes include:
- Bus contention leading to arbitration loss
- Clock stretching timeouts
- DMA underrun/overrun conditions
- NACK from slave devices
A robust implementation should monitor the I2C_SR1 and I2C_SR2 registers for error flags and implement appropriate recovery sequences:
void I2C1_ER_IRQHandler(void) {
if (I2C1->SR1 & I2C_SR1_AF) {
// NACK received
I2C1->SR1 &= ~I2C_SR1_AF;
i2c_recovery_sequence();
}
if (I2C1->SR1 & I2C_SR1_BERR) {
// Bus error
I2C1->SR1 &= ~I2C_SR1_BERR;
i2c_hardware_reset();
}
}
6. Official I2C Specifications
6.1 Official I2C Specifications
- PDF The I C-bus Specification Version 2.0 December 1998 — MODE I2C-BUS SPECIFICATION 19 12 FAST-MODE 19 13 Hs-MODE 20 13.1 High speed transfer 20 13.2 Serial data transfer format in Hs-mode 21 13.3 Switching from F/S- to Hs-mode and back 23 13.4Hs-mode devices at lower speed modes24 13.5 Mixed speed modes on one serial bus system 24 13.5.1 F/S-mode transfer in a mixed-speed bus system 25 13.5.2 Hs ...
- Ch-6 I2C Bus Based Serial Data Communication - Arduino Forum — I2C is called bus; because, we can connect more than one MCU/sensor in parallel (Fig-6.2). Figure-6.1: Formation of I2C bus and its connection between two Arduino. Figure-6.2: Three I2C Bus compatible sensors/devices are connected in parallel. 2. The I2C Interface has two lines: SDA (Serial Data Line) and SCL (Serial Clock Line) which form the ...
- PDF CoreI2C v6.0 Handbook - University of Michigan — communication with a SMBus Temperature Sensor slave, and an I2C slave in FPGA #2. In FPGA #2, CoreI2C is configured in Slave-only mode with CoreABC as its control. Figure 1 † CoreI2C SMBus Application Example V CC SMBus Host Controller (Master/Slave mode) SDA SCL V CC CC I2C Intelligent Device (Slave-only mode) Cortex-M1 Core I2C APB SDAO ...
- Introduction to I2C and SMBus — The Linux Kernel documentation — I2C is widely used with embedded systems. Some systems use variants that don't meet branding requirements, and so are not advertised as being I2C but come under different names, e.g. TWI (Two Wire Interface), IIC. The latest official I2C specification is the "I2C-bus specification and user manual" (UM10204) published by NXP Semiconductors ...
- PDF THE I2C-BUS SPECIFICATION VERSION 2.1 JANUARY 2000 - uoc.gr — The I2C-bus specification 1 PREFACE 1.1 Version 1.0 - 1992 This version of the 1992 I 2C-bus specification includes the following modifications: •Programming of a slave address by software has been omitted. The realization of this feature is rather complicated and has not been used. •The "low-speed mode" has been omitted. This mode is,
- PDF Specification of I2C Driver - autosar.org — Specification of I2C Driver AUTOSAR CP R24-11 5 Dependencies to other modules The I2C Driver module does not take care of setting the registers which configure the clock, prescaler(s) and PLL in its init function. This has to be done by the MCU module [3]. Note: I2C peripherals may depend on the system clock, prescaler(s) and PLL. Thus,
- UM10204 I2C-bus specification and user manual - FlipHTML5 — NXP Semiconductors UM10204 I2C-bus specification and user manual 5.3.1 High speed transfer To achieve a bit transfer of up to 3.4 Mbit/s the following improvements have been made to the regular I2C-bus specification: • Hs-mode master devices have an open-drain output buffer for the SDAH signal and a combination of an open-drain pull-down and ...
- PDF A Basic Guide to I2C - Texas Instruments — Communication between microcontrollers and different peripheral devices require some sort of digital protocol. I2C is a common communication protocol that is used in a variety of devices from many different product families produced by TI. This application note begins with a basic overview of the I2C protocol, describing the history
- 5.1.7.6. I2C Interface Design Guidelines — GUIDELINE: Instantiate the open-drain buffer when routing I 2 C signals through the FPGA fabric.. When routing I 2 C signals through the FPGA, note that the I 2 C pins from the HPS to the FPGA fabric (i2c*_out_data, i2c*_out_clk) are not open-drain and are logic level inverted.Thus, to drive a logic level zero onto the I 2 C bus, drive the corresponding pin high.
- PDF The I C-bus and how to use it (including specifications) — these criteria are involved in the specification of the I 2C-bus. 3.0 THE I2C-BUS CONCEPT The I2C-bus supports any IC fabrication process (NMOS, CMOS, bipolar). Two wires, serial data (SDA) and serial clock (SCL), carry information between the devices connected to the bus. Each device is recognised by a unique address — whether it's a ...
6.2 Recommended Books and Articles
- PDF ROCKCHIP I2C Developer Guide — 6.2.2.2 Case 2 6.2.2.3 Case 3 6.3 I2C waveform. 1. I2C flow ... protocol is exceeded, the I2C communication may fail. The following is the maximum and minimum value ... GPIO method is generally not recommended due to low efficient. 6. I2C FAQ Because we have two i2c drivers, so this chapter still have two parts: i2c@4
- The Book of I2C - O'Reilly Media — 2.6 Resetting the I2C Bus; 2.7 Detecting I2C Peripherals on the Bus; 2.8 Creating Custom Devices; 2.9 Chapter Summary; Chapter 3: A Software Implementation of the I2C Bus. 3.1 A Software I2C Implementation on the Teensy 3.2. 3.1.1 A Software-Based I2C Controller for the Teensy 3.2; 3.1.2 A Software-Based I2C Peripheral for the Teensy 3.2
- The Book of I²C: A Guide for Adventurers » Let Me Read — 1.6 I2C Bus Speeds 1.7 Multicontroller I2C Bus Clock Synchronization 1.8 Multicontroller I2C Bus Arbitration 1.9 Clock Stretching 1.10 Cross Talk 1.11 Chapter Summary Chapter 2: I2C Protocol 2.1 Data on the I2C Bus 2.2 I2C Addresses and Read/Write Control 2.3 Repeated Start Conditions 2.4 Clock Stretching 2.5 Special Addresses 2.5.1 The General ...
- PDF Inter-Integrated Circuit Module (I2C) - University of Illinois Urbana ... — the multi-master mode, in which one or more devices capable of controlling an I2C bus can be connected to the same I2C bus. For data communication, the I2C module has a serial data pin (SDA) and a serial clock pin (SCL), as shown in Section 20.6. These two pins carry information between the 28x device and other devices connected to the I2C bus.
- I2CSec: A secure serial Chip-to-Chip communication protocol — This standard IP core is in charge of I2C communication and is connected to the main processor through a PLB bus. 3. ... Recommended articles. References [1] D.D. Hwang, P. Schaumont, ... Since 2001 he is Assistant Lecturer in electronic technology at the Electronics and Telecommunications Department of the University of the Basque Country. His ...
- Serial Communication: SPI and I2C - SpringerLink — This chapter deals with two types of serial communication Inter-Integrated Circuit (I2C) and Serial Peripheral Interface (SPI). Already, one serial communication protocol UART is discussed earlier in Chap. 12. These two peripherals give access to control various features.
- PDF The I 2 C-bus and how to use it (including specifications) — April 1995 3-6 2.0 INTRODUCTION TO THE I2C-BUS SPECIFICATION For 8-bit digital control applications, such as those requiring microcontrollers, certain design criteria can be established: •A complete system usually consists of at least one microcontroller and other peripheral devices such as memories and I/O expanders
- PDF A Basic Guide to I2C - Texas Instruments — Communication between microcontrollers and different peripheral devices require some sort of digital protocol. I2C is a common communication protocol that is used in a variety of devices from many different product families produced by TI. This application note begins with a basic overview of the I2C protocol, describing the history
- PDF The Art of Electronics — Widely accepted as the best single authoritative text and reference on electronic circuit design, both analog and digital, the first two editions were translated into eight languages, and sold more than a million copies ... He is the author of some 200 scientific articles and reports, has consulted widely for industry and government, ...
- Aardvark I2C/SPI Host Adapter User Manual - Total Phase — Hence, the aa_i2c_write function cannot provide the caller with the information that the 10th byte was ACK'ed or NACK'ed. On the other hand, if the aa_i2c_write_ext is used, the status code will distinguish the two scenarios. This status information could be useful for further communications with that particular slave device.
6.3 Online Resources and Tutorials
- The Book of I2C - O'Reilly Media — Chapter 3: A Software Implementation of the I2C Bus. 3.1 A Software I2C Implementation on the Teensy 3.2. 3.1.1 A Software-Based I2C Controller for the Teensy 3.2; 3.1.2 A Software-Based I2C Peripheral for the Teensy 3.2; 3.1.3 Some Final Comments on the Teensy 3.2 Software I2C Code; 3.2 Basic ATtiny84 and ATtiny85 Hardware
- APDS-9960 RGB and Gesture Sensor Hookup Guide - SparkFun Learn — Arduino Pin APDS-9960 Board Function 3.3V VCC Power GND GND Ground A4 SDA I2C Data A5 SCL I2C Clock 2 INT Interrupt Resources: Include Wire.h and SparkFun_APDS-9960.h Development environment specifics: Written in Arduino 1.0.5 Tested with SparkFun Arduino Pro Mini 3.3V This code is beerware; if you see me (or any other SparkFun employee) at the ...
- I²C Framework Module Guide - Renesas Electronics Corporation — the References section at the end of this document) and should be valuable resources for creating more complex designs. The I2C Framework module provides a ThreadX®-aware high-level API for I2C industry standard serial device communications and configures the I2C peripheral in order to enable serial communication to be used by the framework.
- PDF FT602 I2C User Guide - FTDI — The I2C slave address to be used for this communication is set via the configuration programmer. The I2C slave (e.g. FPGA or FIFO Master) shall implement the registers described in the next sections. ... AN_437 FT602_I2C_User Guide Version 1.0 Document Reference No.: FT_001416 Clearance No.: FTDI#537 12
- 6.1. CSL — Processor SDK RTOS Documentation - Texas Instruments — 6.3.1.1. Driver Overview¶ PDK USB driver (USB LLD) provides the following USB class/functions while isolating application from the complexity of low level USB and USB class protocols: ... Starting link training... * * PCIe Test Start * * EP mode * * Version #: 0x02020003; string PCIE LLD Revision: 02.02.00.03:Dec 24 2015:17:38:37 PCIe ...
- I2C Bus Master - Lattice Semi — This reference design demonstrates how a fast and configurable I2C-Bus Master Controller can be constructed and utilized in a Lattice CPLD/FPGA device. With the flexibility that this I2C-Bus Master Controller offers, a designer can communicate with up to 128 different I2C slave devices operating in standard or fast mode with transactions ...
- PDF A Basic Guide to I2C - Texas Instruments — Communication between microcontrollers and different peripheral devices require some sort of digital protocol. I2C is a common communication protocol that is used in a variety of devices from many different product families produced by TI. This application note begins with a basic overview of the I2C protocol, describing the history
- Aardvark I2C/SPI Host Adapter User Manual - Total Phase — Hence, the aa_i2c_write function cannot provide the caller with the information that the 10th byte was ACK'ed or NACK'ed. On the other hand, if the aa_i2c_write_ext is used, the status code will distinguish the two scenarios. This status information could be useful for further communications with that particular slave device.
- Raspberry Pi SPI and I2C Tutorial - SparkFun Learn — Background & Software Setup. The Raspberry Pi has three types of serial interface on the GPIO header. You're probably already familiar with the UART serial port, which allows you to open a login session from a serial terminal application, such as PuTTY.. The other two serial interfaces are the Serial Peripheral Interface (SPI) and Inter-Integrated-Circuit bus (I2C).
- Getting Started With C2000 Real-Time Control Microcontrollers (MCUs ... — power electronics and provide advanced digital signal processing for industrial and automotive applications. With more than 25 years of experience in developing microcontrollers optimized for simple real-time control, C2000 enables engineers to quickly create the world's most efficient power conversion and motor drive solutions.