/*
  Controlling MAX7219 LED Dot Matrix using Arduino SPI.

  Copyright (C) 2021, Uri Shaked.
*/

#include <SPI.h>

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

#define SEGMENT_COUNT 4

void sendAll(int registerIndex, int value) {
  digitalWrite(CS_PIN, LOW);
  for (int i = 0; i < SEGMENT_COUNT; i++) {
    SPI.transfer(registerIndex);
    SPI.transfer(value);
  }
  digitalWrite(CS_PIN, HIGH);
}

void clearDisplays() {
  for (int row = 1; row <= 8; row++) {
    sendAll(row, 0);
  }
}

void setup() {
  SPI.begin();
  sendAll(0xf, 0); // Disable test mode
  sendAll(0xb, 7); // Set scanlines to 8
  clearDisplays();
  sendAll(0xc, 1); // Enable display
}

int pixel = 0;

void loop() {
  digitalWrite(CS_PIN, LOW);
  // First segment: set a pixel in the 5th line
  SPI.transfer(5);
  SPI.transfer(bit(pixel));
  // Second segment: set a pixel in the 4th line
  SPI.transfer(4);
  SPI.transfer(bit(pixel));
  // Third segment: set a pixel in the 3rd line
  SPI.transfer(3);
  SPI.transfer(bit(pixel));
  // Forth segment: set a pixel in the 2nd line
  SPI.transfer(2);
  SPI.transfer(bit(pixel));
  digitalWrite(CS_PIN, HIGH);
  delay(100);
  pixel++;
  if (pixel > 7) {
    pixel = 0;
  }
}