#include <Wire.h>
#include <Adafruit_SSD1306.h>
// OLED display resolution
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// OLED display object
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
// Pin definitions for the buttons
const int startButtonPin = 2;
const int stopButtonPin = 3;
const int resetButtonPin = 4;
int start=0;
int stp=digitalRead(stopButtonPin);
// Variables to store button state
bool startButtonState = false;
bool stopButtonState = false;
bool resetButtonState = false;
// Variables to store the current time
unsigned long startTime;
unsigned long currentTime;
unsigned long elapsedTime = 0;
bool isRunning = false;
void setup() {
Serial.begin(115200);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize OLED display
display.clearDisplay(); // clear the display's memory
display.display(); // update the display
// Set the button pins as inputs
pinMode(startButtonPin, INPUT_PULLUP);
pinMode(stopButtonPin, INPUT_PULLUP);
pinMode(resetButtonPin, INPUT_PULLUP);
stp=digitalRead(stopButtonPin);
}
void loop() {
startButtonState = digitalRead(startButtonPin) == LOW;
stopButtonState = digitalRead(stopButtonPin) == 0;
resetButtonState = digitalRead(resetButtonPin) == LOW;
// Start the stopwatch if the start button is pressed
if (startButtonState && !isRunning) {
start=start+1;
}
else{
elapsedTime = 0;
start=0;}
if(start==1){
startTime = millis();
isRunning = true;
}
// Stop the stopwatch if the stop button is pressed
if(stp == 1){
if (stopButtonState && isRunning) {
currentTime = millis();
elapsedTime = currentTime - startTime + elapsedTime;
isRunning = false;
}
}
if (stp == 0){
if (!stopButtonState && isRunning) {
currentTime = millis();
elapsedTime = currentTime - startTime + elapsedTime;
isRunning = false;
}
}
// Reset the stopwatch if the reset button is pressed
if (resetButtonState) {
elapsedTime = 0;
isRunning = false;
}
display.clearDisplay(); // clear the display's memory
display.setTextSize(2); // set text size to 2
display.setTextColor(WHITE); // set text color to white
// Display "Timer" on the first line
display.setCursor(12, 05);
display.println("*Sverker*");
display.setCursor(25, 28);
display.setCursor(12, 50);
display.println("MM:SS:Mls");
// Display the elapsed time in the middle of the second line
if (isRunning) {
currentTime = millis();
unsigned long runningTime = currentTime - startTime + elapsedTime;
display.setCursor(25, 28);
display.print((runningTime / 60000L));
display.print(":");
display.print(((runningTime % 60000L) / 1000L));
display.print(":");
display.println(((runningTime % 1000L)));
} else {
display.setCursor(25, 28);
display.print((elapsedTime / 60000L));
display.print(":");
display.print(((elapsedTime % 60000L) / 1000L));
display.print(":");
display.println(((elapsedTime % 1000L)));
}
display.display(); // update the display
}