/* Homework 2 - Stopwatch | Cody Leisgang | 2/20/23
This program functions as a stopwatch. It requires 3 pushbuttons with
3 10k pull-down resistors. It is setup to display output in serial
monitor. Start will start the timer, pause will pause the timer
only when the timer is running, and Stop will stop and/or reset.
===================================================================*/
#define startButton 9
#define pauseButton 8
#define stopButton 7
//Initialize start, pause and stop state variables
int start = 0;
int pause = 1;
int stop = 0;
int startState = start;
int pauseState = pause;
int stopState = stop;
int sec10 = 0;
int minute = 0;
int sec = 0;
int timer = 0;
void setup() {
// initial Serial communication
Serial.begin(9600);
// designate inputs
pinMode(startButton, INPUT);
pinMode(pauseButton, INPUT);
pinMode(stopButton, INPUT);
//title and brief instructions
Serial.println("Stopwatch:");
Serial.println("Start (9) | Pause (8) | Stop/Reset (7)");
}
void loop() {
// toggle and read start button status, ensure button cannot be pressed multiple times in a row
if (digitalRead(startButton) == HIGH && start != 1 && pause == 1) {
//set variables to start timer
Serial.println("Start");
switch (start) {
case 0:
start = 1;
pause = 0;
break;
}
// if button is not pressed and state has changed, store new state
} else if (digitalRead(startButton) == LOW && startState != start) {
startState = start;
}
// toggle and read Pause button, ensure timer is running
if (digitalRead(pauseButton) == HIGH && pause != 1 && start == 1) {
Serial.println("Pause");
switch (pause) {
case 0:
pause = 1;
start = 0;
break;
}
// if button is not pressed and state has changed, store new state
} else if (digitalRead(pauseButton) == LOW && pauseState != pause) {
pauseState = pause;
}
// toggle and read Stop button
if (digitalRead(stopButton) == HIGH && stopState == stop ) {
// stop timer and reset variables
Serial.println("Stop");
switch (stop) {
case 0:
stop = 1;
pause = 1;
start = 0;
timer = 0;
break;
}
//reset stop button state
} else if (digitalRead(stopButton) == LOW && stop == 1) {
stop = 0;
}
// start timer
if (start == 1) {
timer++; //add time per loop
minute = timer / 1000 / 60; //convert time to minutes
sec = timer / 100; //convert time to seconds
sec10 = sec10ths(timer); //convert time to tenths of a second
//add extra zero for two digits if less than 10; output section follows
if (minute < 10) {
Serial.print("0");
}
Serial.print(minute);
Serial.print(":");
sec = secDigits(sec); //check and/or convert setconds to 2 digits
Serial.print(sec);
Serial.print(":");
Serial.println(sec10, 10);
}
delay(1);
}
//convert time to seconds with two digits
int secDigits(int inputTime) {
if (inputTime < 10) {
Serial.print("0");
}
while (inputTime > 100) {
inputTime = inputTime - 100;
}
return inputTime;
}
//convert time to tenths of a second with one digit
int sec10ths(int inputTime) {
while (inputTime > 9) {
inputTime = inputTime - 10;
}
return inputTime;
}