I2C

i2c.start(sda, scl, clock)

Starts I2C in master mode.

  • sda: IO number used for SDA
  • scl: IO number used for SCL
  • clock: Clock frequency in Hz (e.g., 100 * 1000, 400 * 1000). Up to 1MHz.

The internal pull-up resistors of SDA and SCL are enabled. Use external pull-up resistors as well for stable communication.

An I2C session started from Lua is reserved for Lua, and is not available from obniz.js or other external interfaces.

Return value

Value Meaning
0 Success
1 Missing arguments
2 Invalid clock or IO number
3 I2C is already started, or could not be initialized
local err = i2c.start(1, 2, 400 * 1000);
if err ~= 0 then
  os.log("I2C Error: " .. err);
end

i2c.write(address, data)

Writes data to a slave device.

  • address: 7-bit slave address
  • data: Data to write, as a string

The return value is 0 on success, and a non-zero number on failure (for example, when the slave does not respond). 3 means that I2C has not been started.

i2c.write(0x50, string.char(0x00, 0x10));

i2c.read(address, length)

Reads data from a slave device.

  • address: 7-bit slave address
  • length: Number of bytes to read (1 to 10)

On success, returns the received data as a string. On failure, returns a number: 1 for missing arguments, 2 for a length out of range, and 3 if I2C has not been started or the read failed.

local data = i2c.read(0x50, 2);
if type(data) == "string" then
  os.log("received: " .. data:byte(1) .. ", " .. data:byte(2));
end

i2c.stop()

Stops I2C and returns the SDA / SCL IO to the initial (input) state.

Available for OS7.1.0 and later

After i2c.stop(), you can call i2c.start() again with different settings without rebooting.

The return value is 0 on success, and 1 if I2C has not been started.

i2c.stop();

Example

The following example reads 2 bytes from address 0x00 of an I2C EEPROM (slave address 0x50) every second while online.

local err = i2c.start(1, 2, 100 * 1000); -- SDA: IO1, SCL: IO2, 100kHz
os.log("i2c start ret=" .. tostring(err));

local last = 0;

function on_online_loop()
  local now = os.getTick();
  if now - last < 1000 then
    return;
  end
  last = now;

  -- set the memory address, then read
  if i2c.write(0x50, string.char(0x00, 0x00)) == 0 then
    local data = i2c.read(0x50, 2);
    if type(data) == "string" then
      cloud.pluginSend(data);
    end
  end
end