Saturday, August 25, 2012

Understanding I²C and some typical uses

Having worked with multiple I²C sensors, I thought that it might be time to summarize some of my findings. For those new to I²C, the name is short for "inter integrated circuit", sometimes also known as "two wire interface" (TWI), and is very commonly used for communicating with sensors.

I²C a simple bus and allows ICs to communicate with each other in a star topology. Star topology in I²C  means one master, typically a microcontroller communicating to one or more slaves (sensors). Today it is one of the most common, if not the most common, digital interface used for to ICs to communicate.

The basics as well as the stranger features and typical terminology of I²C is covered after the break.

Basics of I²C

The I²C bus consists of a clock line (SCL) and a data line (SDA), and these lines are directly connected between the master and all the slaves. Both lines also have a pull-up (resistor connected to the voltage source). Since the master can send data to the slaves and read data from the slaves, it's clear that the SDA line works as both an input and as an output for all ICs. This is where things get a bit complicated.

When talking about GPIO pins, the pin is often either an input or an output, but doesn't swap between the two, and as outputs they are either high or low.  I²C complicates this by being an output when low, but an input or at least tri-stated when "high". The pull-up resistors on the bus take care of driving the lines high when the bus members are writing a "high" bit, i.e. they make there line an input. By default all devices keep their lines high, so the master can at any time pull the lines low.

The most common SCL frequencies for I²C are 100kHz (normal mode) and 400kHz (fast mode) with practically all sensors supporting both modes. In rare cases much higher data rates may be supported by the sensors, such as high speed mode at over 3MHz.
It is also worth to note that after each byte written, the receiver has an opportunity to acknowledge (ACK) or not acknowledge (NACK) the byte. So when the master writes something to the slave, after each byte, it will release the data line (let it go high) and clock an additional ninth bit. During this byte the receiver, in this case the slave, can pull it low to acknowledge the byte. A NACK is generally used to indicate an error condition, but not always. A common mistake when implementing I²C in software, is to disregard the peculiarity that a master's read sequence must end in a NACK. When the master is reading, the slave controls the SDA line and after each byte the slave awaits that the master clocks out the ninth bit and acknowledges the previous byte. However when the master stops the read, the master is supposed to send a NACK for the last byte, indicating termination of the read cycle. This is not an error condition and many sensors will fail to operate correctly, if the master reads from them but does not end the read cycle with a NACK.

I²C start and stop and repeated start

Communication is initiated by the master, and starts with what is known as a "start condition" followed by the address of the slave the master wants to communicate to. An I²C start condition simply means that the SDA line is pulled low by the master while the SCL line remains high.

A stop condition terminates a communication session, typically releasing the slave to carry on with what it needs to do. The stop condition is indicated by having the SCL released (high) and then also releasing the SDA line.

A repeated start condition simply means that the master doesn't send a stop condition between one start and the next,  and is most commonly used when a master wants to do a write and a read in succession like in a register read.

I²C addresses

The master controls the communication flow, and indicates to which slave it wants to communicate by writing the slaves address onto the bus. The address is 7-bits long, and if a I²C salve realizes the communication is not addressed to it, the slave will ignore all data until the next Start condition is seen. 

