// Project: ATtiny85 version of My4x4Matrix
// Date:    2016 01 03
// Author:  C. D'Arcy
// Video:   https://www.youtube.com/watch?v=NOl9qziIsAo&feature=youtu.be
// Reference:shiftOutCode, Hello World, Authors: Carlyn Maw & Tom Igoe
// Notes:  Drives a custom 4x4 LED matrix assembled with T. Garrow's 3D Jig
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Pin connected to ST_CP of 74HC595
int latchPin = 1;
//Pin connected to SH_CP of 74HC595
int clockPin = 0;
////Pin connected to DS of 74HC595
int dataPin = 2;
// column Anode
byte cols;
// row Cathode
byte rows;
byte data;
int pause = 200;

void setup() {
  //set pins to output because they are addressed in the main loop
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  Serial.begin(9600);
}

void display(byte data) {
  //ground latchPin and hold low for as long as you are transmitting
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, data);
  //return the latch pin high to signal chip that it
  //no longer needs to listen for information
  digitalWrite(latchPin, HIGH);

}

void cycleRows(int times) {
  rows = 0x01;
  cols = 0x01;
  for (int i = 0; i < times << 2; i++) {
    display(cols << 4 | ~rows);
    delay(pause);
    rows = rows < 8 ? rows << 1 : 1;
  }
}

void cycleColumns(int times) {
  rows = 0;
  for (int i = 0; i < times << 2; i++) {
    display(cols << 4 | rows);
    delay(pause);
    cols = cols < 8 ? cols << 1 : 1;
  }
}

void pixel(int c, int r) {
  display(1 << (7 - c) | (~(1 << r) & 0xF));
}

void snake(int times) {
  for (int r = 0; r < 4; r++)
    for (int c = 0; c < 4; c++) {
      if (r % 2 == 0)
        pixel(c, r);
      else
        pixel(3 - c, r);
      delay(pause);
    }
}

void flashAll(int times) {
  byte all = B11110000;
  for (int i = 0; i < times<<1; i++) {
    display(all);
    all = ~all;
    delay(pause);
  }
}
void fourCorners(int times){
  for(int i=0; i<times; i++){
    display(B10010110);
    delay(pause);
    display(0);
    delay(pause);
  }
}
void loop() {
  cycleRows(1);
  cycleColumns(1);
  snake(1);
  fourCorners(4);
  flashAll(4);
//  while(1);
}