#include <TM1637Display.h>
// Pins for the tm1637 display module
#define CLK 2
#define DIO 3
TM1637Display display(CLK, DIO);
// constants won't change. They're used here to set pin numbers:
const int BUTTON = 4; // the number of the pushbutton pin
const int PRESS_TIME = 1000; // Time for long press 1000 = 1 second
int mm=0, ss=0, ms=0;
bool timerStart = false;
char Buffer[3] = " "; // create a buffer to hold the numbers
// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
bool isPressing = false;
bool isLongDetected = false;
void setup() {
pinMode(BUTTON, INPUT_PULLUP);
display.setBrightness(0x0f);
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
unsigned long pressedTime = PRESS_TIME;
}
void loop() {
// read the state of the switch/button:
currentState = digitalRead(BUTTON);
if(lastState == HIGH && currentState == LOW) { // button is pressed
pressedTime = millis();
isPressing = true;
isLongDetected = false;
} else if(lastState == LOW && currentState == HIGH) { // button is released
isPressing = false;
releasedTime = millis();
long pressDuration = releasedTime - pressedTime;
if( pressDuration < PRESS_TIME && (timerStart == false)) {
timerStart = true; // Start stopwatch
delay(100);
}
else if( pressDuration < PRESS_TIME && (timerStart == true)) {
timerStart = false; // Stop stopwatch
delay(100);
}
}
if(isPressing == true && isLongDetected == false) {
long pressDuration = millis() - pressedTime;
if( pressDuration > PRESS_TIME ) {
timerStart = false; // Stop stopwatch
ms=0, ss=0, mm=0; // Reset stopwatch
delay(100);
isLongDetected = true;
}
}
display.showNumberDecEx(ss, 0, true, 2, 2);
display.showNumberDecEx(mm, 0b01000000, true, 2, 0);
// save the the last state
lastState = currentState;
}
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>89)
{timerStart = false;} // Stop stopwatch
}