Skip to content

3cky/usb-i2c-android

Repository files navigation

usb-i2c-android

This 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

Usage

Add jitpack.io repository to your root build.gradle:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Add library to dependencies:

dependencies {
    implementation 'com.github.3cky:usb-i2c-android:1.3.1'
}

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 code:

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

// Set bus clock speed to 400 kbit/s, if supported by adapter 
if (i2cAdapter.isClockSpeedSupported(UsbI2cAdapter.CLOCK_SPEED_FAST)) {
    i2cAdapter.setClockSpeed(UsbI2cAdapter.CLOCK_SPEED_FAST);
}

// 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();

Sample app

For simple I²C device scanner sample app, check an app module.

License

This library is licensed under LGPL Version 2.1. Please see LICENSE.txt for the complete license.

About

Android USB host driver library for USB I2C adapters.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages