Program stop working after about 30 seconds?

I’m using this code to count the number of times my magnetic reed switch (NC) is low over a certain amount of time. The program will work for about 30 seconds, but after that it will show all 0’s in the serial monitor and the board becomes unresponsive. I’m still quite bad at programming the Arduino, so be gentle.

This is my code:

int start;
int count = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  start = millis(); 
  count = 0; 
  
  while (millis()-start < 3000)
  {
  
    
    int sensorValue = analogRead(A0);
    delay(10);        

    if (sensorValue == 0) {
      digitalWrite(13, HIGH);
      count++;
    }
    else {
      digitalWrite(13, LOW);
    }
  }
  Serial.println(count);
}

Any idea what could be wrong?

Change start to type unsigned long.

A 16-bit signed integer will "roll over" and become negative if you try to go over 32,767. (30,000 milliseconds is 30 seconds. :wink: )

millis() returns an unsigned long, and it will roll-over after about 50 days.

I love you.

I figured it was that sort of issue, i just wasn't sure which variable type would have solved the issue. Thank you.

The information is clearly spelled out on the reference page and in the examples.

http://arduino.cc/en/Reference/Millis

Returns
Number of milliseconds since the program started (unsigned long)