I'm trying to create a loop that counts from 5000 to 5000 and after reaching a certain value (30000) turns to zero. Here's the code
int time = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (time > 30000) {
time = 0;
Serial.println(time);
}
time = time + 5000;
Serial.println(time);
delay(5000);
}
However, the reseting of the variable time is not working:
Desired output Actual output
0 0
5000 5000
10000 10000
15000 15000
20000 20000
25000 25000
30000 30000
0 -35000
5000 -30000
... ...
How do I fix this?
You didn’t specify which Arduino board you’re using. I’ll assume an Uno or Mega. On those 8-bit AVR-based boards, an ‘int’ is 16 bits. The largest signed value you can hold in 16 bits is 2^15-1 = 32767.
int time = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (time >= 30000) { //<<<<<<<
time = 0;
Serial.println(time);
}
time = time + 5000;
Serial.println(time);
delay(5000);
}