/* This sketch is uploaded on the Arduino Uno. * It acts as the slave device at address 8 on the I2C bus. */ #include String msg = ""; // stores the message to be sent String input = ""; // buffers the input we get from the computer to output them at once int mode; // indicates transmission state // handler function for incomming data void recv(int count) { char c = Wire.read(); // read the transmition state from peer and save if (c == 0 || c == 1) { // '0' means the peer is listening for data, '1' means the peer is requesting the data mode = c; } else if (c == 2) { // '2' means the peer is sending data while (Wire.available() > 0) { char c = Wire.read(); // read message and print Serial.write(c); } } } // handler function when requested data by the peer void req() { if (mode == 0) { // '0' means the peer is waiting for data Wire.write(msg.length()); // send the length of the message } else if (mode == 1) { // '1' means the peer is requesting data Wire.write(msg.c_str(), msg.length()); // send the actual message msg = ""; // resets the message buffer } } void setup() { Serial.begin(9600); Wire.begin(8); // set the address of the device Wire.onReceive(recv); // setup callback functions Wire.onRequest(req); } void loop() { while (Serial.available() > 0) { // read input from the computer char c = Serial.read; msg += c; // buffer the message to be send when requested by peer input += c; // buffer the line we input if (c == '\n') { // input end, print to the serial monitor and reset Serial.print("me: "); Serial.print(input); input = ""; } } }