Module i2c_hal

I2C Hardware Abstraction Layer behavior.

Description

This module defines the behavior that platform-specific I2C modules must implement. It provides a common interface for I2C (Inter-Integrated Circuit) operations across all supported platforms.

Currently, only ESP32 provides an I2C implementation.

Lifecycle

An I2C bus is opened with open/1 and closed with close/1. The returned handle is passed to all subsequent operations.

Reading data

Data can be read from I2C devices using read_bytes/3 or read_bytes/4:

  • read_bytes/3 reads a number of bytes directly from a device at the given address.

  • read_bytes/4 reads a number of bytes from a specific register within a device.

Writing data

There are two approaches for writing data:

Direct writes: write_bytes/3 and write_bytes/4 write data to a device address, optionally specifying a register:

  i2c:write_bytes(I2C, 16#68, 16#0D, <<16#FF>>).

Transaction-based writes: For more control, use begin_transmission/2, followed by one or more calls to write_byte/2 or write_bytes/2, and finalize with end_transmission/1:

  i2c:begin_transmission(I2C, 16#68),
  i2c:write_byte(I2C, 16#0D),
  i2c:write_bytes(I2C, <<16#FF, 16#00>>),
  i2c:end_transmission(I2C).

Configuration parameters

The open/1 function accepts a proplist of configuration parameters. Common parameters include:

  • {scl, pin()} - SCL (clock) pin number

  • {sda, pin()} - SDA (data) pin number

  • {clock_speed_hz, pos_integer()} - Clock speed in Hz

  • {peripheral, string() | binary()} - I2C peripheral name (e.g. "i2c0", "i2c1")

Example

  I2C = i2c:open([{scl, 22}, {sda, 21}, {clock_speed_hz, 100000}]),
  {ok, Data} = i2c:read_bytes(I2C, 16#68, 16#75, 1),
  i2c:write_bytes(I2C, 16#68, 16#6B, 0),
  i2c:close(I2C).

Data Types

address()


address() = 0..127

7-bit I2C device address (e.g. 16#68).

i2c()


i2c() = port() | pid() | term()

Handle returned by open/1. On ESP32, this is either a port (port driver mode) or a resource tuple (NIF mode).

params()


params() = [term()]

Initialization parameters for the I2C bus. See the module documentation for common parameters.

register()


register() = non_neg_integer()

Register address within an I2C device.