/* * I2C Echo Server * Receive one byte from Master, echo the same byte to Master. */ #define MY_ADDRESS 0x0B #include volatile byte received; volatile int count = 0; void setup() { Serial.begin(9600); Wire.begin(MY_ADDRESS); Serial.println("--- Echo Server ---"); Wire.onReceive(receiveCommand); Wire.onRequest(sendAnswer); } void loop() { static int lastCount = 0; if (count != lastCount) { Serial.print(lastCount + 1); Serial.print(" "); printChar(received); lastCount++; } } /* * Receive a byte from Master */ void receiveCommand(int howMany) { received = Wire.read(); count++; } /* * Send a byte to Master */ void sendAnswer() { Wire.write(received); } /* * Utility print byte received/sent */ void printChar(byte car) { Serial.print("Char "); byte bit = 0x80; for (int i = 0; i < 8; i++) { byte digit = car & bit; Serial.print(digit ? '1' : '0'); bit >>= 1; } Serial.println(); }