You are viewing an older revision! See the latest version

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

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.

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


All wikipages