I've been stumped on a memory problem for almost a month. I am using a 328 with ethernet to POST data to a server. It runs fine, except for a reset that happens every 10 minutes under testing conditions (longer in real world bc it has fewer posts).
I believe the problem to be Strings, which everyone warns against, and I am not sure if the problem ever went away, so I am converting everything I can to char arrays.
I am forming the POST request and therefore have to calculate the length of the array, or string. With a string, this is simple. Also, concatenating strings is very simple as well.
Right now I have: (unitName is a string set earlier and freemem is freeMemory())
I can count the characters to make an array, but how do I substitute? How do I change freemem (int) to a char array when it can bu up to 4 characters, how can I sum the character array and not include blank spaces?
But it might be easier to send the postdata in chunks with separate calls to print rather than trying to assemble it all into one string and send in one call.
True. The advantage of assembling it all in one string is that it makes it easier to measure the length of the string, which is something you need to know prior to POSTing anything.
In your example, you assume that length is known in advance. That is usually not the case.
void postData(String inputData, String filename) {
Serial.println("connected");
// Make a HTTP request:
client.println("POST /dev/telemetry/test/" + filename + ".php HTTP/1.1");
client.println("Host: www.SERVER.com");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(inputData.length());
Serial.println(inputData);
Serial.print("Data Length: ");
Serial.println(inputData.length());
client.println("Connection: close");
client.println();
client.println(inputData);
client.println();
wdt_reset();
unsigned long startMillis = millis();
unsigned long endMillis = startMillis + timeout;
while(client.connected() && (millis() < endMillis)) {
while(client.available()) {
char ch = client.read();
Serial.write(ch);
}
wdt_reset();
}
// if the server's disconnected, stop the client:
Serial.println();
client.stop();
int memory = freeMemory();
if (memory < 275) { // if memory is low, reset uC
delay(15000);
}
}
It seems strange to me that you close the connection before u actually transmit the data.
In any case, if u use a char array[] instead of this...
client.println(inputData.length());
try this...
client.println(strlen(inputData));
I started off with String variables - no problem, when I switched to char array[]'s, I had a repetitive reset issue and it turned out my char array[]'s were too small.
Also make sure for each loop "inputData" starts out as being empty by watching the serial printout of successive posts.