// 4x4 Matrix Keyboard Control Master // Uses the Wire library to write LED data to the leds // and read keypress data from the keypad // Refer to the "Keypad I2C Slave" example for use with this sketch. // This example code is in the public domain. #include void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); //Default Serial I/O } byte leds = 0; // Bit array for LED status byte ledbit = 0; // Bit position of LED to switch byte state = 0; // State of selected LED String cmd; void loop() { byte val = 0; // Get LED control command from User (char COMMAND char VAL HI-BYTE char VAL LO_BYTE) // 3 characters required!! All Hex. while (Serial.available()) { char c = Serial.read(); if ((c == '\n') || (c == '\r')) { if (cmd.length() > 2) { uint8_t ledbit = cmd[0] - 48; // Convert char to byte uint8_t state = cmd[1] - 48; if (state > 9) state -= 7; if (state > 15) state -= 32; uint8_t t = cmd[2] - 48; if (t > 9) t -= 7; if (t > 15) t -= 32; state = state * 16 + t; Serial.println(ledbit, HEX); Serial.println(state, HEX); Wire.beginTransmission(8); // transmit to device #8 Wire.write(ledbit); // send LED number Wire.write(state); // send LED state Wire.endTransmission(); // stop transmitting } cmd = ""; delay(100); } else cmd += c; } // Check for key or button press. Wire.requestFrom(8, 2); // request COL ROW from keypad (device #8) byte r; byte c; while (Wire.available()) { // peripheral may send less than requested r = Wire.read(); c = Wire.read(); } if (r != 0xFF) { // flag keypress Serial.print("R "); Serial.println(r, HEX); // print the character Serial.print("C "); Serial.println(c, HEX); // print the character } delay(500); }