Go Down

Topic: Script using milis() going mad after 33 sec (Read 571 times) previous topic - next topic

Swoosh88

Hi,
I have a script that uses the milis() function, and it works exactly like I want to.
However, after about 33 seconds (I've timed it 5 times) the script goes mad...
Here is my script:
Code: [Select]
int POT1 = 0;
int POT2 = 1;
int POT3 = 3;
int LED1 = 8;
int LED2 = 10;
int LED3 = 12;
int potval = 0;
int interval1 = 0;
int interval2 = 0;
int previousMillis1 = 0;
int previousMillis2 = 0;
boolean LED1on = false;
boolean LED2on = false;

void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  Serial.begin(4800);
}

void loop() {
  interval1 = analogRead(POT1);
  Serial.print("1__");
  Serial.print(interval1);
  if (millis() - previousMillis1 > interval1) {
    previousMillis1 = millis();
    if (digitalRead(LED1) == LOW) {
      digitalWrite(LED1, HIGH);
      LED1on = true;
    }
    else {
      digitalWrite(LED1, LOW);
      LED1on = false;
    }
  }
  Serial.print(" - ");
  Serial.print(LED1on);
  Serial.print("   ");

  interval2 = analogRead(POT2);
  Serial.print("2__");
  Serial.print(interval2);
  if (millis() - previousMillis2 > interval2) {
    previousMillis2 = millis();
    if (digitalRead(LED2) == LOW) {
      digitalWrite(LED2, HIGH);
      LED2on = true;
    }
    else {
      digitalWrite(LED2, LOW);
      LED2on = false;
    }
  }
  Serial.print(" - ");
  Serial.print(LED2on);
  Serial.println();
}


This outputs something like:
Quote
1__400 - 0    2__200 - 0
1__400 - 1    2__200 - 1
1__400 - 1    2__200 - 0
1__400 - 0    2__200 - 1
1__400 - 0    2__200 - 0
(I made this up, it's not copied from the Serial Monitor)

However, after 33 seconds it always turns into something like this:
Quote
1__400 - 1    2__200 - 1
1__400 - 0    2__200 - 0
1__400 - 1    2__200 - 1
1__400 - 0    2__200 - 0
1__400 - 1    2__200 - 1


So after 33 seconds the milis() function goes mad :S
Does anyone have a clue what is happening and why it is happening?

Please help me out!
Thanks in advance!

gardner


Code: [Select]

int previousMillis1 = 0;
int previousMillis2 = 0;



On Arduino int is 16 bits and can hold values from -32768 ... +32767.  millis() is unsigned long, 32-bit value.
If you change your logic to use long variables, you should be okay.

Swoosh88

Oh wow, thanks!
I would never have thought of that, thank you very much!

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy