Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 13

Using the I2C Bus

Judging from my emails, it is quite clear that the I2C bus can be very confusing for the newcomer. I have lots of exam les on using the I2C bus on the website, but many of these are using high level controllers and do not show the detail of what is actually ha ening on the bus. !his short article therefore tries to de"mystify the I2C bus, I ho e it doesn#t have the o osite effect$ The physical I2C bus !his is %ust two wires, called &C' and &(). &C' is the cloc* line. It is used to synchroni+e all data transfers over the I2C bus. &() is the data line. !he &C' , &() lines are connected to all devices on the I2C bus. !here needs to be a third wire which is %ust the ground or - volts. !here may also be a .volt wire is ower is being distributed to the devices. Both &C' and &() lines are /o en drain/ drivers. 0hat this means is that the chi can drive its out ut low, but it cannot drive it high. 1or the line to be able to go high you must rovide ull"u resistors to the .v su ly. !here should be a resistor from the &C' line to the .v line and another from the &() line to the .v line. 2ou only need one set of ull"u resistors for the whole I2C bus, not for each device, as illustrated below3

!he value of the resistors is not critical. I have seen anything from 4*5 645-- ohms7 to 89* 689--- ohms7 used. 4*5, 8*9 and 4-* are common values, but anything in this range should wor* :;. I recommend 4*5 as this gives you the best erformance. If the resistors are missing, the &C' and &() lines will always be low " nearly - volts " and the I2C bus will not wor*. Masters and Slaves !he devices on the I2C bus are either masters or slaves. !he master is always the device that drives the &C' cloc* line. !he slaves are the devices that res ond to the master. ) slave cannot initiate a transfer over the I2C bus, only a master can do that. !here can be, and usually are, multi le slaves on the I2C bus, however there is normally only one master. It is ossible to have multi le masters, but it is unusual and not covered here. :n your robot, the master will be your controller and the slaves will be our modules such as the &<1-5 or C=>&-?. &laves will never initiate a transfer. Both master and slave can transfer data over the I2C bus, but that transfer is always controlled by the master.

The I2C Physical Protocol 0hen the master 6your controller7 wishes to tal* to a slave 6our C=>&-? for exam le7 it begins by issuing a start sequence on the I2C bus. ) start sequence is one of two s ecial sequences defined for the I2C bus, the other being the sto sequence. !he start sequence and sto sequence are s ecial in that these are the only laces where the &() 6data line7 is allowed to change while the &C' 6cloc* line7 is high. 0hen data is being transferred, &() must remain stable and not change whilst &C' is high. !he start and sto sequences mar* the beginning and end of a transaction with the slave device.

(ata is transferred in sequences of 5 bits. !he bits are laced on the &() line starting with the =&B 6=ost &ignificant Bit7. !he &C' line is then ulsed high, then low. <emember that the chi cannot really drive the line high, it sim ly /lets go/ of it and the resistor actually ulls it high. 1or every 5 bits transferred, the device receiving the data sends bac* an ac*nowledge bit, so there are actually @ &C' cloc* ulses to transfer each 5 bit byte of data. If the receiving device sends bac* a low )C; bit, then it has received the data and is ready to acce t another byte. If it sends bac* a high then it is indicating it cannot acce t any further data and the master should terminate the transfer by sending a sto sequence.

How fast? !he standard cloc* 6&C'7 s eed for I2C u to 4--;A+. >hili s do define faster s eeds3 1ast mode, which is u to 8--;A+ and Aigh & eed mode which is u to ?.8=A+. )ll of our modules are designed to wor* at u to 4--;A+. 0e have tested our modules u to 4=A+ but this needs a small delay of a few u& between each byte transferred. In ractical robots, we have never had any need to use high &C' s eeds. ;ee &C' at or below 4--;A+ and then forget about it. I2C Device Addressin )ll I2C addresses are either 9 bits or 4- bits. !he use of 4- bit addresses is rare and is not covered here. )ll of our modules and the common chi s you will use will have 9 bit addresses. !his means that you can have u to 425 devices on the I2C bus, since a 9bit number can be from - to 429. 0hen sending out the 9 bit address, we still always send 5 bits. !he extra bit is used to inform the slave if the master is writing to it or reading from it. If the bit is +ero the master is writing to the slave. If the bit is 4 the master is reading

