#include <LedControl.h>
#include <EEPROM.h>
// ===== CONFIG =====
#define NUM_MODULES 1 // change to 4 for 32x8
#define MAX_VALUE (NUM_MODULES * 64)
#define DIN_PIN 11
#define CLK_PIN 13
#define CS_PIN 10
#define BTN_UP 2
#define BTN_DOWN 3
#define BTN_RESET 4
const unsigned long debounceDelay = 300;
const unsigned long eepromDelay = 3000; // wait 3s after last change
// ==================
LedControl lc = LedControl(DIN_PIN, CLK_PIN, CS_PIN, NUM_MODULES);
int value = 0;
int lastStored = 0;
unsigned long lastChangeTime = 0;
unsigned long lastDebounce = 0;
void setup() {
pinMode(BTN_UP, INPUT_PULLUP);
pinMode(BTN_DOWN, INPUT_PULLUP);
pinMode(BTN_RESET, INPUT_PULLUP);
for (int i = 0; i < NUM_MODULES; i++) {
lc.shutdown(i, false);
lc.setIntensity(i, 8);
lc.clearDisplay(i);
}
EEPROM.get(0, value);
value = constrain(value, 0, MAX_VALUE);
lastStored = value;
drawPixels();
}
void loop() {
bool changed = false;
if (millis() - lastDebounce > debounceDelay) {
if (!digitalRead(BTN_UP) && value < MAX_VALUE) {
value++;
changed = true;
}
if (!digitalRead(BTN_DOWN) && value > 0) {
value--;
changed = true;
}
if (!digitalRead(BTN_RESET)) {
value = 0;
changed = true;
}
if (changed) {
drawPixels();
lastDebounce = millis();
lastChangeTime = millis();
}
}
// EEPROM write after inactivity
if (value != lastStored &&
millis() - lastChangeTime > eepromDelay) {
EEPROM.put(0, value);
lastStored = value;
}
}
void drawPixels() {
// Clear all
for (int m = 0; m < NUM_MODULES; m++) {
lc.clearDisplay(m);
}
// Turn on pixels [0 .. value-1]
for (int i = 0; i < value; i++) {
int module = i / 64;
int pixel = i % 64;
int x = pixel % 8;
int y = pixel / 8;
lc.setLed(module, y, x, true);
}
}