0

This is my code for stopwatch. I want the timer to start when a push button is pressed.

#include <LiquidCrystal.h>
#define PIN 2

const uint16_t load = 0;
volatile int  sec=0;
unsigned int minute =0, hour = 0;
volatile bool buttonPressed = false;

LiquidCrystal lcd(13,12,11,10,9,8);

void setup()
{
  pinMode(PIN,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN), timecount, CHANGE);
  lcd.begin(20,4);
}

ISR(TIMER1_COMPA_vect)
{
  sec++;
}

void loop()
{
  if(buttonPressed)
  {
    buttonPressed = false;
  }
  if(sec > 59)
  {
    minute++;
    sec = 0;
  }
  if(minute > 59)
  {
    hour++;
    minute = 0;
  }
  if(hour<=9999){
    lcd.setCursor(4,0);
    lcd.print("Stopwatch");  
    lcd.setCursor(3,1);
    lcd.print("hhhh : mm : ss");
    char buf[20];
    sprintf(buf,"%04d : %02d : %02d",hour,minute,sec);
    lcd.setCursor(3,2);
    lcd.print(buf);
  }
}

void timecount()
{
  buttonPressed = true;
  noInterrupts();
  TCCR1A = 0;            
  TCCR1B = 0;           
  TCNT1  = 0;            
  OCR1A  = 62500 - 1;    
  TCCR1B = _BV(WGM12)   
         | _BV(CS12);    
  TIMSK1 = _BV(OCIE1A);  
  interrupts();
}

The timer is getting enabled without even pressing the pushbutton. Any suggestion?

  • 1
    Try adding a small delay after the pinMode. Or use FALLING instead of CHANGE. – Gerben Jul 21 '18 at 11:29
  • Thanks it worked and if i want to pause the timer with the same Push button after a while of counting then what should I do? – Peouse Dutta Jul 21 '18 at 12:00
  • 1
    Setup the timer in your “setup” function, except for the CS12 bit. Then in the timecount function toggle the CS12 bit. – Gerben Jul 21 '18 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.