400Hz internal interrupt problem

Hello, after alot of reading on Arduino Interrupts – uCHobby and the datasheet i finaly managed to put this code together:

volatile int count = 0;
volatile byte latency;
volatile byte timerLoadValue;
int m = 0;

byte SetupTimer2()
{
  byte result;
  result = 256 - 156;

  TCCR2A = 0;
  TCCR2B = 1<<CS22 | 1<<CS21 | 0<<CS20; 
  TIMSK2 = 1<<TOIE2;
  TCNT2=result; 
  return(result);
}

ISR(TIMER2_OVF_vect)
{
  count++;
  TCNT2=TCNT2+timerLoadValue; 
}

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Timer2 Test");
  timerLoadValue = SetupTimer2();
  Serial.print("Timer2 Load:");
  Serial.println(timerLoadValue, DEC);
}

void loop(void)
{
  if (m <= millis())
  {
    Serial.println(count);
    count = 0;
    m = millis() + 1000;
  }
}

Simply what it do is output the number of interrupts eatch second... The problem is that it stops after 32 loops... So, what did i do wrong?

Thank you
/J

m is overflowing after 32 loops because its declared as an int. The largest signed integer value is +32,767 so m goes negative at the point when 1000 is addeded to 32000.When that happens, the statement (m <= millis()) is false and after that m is never incremented.

Declaring m as a long will solve the problem, declaring it as an unsigned long is even better.

Thanks mem, that was a really stupid programing error...
Oh well now it works...

Thank you once again
/J

Its not stupid at all. If my personal experience is anything to go by, it happens all the time :wink:

Almost every bug I have ever found in my code (and that is a number so big it would probably also overflow an int) has seemed like a trivial mistake once I had found it, even if it took me days to track down. I do keep telling myself to take more care coding to avoid this kind of thing, but it still happens frequently enough that I have learned to look for 'stupid' mistakes first in my code when my programs misbehave.