#include <Arduino.h>
// LedControl.h provides convenient functions for a MAX7219 LED matrix.
#include <LedControl.h>

// LedControl constructor order is DIN, CLK, CS, number of devices.
// Create one matrix object: data pin 12, clock pin 10, chip-select pin 11, one device.
LedControl matrix(12, 10, 11, 1);
// A two-dimensional array stores seven letter patterns, each made from five byte columns.
const byte LETTERS[7][5] = {
  {0x7E, 0x88, 0x88, 0x88, 0x7E}, // a
  {0x10, 0x20, 0x20, 0x10, 0x3E}, // r
  {0xFE, 0x12, 0x22, 0x12, 0x0E}, // d
  {0x3E, 0x04, 0x02, 0x04, 0x3E}, // u
  {0x00, 0x02, 0xBE, 0x22, 0x00}, // i
  {0x1E, 0x20, 0x20, 0x10, 0x1E}, // n
  {0x1C, 0x22, 0x22, 0x22, 0x1C}  // o
};

// Wake the matrix, set brightness, and clear any old pixels.
void setup() {
  // Device index 0: false means do not leave it in shutdown mode.
  matrix.shutdown(0, false);
  // Set the brightness level (0–15) to a middle value.
  matrix.setIntensity(0, 8);
  matrix.clearDisplay(0);
}

// First show letters, then run several LED pattern animations.
void loop() {
  // Walk through each of the seven entries in the LETTERS array.
  for (uint8_t letter = 0; letter < 7; ++letter) {
    matrix.clearDisplay(0);
    // Set five matrix rows from the selected stored pattern.
    for (uint8_t row = 0; row < 5; ++row) matrix.setRow(0, row, LETTERS[letter][row]);
    delay(500);
  }
  matrix.clearDisplay(0);
  delay(500);

  // Make a row-by-row flashing pattern using nested loops.
  for (uint8_t row = 0; row < 8; ++row) {
    for (uint8_t blink = 0; blink <= row; ++blink) {
      delay(50);
      // 0xA0 is a hexadecimal bit pattern; each set bit lights a pixel.
      matrix.setRow(0, row, 0xA0);
      delay(50);
      matrix.setRow(0, row, 0);
    }
  }
  // Repeat the pattern a column at a time.
  for (uint8_t col = 0; col < 8; ++col) {
    for (uint8_t blink = 0; blink <= col; ++blink) {
      delay(50);
      matrix.setColumn(0, col, 0xA0);
      delay(50);
      matrix.setColumn(0, col, 0);
    }
  }
  // Finally visit each LED coordinate and blink it as the animation fills.
  for (uint8_t row = 0; row < 8; ++row) {
    for (uint8_t col = 0; col < 8; ++col) {
      delay(50);
      matrix.setLed(0, row, col, true);
      delay(50);
      for (uint8_t blink = 0; blink < col; ++blink) {
        matrix.setLed(0, row, col, false);
        delay(50);
        // Set one LED at the current row/column position to ON.
        matrix.setLed(0, row, col, true);
        delay(50);
      }
    }
  }
}
