I2C Server

Hex.pm API docs CI

I2C Server wraps Circuits.I2C reference in a GenServer, creating a separate process for each I2C device. I2C device processes are identified with a composite key of bus name and bus address. By default, I2C device processes are stored in Registry, but you can alternatively use :global.


Just add i2c_server to your list of dependencies in mix.exs:

def deps do
    {:i2c_server, "~> 0.1"}


# Get a PID for a device at the address 0x77 on the "i2c-1" bus
iex> device1 = I2cServer.server_process("i2c-1", 0x77)

# A different device has a different PID
iex> device2 = I2cServer.server_process("i2c-1", 0x38)

# Write 0xff to the register 0x8A
iex> I2cServer.write(device1, 0x8A, 0xff)
iex> I2cServer.write(device1, 0x8A, <<0xff>>)
iex> I2cServer.write(device1, <<0x8A, 0xff>>)
iex> I2cServer.write(device1, [0x8A, 0xff])
iex> I2cServer.write(device1, [0x8A, <<0xff>>])

# Read 3 bytes from the register 0xE1
iex> I2cServer.write_read(device1, 0xE1, 3)
iex> I2cServer.write_read(device1, <<0xE1>>, 3)
{:ok, <<0, 0, 0>>}

I2C device processes will be created under I2cServer.I2cDeviceSupervisor dynamically.


You can change settings in your config file such as config/config.exs file. Here is the default configuration.

config :i2c_server,
  transport_module: Circuits.I2C,
  registry_module: I2cServer.DeviceRegistry

Registry module

The default :registry_module is I2cServer.DeviceRegistry that is a thin wrapper of Registry. You can alternatively use :global for global registration.

config :i2c_server,
  registry_module: :global

Transport module

The default :transport_module is Circuits.I2C. You will most likely use the default, but you may want to replace it with a mock for testing.

config :i2c_server,
  transport_module: I2cServer.MockTransport