from the slave. !he 9 bit address is laced in the u er 9 bits of the byte and the <eadB0rite 6<B07 bit is in the '&B 6'east &ignificant Bit7.

!he lacement of the 9 bit address in the u er 9 bits of the byte is a source of confusion for the newcomer. It means that to write to address 24, you must actually send out 82 which is 24 moved over by 4 bit. It is robably easier to thin* of the I2C bus addresses as 5 bit addresses, with even addresses as write only, and the odd addresses as the read address for the same device. !o ta*e our C=>&-? for exam le, this is at address -xC6CC-7. 2ou would uses -xC- to write to the C=>&-? and -xC4 to read from it. &o the readBwrite bit %ust ma*es it an oddBeven address. The I2C Software Protocol !he first thing that will ha en is that the master will send out a start sequence. !his will alert all the slave devices on the bus that a transaction is starting and they should listen in incase it is for them. Dext the master will send out the device address. !he slave that matches this address will continue with the transaction, any others will ignore the rest of this transaction and wait for the next. Aaving addressed the slave device the master must now send out the internal location or register number inside the slave that it wishes to write to or read from. !his number is obviously de endant on what the slave actually is and how many internal registers it has. &ome very sim le devices do not have any, but most do, including all of our modules. :ur C=>&-? has 4E locations numbered -"4.. !he &<1-5 has ?E. Aaving sent the I2C address and the internal register address the master can now send the data byte 6or bytes, it doesn#t have to be %ust one7. !he master can continue to send data bytes to the slave and these will normally be laced in the following registers because the slave will automatically increment the internal register address after each byte. 0hen the master has finished writing all data to the slave, it sends a sto sequence which com letes the transaction. &o to write to a slave device3 4. &end a start sequence 2. &end the I2C address of the slave with the <B0 bit low 6even address7 ?. &end the internal register number you want to write to 8. &end the data byte .. F: tionally, send any further data bytesG E. &end the sto sequence. )s an exam le, you have an &<1-5 at the factory default address of -xH-. !o start the &<1-5 ranging you would write -x.4 to the command register at -x-- li*e this3 4. &end a start sequence 2. &end -xH- 6 I2C address of the &<1-5 with the <B0 bit low 6even address7 ?. &end -x-- 6Internal address of the command register7 8. &end -x.4 6!he command to start the &<1-5 ranging7 .. &end the sto sequence.

!eadin fro" the Slave !his is a little more com licated " but not too much more. Before reading data from the slave device, you must tell it which of its internal addresses you want to read. &o a read of the slave actually starts off by writing to it. !his is the same as when you want to write to it3 2ou send the start sequence, the I2C address of the slave with the <B0 bit low 6even address7 and the internal register number you want to write to. Dow you send another start sequence 6sometimes called a restart7 and the I2C address again " this time with the read bit set. 2ou then read as many data bytes as you wish and terminate the transaction with a sto sequence. &o to read the com ass bearing as a byte from the C=>&-? module3 4. &end a start sequence 2. &end -xC- 6 I2C address of the C=>&-? with the <B0 bit low 6even address7 ?. &end -x-4 6Internal address of the bearing register7 8. &end a start sequence again 6re eated start7 .. &end -xC4 6 I2C address of the C=>&-? with the <B0 bit high 6odd address7 E. <ead data byte from C=>&-? 9. &end the sto sequence. !he bit sequence will loo* li*e this3

