SPI versus I2C protocols

From BitWizard WIKI
Revision as of 11:04, 16 July 2014 by Rijk (talk | contribs)

Jump to: navigation, search

When buying a BitWizard expansion board, either I2C or SPI can be selected as the interface. This page will help you choose.

Physical Differences

The first difference between I2C and SPI is that I2C is two-wire, while SPI is four-wire.

Technical Differences

The I2C protocol is inherently half-duplex. The SPI protocol is inherently full-duplex. So with SPI, every read is also a write. This could in theory double the speed of the bus, however, when implementing the SPI protocol we noticed that most of the time we didn't have data to send one direction. When you want to read from the device, you have to send "dummy bytes" to the device to trigger the clock signal that allows the slave to send data. Similarly, most of time the slave does not have anything to report back when you are actually sending data to the slave. With these dummy packets, both protocols are now half-duplex.

The addresses on the bus are 7 bits wide. The lower bit specifies if the transaction is to be a read or a write. Write transactions have the lower bit cleared (0), read transactions have the lower bit set (1).

Each transaction on the bus starts with the address of the board. All BitWizard boards will ignore any transactions on the bus that do not start with their own address. The protocols allow for changing the address in case you need more modules of the same type on one bus.

After the address a single byte indicates the "port" on the board that the data is written to. The software can thus define 256 ports on each board.

To write data using SPI or I2C send a number of bytes (usually 3 or 4).

<address> <register>  <data byte2> ....

On SPI you activate (make it low!) the slave select line before the transaction. On I2C you cause a start condition before the transaction. After the transaction, you deactivate the slave select line (make it high) on SPI and cause a STOP condition on I2C.

To read data from the slaves, on I2C you first make a write transaction of just two bytes, the address and the register number. Next you read the data. On SPI this must be done in one transaction: write the address and register number, then write dummy bytes while reading the data.

To read on I2C:

<start> <address + WRITE> <register> <stop>
<start> <address + READ> <byte 1> <byte 2> 

To read on SPI:

MOSI <address> <register> <dummy byte> <dummy byte> 
MISO    xxx       xxx     <byte 1>     <byte 2>