/* This is the sketch that is uploaded on the Xiao RP2040. * The Xiao acts as a master device on the I2C bus to send and * receive message from the slave at address 8. */ #include String input = ""; // stores the input message for echoing on the serial monitor void setup() { Wire.begin(); // join I2C bus (address optional for master) Serial.begin(9600); // start serial for output } void loop() { Wire.beginTransmission(8); // Sends a '0' to indicate that we are listening Wire.write(0); Wire.endTransmission(); int l = Wire.requestFrom(8, 1); // Read from peer if (l == 1) { // A '1' means the peer is sending char n = Wire.read(); // First read the length of the message if (n > 0) { // If we have any data Wire.beginTransmission(8); // Send '1' means we are requesting the data Wire.write(1); Wire.endTransmission(); Wire.requestFrom(8, n); // request n bytes from slave device #8 while (Wire.available()) { // slave may send less than requested char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character } } } // Take input from the computer if (Serial.available() > 0) { Wire.beginTransmission(8); // Starts sending message to peer Wire.write(2); // A '2' indicates the master is sending while (Serial.available() > 0) { char c = Serial.read(); Wire.write(c); // Send the message to peer input += c; // Collects the input message if (c == '\n') { // Print the message that we sent and reset the buffer Serial.print("me: "); Serial.print(input); input = ""; } } Wire.endTransmission(); } }