じゃあ、肝心のArduino側の値をNXTに送るほうのサンプルです。
NXC
#define I2C_PORT IN_1
int getData()
{
byte Wbuf[]={ 0x62,0x20 };
byte Rbuf[2];
short status_code;
int i=2;
int d;
while(I2CCheckStatus(I2C_PORT) == STAT_COMM_PENDING);
status_code = I2CBytes(I2C_PORT, Wbuf, i , Rbuf);
d=Rbuf[0]+(Rbuf[1]<<8) ;
return (d);
}
task main()
{
SetSensorLowspeed(I2C_PORT);
ClearScreen();
NumOut(40,LCD_LINE4,getData());
Wait( 2000 );
}
Arduino
#include <Wire.h>
#define I2C_SLAVE_ADDRESS 0x31
byte requestRegister, requestCommand;
void requestEvent()
{
byte d[2];
int j=-30000;
d[0]=j&0xff;
d[1]=j>>8;
if (requestRegister == 0x20)
{
Wire.send(d,2);
}
}
void receiveEvent(int howMany)
{
requestRegister = Wire.receive();
}
void setup()
{
pinMode(LED_RED, OUTPUT);
digitalWrite(LED_RED, LOW);
Serial.begin(9600);
Wire.begin(I2C_SLAVE_ADDRESS);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() { }
これで、requestEvent() の中で定義した変数 j の値がNXT側に転送されます。
ちょっと以外だったのは・・・
Wire.onReceive(receiveEvent);
を定義しなければならないことです。
Arduino側はリクエストを受けるだけなので、
Wire.onRequest(requestEvent);
があれば、良いのではないか・・・と思うのですが、両方が揃っていないとただしく転送されません。