I²C

#

  • Inter-Integrated Circuit (I²C) is a common serial bus structure, which is used for attaching lower-speed peripheral ICs to processors and microcontrollers in a short-distance and intra-board communication.
  • To know more about I²C, please click here.

Prerequisites

Using I²C

Please read the datasheet to confirm the interface is I²C.

Configuring driver.json

Please declare that your interface is I²C in driver.json. The declaration should be inputs with type as I²C.

{
...
"inputs": {
"i2c": {
"type": "i2c",
"args": {
"address": -1
}
}
}
}

Interface Properties

The following properties is accepted for I²C:

address - defines I²C address from the datasheet.

Writing a Driver

Reading Data

The driver could read data from there bus. For example, you will set a command as 0x01, and then read data in callback according to the datasheet:

function read(callback) {
i2c.readBytes(0x01, function (error, value) {
if (error) {
callback(error);
return;
}

callback(undefined, 0xff - value);
});
}

Writing Data

The driver could write data to the bus. Here is an example that writes a byte to the bus:

var data = 0;
...

i2c.writeByte(-1, data);

For more information , please read I²C API document.

Application

Light Intensity Sensor (GY-30)

Light intensity sensor is a sensor that can measure luminance intensity. According to the datasheet, GY-30 needs an I²C interface whose address is 35. An I²C interface has been declared in driver.json, and the interface address is 35.

{
"models": [
"GY-30"
],
"inputs": {
"i2c": {
"i2c": {
"type": "i2c",
"args": {
"address": 35
}
}
}
}
}

We provide the module with a method listed as follows:

  • getIlluminance
    • Please write 0x20 to setup I²C interface.
    • Wait for a delay, then read two bytes from I²C interface to calculate illuminance.
'use strict';

var driver = require('ruff-driver');

module.exports = driver({
attach: function (inputs, context) {
this._i2c = inputs['i2c'];
},

exports: {
getIlluminance: function(callback) {
var i2c = this._i2c;

i2c.writeByte(-1, 0x20, function(error) {
if (error) {
callback(error);
return;
}

setTimeout(function() {
i2c.readBytes(-1, 2, function (error, values) {
if (error) {
callback(error);
return;
}
var value = Math.floor((values[0] << 8 | values[1]) / 1.2);
callback(undefined, value);
});
}, 180);
};
}
}
});