Serial extrange behavior - out of memory perhaps??

Hi, I'm trying to port some code to the arduino, but I've got stuck with this nasty problem.

Just this easy code:

define MAX_PINS 37

typedef struct { int pin_stat; int apin_stat; int pin_dir; int pin_init; char name[15]; } PIN_STRUCT;


void setup() { Serial.begin(115200); Serial.println(" Ardunio Starting..."); }

void loop() { Serial.println("Hello!!"); delay(1000); }

If I raise MAX_PINS over 37, then serial functions stop working (it only sends blank characters)

What kind of memory am I filling up???

Thx on advance for your help.


Your struct takes up 23 bytes of RAM, so an array of 37 structs takes up 851 bytes of RAM. The mega168 has 1k of RAM, so you might think this is fine, but this neglects the fact that RAM is used as stack space on AVRs. The stack builds from one side of RAM while your data builds from the other, and if they ever meet, your program is basically toast as your data starts overwriting the stack or the stack starts overwriting your data. Stack overflow problems can be some of the hardest to identify and hence the most frustrating bugs you will encounter.

My approach is to try keep my data size at under 500 bytes (50% of RAM), thereby leaving plenty of room for the stack. If I have to use more RAM for data, I need to take great care to avoid filling up the stack (e.g. trace my program to make sure I don't have any nested function calls that are too deep. Also realize that the Arduino environment is storing its own data in RAM and putting its own data on the stack.

My advice to you: make a more compact struct, decrease the array count to below 20, store your data in EEPROM, or buy an external RAM chip to store your data. The mega168 is not designed for this kind of use. Don't assume that your program works ok at 37 because you are either (a) already overrunning the stack and just haven't encountered/identified the bugs this causes yet or (b) about to overrun the stack and a few more function calls in the wrong places will cause your program to fail in strange and unpredictable ways.

  • Ben

Thx very much Ben, I have to start thinking in really MICRO computing using just 1K (it's been so long that memory constrains wasn't important for my programing that I forgot I was working in a relly small think

Thx once again Ben

No problem, I had the same rude awakening when I was first getting started. I was using things like floats and recursion and then wondering why all of these nonsensical errors were popping up.

  • Ben

The hardware serial code uses 128 bytes as buffer space, plus a few more bytes for other things. That almost blows the 1k without using any for the stack.