Go Down

Topic: How to enable TIMER/COUNTERS of an Arduino uno with a push button? (Read 338 times) previous topic - next topic

PEOUSE

This is my code

Code: [Select]
#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?


PaulRB

Personally I would suggest re-writing it from scratch, using no timers and no interrupts. Just use millis().

PEOUSE


MorganS

All the timers, including millis(), are derived from the same clock. They are all equally accurate.

If you need accurate timing over a long period like 24 hours then you need a real-time clock module.
"The problem is in the code you didn't post."

ChrisTenone

The precision of millis() is based on how many of them you count. If you count 1000 of them, it will be one second with the precision of a few microseconds. So use an RTC to reset your counter every second. That way, your time count will never be more than, say 20 microseconds off (as the worst case.) Your button press reaction is 1000 times less precise.
What, I need to say something else too?

Go Up