#ait a "o"ent !hat#s almost it for sim le I2C communications, but there is one more com lication. 0hen the master is reading from the slave, its the slave that laces the data on the &() line, but its the master that controls the cloc*. 0hat if the slave is not ready to send the data$ 0ith devices such as HH><:=s this is not a roblem, but when the slave device is actually a micro rocessor with other things to do, it can be a roblem. !he micro rocessor on the slave device will need to go to an interru t routine, save its wor*ing registers, find out what address the master wants to read from, get the data and lace it in its transmission register. !his can ta*e many u& to ha en, meanwhile the master is blissfully sending out cloc* ulses on the &C' line that the slave cannot res ond to. !he I2C rotocol rovides a solution to this3 the slave is allowed to hold the &C' line low$ !his is called cloc* stretching. 0hen the slave gets the read command from the master it holds the cloc* line low. !he micro rocessor then gets the requested data, laces it in the transmission register and releases the cloc* line allowing the ull"u resistor to finally ull it high. 1rom the masters oint of view, it will issue the first cloc* ulse of the read by ma*ing &C' high and then chec* to see if it really has gone high. If

its still low then its the slave that holding it low and the master should wait until it goes high before continuing. 'uc*ily the hardware I2C orts on most micro rocessors will handle this automatically. &ometimes however, the master I2C is %ust a collection of subroutines and there are a few im lementations out there that com letely ignore cloc* stretching. !hey wor* with things li*e HH><:=#s but not with micro rocessor slaves that use cloc* stretching. !he result is that erroneous data is read from the slave. Beware$ $%a"ple Master Code !his exam le shows how to im lement a software I2C master, including cloc* stretching. It is written in C for the >IC rocessor, but should be a licable to most rocessors with minor changes to the IB: in definitions. It is suitable for controlling all of our I2C based robot modules. &ince the &C' and &() lines are o en drain ty e, we use the tristate control register to control the out ut, *ee ing the out ut register low. !he ort ins still need to be read though, so they#re defined as &C'IID and &()IID. !his definition and the initiali+ation is robably all you#ll need to change for a different rocessor. Jdefine &C' !<I&B8 BB I2C bus Jdefine &() !<I&B4 BB Jdefine &C'IID <B8 BB Jdefine &()IID <B4 BB !o initiali+e the orts set the out ut resisters to - and the tristate registers to 4 which disables the out uts and allows them to be ulled high by the resistors. &() K &C' K 4L &C'IID K &()IID K -L 0e use a small delay routine between &() and &C' changes to give a clear sequence on the I2C bus. !his is nothing more than a subroutine call and return. void i2cIdly6void7 M N !he following 8 functions rovide the rimitive start, sto , read and write sequences. )ll I2C transactions can be built u from these. void i2cIstart6void7 M &() K 4L BB i2c start bit sequence i2cIdly67L &C' K 4L i2cIdly67L &() K -L i2cIdly67L &C' K -L i2cIdly67L

N void i2cIsto 6void7 M &() K -L BB i2c sto bit sequence i2cIdly67L &C' K 4L i2cIdly67L &() K 4L i2cIdly67L N unsigned char i2cIrx6char ac*7 M char x, dK-L &() K 4L for6xK-L xO5L xPP7 M d OOK 4L do M &C' K 4L N while6&C'IIDKK-7L BB wait for any &C' cloc* stretching i2cIdly67L if6&()IID7 d QK 4L &C' K -L N if6ac*7 &() K -L else &() K 4L &C' K 4L i2cIdly67L BB send 6D7)C; bit &C' K -L &() K 4L return dL N bit i2cItx6unsigned char d7 M char xL static bit bL for6xK5L xL x""7 M if6d,-x5-7 &() K 4L else &() K -L &C' K 4L d OOK 4L &C' K -L N

&() K 4L &C' K 4L i2cIdly67L b K &()IIDL &C' K -L return bL N

BB ossible )C; bit

!he 8 rimitive functions above can easily be ut together to form com lete I2C transactions. Aere#s and exam le to start an &<1-5 ranging in cm3 i2cIstart67L i2cItx6-xH-7L i2cItx6-x--7L i2cItx6-x.47L i2cIsto 67L BB send start sequence BB &<1-5 I2C address with <B0 bit clear BB &<1-5 command register address BB command to start ranging in cm BB send sto sequence

