以下、SAKURAをマスター、KURUMIをスレーブにしてWire(I2C)でつなぐときのサンプルです。
●●●ハード構成:
SCL:SAKURAのA5、KURUMIのD7につなげて、1Kぐらいでプルアップ
SDA:SAKURAのA4、KURUMIのD8につなげて、1Kぐらいでプルアップ
●●●スケッチ:
●●SAKURAマスタ側(Wireライブラリのインポートが必要です。)
#include <rxduino.h>#include <Wire.h>void setup(){ Wire.begin(); // join i2c bus (address optional for master)}byte x = 0;void loop(){ Wire.beginTransmission(80); // transmit to device #4 Wire.write("x is "); // sends five bytes Wire.write(x); // sends one byte Wire.endTransmission(); // stop transmitting x++; delay(500);}
●●KURUMIスレーブ側
#include <RLduino78.h>#include <Wire.h>// function that executes whenever data is received from master// this function is registered as an event, see setup()void receiveEvent(int howMany){ while(1 < Wire.available()) // loop through all but the last { char c = Wire.read(); // receive byte as a character Serial.print(c); // print the character } int x = Wire.read(); // receive byte as an integer Serial.println(x); // print the integer}void setup(){ delay(5000); Wire.begin(80); // join i2c bus with address #4 Wire.onReceive(receiveEvent); // register event Serial.begin(9600); // start serial for output}void loop(){ delay(100);}
KURUMIから以下のように出力されます。
x is 198
x is 199
x is 200
x is 201
x is 202
x is 203
x is 204
x is 205
x is 206
x is 207
x is 208
x is 209
x is 210
x is 211
x is 212
●●●スレーブアドレスの注意
スケッチは、Arduinoのサンプルそのままですが、スレーブアドレスを80(0x50)にしています。
Arduinoサンプルのスレーブアドレス4の場合、I2C規格の予約アドレスと競合するため、KURUMIちゃんがきちんと動いてくれません。
www.nxp.com/.../UM10204_JA.pdf
表 3. 予約済のアドレス
X = don’t care; 1 = HIGH; 0 = LOW.
スレーブアドレスR/W ビ ッ ト説明
0000 000 0 ゼネラルコールアドレス[1]
0000 000 1 スタートバイト[2]
0000 001 X CBUS アドレス[3]
0000 010 X 異なるバスフォーマット用に予約[4]
0000 011 X 将来の使用のため予約
0000 1XX X Hs-mod マスタコード
1111 1XX X デバイスID
1111 0XX X 10 ビットスレーブアドレス指定