Strange error creating a String

Now, this is weird.

I am playing with a nanodetx, and I can't initialize a String instance.

Code extract:

Serial.println("loop start");   
    String stringOne = "Hello String";   
  Serial.println(stringOne.length());     
 
  stringOne= "Hello";
  Serial.println(stringOne.length());

Result on the serial monitor:

loop start
0
0

So for some reason, my String is not created.

Serial.println(stringOne); also just prints a blank line. I am using Arduino IDE 1.04.

Any idea what is happening here?

 

Robert Wall's picture

Re: Strange error creating a String

Strange indeed. It looks OK to me, and to my NanodeRF and my Arduino 1.0.4.  I get (both with the statements in loop( ) and in setup( ) ) exactly what you expect:

loop start
12
5

So it has to be something else. What else do you have in your sketch? Has it run out of memory, for example?

Write a sketch with just those lines (preceded by the necessary Serial.begin() of course) in setup( ). If it works then, it's definitely something else causing the problem. You'll need an empty loop( ) to keep the compiler happy!

RBJensen's picture

Re: Strange error creating a String

I had it temporarily working by putting the instance definition outside the method, making it global. But it broke again.

My compiled sketch is 12-14 kB, so plenty of memory left.

Good idea - start with a basic sketch and see how it goes.The other code I have running "should not" interfere, but you never know...

Robert Wall's picture

Re: Strange error creating a String

Ah, but remember there's a very limited amount of RAM for variables and the stack, etc.  See MemoryFree.

calypso_rae's picture

Re: Strange error creating a String

I ran out of memory with my early Mk2i PV Router builds.  The problem was that I had far too many strings.  Having removed many of them, the later versions are fine. 

In my later builds, from Rev4 onwards, I've included a little routine that shows how much RAM remains unused.  This might be worth adding into your sketch, and calling just before your "Hello" string appears to misbehave:

int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

(Sorry, before posting this, I'd not checked the link which Robert provided)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.