Dow after waiting E.m& for the ranging to com lete 6I#ve left that to you7 the following exam le shows how to read the light sensor value from register 4 and the range result from registers 2 , ?. i2cIstart67L BB send start sequence i2cItx6-xH-7L BB &<1-5 I2C address with <B0 bit clear i2cItx6-x-47L BB &<1-5 light sensor register address i2cIstart67L BB send a restart sequence i2cItx6-xH47L BB &<1-5 I2C address with <B0 bit set lightsensor K i2cIrx647L BB get light sensor and send ac*nowledge. Internal register address will increment automatically. rangehigh K i2cIrx647L BB get the high byte of the range and send ac*nowledge. rangelow K i2cIrx6-7L BB get low byte of the range " note we don#t ac*nowledge the last byte. i2cIsto 67L BB send sto sequence Hasy isn#t itR !he definitive s ecs on the I2C bus can be found on the >hili s website. It currently here but if its moved you#ll find it easily be googleing on /i2c bus s ecification/.

2C Bus >rotocol !he I2C bus hysically consists of 2 active wires and a ground connection. !he active wires, called &() and &C', are both bi"directional. &() is the &erial ()ta line, and &C' is the &erial C'oc* line. Hvery device hoo*ed u to the bus has its own unique address, no matter whether it is an =CU, 'C( driver, memory, or )&IC. Hach of these chi s can act as a receiver andBor transmitter, de ending on the functionality. :bviously, an 'C( driver is only a receiver, while a memory or IB: chi can be both transmitter and receiver. !he I2C bus is a multi"master bus. !his means that more than one IC ca able of initiating a data transfer can be connected to it. !he I2C rotocol s ecification states that the IC that initiates a data transfer on the bus is considered the Bus =aster. Consequently, at that time, all the other ICs are regarded to be Bus &laves. )s bus masters are generally microcontrollers, let#s ta*e a loo* at a general #inter"IC chat# on the bus. 'ets consider the following setu and assume the =CU wants to send data to one of its slaves 6also see here for more informationL clic* here for information on how to receive data from a slave7.

1irst, the =CU will issue a &!)<! condition. !his acts as an #)ttention# signal to all of the connected devices. )ll ICs on the bus will listen to the bus for incoming data. !hen the =CU sends the )((<H&& of the device it wants to access, along with an indication whether the access is a <ead or 0rite o eration 60rite in our exam le7. Aaving received the address, all IC#s will com are it with their own address. If it doesn#t match, they sim ly wait until the bus is released by the sto condition 6see below7. If the address matches, however, the chi will roduce a res onse called the )C;D:0'H(SH signal. :nce the =CU receives the ac*nowledge, it can start transmitting or receiving ()!). In our case, the =CU will transmit data. 0hen all is done, the =CU will issue the &!:> condition. !his is a signal that the bus has been released and that the connected ICs may ex ect another transmission to start any moment. 0e have had several states on the bus in our exam le3 &!)<!, )((<H&&, )C;D:0'H(SH, ()!) , &!:>. !hese are all unique conditions on the bus. Before

we ta*e a closer loo* at these bus conditions we need to understand a bit about the hysical structure and hardware of the bus.

2C Bus >rotocol !he I2C bus hysically consists of 2 active wires and a ground connection. !he active wires, called &() and &C', are both bi"directional. &() is the &erial ()ta line, and &C' is the &erial C'oc* line. Hvery device hoo*ed u to the bus has its own unique address, no matter whether it is an =CU, 'C( driver, memory, or )&IC. Hach of these chi s can act as a receiver andBor transmitter, de ending on the functionality. :bviously, an 'C( driver is only a receiver, while a memory or IB: chi can be both transmitter and receiver. !he I2C bus is a multi"master bus. !his means that more than one IC ca able of initiating a data transfer can be connected to it. !he I2C rotocol s ecification states that the IC that initiates a data transfer on the bus is considered the Bus =aster. Consequently, at that time, all the other ICs are regarded to be Bus &laves. )s bus masters are generally microcontrollers, let#s ta*e a loo* at a general #inter"IC chat# on the bus. 'ets consider the following setu and assume the =CU wants to send data to one of its slaves 6also see here for more informationL clic* here for information on how to receive data from a slave7.

