#include <LedControl.h>
// Pin definitions for MAX7219
#define DIN 11 // Data In pin
#define CS 10 // Chip Select pin
#define CLK 13 // Clock pin
// Initialize LedControl: 4 modules, using pins DIN, CLK, CS
LedControl lc = LedControl(DIN, CLK, CS, 4);
// Snake properties
int snakeLength = 72; // Length of the snake
int snakeX[72]; // X coordinates of snake segments
int snakeY[72]; // Y coordinates of snake segments
int snakeDirection; // 0: right, 1: down, 2: left, 3: up
int headPos; // Index of snake head
unsigned long lastMove = 0;
int moveDelay = 300; // Delay between movements in ms
void setup() {
// Initialize all MAX7219 modules
for (int i = 0; i < 4; i++) {
lc.shutdown(i, false); // Wake up display
lc.setIntensity(i, 8); // Set brightness (0-15)
lc.clearDisplay(i); // Clear display
}
// Initialize snake at top-left, moving right
for (int i = 0; i < snakeLength; i++) {
snakeX[i] = i; // Start at x=0 to x=7
snakeY[i] = 0; // Top row
}
headPos = snakeLength - 1;
snakeDirection = 0; // Start moving right
}
void loop() {
if (millis() - lastMove >= moveDelay) {
moveSnake();
updateDisplay();
lastMove = millis();
}
}
void moveSnake() {
// Calculate new head position
int newX = snakeX[headPos];
int newY = snakeY[headPos];
switch (snakeDirection) {
case 0: // Right
newX++;
if (newX > 31) { // Hit right edge
newX = 31;
newY++;
snakeDirection = 1; // Turn down
}
break;
case 1: // Down
newY++;
if (newY > 7) { // Hit bottom edge
newY = 7;
newX--;
snakeDirection = 2; // Turn left
}
break;
case 2: // Left
newX--;
if (newX < 0) { // Hit left edge
newX = 0;
newY--;
snakeDirection = 3; // Turn up
}
break;
case 3: // Up
newY--;
if (newY < 0) { // Hit top edge
newY = 0;
newX++;
snakeDirection = 0; // Turn right
}
break;
}
// Shift snake segments
for (int i = 0; i < headPos; i++) {
snakeX[i] = snakeX[i + 1];
snakeY[i] = snakeY[i + 1];
}
// Update head position
snakeX[headPos] = newX;
snakeY[headPos] = newY;
// Ensure continuous running effect by resetting position after one full cycle
if (newX == 0 && newY == 0 && snakeDirection == 0) {
for (int i = 0; i < snakeLength; i++) {
snakeX[i] = i;
snakeY[i] = 0;
}
headPos = snakeLength - 1;
}
}
void updateDisplay() {
// Clear all displays
for (int i = 0; i < 4; i++) {
lc.clearDisplay(i);
}
// Draw snake
for (int i = 0; i < snakeLength; i++) {
int module = snakeX[i] / 8; // Determine which module (0-3)
int moduleX = snakeX[i] % 8; // X position within module
lc.setLed(module, snakeY[i], moduleX, true); // Set LED on
}
}