////////////////////////////////////////////////////
// File Name: KeyboardProjectRight (SLAVE)
// Revision: 1.0
// Date started: 5/19/2023
// Designed and programmed by Lucas Meyers

//pin D2: I2C SDA  |   usb   |   pin A3:  aux. pot
//pin D3: I2C SCL  |         |   pin A2:  col 8
//pin D4: col 7    |         |   pin A1:  col 6
//pin D5: row 5    |         |   pin A0:  col 5
//pin D6: row 4    |         |   pin D15: col 4
//pin D7: row 3    |         |   pin D14: col 3
//pin D8: row 2    |         |   pin D16: col 2
//pin D9: row 1    |_________|   pin D10: col 1
///////////////////////////////////////////////////

#include <Wire.h> //i2c connection

const int SLAVE_ADDY = 8;
const int ROWS = 5;
const int COLS = 8;

const int rowPins[ROWS] = {9, 8, 7, 6, 5};
const int colPins[COLS] = {A2, 4, A1, A0, 15, 14, 16, 10};

//char keyMap[ROWS][COLS] = {
//  {'6' , '7' , '8' , '9' , '0' , '-' , '+', '\t'},
//  {'y' , 'u' , 'i' , 'o' , 'p' , '[' , ']', '\\'},
//  {'h' , 'j' , 'k' , 'l' , ';' , '\'', '\t','\t'},
//  {'n', 'm' , ',' , '.' , '/' , '\t' , '\t','\t'},
//  {'\t', ' ', '\t', '\t', '\t', '\t' , '+', '\t'},
//};

/////////funciton prototypes: ///////////////
void printByteArray(const unsigned char* array, size_t length);
////////////////////////////////////////////

byte keyStatus[ROWS] = {
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000
};

void setup() {
  Wire.begin(SLAVE_ADDY);   
  
  for (int i = 0; i < ROWS; i++) {  //initialize all rows
    pinMode(rowPins[i], OUTPUT);
  }

  for (int j = 0; j < COLS; j++) {  //initialize all cols
    pinMode(colPins[j], INPUT_PULLUP);
  }
  
  Wire.onRequest(requestEvent); //send keyStatus
}

void loop() {

  for (int i = 0; i < ROWS; i++) { //iterate through each row
    
    digitalWrite(rowPins[i], LOW);  //set row to be checked low
    delayMicroseconds(10);  //for stabilization

    for (int j = 0; j < COLS; j++) { //iterate through each col
      if(digitalRead(colPins[j]) == LOW) {
        keyStatus[i] |= (1 << j); //set bit
      }
      
      else {
        keyStatus[i] &= ~(1 << j); //clear bit
      }
    }
    

    digitalWrite(rowPins[i], HIGH);  //set row high once checked
    delayMicroseconds(100);  //for stabilization
  }
  
  delay(1);    //for stabilization
}

void requestEvent() {
  for(int i = 0; i<5; i++){
    Wire.write(keyStatus[i]);  //write each byte of the keyStatus array
  }
}