#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 bt_start = 2;
const int bt_stop = 3;
const int bt_reset = 4;
int hh=0, mm=0, ss=0, ms=0;
int start=0;
int stp=digitalRead (bt_stop);
bool timerStart = 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(bt_start, INPUT_PULLUP);
pinMode(bt_stop, INPUT_PULLUP);
pinMode(bt_reset, INPUT_PULLUP);
noInterrupts(); // disable all interrupts
TCCR1A = 0; // set entire TCCR1A register to 0 //set timer1 interrupt at 1kHz // 1 ms
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // set timer count for 1khz increments
OCR1A = 1999; // = (16*10^6) / (1000*8) - 1
//had to use 16 bit timer1 for this bc 1999>255, but could switch to timers 0 or 2 with larger prescaler
// turn on CTC mode
TCCR1B |= (1 << WGM12); // Set CS11 bit for 8 prescaler
TCCR1B |= (1 << CS11); // enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
interrupts(); // enable
}
void loop() {
if(digitalRead (bt_start) == 0){
start=start+1;
}
else{start=0;}
if(start==1){
ms=0, ss=0, mm=0, hh=0; // Reset stopwatch
timerStart = true; // Start stopwatch
}
if (stp == 1) {
if(digitalRead (bt_stop) == 0){
timerStart = false; // Stop stopwatch
}
}
else if (stp == 0) {
if(!digitalRead (bt_stop) == 0){
timerStart = false; // Stop stopwatch
}
}
if(digitalRead (bt_reset) == 0){
ms=0, ss=0, mm=0, hh=0; // Reset stopwatch
}
stp=digitalRead (bt_stop);
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 (timerStart==true) {
display.setCursor(12, 28);
display.print((mm/10)%10);
display.print(mm%10);
display.print(":");
display.print((ss/10)%10);
display.print(ss%10);
display.print(":");
display.print((ms/100)%10);
display.print((ms/10)%10);
display.print(ms%10);
}
else
{
display.setCursor(12, 28);
display.print((mm/10)%10);
display.print(mm%10);
display.print(":");
display.print((ss/10)%10);
display.print(ss%10);
display.print(":");
display.print((ms/100)%10);
display.print((ms/10)%10);
display.print(ms%10);
}
display.display(); // update the display
}
ISR(TIMER1_COMPA_vect){
if(timerStart == true){ms=ms+1;
if(ms>999){ms=0;ss=ss+1;
if(ss>59){ss=0; mm=mm+1;}
if(mm>59){mm=0; hh=hh+1;}
}
}
}