/*
Modified example to bit bang MAX7219 for fun

*/


#include <MD_MAX72xx.h>

//#define	MAX_DEVICES	2
#define	MAX_DEVICES	1

const int maxX = MAX_DEVICES * 8 - 1;
const int maxY = 7;

#define	CLK_PIN		13
#define	DATA_PIN	11
#define	CS_PIN		10

#define VERT_PIN A0
#define HORZ_PIN A1
#define SEL_PIN  2

#define DLY 1

MD_MAX72XX mx = MD_MAX72XX(MD_MAX72XX::PAROLA_HW, CS_PIN, MAX_DEVICES);

int x = 0;
int y = 0;

void setup() {
  Serial.begin(9600);
  mx.begin();
  mx.control(MD_MAX72XX::INTENSITY, MAX_INTENSITY / 2);
  mx.clear();

  pinMode(VERT_PIN, INPUT);
  pinMode(HORZ_PIN, INPUT);
  pinMode(SEL_PIN, INPUT_PULLUP);
}

// the loop function runs over and over again forever
void loop2() {
  int horz = analogRead(HORZ_PIN);
  int vert = analogRead(VERT_PIN);
  if (vert < 300) {
    y = min(y + 1, maxY);
  }
  if (vert > 700) {
    y = max(y - 1, 0);
  }
  if (horz > 700) {
    x = min(x + 1, maxX);
  }
  if (horz < 300) {
    x = max(x - 1, 0);
  }
  if (digitalRead(SEL_PIN) == LOW) {
    mx.clear();
  }
  mx.setPoint(y, x, true);
  mx.update();
  delay(100);
}

/*
* --______________________
* ==X====X====X====X====X=
*    D15  D14 
* ____--___--___--___--___
*/

void send( int cmd ){
  int mask = 0x8000;
  int cnt  = 0;

  digitalWrite( DATA_PIN, 0 );
  digitalWrite(CS_PIN,1);

  digitalWrite(CS_PIN,0);
  delay(10);
  mask = 0x8000;
  //Serial.println( "===" );
  //Serial.println( cmd , HEX );   
  for( cnt = 0 ; cnt < 16 ; cnt++ ){
    delay(DLY); 
    //Serial.println( ( cmd & mask ), HEX );
    if ( (cmd & mask ) != 0  ){
      digitalWrite( DATA_PIN, 1 );
    } else { 
      digitalWrite( DATA_PIN, 0 );
    }  
    // mask >> 1 is arthimatic shift 
    if ( mask == 0x8000){
      mask = 0x4000;
    } else {  
      mask = mask>>1;
    } 
    delay(DLY);   
    digitalWrite( CLK_PIN,1 );
    delay(DLY);   
    digitalWrite( CLK_PIN,0 );
    delay(DLY);      
  }
  digitalWrite(CS_PIN,1);
  delay(DLY);   
}

void loop() {
//  #bottom row - lsb on left, msb on right
send( 0x08AA );
send( 0x0755 );
send( 0x06AA );
send( 0x0555 );
send( 0x04AA );
send( 0x0355 );
send( 0x02AA );
send( 0x0155 );
//time.sleep(1);

//# top row - lsb on left, 
send( 0x0101 );
send( 0x0202 );
send( 0x0304 );
send( 0x0408 );
send( 0x0510 );
send( 0x0620 );
send( 0x0740 );
send( 0x0880 );

//#control - not implimented in wokwi
//send( 0x0A01 );
//send( 0x0B07 );
//send( 0x0C01 );
//send( 0x0C01 );
;
//#send( 0x0f55 );

//time.sleep(1);
send( 0x08AA );
send( 0x0755 );
send( 0x06AA );
send( 0x0555 );
send( 0x04AA );
send( 0x0355 );
send( 0x02AA );
send( 0x0155 );
delay(1000);  
}