Raspberry Pi3 でAndroid ThingsのI2C通信を試してみます。
今回は手元にあったAPDS-9960というジェスチャーセンサーのデバイスで試してみました。
データシートは下記にあります。
https://cdn.sparkfun.com/datasheets/Sensors/Proximity/apds9960.pdf
スレーブアドレスは 0x39 です。
APDS-9960の使い方はこちらが参考になります。
http://www.geocities.jp/zattouka/GarageHouse/micon/Arduino/Gesture/APDS.htm
■公式
https://developer.android.com/things/sdk/pio/i2c.html
今回も公式の通りですぐに試せます。
■スレーブデバイスへの接続
GPIOやPWMと同様に利用可能なデバイス名のリストアップ
1 2 3 4 5 6 7 |
PeripheralManagerService manager = new PeripheralManagerService(); List<String> deviceList = manager.getI2cBusList(); if (deviceList.isEmpty()) { Log.i(TAG, "No I2C bus available on this device."); } else { Log.i(TAG, "List of available devices: " + deviceList); } |
“I2C1″という名前が取得できます。
I2C通信は I2cDevice というクラスを使って行います。
1 |
private I2cDevice mDevice; |
I2cDeviceのopenI2cDevice()を使ってデバイス毎にオープンします。
1 2 3 4 5 |
try { mDevice = manager.openI2cDevice(I2C_DEVICE_NAME, APDS9960_I2C_ADDR); } catch (IOException e) { Log.w(TAG, "Unable to access I2C device", e); } |
■Read / Write
レジスタに対する読み書きは、readRegByte() / writeRegByte() を使います。
1 2 3 4 5 |
1 byteのWrite device.writeRegByte(address, value); 1 byteのRead byte value = device.readRegByte(address); |
複数バイトの読み出し関数なども用意されています。
1 2 3 |
byte[] data = new byte[3]; device.readRegBuffer(startAddress, data, data.length); これだけでdataに入って来ます。 |
実際にこのデバイスを使うのはまた今度。