I2C class Reference
I2C API Reference

I2C is a method for communicating with other electronic components. The strongest feature of I2C is that multiple units can be connected to the same wiring. Therefore, if there are many sensors, they can be connected to the same I2C, making wiring easy. Unlike UART and SPI, data is sent while communicating with the other party, so if there is no other party or it refuses, the transmission itself will result in an error. Instead, the communication speed is not so fast as other methods such as SPI.

The features of I2C are as follows:

  • Two-way communication using only two lines, and multiple units can communicate.
  • There is a master-slave system, and a lots of slave devices can be connected to one master device.
  • The slave device has its address.
  • The master device starts communicating with one slave device at any time, and data is written and read.
  • The slave device always "responds" to the master device for both writing and reading, and an error will occur if there is no reply.
  • The slave device can respond to the master device, sayings "Wait a minute, I'm preparing now." or "It's impossible." These responses are called NAK.

The points of wiring

I2C communicates on two bidirectional lines, SDA and SCL, so open drain and pull-up resistor are needed.

The internal pull-up resistor in the microcomputer is so weak that it may not be enough for I2C. For stable communication, it is necessary to pull up externally with a resistance of several kiloohms. It is weak in communication over long distances than UART and SPI.

Initial Settings

The number of available I2C depends on a device. In terms of obniz Board series, it is only I2C0. Set the I2C by i2c.start(). The I2C is different from IO, and specify the IO number for SDA and SCL of I2C in start().

For example, if IO0 is SDA and IO1 is SCL in the master mode, the code is as follows:

// Javascript Example

var i2c = obniz.getFreeI2C();
i2c.start({mode:"master", sda:0, scl:1, clock:400000}); 

Get unused I2C by obniz.getFreeI2C(), or directly set the I2C.

// Javascript Example

obniz.i2c0.start({mode:"master", sda:0, scl:1, clock:400000}); 

With pull you can specify internal pull-up for SDA and SCL. What can be set with io.pull() can be used. Up to 400kHz when using internal pull-up. In particular, since the internal pull-up with 3V is weak, if you set the internal pull-up with 3V, it will be up to 100kHz. If the voltage is over, an error will occur. Also, if GND is not connected to the other party's circuit or sensor, and you want to connect IO to the other party's GND, you can also specify the IO used in GND.

// Javascript Example

obniz.i2c0.start({mode:"master", sda:0, scl:1, gnd:2, clock:400000, pull:"5v"}); 

These are for the case of master. The initial settings for slave is different from these. Please check the each page.


The started I2C ends by i2c.end().