#include <LiquidCrystal_I2C.h>
//initialize lcd
LiquidCrystal_I2C lcd(0x27,16,2);
#define startstopPin 3
#define resetPin 2
#define startstopLED 4
byte startstopState = LOW;
byte oldstartstopState = LOW;
byte start = false;
int hh=0, mm=0, ss=0, ms=0;
void setup() { // put your setup code here, to run once
pinMode(startstopPin, INPUT_PULLUP);
pinMode(resetPin, INPUT_PULLUP);
pinMode(startstopLED, OUTPUT);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor (0,0);
lcd.print(" FYP Wear Rig ");
lcd.setCursor (0,1);
lcd.print(" Stopwatch ");
delay(2000);
lcd.clear();
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() {
startstopState = digitalRead(startstopPin);
if(startstopState != oldstartstopState){
oldstartstopState = startstopState;
if(startstopState == LOW){
start = (start == true) ? false: true;
}
}
if(digitalRead (resetPin) == LOW && start == false){
ms=0, ss=0, mm=0, hh=0; // Reset stopwatch
delay(100);
}
lcd.setCursor (0,0);
lcd.print(" Stopwatch ");
lcd.setCursor (2,1);
lcd.print((hh/10)%10);
lcd.print(hh%10);
lcd.print(":");
lcd.print((mm/10)%10);
lcd.print(mm%10);
lcd.print(":");
lcd.print((ss/10)%10);
lcd.print(ss%10);
lcd.print(":");
lcd.print((ms/100)%10);
lcd.print((ms/10)%10);
lcd.print(ms%10);
if(start==true){
digitalWrite(startstopLED, HIGH); // Turn LED on.
}else{
digitalWrite(startstopLED, LOW); // Turn LED off.
}
}
ISR(TIMER1_COMPA_vect){
if(start == 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;}
}
}
}