// Arduino slave three bytes
#include <Wire.h>
#include <Servo.h>
Servo myservo1;
Servo myservo2;
int pos = 0;
byte i2c_rcv_opcode;
byte i2c_rcv_target; // data received from I2C bus
byte i2c_rcv_value; // data received from I2C bus
//byte i2c_send; // confirmation
void setup(){
myservo1.attach(3);
myservo2.attach(13);
int inMin = 3; // Lowest output pin
int inMax = 13; // Highest output pin
for(int i=inMin; i<=inMax; i++)
{
pinMode(i, OUTPUT);
}
Wire.begin(0x08); // join I2C bus as Slave with address 0x08
// event handler initializations
Wire.onReceive(dataRcv); // register an event handler for received data
Wire.onRequest(dataRqst); // register an event handler for data requests
// initialize global variables
i2c_rcv_opcode = 255;
i2c_rcv_target = 255;
i2c_rcv_value = 255;
}
void loop(){
}
//received data handler function
void dataRcv(int numBytes){
while(Wire.available()) { // read all bytes received
i2c_rcv_opcode = Wire.read();
i2c_rcv_target = Wire.read();
i2c_rcv_value = Wire.read();
}
switch ( i2c_rcv_opcode) {
case 100:
digitalWrite(i2c_rcv_target,i2c_rcv_value) ;
break;
case 101:
myservo1.write(i2c_rcv_value) ;
delay(1000);
break;
case 102:
myservo2.write(i2c_rcv_value) ;
delay(1000);
break;
default:
break;
}
}
// requests data handler function
void dataRqst(){
Wire.write(i2c_rcv_target); // send confirmation
Wire.write(i2c_rcv_value); // send confirmation
}