1irst, the =CU will issue a &!)<! condition. !his acts as an #)ttention# signal to all of the connected devices. )ll ICs on the bus will listen to the bus for incoming data. !hen the =CU sends the )((<H&& of the device it wants to access, along with an indication whether the access is a <ead or 0rite o eration 60rite in our exam le7. Aaving received the address, all IC#s will com are it with their own address. If it doesn#t match, they sim ly wait until the bus is released by the sto condition 6see below7. If the address matches, however, the chi will roduce a res onse called the )C;D:0'H(SH signal. :nce the =CU receives the ac*nowledge, it can start transmitting or receiving ()!). In our case, the =CU will transmit data. 0hen all is done, the =CU will issue the &!:> condition. !his is a signal that the bus has been released and that the connected ICs may ex ect another transmission to start any moment. 0e have had several states on the bus in our exam le3 &!)<!, )((<H&&, )C;D:0'H(SH, ()!) , &!:>. !hese are all unique conditions on the bus. Before

we ta*e a closer loo* at these bus conditions we need to understand a bit about the hysical structure and hardware of the bus.

I2C Info & I2C 'us( Interface and Protocol


I2C is a serial rotocol for two"wire interface to connect low"s eed devices li*e microcontrollers, HH><:=s, )B( and (B) converters, IB: interfaces and other similar eri herals in embedded systems. It was invented by >hili s and now it is used by almost all ma%or IC manufacturers. Hach I2C slave device needs an address T they must still be obtained from DU> 6formerly >hili s semiconductors7.

I2C bus is o ular because it is sim le to use, there can be more than one master, only u er bus s eed is defined and only two wires with ull"u resistors are needed to connect almost unlimited number of I2C devices. I2C can use even slower microcontrollers with general" ur ose IB: ins since they only need to generate correct &tart and &to conditions in addition to functions for reading and writing a byte. Hach slave device has a unique address. !ransfer from and to master device is serial and it is s lit into 5"bit ac*ets. )ll these sim le requirements ma*e it very sim le to im lement I2C interface even with chea microcontrollers that have no s ecial I2C hardware controller. 2ou only need 2 free IB: ins and few sim le i2C routines to send and receive commands. !he initial I2C s ecifications defined maximum cloc* frequency of 4-- *A+. !his was later increased to 8-- *A+ as 1ast mode. !here is also a Aigh s eed mode which can go u to ?.8 =A+ and there is also a . =A+ ultra"fast mode.

I2C Interface
I2C uses only two wires3 &C' 6serial cloc*7 and &() 6serial data7. Both need to be ulled u with a resistor to PVdd. !here are also I2C level shifters which can be used to connect to two I2C buses with different voltages.

I2C Addresses
Basic I2C communication is using transfers of 5 bits or bytes. Hach I2C slave device has a 9"bit address that needs to be unique on the bus. &ome devices have fixed I2C address

while others have few address lines which determine lower bits of the I2C address. !his ma*es it very easy to have all I2C devices on the bus with unique I2C address. !here are also devices which have 4-"bit address as allowed by the s ecification. 9"bit address re resents bits 9 to 4 while bit - is used to signal reading from or writing to the device. If bit - 6in the address byte7 is set to 4 then the master device will read from the slave I2C device. =aster device needs no address since it generates the cloc* 6via &C'7 and addresses individual I2C slave devices.

I2C Protocol

In normal state both lines 6&C' and &()7 are high. !he communication is initiated by the master device. It generates the &tart condition 6&7 followed by the address of the slave device 6B47. If the bit - of the address byte was set to - the master device will write to the slave device 6B27. :therwise, the next byte will be read from the slave device. :nce all bytes are read or written 6Bn7 the master device generates &to condition 6>7. !his signals to other devices on the bus that the communication has ended and another device may use the bus. =ost I2C devices su ort re eated start condition. !his means that before the communication ends with a sto condition, master device can re eat start condition with address byte and change the mode from writing to reading.

You might also like