#define ROWS 7
#define COLUMNS 20

int rowPins[] = {A1, A2, A3, A5, A6, A7, A8};
int columnPins[] = {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53};

unsigned int vals[COLUMNS]; 
int band = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("starting!");
  Serial.println(sizeof (int));
  
  for (int r = 0; r < ROWS; r++) {
      pinMode(rowPins[r], OUTPUT);
  }

  for (int c = 0; c < COLUMNS; c++) {
      pinMode(columnPins[c], OUTPUT);
  }
  //Zero out vals
  for (int i = 0; i < COLUMNS; i++) vals[i] = 0;
  
  clearPins();
}
int col = 0;
void loop() {
   unsigned int nextVal = 0;
   //Read next value
   if (Serial.available() > 0) {
        nextVal = Serial.read();
        if (nextVal == '0') nextVal = 129;
        if (nextVal < 128) { //i.e if the 8th bit from the right is 0(aka 1st bit from the left)
            //Use the value to determine the lights that should be on
            int numVal = 0;
            int power = 1;
            for (int i = 0; i < nextVal; i++) {
                numVal += power;
                power *= 2;
            }
            nextVal = numVal;
        } else { // if the 8th bit from the right is 1, meaning use the bits to the right
            //Subtract the 128
            nextVal -= 128;
        } 

          // lights should be on
        band++;
        if (band % COLUMNS == 0) band = 0;
        vals[band] = nextVal;

   }
    
   //Light the bands
   
   //Shifting over one band at a time
   int cBand = band;
   for (int i = 0; i < COLUMNS; i++) {
       unsigned int value = vals[cBand];
       for (int l = 0; l < ROWS; l++) {
           /*if (i == 0) { 
             Serial.print(value); Serial.print(" "); Serial.print(l); Serial.print(" "); Serial.println(bitRead(value, l));
           }*/
           if (bitRead(value, l)) power(l, i);
       }
       cBand--;
       if (cBand < 0) cBand = COLUMNS - 1;
   }
   
   //Overwriting bands right to left
   /*for (int i = 0; i < COLUMNS; i++) {
       unsigned int level = vals[i];
       for (int l = 0; l < level && l < ROWS; l++) {
           power(l, i);
       }
   }*/
   
}

void clearPins() {
    for (int r = 0; r < ROWS; r++) {
         for (int c = 0; c < COLUMNS; c++) {
               digitalWrite(rowPins[r], LOW);
               digitalWrite(columnPins[c], HIGH);
         }
    }
}

void power(int row, int column) {
    //clearPins();
    //Send a high signal through the column and make the row an output
    //if (row ==6 && column == 0) {Serial.print("Lighting top "); Serial.println(row);}
    digitalWrite(columnPins[column], LOW);
    digitalWrite(rowPins[row], HIGH);
    delayMicroseconds(1);
    digitalWrite(columnPins[column], HIGH);
    digitalWrite(rowPins[row], LOW);
}
