I encounterd some weird problems with substring. I had a working function that uses substring to find some data within a string.
After I added some more code to this function the substring functions return nothing...
Below is a little bit of code that shows the problem. In the first piece of code the substring returns 21 and in the second piece of code the substring returns nothing...
As you can see I only added some declarations
Its seems a little buggie, can anyone explains this?
//Working
void SetTime(String sTime, int type){ // sTime = GET /SYST21,14,55,09,28,13
String sHour;
// String sMinute;
// String sSecond;
// String sMonth;
// String sDay;
// String sYear;
// int iHour;
// int iMinute;
// int iSecond;
// int iMonth;
// int iDay;
// int iYear;
Serial.println(sTime);
sHour = sTime.substring(9,11);
Serial.print("Hour: ");
Serial.println(sHour); //Prints 21
}
//Not working
void SetTime(String sTime, int type){ // sTime = GET /SYST21,14,55,09,28,13
String sHour;
String sMinute;
String sSecond;
String sMonth;
String sDay;
String sYear;
int iHour;
int iMinute;
int iSecond;
int iMonth;
int iDay;
int iYear;
Serial.println(sTime);
sHour = sTime.substring(9,11);
Serial.print("Hour: ");
Serial.println(sHour); //Prints nothing!
}
The first not-necessarily valid assumption here is that sTime is at least 11 characters long. You should never ask for a substring without checking the length of the String the substring is to be extracted from.
Since the second snippet with its boatload of String instances fails, I'd guess that you are out of memory or have fragmented the memory you do have all to hell.
The length of the time object is capped. Using char arrays like a big boy wastes a lot fewer resources.
If you place the code below before the code it will compile.
The funny thing is when I tested this little program is works for both codes.
I think it has something to do with memory or something because my real program is much bigger. But the compiler says that I used 17568 bytes from 32.256 bytes so that should't be a problem right?
In the mean while I got some answers while I was typing the last message
Aha so it has probably to do something with memory. Is there a way to check?
And how can I prevent this from happening because I still have to add some more code to my program.
Using only small strings? Not integers but bytes when I have small numbers for example?