#include <LedControl.h>
// Pin definitions for the MAX7219
#define DATA_IN 11 // Pin connected to DATA IN of MAX7219
#define LOAD 8 // Pin connected to LOAD of MAX7219
#define CLOCK 13 // Pin connected to CLOCK of MAX7219
#define MAX_DEVICES 4 // Number of 8x8 matrices in the chain
// Initialize LedControl library
LedControl lc = LedControl(DATA_IN, CLOCK, LOAD, MAX_DEVICES);
// Button Pin
const int buttonPin = 7; // Button connected to pin 2
int buttonState = 0; // Variable to hold button state
int lastButtonState = 0; // Variable to remember last button state
unsigned long lastDebounceTime = 0; // For debouncing the button
unsigned long debounceDelay = 50; // debounce time (milliseconds)
// Stopwatch time variables
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
bool running = false; // Indicates if the stopwatch is running
void setup() {
// Set button pin as input
pinMode(buttonPin, INPUT_PULLUP);
// Initialize the MAX7219 display
for (int i = 0; i < MAX_DEVICES; i++) {
lc.shutdown(i, false); // Wake up the display
lc.setIntensity(i, 8); // Set brightness to middle
lc.clearDisplay(i); // Clear display
}
}
void loop() {
// Read the button state
int reading = digitalRead(buttonPin);
// Check for button press (debouncing)
if (reading != lastButtonState) {
lastDebounceTime = millis(); // reset debounce timer
}
// If the button state has changed and the debounce delay has passed
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button is pressed (LOW signal, due to INPUT_PULLUP)
if (reading == LOW && lastButtonState == HIGH) {
if (running) {
// Stop the stopwatch and reset it
running = false;
elapsedTime = 0;
} else {
// Start the stopwatch
startTime = millis() - elapsedTime;
running = true;
}
}
}
// Store the button state for the next loop
lastButtonState = reading;
// If the stopwatch is running, update the elapsed time
if (running) {
elapsedTime = millis() - startTime;
}
// Display the time in seconds (for simplicity)
unsigned long seconds = elapsedTime / 1000;
unsigned long minutes = seconds / 60;
seconds = seconds % 60;
// Display minutes and seconds on the MAX7219
displayTime(minutes, seconds);
}
void displayTime(unsigned long minutes, unsigned long seconds) {
// Split minutes and seconds into digits
byte digits[4] = {
map(minutes / 10, 0, 9, 0, 15), // Tens place of minutes
map(minutes % 10, 0, 9, 0, 15), // Ones place of minutes
map(seconds / 10, 0, 9, 0, 15), // Tens place of seconds
map(seconds % 10, 0, 9, 0, 15) // Ones place of seconds
};
// Display each digit on the 4x8 matrices
for (int i = 0; i < 4; i++) {
lc.setDigit(i, 0, digits[i], false); // Set the digit on each 8x8 matrix
}
}