// Define pins for 7 segment display
const int SEGMENT_PINS[4][7] = {
{2, 3, 4, 5, 6, 7, 8}, // digit 1
{2, 3, 4, 5, 6, 7, 8}, // digit 2
{2, 3, 4, 5, 6, 7, 8}, // digit 3
{2, 3, 4, 5, 6, 7, 8} // digit 4
};
// Define pins for digits
const int DIGIT_PINS[4] = {9, 10, 11, 12};
// Define pins for buttons
const int START_STOP_PIN = 13;
const int RESET_PIN = 1;
// Define variables to store time
int minutes = 0;
int seconds = 0;
int tenths = 0;
// Define variables to store button states
int startStopButtonState = LOW;
int resetButtonState = LOW;
// Define variables to store whether timer is running and whether it has been reset
bool isRunning = false;
bool isReset = true;
void setup() {
// Set segment and digit pins as output
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 7; j++) {
pinMode(SEGMENT_PINS[i][j], OUTPUT);
}
pinMode(DIGIT_PINS[i], OUTPUT);
}
// Set button pins as input
pinMode(START_STOP_PIN, INPUT_PULLUP);
pinMode(RESET_PIN, INPUT_PULLUP);
// Start serial communication
Serial.begin(9600);
}
void loop() {
// Read button states
startStopButtonState = digitalRead(START_STOP_PIN);
resetButtonState = digitalRead(RESET_PIN);
// If reset button is pressed, reset the timer
if (resetButtonState == LOW && !isReset) {
isRunning = false;
isReset = true;
minutes = 0;
seconds = 0;
tenths = 0;
}
// If start/stop button is pressed, start or stop the timer
if (startStopButtonState == LOW) {
isRunning = !isRunning;
delay(100);
}
// If the timer is running, increment time
if (isRunning) {
tenths++;
if (tenths == 10) {
tenths = 0;
seconds++;
}
if (seconds == 60) {
seconds = 0;
minutes++;
}
if (minutes == 10) {
minutes = 0;
}
}
// Display time
displayDigit(0, minutes);
delay(2);
displayDigit(1, seconds / 10);
delay(2);
displayDigit(2, seconds % 10);
delay(2);
displayDigit(3, tenths);
delay(2);
}
// Display a digit on a 7 segment display
void displayDigit(int digit, int value) {
// Define which segments to turn on for each digit
const bool digitSegments[10][7] = {
{1, 1, 1, 1, 1, 1, 0}, // 0
{0, 1, 1, 0, 0, 0, 0}, // 1
{1, 1, 0, 1, 1, 0, 1}, // 2
{1, 1, 1, 1, 0, 0, 1}, // 3
{0, 1, 1, 0, 0, 1, 1}, // 4
{1, 0, 1, 1, 0, 1, 1}, // 5
{1, 0, 1, 1, 1, 1, 1}, // 6
{1, 1, 1, 0, 0, 0, 0}, // 7
{1, 1, 1, 1, 1, 1, 1}, // 8
{1, 1, 1, 1, 0, 1, 1}, // 9
};
// Turn on the necessary segments for the given value
for (int i = 0; i < 7; i++) {
digitalWrite(SEGMENT_PINS[digit][i], digitSegments[value][i]);
}
// Turn on the appropriate digit
for (int i = 0; i < 4; i++) {
digitalWrite(DIGIT_PINS[i], i == digit ? LOW : HIGH);
}
}