Pages: [1]   Go Down
Author Topic: Script using milis() going mad after 33 sec  (Read 401 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 22
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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!
Logged

Ontario
Offline Offline
God Member
*****
Karma: 24
Posts: 860
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
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.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 22
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: