Calculation gives wrong value (solved)

Hi All,

I'm trying to read potentiometer values and to use millis() for no blocking delay. Everything works fine until potentiometer value goes over ~305.

Can anybody please help me figure out what is the problem that suddenly calculation result gets wrong when potentiometer value reaches certain level.

Code:

unsigned long time_now = 0;

int potValue = 0;

void setup() {

 Serial.begin(9600);

}

void loop() {

 potValue = analogRead(A2);

 if(millis() > time_now + (100 * potValue)){
     time_now = millis();
             Serial.println("..................");
             Serial.println(time_now);
             Serial.println(potValue);
             Serial.println(time_now + (100 * potValue));
             Serial.println("..................");
 }
}

Results:

..................
14557
68
21357
..................
..................
21372
68
28172
..................
..................
38962
175
56462
..................
..................
69329
303
99629
..................
..................
71432
328
38696
..................
..................
71434
328
38698
..................

You need to change the variable potValue to unsigned long. The maximum value for an int is 32767, after that it immediately goes to -32768

A simple rule is always use unsigned long for variables that work with millis()

...R



Aka, read How to use the forum and edit your post to use code tags please :wink:

And you're barking up the wrong three :wink: Nothing to do with millis().

Try adding

Serial.println(100 * potValue);

and see if that rings a bell :slight_smile:

Robin2, spoilers :stuck_out_tongue: Or simpler (and in my opinion more sensible), use 100UL instead of 100.

Hi,
Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html . Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom.. :slight_smile:

I forgot about int maximum value and I also edited my post to be more readable.

Thank you all!