差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录 前一修订版
后一修订版
前一修订版
i2c [2016/05/30 13:14]
gongyu [External links]
i2c [2021/09/13 23:31] (当前版本)
gongyu
行 1: 行 1:
-I²C (Inter-Integrated Circuit), pronounced I-squared-C,​ is a multi-master,​ multi-slave,​ single-ended,​ serial computer bus invented by Philips Semiconductor (now NXP Semiconductors). It is typically used for attaching lower-speed peripheral ICs to processors and microcontrollers in short-distance,​ intra-board communication. Alternatively I²C is spelled ​I2C (pronounced I-two-C) or IIC (pronounced I-I-C).+## I2C - 集成电路之间的同步、半双工数据传输
  
-Since October 10, 2006, no licensing fees are required to implement the I²C protocolHowever, fees are still required to obtain I²C slave addresses allocated by NXP.+I2C是一种简单地连接多个芯片的总线方式,尤其是在[[FPGA]]s/​[[CPLD]]s中. 
 +{{ ::i2cslave.gif |}}
  
-Several competitors,​ such as Siemens AG (later Infineon Technologies AG, now Intel mobile communications),​ NEC, Texas Instruments,​ STMicroelectronics (formerly SGS-Thomson),​ Motorola (later Freescale, now merged with NXP), Nordic Semiconductor and Intersil, have introduced compatible I²C products to the market since the mid-1990s.+### I2C总线特性
  
-SMBusdefined by Intel in 1995is a subset of I²C that defines the protocol use more strictly. One purpose of SMBus is to promote robustness and interoperability. Accordingly,​ modern I²C systems incorporate some policies and rules from SMBus, sometimes supporting both I²C and SMBus, requiring only minimal reconfiguration either by commanding or output pin use.+  * 除了“电源”和“地”之外,只用了"​SDA"​和"​SCL"​两根信号线 
 +  * 在同一个总线上最多可以支持到100个器件,每个挂在总线的器件都有一个地址用于寻址 
 +  * 多个“主”设备(例如,两个[[CPU]]可以简单地共用同一个I2C器件) 
 +  * 为业界标准,由Philips开发被很多其它厂商采用 
 +  * 用途非常广泛,比如电视机、PCs
  
-====Revisions==== +但是: 
-The history of I²C specification releases: +  ​* 速度相对比较慢(100Kbps基础速率,可以扩展到3.4Mbps
-  ​- In 1982, the original 100 kHz I²C system was created as a simple internal bus system for building control electronics with various Philips chips. +  ​* 不支持“即插即用”
-  - In 1992, Version 1 added 400 kHz Fast-mode ​(Fm) and a 10-bit addressing mode to increase capacity to 1008 nodes. This was the first standardized version. +
-  - In 1998Version 2 added 3.4 MHz High-speed mode (Hswith power-saving requirements for electric voltage and current. +
-  ​- In 2000, Version 2.1 introduced a minor cleanup of version 2. +
-  - In 2007, Version 3 added 1 MHz Fast-mode plus (Fm+), and a device ID mechanism. +
-  - In 2012, Version 4 added 5 MHz Ultra Fast-mode (UFm) for new USDA and USCL lines using push-pull logic without pull-up resistors, and added assigned manufacturer ID table. +
-  - In 2012, Version 5 corrected mistakes. +
-  - In 2014, Version 6 corrected two graphs. This is the most recent standard.+
  
-====Design==== 
-A sample schematic with one master (a microcontroller),​ three slave nodes (an ADC, a DAC, and a microcontroller),​ and pull-up resistors Rp 
-I²C uses only two bidirectional open-drain lines, Serial Data Line (SDA) and Serial Clock Line (SCL), pulled up with resistors. Typical voltages used are +5 V or +3.3 V although systems with other voltages are permitted. 
  
-The I²C reference design has a 7-bit or a 10-bit (depending on the device used) address space. Common I²C bus speeds are the 100 kbit/s standard mode and the 10 kbit/s low-speed mode, but arbitrarily low clock frequencies are also allowed. Recent revisions of I²C can host more nodes and run at faster speeds (400 kbit/s Fast mode, 1 Mbit/s Fast mode plus or Fm+, and 3.4 Mbit/s High Speed mode). These speeds are more widely used on embedded systems than on PCs. There are also other features, such as 16-bit addressing.+一个I2C总线需要至少一个I2C主和I2C从. 
 +I2C“主”即可以向“从”写也可以从“从”设备中读取
  
-Note the bit rates are quoted for the transactions between master and slave without clock stretching or other hardware overhead. Protocol overheads include a slave address and perhaps a register address within the slave device as well as per-byte ACK/NACK bits. Thus the actual transfer rate of user data is lower than those peak bit rates alone would imply. For example, if each interaction with a slave inefficiently allows only 1 byte of data to be transferred,​ the data rate will be less than half the peak bit rate.+#### I2C波形 ​
  
-The maximum number of nodes is limited by the address space, and also by the total bus capacitance of 400 pF, which restricts practical communication distances to a few meters. The relatively high impedance and low noise immunity requires a common ground potential, which again restricts practical use to communication within the same PC board or small system of boards.+这个图示为向地址为0x51的EEPROM进行写2个字节的数据0x50和0x0F.
  
-====参考设计==== + ​{{ ​::i2c_writetoeeprom.gif |initiator}}
-The before mentioned reference design is a bus with a clock (SCL) and data (SDA) lines with 7-bit addressing. The bus has two roles for nodesmaster and slave:+
  
-Master node — node that generates the clock and initiates communication with slaves +一个I2C过程由"​起始"​开始接着是我们要通信的设备的地址,有一位标记此操作是“读”还是“写”;要读取或写入的“数据”,最后是个“终止”位。
-Slave node — node that receives the clock and responds when addressed by the master +
-The bus is a multi-master bus which means any number of master nodes can be present. Additionallymaster and slave roles may be changed between messages (after a STOP is sent).+
  
-There may be four potential modes of operation for a given bus device, although most devices only use a single role and its two modes:+还有其它的一些细节,比如在每个字节传输以后需要一个”应答“位,参看波形图。
  
-master transmit — master node is sending data to a slave +在FPGA或CPLD中有两种方式创建一个I2C从功能: 
-master receive — master node is receiving data from a slave +  * 直接使用你FPGA/CPLD中的SCL信号线作为时钟信号 
-slave transmit — slave node is sending data to the master +  * 使用更快的时钟信号过取样你的SDA和SCL信号
-slave receive — slave node is receiving data from the master +
-The master is initially in master transmit mode by sending a start bit followed by the 7-bit address of the slave it wishes to communicate with, which is finally followed by a single bit representing whether it wishes to write(0) to or read(1) from the slave.+
  
-If the slave exists on the bus then it will respond with an ACK bit (active low for acknowledged) for that address. The master then continues in either transmit or receive mode (according to the read/write bit it sent), and the slave continues in its complementary mode (receive or transmit, respectively).+第一种方法设计比较紧凑,但不如第二种方法可靠,在这里我们简单讲一下第一种方法的实现过程。
  
-The address and the data bytes are sent most significant bit first. The start bit is indicated by a high-to-low transition of SDA with SCL high; the stop bit is indicated by a low-to-high transition of SDA with SCL high. All other transitions of SDA take place with SCL low.+目标:通过I2C进行IO端口扩展,SCL在FPGA/CPLD中作为时钟信号
  
-If the master wishes to write to the slave then it repeatedly sends a byte with the slave sending an ACK bit. (In this situation, the master is in master transmit mode and the slave is in slave receive mode.) 
  
-If the master wishes to read from the slave then it repeatedly receives a byte from the slave, the master sending an ACK bit after every byte but the last one(In this situation, the master is in master receive mode and the slave is in slave transmit mode.)+{{ ::i2cslave.gif |}}
  
-The master then either ends transmission with a stop bit, or it may send another START bit if it wishes to retain control of the bus for another transfer (a "​combined message"​).+I2C从模块连接到一个小的8位存储器,这个存储器可以通过I2C总线进行读写,这8位为FPGA/CPLD的外部连线,这样就实现了一个I2C的IO端口扩展
  
-====Message protocols==== +第一步,先定义模块 
-I²C defines basic types of messageseach of which begins with a START and ends with a STOP: +<code verilog>​ 
-Single message where a master writes data to a slave+module I2CslaveWith8bitsIO(SDASCL, IOout); 
-Single message where a master reads data from a slave+inout SDA
-Combined messages, where a master issues at least two reads and/or writes to one or more slaves. +input SCL
-In a combined message, each read or write begins with a START and the slave address. After the first START in a combined message these are also called repeated START bits. Repeated START bits are not preceded by STOP bits, which is how slaves know the next transfer is part of the same message.+output [7:0] IOout; 
 +</​code>​
  
-Any given slave will only respond to certain messages, as specified in its product documentation.+接着是我们需要的I2C“从”设备的7位地址
  
-Pure I²C systems support arbitrary message structures. SMBus is restricted to nine of those structures, such as read word N and write word N, involving a single slave. PMBus extends SMBus with a Group protocol, allowing multiple such SMBus transactions to be sent in one combined message. The terminating STOP indicates when those grouped actions should take effect. For example, one PMBus operation might reconfigure three power supplies (using three different I2C slave addresses), and their new configurations would take effect at the same time: when they receive that STOP.+<code verilog>​ 
 +parameter I2C_ADR = 7'​h27;​ 
 +</​code>​
  
-With only a few exceptions, neither I²C nor SMBus define message semantics, such as the meaning of data bytes in messages. Message semantics are otherwise product-specific. Those exceptions include messages addressed to the I²C general call address (0x00) or to the SMBus Alert Response Address; and messages involved in the SMBus Address Resolution Protocol (ARP) for dynamic address allocation and management.+接着是“起始”和“终止”检测逻辑,这也是本设计中最神秘的部分。
  
-In practice, most slaves adopt request/response control models, where one or more bytes following ​write command are treated as a command or address. Those bytes determine how subsequent written bytes are treated ​and/or how the slave responds on subsequent readsMost SMBus operations involve single byte commands.+<code verilog>​ 
 +// We use two wires with combinatorial loop to detect the start and stop conditions 
 +//  ​... making sure these two wires don't get optimized away 
 +wire SDA_shadow ​   /* synthesis keep = 1 */; 
 +wire start_or_stop /* synthesis keep = 1 */; 
 +assign SDA_shadow = (~SCL | start_or_stop) ? SDA : SDA_shadow;​ 
 +assign start_or_stop = ~SCL ? 1'b0 : (SDA ^ SDA_shadow);​
  
-Messaging example: 24c32 EEPROM[edit] +reg incycle; 
-One specific example is the 24c32 type EEPROM, which uses two request bytes that are called Address High and Address Low. (Accordingly,​ these EEPROMs are not usable by pure SMBus hosts, which only support single byte commands ​or addresses.These bytes are used to address bytes within the 32 kbit (4 kBsupported by that EEPROMthe same two byte addressing is also used by larger EEPROMs, such as 24c512 ones storing 512 kbits (64 kB). Writing and reading data to these EEPROMs uses a simple protocol: the address is written, and then data is transferred until the end of the message. (That data transfer part of the protocol also makes trouble for SMBus, since the data bytes are not preceded by a count and more than 32 bytes can be transferred at once. I²C EEPROMs smaller than 32 kbits, such as 2 kbit 24c02 ones, are often used on SMBus with inefficient single byte data transfers.)+always @(negedge SCL or posedge start_or_stop) 
 +if(start_or_stopincycle <= 1'b0else if(~SDAincycle <= 1'​b1;​ 
 +</​code>​
  
-A single message writes to the EEPROM. After the START, the master sends the chip's bus address with the direction bit clear (write), then sends the two byte address of data within the EEPROM and then sends data bytes to be written starting at that address, followed by a STOP. When writing multiple bytes, all the bytes must be in the same 32 byte page. While it is busy saving those bytes to memory, the EEPROM will not respond to further I²C requests. (That is another incompatibility with SMBus: SMBus devices must always respond to their bus addresses.)+现在我们可以计数进来的I2C的位数。
  
-To read starting at a particular address in the EEPROM, a combined message is used. After a START, the master ​first writes that chip's bus address with the direction ​bit clear (write) and then the two bytes of EEPROM data address. It then sends a (repeated) START and the EEPROM'​s bus address with the direction ​bit set (read). The EEPROM will then respond with the data bytes beginning at the specified EEPROM data address -— a combined message, first a write then a read. The master issues an ACK after each read byte except the last byte, and then issues a STOP. The EEPROM increments the address after each data byte transferredmulti-byte reads can retrieve the entire contents of the EEPROM using one combined message...+<code verilog>​ 
 +reg [3:0] bitcnt; ​ // counts ​the I2C bits from 7 downto 0plus an ACK bit 
 +wire bit_DATA = ~bitcnt[3]; ​ // the DATA bits are the first 8 bits sent 
 +wire bit_ACK = bitcnt[3]; ​ // the ACK bit is the 9th bit sent 
 +reg data_phase;
  
-===Physical layer==+always @(negedge SCL or negedge incycle) 
-At the physical layer, both SCL and SDA lines are of open-drain design, thus, pull-up resistors are needed. Pulling the line to ground is considered a logical zero while letting the line float is a logical one. This is used as a channel access method. High speed systems (and some others) also add a current source pull up, at least on SCLthis accommodates higher bus capacitance and enables faster rise times.+if(~incycle) 
 +begin 
 +    bitcnt <4'​h7; ​ // the bit 7 is received first 
 +    data_phase <0; 
 +end 
 +else 
 +begin 
 +    if(bit_ACK) 
 +    begin 
 +    bitcnt <4'​h7;​ 
 +    data_phase <1; 
 +    end 
 +    else 
 +    bitcnt <= bitcnt ​4'h1; 
 +end 
 +</​code>​
  
-An important consequence of this is that multiple nodes may be driving the lines simultaneously. If any node is driving the line low, it will be low. Nodes that are trying to transmit a logical one (i.e. letting the line float high) can see this, and thereby know that another node is active at the same time.+并且检测I2C的地址是否匹配
  
-When used on SCLthis is called clock stretching and gives slaves a flow control mechanism. When used on SDAthis is called arbitration and ensures there is only one transmitter at a time.+<code verilog>​ 
 +wire adr_phase = ~data_phase;​ 
 +reg adr_matchop_readgot_ACK; 
 +// sample SDA on posedge since the I2C spec specifies as low as 0µs hold-time on negedge 
 +reg SDAr;  always @(posedge SCL) SDAr<​=SDA;​ 
 +reg [7:0] mem; 
 +wire op_write = ~op_read;
  
-When idle, both lines are high. To start a transaction,​ SDA is pulled low while SCL remains high. Releasing SDA to float high again would be a stop marker, signaling ​the end of a bus transaction. Although legal, this is typically pointless immediately after start, so the next step is to pull SCL low.+always @(negedge ​SCL or negedge incycle) 
 +if(~incycle) 
 +begin 
 +    got_ACK <= 0; 
 +    adr_match <= 1; 
 +    op_read <= 0; 
 +end 
 +else 
 +begin 
 +    if(adr_phase & bitcnt==7 & SDAr!=I2C_ADR[6]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==6 & SDAr!=I2C_ADR[5]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==5 & SDAr!=I2C_ADR[4]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==4 & SDAr!=I2C_ADR[3]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==3 & SDAr!=I2C_ADR[2]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==2 & SDAr!=I2C_ADR[1]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==1 & SDAr!=I2C_ADR[0]) adr_match<​=0;​ 
 +    if(adr_phase & bitcnt==0) op_read <= SDAr; 
 +    // we monitor the ACK to be able to free the bus when the master doesn'​t ACK during ​read operation 
 +    if(bit_ACK) got_ACK <= ~SDAr;
  
-Except for the start and stop signals, the SDA line only changes while the clock is lowtransmitting a data bit consists of pulsing the clock line high while holding the data line steady at the desired level.+    if(adr_match & bit_DATA & data_phase & op_write) mem[bitcnt] <= SDAr // memory write 
 +end 
 +</​code>​
  
-While SCL is low, the transmitter (initially the master) sets SDA to the desired value and (after a small delay to let the value propagate) lets SCL float high. The master then waits for SCL to actually go high; this will be delayed by the finite rise-time of the SCL signal (the RC time constant of the pull-up resistor and the parasitic capacitance of the bus), and may be additionally delayed by a slave'​s clock stretching.+如有需要驱动=SDA信号线
  
-Once SCL is high, the master waits a minimum time (4 μs for standard speed I²C) to ensure the receiver has seen the bit, then pulls it low again. This completes transmission of one bit.+<code verilog>
  
-After every 8 data bits in one direction, an "​acknowledge"​ bit is transmitted in the other direction. The transmitter and receiver switch roles for one bit, and the original receiver transmits a single ​bit (ACKback. If the transmitter sees a bit (NACK) instead, it learns that:+wire mem_bit_low = ~mem[bitcnt[2:​0]]; 
 +wire SDA_assert_low = adr_match & bit_DATA & data_phase & op_read & mem_bit_low & got_ACK; 
 +wire SDA_assert_ACK = adr_match & bit_ACK & (adr_phase | op_write)
 +wire SDA_low = SDA_assert_low | SDA_assert_ACK;​ 
 +assign SDA = SDA_low ? 1'​b0 ​1'bz;
  
-(If master transmitting to slave) The slave is unable to accept the data. No such slave, command not understood, or unable to accept any more data. +assign IOout mem
-(If slave transmitting to master) The master wishes the transfer to stop after this data byte. +endmodule
-During the acknowledgment,​ SCL is always controlled by the master. +
- +
-After the acknowledge bit, the master may do one of three things: +
- +
-Prepare to transfer another byte of data: the transmitter set SDA, and the master pulses SCL high. +
-Send a "​Stop":​ Set SDA low, let SCL go high, then let SDA go high. This releases the I²C bus. +
-Send a "​Repeated start":​ Set SDA high, let SCL go high, and pull SDA low again. This starts a new I²C bus transaction without releasing the bus. +
-Clock stretching using SCL[edit] +
-One of the more significant features of the I²C protocol is clock stretching. An addressed slave device may hold the clock line (SCL) low after receiving (or sending) a byte, indicating that it is not yet ready to process more data. The master that is communicating with the slave may not finish the transmission of the current bit, but must wait until the clock line actually goes high. If the slave is clock stretching, the clock line will still be low (because the connections are open-drain). The same is true if a second, slower, master tries to drive the clock at the same time. (If there is more than one master, all but one of them will normally lose arbitration.) +
- +
-The master must wait until it observes the clock line going high, and an additional minimum time (4 μs for standard 100 kbit/s I²C) before pulling the clock low again. +
- +
-Although the master may also hold the SCL line low for as long as it desires (this is not allowed in newest Rev. 6 of the protocol - subsection 3.1,1), the term "clock stretching"​ is normally used only when slaves do it. Although in theory any clock pulse may be stretched, generally it is the intervals before or after the acknowledgment bit which are used. For example, if the slave is a microcontroller,​ its I²C interface could stretch the clock after each byte, until the software decides whether to send a positive acknowledgment or a NACK. +
- +
-Clock stretching is the only time in I²C where the slave drives SCL. Many slaves do not need to clock stretch and thus treat SCL as strictly an input with no circuitry to drive it. Some masters, such as those found inside custom ASICs may not support clock stretching; often these devices will be labeled as a "​two-wire interface"​ and not I²C. +
- +
-To ensure a minimum bus throughput, SMBus places limits on how far clocks may be stretched. Hosts and slaves adhering to those limits cannot block access to the bus for more than a short time, which is not a guarantee made by pure I²C systems. +
- +
-Arbitration using SDA[edit] +
-Every master monitors the bus for start and stop bits, and does not start a message while another master is keeping the bus busy. However, two masters may start transmission at about the same time; in this case, arbitration occurs. Slave transmit mode can also be arbitrated, when a master addresses multiple slaves, but this is less common. In contrast to protocols (such as Ethernet) that use random back-off delays before issuing a retry, I²C has a deterministic arbitration policy. Each transmitter checks the level of the data line (SDA) and compares it with the levels it expects; if they do not match, that transmitter has lost arbitration,​ and drops out of this protocol interaction. +
- +
-If one transmitter sets SDA to 1 (not driving a signal) and a second transmitter sets it to 0 (pull to ground), the result is that the line is low. The first transmitter then observes that the level of the line is different from that expected, and concludes that another node is transmitting. The first node to notice such a difference is the one that loses arbitration:​ it stops driving SDA. If it's a master, it also stops driving SCL and waits for a STOP; then it may try to reissue its entire message. In the meantime, the other node has not noticed any difference between the expected and actual levels on SDA, and therefore continues transmission. It can do so without problems because so far the signal has been exactly as it expected; no other transmitter has disturbed its message. +
- +
-If the two masters are sending a message to two different slaves, the one sending the lower slave address always "​wins"​ arbitration in the address stage. Since the two masters may send messages to the same slave address—and addresses sometimes refer to multiple slaves—arbitration must continue into the data stages. +
- +
-Arbitration occurs very rarely, but is necessary for proper multi-master support. As with clock-stretching,​ not all devices support arbitration. Those that do generally label themselves as supporting "​multi-master"​ communication. +
- +
-In the extremely rare case that two masters simultaneously send identical messages, both will regard the communication as successful, but the slave will only see one message. Slaves that can be accessed by multiple masters must have commands that are idempotent for this reason. +
- +
-Arbitration in SMBus[edit] +
-While I²C only arbitrates between masters, SMBus uses arbitration in three additional contexts, where multiple slaves respond to the master, and one gets its message through. +
- +
-Although conceptually a single-master bus, a slave device that supports the "host notify protocol"​ acts as a master to perform the notification. It seizes the bus and writes a 3-byte message to the reserved "SMBus Host" address (0x08), passing its address and two bytes of data. When two slaves try to notify the host at the same time, one of them will lose arbitration and need to retry. +
-An alternative slave notification system uses the separate SMBALERT# signal to request attention. In this case, the host performs a 1-byte read from the reserved "SMBus Alert Response Address"​ (0x0c), which is a kind of broadcast address. All alerting slaves respond with a data bytes containing their own address. When the slave successfully transmits its own address (winning arbitration against others) it stops raising that interrupt. In both this and the preceding case, arbitration ensures that one slave'​s message will be received, and the others will know they must retry. +
-SMBus also supports an "​address resolution protocol",​ wherein devices return a 16-byte "​universal device ID" (UDID). Multiple devices may respond; the one with the lowest UDID will win arbitration and be recognized. +
-Circuit interconnections[edit] +
-I²C is popular for interfacing peripheral circuits to prototyping systems, such as the Arduino and Raspberry Pi. I²C does not employ a standardized connector, however, and board designers have created various wiring schemes for I²C interconnections. To minimize the possible damage due to plugging 0.1-inch headers in backwards, some developers have suggested using alternating signal and power connections of the following wiring schemes: (GND, SCL, VCC, SDA) or (VCC, SDA, GND, SCL).[5] +
- +
-Buffering and multiplexing[edit] +
-When there are many I²C devices in a system, there can be a need to include bus buffers or multiplexers to split large bus segments into smaller ones. This can be necessary to keep the capacitance of a bus segment below the allowable value or to allow multiple devices with the same address to be separated by a multiplexer. Many types of multiplexers and buffers exist and all must take into account the fact that I²C lines are specified to be bidirectional. Multiplexers can be implemented with analog switches which can tie one segment to another. Analog switches maintain the bidirectional nature of the lines but do not isolate the capacitance of one segment from another or provide buffering capability. +
- +
-Buffers can be used to isolate capacitance on one segment from another and/or allow I²C to be sent over longer cables or traces. Buffers for bi-directional lines such as I²C must use one of several schemes for preventing latch-up. I²C is open-drain so buffers must drive a low on one side when they see a low on the other. One method for preventing latch-up is for a buffer to have carefully selected input and output levels such that the output level of its driver is higher than its input threshold, preventing it from triggering itself. For example, a buffer may have an input threshold of 0.4 V for detecting a low, but an output low level of 0.5 V. This method requires that all other devices on the bus have thresholds which are compatible and often means that multiple buffers implementing this scheme cannot be put in series with one another. +
- +
-Alternatively,​ other types of buffers exist that implement current amplifiers, or keep track of the state (i.e. which side drove the bus low) to prevent latch-up. The state method typically means that an unintended pulse is created during a hand-off when one side is driving the bus low, then the other drives it low, then the first side releases (this is common during an I²C acknowledgement). +
- +
-Timing diagram[edit] +
-Data transfer sequence +
-Data Transfer is initiated with a START bit (S) signaled by SDA being pulled low while SCL stays high. +
-SDA sets the 1st data bit level while keeping SCL low (during blue bar time.) +
-The data is sampled (received) when SCL rises (green) for the first bit (B1). +
-This process repeats, SDA transitioning while SCL is low, and the data being read while SCL is high (B2, Bn). +
-A STOP bit (P) is signaled when SDA is pulled high while SCL is high. +
-In order to avoid false marker detection, SDA is changed on the SCL falling edge and is sampled and captured on the rising edge of SCL. +
- +
-Example of bit-banging the I²C Master protocol[edit] +
-Below is an example of bit-banging the I²C protocol as an I²C master. The example is written in pseudo C. It illustrates all of the I²C features described before (clock stretching, arbitration,​ start/stop bit, ack/nack) +
- +
-<code c> +
-// Hardware-specific support functions that MUST be customized:​ +
-#define I2CSPEED 100 +
-void I2C_delay( void ); +
-bool read_SCL( void ); // Set SCL as input and return current level of line, 0 or 1 +
-bool read_SDA( void ); // Set SDA as input and return current level of line, 0 or 1 +
-void set_SCL( void ); // Actively drive SCL signal high +
-void clear_SCL( void ); // Actively drive SCL signal low +
-void set_SDA( void ); // Actively drive SDA signal high +
-void clear_SDA( void ); // Actively drive SDA signal low +
-void arbitration_lost( void ); +
- +
-bool started ​false// global data +
- +
-void i2c_start_cond( void )  +
-+
-  if( started )  +
-  {  +
-    // if started, do a restart cond +
-    // set SDA to 1 +
-    set_SDA();​ +
-    I2C_delay();​ +
- +
-    while( read_SCL() == 0 )  +
-    {  // Clock stretching +
-      // You should add timeout to this loop +
-    } +
- +
-    // Repeated start setup time, minimum 4.7us +
-    I2C_delay();​ +
- +
-  } +
- +
-  if( read_SDA() == 0 )  +
-  { +
-    arbitration_lost();​ +
-  } +
- +
-  // SCL is high, set SDA from 1 to 0. +
-  clear_SDA();​ +
-  I2C_delay();​ +
-  clear_SCL();​ +
-  started = true; +
- +
-+
- +
-void i2c_stop_cond( void ) +
-+
-  // set SDA to 0 +
-  clear_SDA();​ +
-  I2C_delay();​ +
- +
-  // Clock stretching +
-  while( read_SCL() == 0 )  +
-  { +
-    // add timeout to this loop. +
-  } +
- +
-  // Stop bit setup time, minimum 4us +
-  I2C_delay();​ +
- +
-  // SCL is high, set SDA from 0 to 1 +
-  set_SDA();​ +
-  I2C_delay();​ +
- +
-  if( read_SDA() == 0 )  +
-  { +
-    arbitration_lost();​ +
-  } +
- +
-  I2C_delay();​ +
-  started = false; +
- +
-+
- +
-// Write a bit to I2C bus +
-void i2c_write_bit( bool bit )  +
-+
-  if( bit )  +
-  { +
-    set_SDA();​ +
-  }  +
-  else  +
-  { +
-    clear_SDA();​ +
-  } +
- +
-  // SDA change propagation delay +
-  I2C_delay(); ​  +
- +
-  // Set SCL high to indicate a new valid SDA value is available +
-  set_SCL();​ +
- +
-  // Wait for SDA value to be read by slave, minimum of 4us for standard mode +
-  I2C_delay();​ +
- +
-  while( read_SCL() == 0 )  +
-  { // Clock stretching +
-    // You should add timeout to this loop +
-  } +
- +
-  // SCL is high, now data is valid +
-  // If SDA is high, check that nobody else is driving SDA +
-  if( bit && ( read_SDA() == 0 ) ) +
-  { +
-    arbitration_lost();​ +
-  } +
- +
-  // Clear the SCL to low in preparation for next change +
-  clear_SCL();​ +
-+
- +
-// Read a bit from I2C bus +
-bool i2c_read_bit( void )  +
-+
-  bool bit; +
- +
-  // Let the slave drive data +
-  set_SDA();​ +
- +
-  // Wait for SDA value to be written by slave, minimum of 4us for standard mode +
-  I2C_delay();​ +
- +
-  // Set SCL high to indicate a new valid SDA value is available +
-  set_SCL();​ +
- +
-  while( read_SCL() == 0 )  +
-  { // Clock stretching +
-    // You should add timeout to this loop +
-  } +
- +
-  // Wait for SDA value to be read by slave, minimum of 4us for standard mode +
-  I2C_delay();​ +
- +
-  // SCL is high, read out bit +
-  bit = read_SDA();​ +
- +
-  // Set SCL low in preparation for next operation +
-  clear_SCL();​ +
- +
-  return bit; +
- +
-+
- +
-// Write a byte to I2C bus. Return 0 if ack by the slave. +
-bool i2c_write_byte( bool          send_start , +
-                     ​bool ​         send_stop ​ , +
-                     ​unsigned char byte         )  +
-+
-  unsigned bit; +
-  bool     ​nack;​ +
- +
-  if( send_start )  +
-  { +
-    i2c_start_cond();​ +
-  } +
- +
-  for( bit = 0; bit < 8; bit++ )  +
-  { +
-    i2c_write_bit( ( byte & 0x80 ) != 0 ); +
-    byte <<= 1; +
-  } +
- +
-  nack = i2c_read_bit();​ +
- +
-  if (send_stop)  +
-  { +
-    i2c_stop_cond();​ +
-  } +
- +
-  return nack; +
- +
-+
- +
-// Read a byte from I2C bus +
-unsigned char i2c_read_byte( bool nack , bool send_stop )  +
-+
-  unsigned char byte = 0; +
-  unsigned char bit; +
- +
-  for( bit = 0; bit < 8; bit++ )  +
-  { +
-    byte = ( byte << 1 ) | i2c_read_bit();​ +
-  } +
- +
-  i2c_write_bit( nack ); +
- +
-  if( send_stop )  +
-  { +
-    i2c_stop_cond();​ +
-  } +
- +
-  return byte; +
- +
-+
- +
-void I2C_delay( void )  +
-{  +
-  volatile int v; +
-  int i; +
- +
-  for( i = 0; i < I2CSPEED / 2; i++ ) +
-  { +
-    v; +
-  } +
- +
-}+
 </​code>​ </​code>​
  
-Applications[edit] +结果如何?​
-I²C is appropriate for peripherals where simplicity and low manufacturing cost are more important than speed. Common applications of the I²C bus are: +
- +
-Reading configuration data from SPD EEPROMs on SDRAM, DDR SDRAM, DDR2 SDRAM memory sticks (DIMM) and other stacked PC boards +
-Supporting systems management for PCI cards, through an SMBus 2.0 connection. +
-Accessing NVRAM chips that keep user settings. +
-Accessing low speed DACs and ADCs. +
-Changing contrast, hue, and color balance settings in monitors (Display Data Channel). +
-Changing sound volume in intelligent speakers. +
-Controlling OLED/LCD displays, like in a cellphone. +
-Reading hardware monitors and diagnostic sensors, like a CPU thermistor[citation needed] or fan speed.[6] +
-Reading real-time clocks. +
-Turning on and turning off the power supply of system components.[7] +
-A particular strength of I²C is the capability of a microcontroller to control a network of device chips with just two general purpose I/O pins and software. Many other bus technologies used in similar applications,​ such as Serial Peripheral Interface Bus, require more pins and signals to connect devices. +
- +
-Operating system support[edit] +
-In AmigaOS one can use the i2c.resource component[8] for AmigaOS 4.x and MorphOS 3.x or the shared library i2c.library by Wilhelm Noeker for older systems. +
-Arduino developers can use the '​Wire'​ library. +
-Maximite supports I²C communications natively as part of its MMBasic. +
-PICAXE uses the i2c and hi2c commands +
-eCos supports I²C for several hardware architectures. +
-ChibiOS/RT supports I²C for several hardware architectures. +
-FreeBSD, NetBSD and OpenBSD also provide an I²C framework, with support for a number of common master controllers and sensors. +
-In Linux, I²C is handled with a device driver for the specific device, and another for the I²C (or SMBus) adapter to which it is connected. Several hundred such drivers are part of current releases. +
-In Mac OS X, there are about two dozen I²C kernel extensions which communicate with sensors for reading voltage, current, temperature,​ motion, and other physical status. +
-In Microsoft Windows, I²C is implemented by the respective device drivers of much of the industry'​s available hardware. +
-Unison OS a POSIX RTOS for IoT supports I²C for several MCU and MPU hardware architectures. +
-In Windows CE, I²C is implemented by the respective device drivers of much of the industry'​s available hardware. +
-In RISC OS, I²C is provided with a generic I²C interface from the IO-controller and supported from the OS module system +
-In Sinclair QDOS and Minerva QL operating systems I²C is supported via a set of extensions provided by TF Services. +
-Development tools[edit] +
-When developing or troubleshooting systems using I²C, visibility at the level of hardware signals can be important. +
- +
-I²C host adapters[edit] +
-There are a number of hardware solutions for host computers, running Linux, Mac or Windows, I²C master and/or slave capabilities. Most of them are based on Universal Serial Bus (USB) to I²C adapters. Not all of them require proprietary drivers or APIs. +
- +
-I²C protocol analyzers[edit] +
-I²C Protocol Analyzers are tools which sample an I²C bus and decode the electrical signals to provide a higher-level view of the data being transmitted on the bus. +
- +
-Logic analyzers[edit] +
-When developing and/or troubleshooting the I²C bus, examination of hardware signals can be very important. Logic analyzers are tools which collect, analyze, decode, and store signals so people can view the high-speed waveforms at their leisure. Logic analyzers display time-stamps of each signal level change, which can help find protocol problems. Most logic analyzers have the capability to decode bus signals into high-level protocol data and show ASCII data. +
- +
-Limitations[edit] +
-The assignment of slave addresses is one weakness of I²C. Seven bits is too few to prevent address collisions between the many thousands of available devices, and manufacturers rarely dedicate enough pins to configure the full slave address used on a given board. Three pins is typical, giving only eight choices of slave address. While some devices can set multiple address bits per pin,[9][10] e.g., by using a spare internal ADC channel to sense one of eight ranges set by an external voltage divider, usually each pin controls one address bit. Manufacturers may provide pins to configure a few low order bits of the address and arbitrarily set the higher order bits to some value based on the model. This limits the number of devices of that model which may be present on the same bus to some low number, typically between two and eight. That partially addresses the issue of address collisions between different vendors. Ten-bit I²C addresses are not yet widely used, and many host operating systems do not support them.[11] Neither is the complex SMBus "​ARP"​ scheme for dynamically assigning addresses (other than for PCI cards with SMBus presence, for which it is required). +
- +
-Automatic bus configuration is a related issue. A given address may be used by a number of different protocol-incompatible devices in various systems, and hardly any device types can be detected at runtime. For example, 0x51 may be used by a 24LC02 or 24C32 EEPROM, with incompatible addressing; or by a PCF8563 RTC, which cannot reliably be distinguished from either (without changing device state, which might not be allowed). The only reliable configuration mechanisms available to hosts involve out-of-band mechanisms such as tables provided by system firmware which list the available devices. Again, this issue can partially be addressed by ARP in SMBus systems, especially when vendor and product identifiers are used; but that has not really caught on. The rev. 03 version of the I²C specification adds a device ID mechanism. +
- +
-I²C supports a limited range of speeds. Hosts supporting the multi-megabit speeds are rare. Support for the Fm+ one-megabit speed is more widespread, since its electronics are simple variants of what is used at lower speeds. Many devices do not support the 400 kbit/s speed (in part because SMBus does not yet support it). I²C nodes implemented in software (instead of dedicated hardware) may not even support the 100 kbit/s speed; so the whole range defined in the specification is rarely usable. All devices must at least partially support the highest speed used or they may spuriously detect their device address. +
- +
-Devices are allowed to stretch clock cycles to suit their particular needs, which can starve bandwidth needed by faster devices and increase latencies when talking to other device addresses. Bus capacitance also places a limit on the transfer speed, especially when current sources are not used to decrease signal rise times. +
- +
-Because I²C is a shared bus, there is the potential for any device to have a fault and hang the entire bus. For example, if any device holds the SDA or SCL line low it prevents the master from sending START or STOP commands to reset the bus. Thus it is common for designs to include a reset signal that provides an external method of resetting the bus devices. However many devices do not have a dedicated reset pin forcing the designer to put in circuitry to allow devices to be power cycled if they need to be reset. +
- +
-Because of these limits (address management, bus configuration,​ potential faults, speed), few I²C bus segments have even a dozen devices. It is common for systems to have several such segments. One might be dedicated to use with high speed devices, for low latency power management. Another might be used to control a few devices where latency and throughput are not important issues; yet another segment might be used only to read EEPROM chips describing add-on cards (such as the SPD standard used with DRAM sticks).+
  
-Derivative technologies[edit] +此代码已经在Xilinx和Altera的多个器件上进行过测试,​能够同硬化的I2C主进行通信,在这里可以下载[[http://www.fpga4fun.com/​files/​I2Cslave1.zip|完整的代码]]
-I²C is the basis for the ACCESS.bus, the VESA Display Data Channel (DDC) interface, the System Management Bus (SMBus), Power Management Bus (PMBus) and the Intelligent Platform Management Bus (IPMB, one of the protocols of IPMI)These variants have differences in voltage and clock frequency ranges, and may have interrupt lines.+
  
-High availability systems (AdvancedTCA,​ MicroTCA) use 2-way redundant I²C for shelf management. Multi-master I²C capability is a requirement in these systems.+不过此代码有两个缺点::​ 
 +  * 在FPGA/CPLD中SCL被用做了时钟信号,强烈建议在SCL输入端加入施密特触发器以避免错误的行为发生,如果不加施密特触发器,在SCL线上的任何噪声或振铃都会导致多余的时钟周期,导致功能失效 
 +  * “起始”和“终止”的条件检查逻辑采用的是组合反馈环路,这种方式是不建议的。同样其它电路的异步复位也不建议采用“周期内信号”
  
-TWI (Two Wire Interface) or TWSI (Two-Wire Serial Interface) is essentially the same bus implemented on various system-on-chip processors from Atmel and other vendors.[12] Vendors use the name TWI, even though I²C is not a registered trademark. Trademark protection only exists for the respective logo (See upper right corner) and patents on I²C have now lapsed.+如果你能够容忍这些缺点,这应该是I2C从模式非常简洁的设计,否则你只能用外部时钟对SDA和SCL进行过取样,通过数字滤波器将毛刺给滤除掉,“起始”和“终止”的检测也变得比较容易,当然代价就是设计变得更复杂。
  
-In some cases, use of the term "​two-wire interface"​ indicates incomplete implementation of the I²C specification. Not supporting arbitration or clock stretching is one common limitation, that is still useful for a single master communicating with simple slaves that never stretch the clock. 
  
-See also[edit] +### 相关设计资源参考
-Portal icon Electronics portal +
-DVI +
-DisplayPort +
-HDMI +
-List of network buses +
-UEXT Connector +
-VGA +
-System Management Bus +
-References[edit] +
-Jump up ^ I²C Licensing Information +
-Jump up ^ Freescale merger with NXP +
-Jump up ^ Official I2C Specification Version 6 +
-Jump up ^ 7-bit, 8-bit, and 10-bit I2C Slave Addressing +
-Jump up ^ Is there any definitive I2C pin-out guidance out there? Not looking for a “STANDARD”;​ StackExchange. +
-Jump up ^ Speedfan - reading computer hardware monitoring chips Archived August 16, 2015, at the Wayback Machine. +
-Jump up ^ "​Benefits of Power Supplies Equipped with I2C Ethernet Communications"​. Aegis Power Systems, Inc. Aegis Power Systems, Inc. Retrieved 21 December 2015. +
-Jump up ^ i2c.resource component for AmigaOS 4.x +
-Jump up ^ Maxim'​s MAX7314 uses a common purely digital low/​high/​SDA/​SCL scheme to configure four addresses per address pin. +
-Jump up ^ TI's UCD9112 uses two ADC channels to select any valid 7-bit address. +
-Jump up ^ http://​lkml.org/​lkml/​2005/​8/​16/​156 +
-Jump up ^ avr-libc: Example using the two-wire interface (TWI) +
-Further reading[edit] +
-Mastering the I²C Bus; Vincent Himpe; 248 pages; 2011; ISBN 978-0-905705-98-9. +
-The I2C Bus : From Theory to Practice; Dominique Paret; 314 pages; 1997; ISBN 978-0-471-96268-7.+
  
-====External links==== +  ​* [I2C规范](http://​www.nxp.com/​documents/​user_manual/​UM10204.pdf). 
-===Official=== +  * Philips多方面深度讨论I2C的[应用指南](http://www.nxp.com/documents/application_note/​AN10216.pdf) 
-  ​* [[http://​www.nxp.com/​documents/​user_manual/​UM10204.pdf|Official I2C specification (free)]], NXP +  * [I2C常见问题](http://www.esacademy.com/faq/i2c/) 
-  * [[http://www.diolan.com/downloads/i2c-address-allocation-table.pdf|List of assigned NXP / Philips I2C addresses (free)]], NXP +  * [关于I2C和SMBus区别的文章](http://​www.totalphase.com/​support/​kb/​10040/)(SMBus是由Intel公司开发的,基本跟I2C兼容) 
-===Other=== +  * 苏老师公众号文章 - [几种最常用的串行数据传输总线(2)-I2C](https://mp.weixin.qq.com/s/UVlecH-zBVG5Ug4Bx6TVeQ) 
-  * [[http://​www.i2c-bus.org/​|Detailed Introduction,​ Primer]+  * Lattice Semi的[I2C Master](http://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/ReferenceDesigns/ReferenceDesigns02/I2CBusMaster)使用说明,及IP参考代码下载 
-  * [[http://www.corelis.com/whitepapers/CAS-1000%20Whitepaper.pdf|Tackling I2C Development Complexities Using Innovative Tools]] +  * Lattice Semi的[支持Wisbone总线的I2C Master](http://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/ReferenceDesigns/ReferenceDesigns02/I2CMasterWISHBONECompatible)使用说明,及IP参考代码下载 
-  * [[http://​www.corelis.com/​products/​I2C-Demo.htm|Advanced I²C Bus Analysis Webinar]+  * Lattice Semi的[I2C总线控制器](http://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/ReferenceDesigns/ReferenceDesigns02/I2CBusControllerforSerialEEPROM)使用说明,及IP参考代码下载 
-  * [[http://​www.totalphase.com/​support/​kb/​10037/|I²C Background]] +  * Lattice Semi的[I2C主控制器](http://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/ReferenceDesigns/ReferenceDesigns02/I2CMasterController)使用说明,及IP参考代码下载 
-  * [[http://www.interfacebus.com/Design_Connector_I2C.html|I²C Bus Access Bus]] +  * Lattice Semi的[用于嵌入式功能块中的I2C从设备](http://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/ReferenceDesigns/ReferenceDesigns02/I2CSlavePeripheralusingEmbeddedFunctionBlock)使用说明,及IP参考代码下载 
-  * [[http://​www.linuxjournal.com/​article/​1342|Using the I²C Bus with Linux]+  * Lattice Semi的[I2C从到SPI主的桥接](http://www.latticesemi.com/en/Products/DesignSoftwareAndIP/IntellectualProperty/ReferenceDesigns/ReferenceDesigns02/I2CSlavetoSPIMasterBridge)使用说明,及IP参考代码下载 
-  * [[http://www.maxim-ic.com/appnotes.cfm/an_pk/4267/CMP/ELK10|Proven Implementations of the I²C Bus]] +  * FPGA4FUN上的[关于I2C的介绍及相应的Verilog代码资源](https://www.fpga4fun.com/I2C.html) 
-  * [[http://www.openbsd.org/​cgi-bin/​man.cgi?​query=iic&​sektion=4|OpenBSD iic(4manual page]] +  * FPGA4FUN上的I2C从设备的[[http://​www.fpga4fun.com/files/I2Cslave1.zip|完整的代码]]
-  * [[http://www.lm-sensors.org/|lm-sensors]],​ Linux-monitoring sensors package which supports sensors using the I²C bus, among others +
-  * [[http://www.lm-sensors.org/wiki/I2CTools|I²C Tools for Linux]], Tools to access I²C and SMBus devices +
-  * [[http://techref.massmind.org/​techref/​i2cs.htm|massmind I²C page Source code]], samples and technical information for using I²C with PC, PIC and SX microcontrollers. +
-  * [[http://www.epanorama.net/links/serialbus.html|Serial buses information page]] +
-  * [[http://www.esacademy.com/faq/i2c/|I²C Bus Technical Overview and Frequently Asked Questions]] +
-  * [[http://​www.bus-buffer.com/​|The Bus Buffer Resource. For 2-wire buses such as I²C, SMBus, PMBus, IPMB & IPMI]+
-  * [[http://www.dnatechindia.com/Tutorial/8051-Tutorial/Introduction-to-I2C-Protocol.html|I²C Protocol]] +
-  * [[http://focus.ti.com/logic/docs/​littlelogicI2C.tsp?​sectionId=460&​DCMP=I2CLOGIC+Other&​HQS=Other+OT+i2c|I²C logic microchips from Texas Instruments]] +
-  * [[http://www.zipcores.com/skin1/zipdocs/datasheets/i2c_master.pdf|A commercial hardware implementation of I²C written]] in VHDL +
-  * [[http://www.opencores.org/?​do=project&​who=i2c|OpenCores]] open source hardware implementation,​ in Verilog and VHDL +
-  * [[http://www.byteparadigm.com/kb/article/AA-00255/22/Introduction-to-SPI-and-IC-protocols.html|Introduction to SPI and I2C protocols]] +
-  * [[http://tronixstuff.wordpress.com/​2010/​10/​20/​tutorial-arduino-and-the-i2c-bus/​|Beginner'​s guide to using Arduino with I²C devices, including worked examples]] +
-  * [[http://www.dsscircuits.com/index.php/​articles/​47-effects-of-varying-i2c-pull-up-resistors|Effects of Varying I²C Pull-up Resistors]] +
-  * [[http://​www.corelis.com/education/I2C_Exerciser_Advanced_Trigger_Tutorial.htm|I2C Tutorial]] +
-  * [[http://​howtomechatronics.com/​tutorials/​arduino/​how-i2c-communication-works-and-how-to-use-it-with-arduino/​|How I2C Communication Works]]+