// Use the MD_MAX72XX library to Print some text on the display
//
// Demonstrates the use of the library to print text.
//
// User can enter text on the serial monitor and this will display as a
// message on the display.
// Library doc https://majicdesigns.github.io/MD_MAX72XX/class_m_d___m_a_x72_x_x.html

#include <MD_MAX72xx.h>
#include <SPI.h>

#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define HARDWARE_TYPE MD_MAX72XX::DR1CR0RR0_HW    
#define MAX_DEVICES 8

#define CLK_PIN   32  // or SCK
#define DATA_PIN  33  // or MOSI
#define CS_PIN    25 // or SS

// 'test-frame', 32x16px
const unsigned char epd_bitmap_test_frame [] PROGMEM = {
  0x00, 0x00, 0x00, 0x00, 
  0x00, 0x00, 0x00, 0x00, 
  0x00, 0x00, 0x00, 0x00, 
  0x22, 0x00, 0x00, 0x44, 
  0x44, 0x00, 0x00, 0x22, 
  0x89, 0x80, 0x01, 0x91, 
  0x92, 0x40, 0x02, 0x49, 
  0x82, 0x40, 0x02, 0x41, 
  0x81, 0x80, 0x01, 0x81, 
  0x80, 0x04, 0x40, 0x01, 
  0x80, 0x09, 0x20, 0x01, 
  0x87, 0x89, 0x21, 0xe1, 
  0x40, 0x06, 0xc0, 0x02, 
  0x27, 0x80, 0x01, 0xe4, 
  0x00, 0x00, 0x00, 0x00, 
  0x00, 0x00, 0x00, 0x00
};

// Array of all bitmaps for convenience. (Total bytes used to store images in PROGMEM = 80)
const int epd_bitmap_allArray_LEN = 1;
const unsigned char* epd_bitmap_allArray[1] = {
  epd_bitmap_test_frame
};


// SPI hardware interface
//MD_MAX72XX mx = MD_MAX72XX(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// Arbitrary pins
MD_MAX72XX mx = MD_MAX72XX(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

byte fByte(byte c){ char r=0; for(byte i = 0; i < 8; i++){ r <<= 1; r |= c & 1; c >>= 1; } return r;}
void renderFrame(){

  //Top half of the display
  int fsize = sizeof(epd_bitmap_test_frame);
  for (int i = 0; i < fsize/2; i+=4) {
    for (int d=0; d<=3; d++){
      //For each of the driver, from 0 to 3
      byte rowData = pgm_read_byte(&epd_bitmap_test_frame[i + d]);
      mx.setRow(d,d,7 - int(i/4),fByte(rowData));
    }
  }
  //Bottom half of the display
  for (int i = fsize/2; i < fsize; i+=4) {
    for (int d=4; d<=7; d++){
      //For each of the driver, from 4 to 7
      byte rowData = pgm_read_byte(&epd_bitmap_test_frame[i + (d - 4)]);
      mx.setRow(d,d,7 - (int(i/4) - 8),fByte(rowData));
    }
  }
  
}

void setup(){
  mx.begin();

  Serial.begin(57600);
  Serial.print("\nFrame Rendering");
  renderFrame();
  Serial.print("\nDone");
}

void loop(){

}
