Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any tips for dealing with a very small stack?

I was wondering if any developers in the embedded space know of any interesting tricks to help lessen the pain of developing for microcontrollers with very limited stack space. I've recently been writing some firmware for 8-bit uCs (Microchip PIC18F family, 31 byte stack) and as a consequence I have had to flatten my programs and reduce the number of parameters passed to functions. I've also tried to minimize my dependence on larger local variables. The flattening was designed to put fewer things on the stack and reducing locals variables helps conserve space in the "automatic variable" program section (psect) in RAM. Harvard architecture is not fun, I know, but it is what I'm dealing with. I've noticed issues with calling more than a few functions deep from an ISR, which is probably the result of my stack window being affected by IRQ context saving. I know I'm working with a limiting architecture, but I wonder if anyone has any tips for reducing headaches. I use pointers and bounds checking whenever possible, but I'm sure there are nuggets of wisdom I haven't discovered myself. As a disclaimer, I'm currently using function pointers to facilitate a state machine. I feel like I'm walking a tightrope between 90 line void functions and code that actually uses functions as they are intended.

like image 358
Nate Avatar asked Sep 02 '10 03:09

Nate


3 Answers

Use register variables for parameters and locals. Of course, depending on the number of registers available in the processor and the quality of the code the compiler generates, this may be no benefit at all. Declare locals as static where possible. This will keep them from being allocated on the stack.

like image 143
BillP3rd Avatar answered Oct 05 '22 15:10

BillP3rd


For non-recursive functions, you can make your local variables static.

BTW, the term "Harvard architecture" simply refers to the fact that there are separate address spaces for instructions and data, as opposed to a "Von Neumann architecture" that loads instructions from the same address space that data comes from. This is irrelevant to your problem, as all it means is that you can't write self-modifying code.

like image 42
Gabe Avatar answered Oct 05 '22 15:10

Gabe


  1. Use a whole-program optimizing compiler that can effectively statically allocate the "stack" -- I believe the Hi-Tech PICC compilers can do this. See section 5.9 in the PICC18 manual

  2. Use protothreads

like image 26
Doug Currie Avatar answered Oct 05 '22 14:10

Doug Currie