I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?
int light=9;
void setup() {
Serial.begin(9600);
pinMode(light, OUTPUT);
}
void loop() {
Serial.println("How long do you want the light on for (in seconds)?");
while(Serial.available()==0){}
int on_time = (Serial.parseInt() * 1000);
digitalWrite(light, HIGH);
delay(on_time);
digitalWrite(light, LOW);
Serial.print("The light was just on for ");
Serial.print(on_time/1000);
Serial.print(" seconds. ");
}
1 Answer 1
If you add Serial.println(on_time);
right after int on_time = (Serial.parseInt() * 1000);
you will see the problem. Once you enter the number 33 for example, the integer
value printed is -32536. The Allowed data type for delay()
is unsigned long
, so the negative number is causing a problem.
Using Serial.println()
judiciously can be very helpful when you are trying to debug a sketch.
-
Hi! Thanks for taking the time to help! I've just done as you suggested an yeah i saw the negative number. 2 questions: 1) Why is this happening? Shouldn't it just be 33x1000? I'm a total noob so i don't understand what "unsigned long" is. 2) How can i go about fixing this/avoiding this problem in the future?ThisUsernameHasBeenTaken– ThisUsernameHasBeenTaken2019年05月30日 21:10:47 +00:00Commented May 30, 2019 at 21:10
-
1) On an UNO, the largest "number" you can store in a
integer
is 32767. 33 seconds times 1000ms = 33000, which is over the 32767 maximum, so the integer becomes a negative "number". Anunsigned long
variable can hold a "number" up to 4,294,967,295. 2) To avoid this type of problem, arm yourself with knowledge. I found the examples that came with the IDE were very helpful to determine what variable types to use, and how to use them. Another source of information about variable types, functions, etc. is the Language Reference found here: arduino.cc/reference/en.VE7JRO– VE7JRO2019年05月30日 22:19:10 +00:00Commented May 30, 2019 at 22:19 -
That all makes sense. Thanks again!ThisUsernameHasBeenTaken– ThisUsernameHasBeenTaken2019年05月31日 00:35:10 +00:00Commented May 31, 2019 at 0:35
-
@ThisUsernameHasBeenTaken: Re "Why is this happening?": Since you are using a signed number, the most significant bit is interpreted as a sign bit. This is how two's complement arithmetic works.Edgar Bonet– Edgar Bonet2019年06月01日 17:35:15 +00:00Commented Jun 1, 2019 at 17:35
int
has values -32,768 to 32,767. Anunsigned int
is from0
to65,535
(ie. it's only 16 bits). Try using anunsigned long
instead ofint
to see if that helps.