Page 287
int freeRam ()
{
extern int __heap_start, *__brkval;
int f;
return (int) &f - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
// three lines needed by freeRam()
#include <malloc.h>
extern char _end;
extern "C" char *sbrk(int i);
int freeRam() {
char *ramstart=(char *)0x20070000;
char *ramend=(char *)0x20088000;
char *heapend=sbrk(0);
register char * stack_ptr asm ("sp");
struct mallinfo mi=mallinfo();
return stack_ptr - heapend + mi.fordblks;
// mi.uordblks would return ram used
// ramend - stack_ptr would return stack size
}
The new keyword
My mention of the C++ new keyword and the potential for a memory leak was a bit "off the cuff" and not properly explained. No excuses.
The new keyword can create a new instance of a class returning a pointer but the class is created on the heap and not on the stack. As it is not created on the stack
it is not destroyed when a wrapping code block or function comes to an end.
The delete keyword is required to explicitely destroy the class instance.
The String Class
Came across a brilliant blog post from Benoît Blanchon titled
"8 tips to use the String class efficiently". Well worth a read.
Page 290
const char welcome[] PROGMEM = {"Hello world of Arduino"};
const int someData[] PROGMEM = {234, 543, 765, 987, 295};
void setup() {
Serial.begin(115200);
for(int i = 0, j = strlen_P(welcome); i < j; i++)
{
char nChar = pgm_read_byte_near(welcome + i);
Serial.print(nChar);
}
Serial.println();
for(int I = 0; i < 5; i++)
{
int nInt = (int)pgm_read_word_near(someData + i);
Serial.println(nInt);
}
}
const char jan[] PROGMEM = "January";
const char feb[] PROGMEM = "February";
const char mar[] PROGMEM = "March";
const char apr[] PROGMEM = "April";
const char may[] PROGMEM = "May";
const char jun[] PROGMEM = "June";
const char jul[] PROGMEM = "July";
const char aug[] PROGMEM = "August";
const char sep[] PROGMEM = "September";
const char oct[] PROGMEM = "October";
const char nov[] PROGMEM = "November";
const char dec[] PROGMEM = "December";
const char* const monthTable[] PROGMEM = {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec};
void setup() {
char buffer[10]; // minimum 10 as longest string is 10 bytes
Serial.begin(115200);
Serial.println(F("Months of the year"));
for(int i = 0; i < 12; i++)
{
strcpy_P(buffer, (char*)pgm_read_word(&(monthTable[i])));
Serial.println(buffer);
}
}