Strange behavior of my arduino uno

Hello my fellow arduino enthusiasts,

Im using an arduino nano board to control a big machine, The machine has a rotary encoder, which gives short impulses. I catch these pulses with an interrupt routine. If a certain number of pulses is reached, the machine stops and runs out. The encoder signals are further recorded. To monitor how long the machine needs to run out, I stop it with the arduino when it reaches 1000 encoder pulses. In the following I will wait until the machine has run down. The pulses are still counted. The difference to the 1000 pulses at which the machine stops is output.

Now it happens again and again that negative values are output, which should be impossible according to my understanding.

Does anyone have an idea what the cause could be?

The Code:

volatil int a;

void setup() {

Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), count, RISING);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
a = 0;
}

void loop() {
if (a >1000) {
digitalWrite(13, LOW);
delay(1500);
Serial.println(a - 1000);
a=0;
digitalWrite(13,HIGH);
}
}

void count(){
++a;
}

NOTES:
I tried it with a as an volatile and a "normal" int value. It doesnt change the output.
The Pin 13 is used to start and stop the machine.

Some recorded values:
-69
168
-74
-77
154
-79
-39
174
167
458
165
197
181
-71

Thank you very much for your help. I hope im in the right place here for this request.

Greetings from Germany

In loop() you have these lines

if (a >1000) {
 // and
Serial.println(a - 1000);

both of which must read the variable that is updated by the ISR. Because the variable is an int comprising two bytes it is possible that half of it can change due to an interrupt while the other half is being read. The correct way to deal with it is to take a copy of the variable while interrupts are briefly halted - like this

noInterrupts();
  copyOfA = a;
  a = 0;
interrupts();
if (copyOfA > 1000) {
  // etc

...R
PS ... single character variable names are awful - meaningless and impossible to find with Search

PPS ... When posting code please use the code button </>
codeButton.png

so your code 
looks like this

and is easy to copy to a text editor See How to use the Forum

Thank you really much. I had already thought something like this. I will try it next week.

You are absolutly right about the variable names. This Code was just a "debug"code after i got this error on my main program.

Greetings