Timer problem


beneath small stripped hypothetical program illustrate problem have timers.

two buttons. 1 of them starts timer counts down time in seconds, other increase start time (+1 each push).

the problem comes when start count down right after have pushed settimebutton.then intervals becomes: 65 4 3 2 1 0.  in other words count down 5 should come after 1s comes immediately. next times press countdownbutton intervals becomes right: 6 5 4 3 2 1 0.

when give cnt initial value other 0 same problem occurs without first pressing settimebutton.

code: [select]

#define settimebutton 4
#define countdownbutton 5

boolean countdownstate = false;
volatile boolean newvalue = false;   
int startvalue = 5;
volatile int cnt;

void setup()
{
  pinmode(settimebutton,input_pullup);
  pinmode(countdownbutton,input_pullup);
  inittimer();
  serial.begin(9600);
  serial.print(startvalue);
}

void loop()
{
   if((digitalread(countdownbutton) == low) && (countdownstate == false))
   {
      startcountdown();   
   }
   if(digitalread(settimebutton) == low)
   {
      increasestarttime();
   }
   if(cnt == 0)
   {
      stopcountdown();
   }
   if(newvalue)
   {
      newvalue = false;
      serial.print(cnt);
   }
}

void startcountdown()
{
   countdownstate = true;
   serial.print(startvalue);
   cnt = startvalue;
   tcnt1 = 0;
   timsk1 |= (1<<ocie1a);   // enable timer compare match interrupt 
}

void stopcountdown()
{
   tcnt1 = 0;
   countdownstate = false;
   timsk1 &= ~(1<<ocie1a);     // disable timer compare match interrupt
}

void increasestarttime()
{
   delay(50);
   if(digitalread(settimebutton) == low)
   {
      startvalue++;
      cnt = startvalue;
      newvalue = true;
   }
}

void inittimer()
{
   tccr1a = 0;
   tccr1b = 0;
   tcnt1 = 0;                  // initial timer value
   ocr1a = 15625;              // number of ticks reach 1s prescaler 1024   
   tccr1b |= (1<<wgm12)|(1<<cs10)|(1<<cs12);   // prescaler 1024 , ctc mode
}

isr(timer1_compa_vect)       
{
   cnt--;
   newvalue = true;
}




any appreciated!

if first interrupt triggered early, maybe have @ clearing  bit

ocf1a in register tifr1 before enabling interrupts manipulating ocie1a


Arduino Forum > Using Arduino > Programming Questions > Timer problem


arduino

Comments

Popular posts from this blog

Error compiling for board Arduino/Genuino Uno.

Installation database is corrupt

esp8266 (nodemcu 0.9) client.write très lent ???