Alex Rivera | Logout

Loose-coupling patterns for embedded systems programming

Asked 2010-01-04T16:10:55.557
22

Where can I find some good, proven guidelines or examples on writing extensible, modular, loosely-coupled code in C (if possible)?

Background of our problem is that we are maintaining large plain C, legacy code project for a low-cost microcontroller with limited computing and memory resources. Due to the fact that the system must be extremely reliable and the memory is rather limited, one of the first constraints is not to use dynamic memory allocation at all. All structures are mapped statically.

So we are looking for ways to make this code more maintainable and more modular. We are not interested in coding standards, but rather design suggestions. We have good coding conventions (naming, organizing code, SVN) so this is not a problem.

From what I've seen on the web (I may be wrong), it seems most of the programmers which program exclusively in plain C or assembler, at least in the uC/Embedded community, restrain from using anything more that plain procedural programming.

For example, we could get most of the OOP benefits and decoupling in plain C using callback functions, structs containing function pointers and similar stuff (it wouldn't require dynamic allocation, just passing around pointers to structs), but we would like to see if there are some proven methods already around.

Do you know of such resources, or have similar suggestions besides from "why don't you switch to C++ or other programming language"?

[Edit]

Thanks a lot for all the answers, I haven't had the time to examine them yet. Platform is 16-bit (XC166 or similar) uC, naked hw (no RTOS).

Edit
Report

1 Answer

1

We are not using many small devices, but we do have some with memory constraints. We are allocating static buffers, but we found that sometimes dynamic memory allocation actually helps reducing the memory usage. We tightly control the heap size and allocation policy and have to check and handle out of memory conditions not as errors but as normal operation. E.g. we are out of memory, so we send out the data that we have, clear the buffers and resume operations where we left of.

Why do we not switch to C++? I would love to. We don't switch for mainly these reasons:

  1. Our code monkeys would not grok it, and are reluctant to learn.
  2. The C++ libraries are significantly larger (although we may be able to work around this one.)
  3. For those really small RTOS devices it's usually not necessary. For bigger devices, where we are running an embedded Linux, it would be nice.
answered 2010-01-04T16:47:44.913

Your Answer