Looks like String corrupts the heap. I added freeMemory() to a simplified version of the program and the result makes no sense. The problem seems to be with the free list.
Here is the simple program that fails:
#include <MemoryFree.h>
void setup() {
Serial.begin(9600);
Serial.println(freeMemory());
}
void loop() {
int id = 0;
while (id <= 20)
{
//Main battery Voltage
int voltage = 20*id; //analogRead(1);
//Sense Resistance/ Current Drawn
int current = 30*id; //analogRead(2);
//Create Data string for storing to SD card
String dataString = String(id)+ ", " +String(voltage)+", "+ String(current)+", "+String(freeMemory());
Serial.println(dataString);
//Increment ID number
id++;
delay(500);
}
}
Here is the printout. The last column is the value returned by freeMemory() which is nonsense.
0, 0, 0, 1742
1, 20, 30, 1740
2, 40, 60, 13050
3, 60, 90, 24360
4, 80, 120, -29868
5, 100, 150, -17534
6, 120, 180, -3919
7, 140, 210, 10464
8, 160, 240, 23056
9, 180, 270, -29120
If I comment out this line in freeMemory
// free_memory += freeListSize();
I get this
1828
0, 0, 0, 1742
1, 20, 30, 1703
2, 40, 60, 1703
3, 60, 90, 1703
4, 80, 120, 1703
5, 100, 150, 1703
6, 120, 180, 1703
7, 140, 210, 1703
8, 160, 240, 1703
9, 180, 270, 1703
So a bug in String must write over the free list.