I wanted to check how much memory (RAM) is used by an "empty" sketch. Here is my code:
int freeRam()
{
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup()
{
Serial.begin(9600);
Serial.println(freeRam());
}
void loop()
{
}
My result was that I have 1839 bytes of free RAM. I have an Arduino UNO, so there are 2048 bytes of RAM in total. Which means that 209 bytes are already taken. Wait, 209 bytes?! I started thinking and figured out that the Serial buffer must take some space. I've opened HardwareSerial.h and found this:
#if (RAMEND < 1000)
#define SERIAL_BUFFER_SIZE 16
#else
#define SERIAL_BUFFER_SIZE 64
#endif
I've changed SERIAL_BUFFER_SIZE to 16 to see what will happen. (I've tried decreasing it to 1, but then the serial communication didn't work properly and I wasn't able to display the amount of free RAM). After this modification my result is 1935. So now "only" 113 bytes are taken. But what is taking this memory? HardwareSerial has 2 buffers:
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer rx_buffer = { { 0 }, 0, 0};
ring_buffer tx_buffer = { { 0 }, 0, 0};
So when the SERIAL_BUFFER_SIZE is 16 they take exactly 40 bytes. What is taking the remaining bytes (113-40= 73 bytes)? I'm aware that stack frames take some memory - calling main() which calls setup() whichs calls freeRam() probably take a few bytes, but 73 still seems too much.