#include <Arduino.h>
// Define pin numbers for the buttons
#define START_BUTTON_PIN 2
#define STOP_BUTTON_PIN 4
#define RESET_BUTTON_PIN 5
// Variables to track stopwatch state and time
volatile bool stopwatchRunning = false;
volatile unsigned long startTime = 0;
volatile unsigned long elapsedTime = 0;
// Interrupt service routine for the start button
void startButtonISR() {
if (!stopwatchRunning) {
startTime = millis();
stopwatchRunning = true;
}
}
// Interrupt service routine for the stop button
void stopButtonISR() {
if (stopwatchRunning) {
elapsedTime = millis() - startTime;
stopwatchRunning = false;
}
}
// Interrupt service routine for the reset button
void resetButtonISR() {
if (!stopwatchRunning) {
elapsedTime = 0;
}
}
void setup() {
Serial.begin(9600);
// Configure button pins as inputs with pull-up resistors
pinMode(START_BUTTON_PIN, INPUT_PULLUP);
pinMode(STOP_BUTTON_PIN, INPUT_PULLUP);
pinMode(RESET_BUTTON_PIN, INPUT_PULLUP);
// Attach interrupt service routines to the buttons
attachInterrupt(digitalPinToInterrupt(START_BUTTON_PIN), startButtonISR, FALLING);
attachInterrupt(digitalPinToInterrupt(STOP_BUTTON_PIN), stopButtonISR, FALLING);
attachInterrupt(digitalPinToInterrupt(RESET_BUTTON_PIN), resetButtonISR, FALLING);
}
void loop() {
if (stopwatchRunning) {
unsigned long currentTime = millis();
unsigned long displayTime = elapsedTime + (currentTime - startTime);
// Display elapsed time
Serial.print("Elapsed Time: ");
Serial.print(displayTime / 1000); // Convert milliseconds to seconds
Serial.println(" seconds");
}
delay(100); // Add a small delay to debounce buttons
}