usb-i2c-android is a library for communication with I²C devices on Android using USB I²C adapters connected to the Android USB Host (OTG). No root access or special kernel drivers are required.
Supported adapters in usb-i2c-android
version 1.1.0:
For example, here is I²C 0.96" OLED display working with Pixel 3 phone:
The library also includes a simple I²C device scanner app:
To use the library in your project, first of all, add jitpack.io repository to your root build.gradle
file:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
And then add the library to dependencies:
dependencies {
implementation 'com.github.3cky:usb-i2c-android:1.1.0'
}
Also, add USB host feature usage to your app manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
<uses-feature android:name="android.hardware.usb.host" />
...
</manifest>
Example I²C device communication code (simplified, for complete example please check project app directory):
import com.github.ykc3.android.usbi2c.UsbI2cAdapter;
import com.github.ykc3.android.usbi2c.UsbI2cDevice;
import com.github.ykc3.android.usbi2c.UsbI2cManager;
...
// Get Android UsbManager
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// Find all connected I²C adapters
UsbI2cManager usbI2cManager = UsbI2cManager.create(usbManager).build();
List<UsbI2cAdapter> i2cAdapters = usbI2cManager.getAdapters();
if (i2cAdapters.isEmpty()) {
return;
}
// Get first adapter
UsbI2cAdapter i2cAdapter = i2cAdapters.get(0);
// Request USB access permission
usbManager.requestPermission(i2cAdapter.getUsbDevice(), usbPermissionIntent);
...
// USB permission intent handler called with success result
// Open adapter
i2cAdapter.open();
// Get device with I²C address 0x42
UsbI2cDevice i2cDevice = i2cAdapter.getDevice(0x42);
// Read device register 0x01.
// Throws java.lang.IOException if device is not connected or I/O error caused
byte value = i2cDevice.readRegByte(0x01);
// Close adapter
i2cAdapter.close();
Comments