possible bug

Hi,
Let me start by saying that this is my first post on the forum.

I have a dc motor with an optical sensor from an old wheelmouse, to measure how far the dc motor has run. The sensor is connected to interrupt pin 0 (digital pin 2). In my sketch I wish to run the motor for a specific number of steps.
First I power on the motor then calls the function posted below, and the turns off the motor again.

int run_DC(unsigned int steps){
  teeth=0;
  while(steps > teeth){
  }
  return 0;
}

The variable "teeth" is incremented for each interrupt from the sensor, see code below:

void dc_tooth(){ //keeps track of dc-motor
teeth++;
}

My Problem is that the motor does not always run all the desired number of "steps", sometimes it stops too early, while the condition of the while-loop is still fulfilled.

I have tried debugging by printing the "steps" value before the motor starts and the "teeth" value after the motor has stopped, and when its stops early the "teeth" value is till lower than "steps", so i am quite sure that it the problem does not relate to the mechanical parts of the system.

To point out the problem:
why does the arduino get out of the loop when the condition is still fulfilled?

It is a weird problem because its occurrence doesn't seem to follow any kind of pattern.

The only kind of pattern I can see, is that the early stop values are the same every time for a specific desired value: 256 for a desired 500, 768 for a desired 1000 steps, 1792 for 2000, and 2816 for 3000.

Can this be caused by some kind of overflow or interrupt?

Regards
/tro4els

Assuming teeth is an int, your problem may be that the interrupt handler may be changing the value teeth in the middle of the (steps > teeth) test in the run_DC function. The simplest way of fixing this is to forget about the interrupt handler and put code in the while loop that monitors and counts the number of transitions.

Perhaps something like this:

int run_DC(unsigned int steps){
  int teeth=0;
  while(steps > teeth){
      while(digitalRead(teethPin) == HIGH) 
            ; // wait for the pin to go high
      while(digitalRead(teethPin) == LOW)        
           ; // wait for the pin to go low
       teeth++ ; // a tooth has passed the sensor so inc the counter   
  }
  return 0;
}

Thank you for your fast reply.

It seems to work with the structure you suggested.
Thank You very much

Good to hear you have that working.

Its been my experience with Arduino projects that interrupts are best avoided except in those rare cases where there is no other easy way to do a task.