I2C

mbed OS 2 and mbed OS 5

This is the handbook for mbed OS 2. If you’re working with mbed OS 5, please see the new handbook and API References. For the latest I2C API, please see I2C.

The I2C interface provides I2C Master functionality.

This interface can be used for communication with a I2C devices, such as serial memories, sensors and other modules or integrated circuits.

Hello World!

Import program

00001 #include "mbed.h"
00002  
00003 // Read temperature from LM75BD
00004 
00005 I2C i2c(p28, p27);
00006 
00007 const int addr = 0x90;
00008 
00009 int main() {
00010     char cmd[2];
00011     while (1) {
00012         cmd[0] = 0x01;
00013         cmd[1] = 0x00;
00014         i2c.write(addr, cmd, 2);
00015  
00016         wait(0.5);
00017  
00018         cmd[0] = 0x00;
00019         i2c.write(addr, cmd, 1);
00020         i2c.read(addr, cmd, 2);
00021  
00022         float tmp = (float((cmd[0]<<8)|cmd[1]) / 256.0);
00023         printf("Temp = %.2f\n", tmp);
00024     }
00025 }

Warning

Remember, you will need a pull-up resistor on sda and scl.

All drivers on the I2C bus are required to be open collector, and so it is necessary for pull up resistors to be used on the two signals. A typical value for the pullup resistors is around 2.2k ohms, connected between the pin and 3v3.

API

Note

The mbed API uses 8 bit addresses, so make sure to take that 7 bit address and left shift it by 1 before passing it.

Import library

Public Member Functions

  I2C (PinName sda, PinName scl)
  Create an I2C Master interface, connected to the specified pins.
void  frequency (int hz)
  Set the frequency of the I2C interface.
int  read (int address, char *data, int length, bool repeated=false)
  Read from an I2C slave.
int  read (int ack)
  Read a single byte from the I2C bus.
int  write (int address, const char *data, int length, bool repeated=false)
  Write to an I2C slave.
int  write (int data)
  Write single byte out on the I2C bus.
void  start (void)
  Creates a start condition on the I2C bus.
void  stop (void)
  Creates a stop condition on the I2C bus.
virtual void  lock (void)
  Acquire exclusive access to this I2C bus.
virtual void  unlock (void)
  Release exclusive access to this I2C bus.
int  transfer (int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event=I2C_EVENT_TRANSFER_COMPLETE, bool repeated=false)
  Start non-blocking I2C transfer.
void  abort_transfer ()
  Abort the on-going I2C transfer.

Interface

/media/uploads/chris/pinout-thumbnails.jpg
See the Pinout page for more details

The default frequency of the I2C interface is 100KHz.

I2C is a two wire serial protocol that allows an I2C Master exchange data with an I2C Slave. The I2C protocol support upto 127 devices per bus. The I2C interface can be used for writing data words out of the I2C port, returning the data recieved back from I2C slave. The I2C clock frequency can be configured.

References