Simple? Code crashing

Hi,

I have the following code:

int INT = 110;
unsigned long LAST_ACTION = 2000;
 
 
void setup()
{
    Serial.begin(9600);
    Serial.println("Hello");
}
 
void loop()
{
 
  Serial.print(millis());
  Serial.print(" - ");
  Serial.println(LAST_ACTION);
 
  if ( (millis() - LAST_ACTION) >= 2400)
  {
    INT--;
    LAST_ACTION = millis();
  }
 
  Serial.println(String(INT) + " " + String( (2400 - (millis() - LAST_ACTION))) + " ms");
  delay(100);
}

It keeps crashing AFTER the INT has reached below 100, which is really odd. Here's an example output I get from an Arduino Mega, and Arduino UNO

0 - 2000
109 2400 ms
100 - 0
109 2299 ms
201 - 0
109 2199 ms
302 - 0
109 2097 ms
403 - 0
109 1997 ms
503 - 0
109 1896 ms
605 - 0
109 1795 ms
705 - 0
109 1694 ms
806 - 0
109 1594 ms
907 - 0
109 1492 ms
1008 - 0
109 1392 ms
1108 - 0
.... miss a few ....
 
99 74 ms
26690 - 24264
98 2400 ms
26791 - 26691
98 2299 ms
26893 - 26691
¨b¬µ 0-° F0 ÍKÿ11-±©9²0­Öê21-±©9²¹

Now, If I use the following code:

  Serial.print(String(INT) + " ");
  Serial.print( (2400 - (millis() - LAST_ACTION)) );
  Serial.println(" ms");

It doesn't seem to crash. Could somebody please explain why this might be happening?

Thanks!

The String class operations are malloc'ing memory every time they run, and the processor only has 2k RAM to play with - in practice this makes the String class useless for a small microcontroller and is best avoided really... Running out of memory means that the machine will crash (the stack has been over-written).

MarkT:
The String class operations are malloc'ing memory every time they run, and the processor only has 2k RAM to play with - in practice this makes the String class useless for a small microcontroller and is best avoided really... Running out of memory means that the machine will crash (the stack has been over-written).

This is the likely answer.

You should be using a null terminated char array for strings to avoid using Strings.