Timer1.attachInterrupt( timerIsr ) problem

hi,
i'm working with arduino mega To calculate harmoic of signal but i don't know why my result is not correct ( is not the same every time "c" ) and my counter stopping always in the 21 but Was due to him increase every time to 50 please help me.

that's my program :

void setup() 
{
  Serial.begin(57600);
  pinMode(A0,INPUT);
 Timer1.initialize(400);
 Timer1.attachInterrupt( timerIsr ); 
} 
void timerIsr()
{
x=analogRead(A0);
var[n]=x;
n=n+1;
Serial.println(n);
if(n==50) {
interrupts();
}
}

Firstly you are hanging the system by calling Serial in an ISR:

void timerIsr()
{
  x=analogRead(A0);
  var[n]=x;
  n=n+1;
  Serial.println(n);  // MUST NOT CALL Serial methods in an ISR!!!!!!!
  if(n==50) {
    interrupts();    // pointless, interrupts are re-enabled on exiting an ISR
  }
}

secondly you confuse == with = here:

 for (i ==1;i<51;i++)

Thirdly variables shared between an ISR and the rest of the code must
be declared volatile, and if more than a single byte in size have to be
accessed within “noInterrupts() ; … ; interrupts () ;” from the main
body of the program to avoid mangling.

hi MarkT thank you for your answer,
i changed "== "by" = "and i cleared " interrupt" and i wrote volatile unsigned long var[n] but nothing happened. maybe i made ??a mistake in your instructions no ?
another question :How do I guarantee that "n" is increment to the 50 without put the serial inside the ISR ?

click the MODIFY button in the upper right of the post window.
Highlight all you code.
click the "#" CODE TAGS button on the toolbar above just to the left of the QUOTE button.
click SAVE (at the bottom).
When you post code on the forum, please make a habit of using the code tags "#" button.

coupa:
How do I guarantee that "n" is increment to the 50 without put the serial inside the ISR ?

That's the fun of programming with interrupts - you can't use the normal methods to verify the ISR is working.

...R

coupa:
i changed "== "by" = "and i cleared " interrupt" and i wrote volatile unsigned long var[n] but nothing happened.

You need to do these things, too:

  • Declare n as volatile. It's shared between the ISR and other code.
  • Delete the Serial.print() from Timer1 ISR. That statement is what's stops execution.

How do I guarantee that "n" is increment to the 50 without put the serial inside the ISR ?

Serial.print() n from loop().

i think that your sketch still won't give you accurate results after you make those changes, but it ought to run. The best I can tell, there will still be plenty of things wrong with it. Your code is garbled because you didn't use code tags when you posted it. Anyone who wants to help you will have to guess at what your code really looks like. It's easy for you to make your intent clear; it's hard to guess what you meant. It's been said before in this thread, but I'll be repetitive and say it again:

Use code tags when you post code.