unsigned long in a while loop not working properly

Changing int to unsigned long makes my while loop no longer stop when wanted.

I have my Arduino operating a stepper motor through a driver.

I want the stepper motor to move back and forth a certain amount of times.

Using int for my variable worked fine, the stepper moved exactly how many times I wanted.

I changed int to unsigned long because I wanted 100,000+ movements.

The stepper motor should have stopped moving 1.5 hours ago, but its still going. Its not a time calculation issue. Does an unsigned long variable not work for a while loop?


int dirPin = 2;
int stepperPin = 3;
unsigned long x = 0;

void setup() {  
  pinMode(dirPin, OUTPUT);  
  pinMode(stepperPin, OUTPUT);

void step(boolean dir,int steps){  
  for(int i=0;i<steps;i++){   
    digitalWrite(stepperPin, HIGH);    
    digitalWrite(stepperPin, LOW);    

void loop(){
  x += 1;

Not counting the time required to move the stepper motor, you are asking the loop function to do something useful for 82,800 seconds. That's 1,380 minutes, or 23 hours.

How long has the program been moving the stepper motor?

If you add in the time used in the step() function (58ms when called with 40 steps) x 82,800, you add a little over one hour and 20 minutes.



Actually it was set for 64800 (~18 hours), which should have stopped at around 9am EST this morning. Its 2 hours past, and even including the time for each step it should have been done by now. When I the variable set as int, it stopped right on time. The only change I have made was changing int to unsigned long.

I think you have to mark the constant to which the value of x is compared as an unsigned long value too

void loop(){



I apologize, it is working fine. All accounted for, it will take 1.116 seconds per complete cycle. 64,800 cycles gives 20.088 hours. That is how long it took; soon after I posted that it was 2 hours past when it should have stopped, it stopped.

Sorry for wasting your guys time and thanks for the responses.