After the 7-bits, there is an additional 1-bit indicator whether or not the I²C operation is a read or a write (from the master's perspective). If the master wishes to read, it will set the bit high, and if the operation is a write to the slave, the bit will be low. Sometimes datasheets use the full 8-bits containing both the address and the read/write bit and specify the "read address" and "write address" separately. As an example, if the 7-bit address of a sensor is 0x40 (64 in decimal), then the 8-bit read address would be 0x81 (the address shifted left by one + the read bit), and the 8-bit write address would be 0x80.

Sensors also often have one or more address pins, typically named A0, A1 or simply ADDR. These address pins allow a hardware designer to control the 7-bit I²C address, in order to avoid two chips having the same address. This is especially important when attaching two chips of the same model to a single I²C bus.

I²C reads and registers

As explained in the address section, the first byte contains the information whether the master wants to perform a read or a write. In practically all sensors, a read is preceded by a write, indicating what information is going to be read. This means a read sequence consists of the master first writing to indicate what is going to be read, and then performing a read to fetch the data.

It is very common that sensors organize their information in what is called registers. Each register has an address and the value is most commonly a single byte. To perform a read of a register, the master first does a write where it indicates the register address, and then does a read to retrieve the contents. This is also the most common use case for a repeated start condition.

So a 1 byte "register read" will consist of the following:
  • Master: start condition
  • Master: 7-bit slave address + write bit
  • Slave: ACK
  • Master: register address
  • Slave: ACK
  • Master: start condition (repeated start)
  • Master: 7-bit slave address + read bit
  • Slave: ACK
  • Slave: transmit byte from register address (master is controlling the clock)
  • Master: NACK
  • Master: STOP 

Multibyte reads over I²C

Because I²C is byte oriented, and register values are commonly one byte long, different vendors have come up with different ways of reading multiple bytes over I²C. The basic problem these schemes try to solve is, how to avoid the sensor updating the value as it is still being read. For example if a 16bit value is split over two registers, there is a race between when the host reads the individual bytes and when the sensor updates them.

Perhaps the simplest way is to have register values span multiple bytes, so that a read can simply read all the bytes in one go.

A more common way sensors solve this is by not updating any registers after a start and before a stop. This relies on the master using repeated start conditions to read multiple register values.

Another very common way is to allow the host to read multiple registers by extending the read. So if the read starts at register 0x03, by reading 3 bytes instead of one, the master will actually have read bytes 0x03, 0x04 and 0x05.

The last but way we've come across is having a register read trigger an update. So when a value spans registers 0x03, 0x04 and 0x05, the sensor will keep the value locked until the master reads the register 0x05. Typically reading the most significant byte of the value will in effect trigger updating the value.

Power consumption of I²C

Perhaps surprisingly, using I²C has a direct effect on power consumption. I²C inherently consumes power because of its physical properties. When anyone on the bus writes a zero, i.e. pulls the line low, power is flowing from the power supply through the pull-ups to the IC writing the zero. 

Calculating how much power is consumed when writing a zero bit over I²C is an easy exercise:  The voltage of the pull-up is connected to is simply divided by the resistance of the pull-up to obtain the current flow. This current flow lasts a clock cycle on the data line, so for 100kHz clock that is 10 micro seconds, and half a clock cycle (5us) for the clock line.

In practice this is not a very large drain under most circumstances but should nevertheless not be overlooked. Let's say we have a coin cell (CR2032) with a capacity of 220mAh and operating at a voltage of 3V and the I²C bus uses 1kOhm pull-ups on both lines. Writing a zero bit, the SDA line will be low for the entire time and the SDC line for half the time. Each zero bit will thus consume 10us*3V/1000Ohm + 5us*3V/1000Ohm = 4.5 * 10^-8 As. This means that the I²C will drain the battery after writing 17Gb, i.e. after writing zeros for about 2 days continuously.

To get the absolute minimum power consumption on systems with a busy I2C bus, the bus should be run at the maximum speed and all sensor's address pins should be tied high. However, please note that the leakage currents on the address pin may be significant when talking about such minuscule optimizations, so you will need to consult your datasheet. 

I²C clock stretching 

I²C clock stretching must be supported by an I²C master, and it is a way for the slave to indicate that it is not ready to perform what ever task is required of it. In practice it means that as the master attempts to control the clock, the slave will keep to clock signal (SCL) low and prevent it from going high. The master must notice when the clcok doesn't rise, and simply wait until the slave releases the clock. This is called clock stretching.

The most common use case for clock stretching is when a master has indicated to the slave that a measurement value is to be read. Then the sensor may choose to keep the clock low, until it has actually updated the measurement value and it is ready to be read. The master will simply have to wait until the clock goes back up, thus in effect forcing the master to wait until the slave is ready.

It is worth noting that during clock stretching the I²C bus cannot be used for anything, and thus some sensors make the use of clock stretching configurable. Another noteworthy thing is that with clock stretching in effect, current is constantly flowing through the pull-ups, wasting power.

I²C layout considerations

There are one or two things that must be taken into account when laying out I²C lines. The main thing is the capacitance of the lines together with the strength of the pull-ups and how these affect the rise times of the SCL and SDA lines. 

In simple terms, long lines very closely to a ground plane will make the line act as a small capacitor, this unintended capacitance is known as parasitic capacitance. When the lines are pulled high, the capacitance will slow down the rise time, and if the pull-ups are too weak the timing requirements for the rise-time will not be met. Each sensor on the bus will also add capacitance.

In order to not violate the timing requirements for the rise times, the pull-up resistors can be made smaller, resulting in more current flowing to counter act the parasitic capacitance. This will of course increase the power consumption somewhat.

Another way would be to decrease the clock rate of the bus, which will also yield higher power consumption as each zero on the line will last longer, but also lower the data throughput, potentially keeping the microcontroller and the sensors awake for longer times and resulting in much worse power consumption.

The  best way to ensure good quality I²C lines is to pay attention during the layout phase to the sources of parasitic capacitance. This means keeping the SDA and SCL lines as short as possible, not running the lines close to each other or ground.

Common I²C problems

For a relatively simple bus, there are a lot of common problems that people stumble across. The best way to debug I2C problems is with an oscilloscope and a logic analyzer. 

Hardware related problems:
  • No pull-ups or too weak pull-ups, resulting in the violation of the timing requirements.
    • Symptom: Random errors, or one sensor works on the I²C bus while another doesn't
    • Easiest to diagnose with an oscilloscope looking at the rising edge of the signals
  • SDA and SCL are crossed
    • Symptom: No communication is successful
  • Master doesn't support clock stretching
    • Symptom: The slave will randomly fail, or fail unless some timeouts are added between steps in register read. Reducing clock may also hide the problem.
  • Leaving a sensor's address configuring line to float
    • Symptom: The sensor will seem to work sometimes, and sometimes appear completely dead. Touching some part of the PCB may appear to help / break the system.
  • Not connecting all voltages and grounds on master or slave side.
    • Symptom: If the sensor is lacking some voltages, nothing appears to work even though the messages may appear correct when looked with an oscilloscope or logic analyzer.
Software related:

  • Confusing 7-bit and 8-bit addresses
    • Symptom: The sensor doesn't appear to answer
  • Not using the correct address if the address is configurable in hardware.
    • Symptom: The sensor doesn't appear to answer
  • Not using repeated starts and the sensor requires them for proper operation
    • Symptom: The sensor responds with garbled data on reads.
  • Not terminating reads with a NACK
    • Symptom: The first read succeeds, but the following ones don't until you reset the sensor.
  • Not configuring the I2C subsystem correctly, i.e. not configuring the GPIOs for I2C or using the wrong I2C bus on the microcontroller
    • Symptom: Nothing works, the oscilloscope doesn't show I²C traffic on the bus.

No comments:

Post a Comment