Using timer interupt to break out of button hold problem

Hi there,

I've been having a small problem with this code and cannot seem to get whats going wrong.

The programme must do the following:
check if button is being pressed -> if button press == 1 sec -> do something & break from loop
the timer is also switched on only when it is being used - I need to use timer2 as timer1 will be used by another function.

I am using an Arduino uno.

my code looks as follows (take note of the commented out delay(1) call for now)

unsigned char count = 0;    //global variable to be accessed by ISR

void setup(){
DDRC = 0b000000;      //All Port C to Inputs (A0:5)
PORTC = 0b001111;      //Pull-up enbabled on A0:3   -Button connected to A3

TCCR2A = 0b00000000;      //no OC/IC or PWM
TCCR2B = 0b00000000;      //timer switched off for now
TIMSK2 = 0b00000001;      //interrupts enabled


sei();                  //enable interrupts

void loop(){
  if(!(PINC & _BV(3))){      //if button A3 is pushed
    TCCR2B = 0b00000111;     //turns timer on - prescaler==1024 
    count = 0;               //resets count  
      while(!(PINC & _BV(3))){    //waits here while button is pressed
      //  delay(1);   
         if(count >= 61){       //timer2 overflows 61 times (1 second timed)     
         Serial.println("1 second passed");
         //does stuff here        
    Serial.println("breaked out");
    TCCR2B = 0b00000000;     //turns timer off

// ISR for button hold - Timer2 overflow

The calculation that an overflow needs to occur 61 times for 1 seconds is correct.
This piece of code does not work. from what I gather, it is not executing the if(count>=61) line. however, when I add in the delay(1) call - it miraculously does work as expected.

Anyone have any ideas? I thought the delay() function uses timer0 and cannot make any connections as to why the code then works.


Firstly, count needs to be "volatile" or the compiler will optimize it out. Secondly, why on earth are you using a timer for this? Just use millis()!

Ah Fantastic, thank you! didn't think of that.

I have quite a lot going on in my bigger project - staying away from arduino functions that I don't completely understand (get more control over the hardware that way :smiley: )

There's not a lot to understand about millis(). It basically does what you are trying to do, but in a nicer way.

A timer ticks away incrementing the millis counter (the same as your "counter" variable), and the millis() function returns that counter (the same as you examining your "counter" variable).

You're replicating what millis() does needlessly.

fair enough, but im going to remain stubborn :open_mouth:

thanks again!

fair enough, but im going to remain stubborn :open_mouth:

thanks again!

I'll only allow that if you will allow me to remain bemused.