Skip to content

i2c

ts
import {I2C} from 'mikrojs/i2c'

Communicate with I2C devices such as temperature sensors, displays, and EEPROMs.

Usage

ts
import {I2C} from 'mikrojs/i2c'

const bus = new I2C(0, {sda: 6, scl: 7, freq: 400000})
bus.begin().orPanic('I2C init failed')

// Scan for devices
const devices = bus.scan().orPanic('scan failed')
console.log('Found devices at:', Array.from(devices))

// Read 2 bytes from device at address 0x44
const data = bus.read(0x44, 2).orPanic('read failed')

bus.end()

Constructor

new I2C(busNo, options?)

ts
new I2C(busNo: 0 | 1, options?: I2COptions)

Parameters:

  • busNo: I2C bus number (0 or 1)
  • options: see I2COptions

Methods

bus.begin()

ts
begin(): Result<void, I2CError>

Initialize the I2C bus. Must be called before any read/write/scan operations.

bus.end()

ts
end(): Result<void, I2CError>

Deinitialize the bus and release resources.

bus.read(address, bytes)

ts
read(address: number, bytes: number): Result<Uint8Array, I2CError>

Read bytes bytes from the device at address.

bus.write(address, data, stop?)

ts
write(address: number, data: Uint8Array, stop?: boolean): Result<void, I2CError>

Write data to the device at address. Set stop to false to send without a stop condition (for repeated start).

bus.scan()

ts
scan(): Result<Uint8Array, I2CError>

Scan the bus and return an array of addresses that responded.

Types

I2COptions

ts
interface I2CBaseOptions {
  freq?: number // clock frequency in Hz (default: 100000)
  timeout?: number // timeout in ms
}

interface I2COptionsWithPins extends I2CBaseOptions {
  sda: number // SDA pin
  scl: number // SCL pin
}

type I2COptions = I2CBaseOptions | I2COptionsWithPins

If sda and scl are omitted, the bus uses the board's default I2C pins.

Errors

I2CError

VariantFieldsDescription
BusInitFailedmessageFailed to initialize the bus
BusDeinitFailedmessageFailed to deinitialize
NotStartedbegin() was not called
MissingPinsPins required but not provided
AddDeviceFailedmessageFailed to add device to bus
WriteFailedmessageWrite operation failed
WriteTooLargeWrite data exceeds buffer size
ReadFailedmessageRead operation failed