Strange bug

Hi all,
I’m wondering what I’ve done wrong in my sketch because I get a strange output.
I’m testing a DIY encoder and printing the counts and rpms every second. After the 32nd print to the screen, or 32nd second, the print output skips the second timer and prints continously. I checked the timer output and it jumps from 1001 to 65537 after 32 seconds. Am I missing something regarding the use of millis() timers? Thanks for the help.

Here’s the code:

// This is for testing the output of a motor encoder using a slotted
// optical switch as a sensor and an encoder wheel with 20 slots.

int sensorPin = 2;
int potVal = 0;
int potPin = A0;
int counter = 0;  // counter for the number of sensor inputs.
int sensorState = 0;  // current state of the sensor counter.
int lastSensorState = 0;  // previous state of the sensor counter.
int time = 0;  // timer for counter
int revsPersec = 0;  // counter for revolutions per second
int revsPermin = 0;  // counter for rpms
int dirPinAM1 = 3; 
int dirPinBM1 = 4;
int enMotor1 = 6; // enable motor
int lSpeed = 0;

void setup() {
  // initialize the sensor pin as input:
  pinMode(sensorPin, INPUT);
  pinMode(potPin, INPUT);
  // initialize the counter timer
  time = millis();

  Serial.begin(9600);
}

void loop() {
  potVal = analogRead(potPin);
  lSpeed = map(potVal, 0, 1023, 0, 255);

  analogWrite(enMotor1, lSpeed);
  digitalWrite(dirPinAM1, HIGH);
  digitalWrite(dirPinBM1, LOW);

  // read the sensor input pin:
  sensorState = digitalRead(sensorPin);

  // compare the sensorState to its previous state
  if (sensorState != lastSensorState) {
    // if the state has changed, increment the counter
    if (sensorState == HIGH) {
      counter++;
    } 

  }
  // save the current state as the last state, 
  //for next time through the loop
  lastSensorState = sensorState;

  if(millis() - time > 1000){

    Serial.println(millis() - time);

    // after 1 second, calculate the revs per sec and rpms 
    revsPersec = counter/20;
    revsPermin = revsPersec*60;

    Serial.print("Counts per second ");
    Serial.println(counter);
    Serial.print("Revs per second ");
    Serial.println(revsPersec);
    Serial.print("RPM ");
    Serial.println(revsPermin);

    // reset the counters and timer for next second
    counter = 0;  
    revsPersec = 0; 
    revsPermin = 0;  
    time = millis(); 
  }

time = millis();

millis() returns an unsigned long == 32 bits number

you assign it to time which is an signed int == 16 bits number

So check the datatypes of functions and variables and your sketch will behave better (not guaranteed perfect , just better :wink:

Thanks Rob,

I didn't notice the unsigned long data type when I read the millis() info. My normal not paying attention mode.