The Embedded New Testament

The "Holy Bible" for embedded engineers


Project maintained by theEmbeddedGeorge Hosted on GitHub Pages — Theme by mattgraham

C Language Fundamentals for Embedded Systems

Essential C programming concepts for embedded software development

📋 Table of Contents


🎯 Overview

C is the primary programming language for embedded systems due to its:

Key Characteristics for Embedded Development

🤔 What is C Programming?

C is a general-purpose programming language developed in the 1970s by Dennis Ritchie at Bell Labs. It was designed to be a simple, efficient language that provides low-level access to memory while maintaining portability across different computer architectures.

Core Philosophy

  1. Simplicity: C provides a minimal set of features that can be easily understood
  2. Efficiency: C code can be compiled to efficient machine code with minimal overhead
  3. Portability: C programs can be compiled for different architectures with minimal changes
  4. Low-level Access: C provides direct access to memory and hardware features

Language Characteristics

Strengths:

Limitations:

C vs. Other Languages

Language Comparison for Embedded Systems:

┌─────────────────┬─────────────┬─────────────┬─────────────────┐
│   Language      │ Performance │ Safety      │ Learning Curve  │
├─────────────────┼─────────────┼─────────────┼─────────────────┤
│   C             │    High     │    Low      │    Medium       │
│   C++           │    High     │   Medium    │     High        │
│   Rust          │    High     │    High     │     High        │
│   Python        │     Low     │    High     │     Low         │
│   Assembly      │   Highest   │    Low      │     High        │
└─────────────────┴─────────────┴─────────────┴─────────────────┘

🎯 Why C for Embedded Systems?

Historical Reasons

C became the dominant language for embedded systems due to several historical factors:

  1. Unix Heritage: C was developed alongside Unix, which influenced early embedded systems
  2. Compiler Technology: C compilers were among the first to generate efficient code
  3. Hardware Access: C’s pointer arithmetic provided direct hardware access
  4. Standardization: ANSI C standardization provided stability and portability

Technical Advantages

Performance Benefits:

Resource Efficiency:

Embedded-Specific Benefits

Hardware Integration:

System Control:

When to Use C

Use C When:

Consider Alternatives When:

🧠 C Language Concepts

Programming Paradigm

C is primarily a procedural programming language, which means:

  1. Function-Based: Code is organized into functions
  2. Top-Down Design: Programs are designed from high-level to low-level
  3. Data and Code Separation: Data structures are separate from functions
  4. Step-by-Step Execution: Programs execute instructions sequentially

Memory Model

C uses a static memory model with manual memory management:

C Memory Layout:
┌─────────────────────────────────────────────────────────────┐
│                    Stack (Local Variables)                 │
│                    ↓ Grows downward                       │
├─────────────────────────────────────────────────────────────┤
│                    Heap (Dynamic Memory)                  │
│                    ↑ Grows upward                         │
├─────────────────────────────────────────────────────────────┤
│                    .bss (Uninitialized Data)              │
├─────────────────────────────────────────────────────────────┤
│                    .data (Initialized Data)               │
├─────────────────────────────────────────────────────────────┤
│                    .text (Code)                           │
└─────────────────────────────────────────────────────────────┘

Compilation Process

C on embedded targets compiles into multiple object files (translation units) that the linker places into memory regions defined by a linker script. Understanding this flow helps you read the map file and control where data/code lands.

Concept: Translation units, linkage, and the linker script

Try it

  1. Build with -Wl,-Map=out.map and open the map file. Locate a static const table vs a non-const global.
  2. Change a symbol from static to non-static and observe its visibility (external vs internal linkage).

Takeaways

C programs go through several stages before execution:

Compilation Process:
┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│   Source    │ →  │  Preprocess │ →  │   Compile   │ →  │    Link     │
│   Code      │    │   (Macros)  │    │  (Assembly) │    │  (Executable)│
└─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘

Type System

C uses a static type system with weak typing:

  1. Static Typing: Types are checked at compile time
  2. Weak Typing: Implicit type conversions are allowed
  3. Explicit Casting: Manual type conversion when needed
  4. Type Safety: Limited type safety compared to modern languages

Scope and Lifetime

Scope Rules:

Lifetime Rules:

🔢 Variables and Data Types

Concept: Where does the object live and when does it die?

Rather than memorizing types, think in terms of storage duration and lifetime: who owns the object, where is it placed in memory, and when is it initialized/destroyed. On MCUs, these choices affect RAM usage, startup cost, determinism, and safety.

Why it matters in embedded

Minimal example

int g1;                 // Zero-initialized (\`.bss\`)
static int g2 = 42;     // Pre-initialized (\`.data\`)

void f(void) {
  int a;                // Uninitialized (stack, indeterminate)
  static int b;         // Zero-initialized, retains value across calls
  static const int lut[] = {1,2,3}; // Often placed in Flash/ROM
  (void)a; (void)b; (void)lut;
}

Try it

  1. Print addresses of g1, g2, a local variable, and b. Inspect the linker map to see section placement (`.text`, `.data`, `.bss`, stack).
  2. Make lut large and observe Flash vs RAM usage in the map file when const is present vs removed.

Takeaways

Platform note: On Cortex‑M, large zero‑initialized objects increase `.bss` and extend startup clear time; large initialized objects increase `.data` copy time from Flash to RAM.

What are Variables?

Variables are named storage locations in memory that can hold data. In C, variables must be declared before use, specifying their type and optionally initializing them with a value.

Variable Concepts

Declaration vs. Definition:

Variable Attributes:

Data Type Categories

Integer Types:

Floating Point Types:

Character Types:

Basic Data Types

Integer Types

// Signed integers
int8_t   small_int;    // 8-bit signed (-128 to 127)
int16_t  medium_int;   // 16-bit signed (-32768 to 32767)
int32_t  large_int;    // 32-bit signed (-2^31 to 2^31-1)
int64_t  huge_int;     // 64-bit signed

// Unsigned integers
uint8_t  small_uint;   // 8-bit unsigned (0 to 255)
uint16_t medium_uint;  // 16-bit unsigned (0 to 65535)
uint32_t large_uint;   // 32-bit unsigned (0 to 2^32-1)
uint64_t huge_uint;    // 64-bit unsigned

// Traditional C types (avoid in embedded)
int      platform_dependent;  // Size varies by platform
long     also_variable;       // Size varies by platform

Floating Point Types

float    single_precision;    // 32-bit IEEE 754
double   double_precision;    // 64-bit IEEE 754 (avoid in embedded)

Character Types

char     character;           // Usually 8-bit
uint8_t  byte_data;          // Explicit 8-bit unsigned

Variable Declaration and Initialization

Best Practices

// ✅ Good: Explicit initialization
uint32_t counter = 0;
uint8_t status = 0xFF;
float temperature = 25.5f;

// ❌ Bad: Uninitialized variables
uint32_t counter;  // Contains garbage data

Constants

// Compile-time constants
#define MAX_BUFFER_SIZE 1024
#define PI 3.14159f

// Runtime constants
const uint32_t TIMEOUT_MS = 5000;
const float VOLTAGE_REFERENCE = 3.3f;

// Enum constants
typedef enum {
    LED_OFF = 0,
    LED_ON = 1,
    LED_BLINK = 2
} led_state_t;

🔧 Functions

Concept: Keep work small, pure when possible, and observable

In embedded, function design drives predictability and testability. Prefer small, single-purpose functions with explicit inputs/outputs. Avoid hidden dependencies (globals) except for well-defined hardware interfaces behind an abstraction.

Why it matters in embedded

Minimal example: refactor side effects

// Before: mixes IO, computation, and policy
void control_loop(void) {
  int raw = adc_read();
  float temp = convert_to_celsius(raw);
  if (temp > 30.0f) fan_on(); else fan_off();
}

// After: separate IO from policy
float read_temperature_c(void) { return convert_to_celsius(adc_read()); }
bool fan_required(float temp_c) { return temp_c > 30.0f; }
void apply_fan(bool on) { if (on) fan_on(); else fan_off(); }

Try it

  1. Write a unit test for fan_required off-target (no hardware) to validate thresholds and hysteresis.
  2. Inspect call sites to ensure high-frequency paths remain small enough to inline.

Takeaways

What are Functions?

Functions are reusable blocks of code that perform specific tasks. They are the primary mechanism for code organization and reuse in C programming.

Function Concepts

Function Components:

Function Types:

Function Design Principles

Single Responsibility:

Parameter Design:

Error Handling:

Function Implementation

Basic Function Structure

// Function declaration (prototype)
return_type function_name(parameter_list);

// Function definition
return_type function_name(parameter_list) {
    // Function body
    // Local variables
    // Statements
    return value;  // Optional
}

Function Examples

// Simple function with no parameters
void initialize_system(void) {
    // System initialization code
    configure_clocks();
    setup_peripherals();
    enable_interrupts();
}

// Function with parameters and return value
uint32_t calculate_average(uint32_t* values, size_t count) {
    if (count == 0) return 0;
    
    uint32_t sum = 0;
    for (size_t i = 0; i < count; i++) {
        sum += values[i];
    }
    return sum / count;
}

// Function with multiple return points
bool validate_sensor_data(uint16_t value, uint16_t min, uint16_t max) {
    if (value < min) return false;
    if (value > max) return false;
    return true;
}

🔄 Control Structures

Concept: Prefer early returns and shallow nesting

Deeply nested branches increase cyclomatic complexity and code size on MCUs. Early returns with guard clauses keep critical paths obvious and reduce stack pressure in error paths.

Minimal example

// Nested
bool handle_packet(const pkt_t* p) {
  if (p) {
    if (valid_crc(p)) {
      if (!seq_replay(p)) { process(p); return true; }
    }
  }
  return false;
}

// Guarded
bool handle_packet(const pkt_t* p) {
  if (!p) return false;
  if (!valid_crc(p)) return false;
  if (seq_replay(p)) return false;
  process(p);
  return true;
}

Takeaways

What are Control Structures?

Control structures determine the flow of program execution. They allow programs to make decisions, repeat operations, and organize code execution.

Control Structure Concepts

Decision Making:

Looping:

Flow Control:

Decision Structures

if-else Statements

// Simple if statement
if (temperature > 30.0f) {
    turn_on_fan();
}

// if-else statement
if (battery_level > 20) {
    normal_operation();
} else {
    low_power_mode();
}

// Nested if-else
if (sensor_status == SENSOR_OK) {
    if (temperature > threshold) {
        activate_cooling();
    } else {
        deactivate_cooling();
    }
} else {
    handle_sensor_error();
}

switch Statements

// Switch statement for multiple conditions
switch (button_pressed) {
    case BUTTON_UP:
        increase_volume();
        break;
    case BUTTON_DOWN:
        decrease_volume();
        break;
    case BUTTON_SELECT:
        select_option();
        break;
    default:
        // Ignore unknown buttons
        break;
}

Loop Structures

for Loops

// Traditional for loop
for (int i = 0; i < 10; i++) {
    process_data(i);
}

// Embedded-style for loop
for (uint32_t i = 0; i < BUFFER_SIZE; i++) {
    buffer[i] = 0;  // Initialize buffer
}

// Infinite loop (common in embedded systems)
for (;;) {
    process_events();
    update_display();
    delay_ms(100);
}

while Loops

// Condition-checked loop
while (data_available()) {
    process_data();
}

// Infinite loop with break
while (1) {
    if (shutdown_requested()) {
        break;
    }
    main_loop();
}

do-while Loops

// Execute at least once
do {
    read_sensor();
} while (sensor_error());

💾 Memory Management

What is Memory Management?

Memory management in C involves allocating, using, and freeing memory resources. Unlike higher-level languages, C requires manual memory management, giving programmers direct control but also responsibility for memory safety.

Memory Management Concepts

Memory Types:

Memory Lifecycle:

Memory Safety:

Stack vs. Heap

Stack Memory:

Heap Memory:

Memory Management Implementation

Stack Memory

void stack_example(void) {
    // Stack-allocated variables
    uint32_t local_var = 42;
    uint8_t buffer[256];
    struct sensor_data data;
    
    // Memory automatically freed when function returns
}

Heap Memory

void heap_example(void) {
    // Allocate memory
    uint8_t* buffer = malloc(1024);
    if (buffer == NULL) {
        // Handle allocation failure
        return;
    }
    
    // Use memory
    memset(buffer, 0, 1024);
    
    // Free memory
    free(buffer);
    buffer = NULL;  // Prevent use-after-free
}

🎯 Pointers

What are Pointers?

Pointers are variables that store memory addresses. They provide indirect access to data and are fundamental to C programming, especially in embedded systems where direct memory manipulation is common.

Pointer Concepts

Address and Value:

Pointer Types:

Pointer Arithmetic:

Pointer Implementation

Basic Pointer Operations

// Pointer declaration and initialization
uint32_t value = 42;
uint32_t* ptr = &value;  // Address-of operator

// Dereferencing
uint32_t retrieved = *ptr;  // Dereference operator

// Pointer arithmetic
uint32_t array[5] = {1, 2, 3, 4, 5};
uint32_t* array_ptr = array;

// Access elements
uint32_t first = *array_ptr;      // array[0]
uint32_t second = *(array_ptr + 1); // array[1]
uint32_t third = array_ptr[2];    // array[2]

Function Pointers

// Function pointer type
typedef void (*callback_t)(uint32_t);

// Function that takes a callback
void process_data(uint32_t data, callback_t callback) {
    // Process data
    if (callback != NULL) {
        callback(data);
    }
}

// Callback function
void data_handler(uint32_t data) {
    printf("Received: %u\n", data);
}

// Usage
process_data(42, data_handler);

📊 Arrays and Strings

Mental model: Arrays are blocks; pointers are addresses with intent

An array name in an expression decays to a pointer to its first element. The array itself has a fixed size and lives where it was defined (stack, `.bss`, `.data`). A pointer is just an address that can point anywhere and can be reseated.

Why it matters in embedded

Minimal example: decay and sizeof

static uint8_t table[16];

size_t size_in_caller = sizeof table;      // 16

void use_array(uint8_t *p) {
  size_t size_in_callee = sizeof p;        // size of pointer, not array
  (void)size_in_callee;
}

void demo(void) {
  use_array(table);                        // array decays to uint8_t*
}

Try it

  1. Print sizeof table in the defining scope and inside a callee parameter.
  2. Change the parameter to uint8_t a[16] and observe it’s still a pointer in the callee.
  3. Create static const uint16_t lut[] = { ... } and verify via the map file whether it resides in Flash/ROM.

Takeaways

Cross‑links: See Type_Qualifiers.md for const/volatile on memory‑mapped regions, and Structure_Alignment.md for layout implications.

What are Arrays?

Arrays are collections of elements of the same type stored in contiguous memory locations. They provide efficient access to multiple related data items.

Array Concepts

Array Characteristics:

Array Operations:

Array Limitations:

String Concepts

String Representation:

String Operations:

Array and String Implementation

Array Operations

// Array declaration and initialization
uint32_t numbers[5] = {1, 2, 3, 4, 5};

// Array traversal
for (size_t i = 0; i < 5; i++) {
    printf("Element %zu: %u\n", i, numbers[i]);
}

// Array as function parameter
void process_array(uint32_t* array, size_t size) {
    for (size_t i = 0; i < size; i++) {
        array[i] *= 2;  // Double each element
    }
}

String Operations

// String declaration
char message[] = "Hello, World!";

// String length calculation
size_t length = 0;
while (message[length] != '\0') {
    length++;
}

// String copying
char destination[20];
size_t i = 0;
while (message[i] != '\0') {
    destination[i] = message[i];
    i++;
}
destination[i] = '\0';  // Null-terminate

🏗️ Structures and Unions

What are Structures?

Structures are user-defined data types that group related data items of different types into a single unit. They provide a way to organize complex data in embedded systems.

Structure Concepts

Structure Components:

Structure Usage:

Structure Design:

Union Concepts

Union Characteristics:

Union Applications:

Structure and Union Implementation

Structure Examples

// Basic structure
typedef struct {
    uint32_t id;
    float temperature;
    uint8_t status;
} sensor_data_t;

// Structure with bit fields
typedef struct {
    uint8_t red : 3;    // 3 bits for red
    uint8_t green : 3;  // 3 bits for green
    uint8_t blue : 2;   // 2 bits for blue
} rgb_color_t;

// Structure with function pointer
typedef struct {
    uint32_t (*read)(void);
    void (*write)(uint32_t value);
    uint32_t address;
} hardware_register_t;

Union Examples

// Union for type conversion
typedef union {
    uint32_t as_uint32;
    uint8_t as_bytes[4];
    float as_float;
} data_converter_t;

// Union for protocol messages
typedef union {
    struct {
        uint8_t type;
        uint8_t length;
        uint8_t data[32];
    } message;
    uint8_t raw[34];
} protocol_message_t;

🔧 Preprocessor Directives

Guideline: Keep macros minimal and local. Prefer static inline functions for type safety, debuggability, and better compiler analysis unless you truly need token pasting/stringification or compile‑time branching.

What are Preprocessor Directives?

Preprocessor directives are instructions to the C preprocessor that are processed before compilation. They provide text substitution, conditional compilation, and file inclusion capabilities.

Preprocessor Concepts

Text Substitution:

Conditional Compilation:

File Management:

Preprocessor Implementation

Macro Definitions

// Simple macro
#define MAX_BUFFER_SIZE 1024
#define PI 3.14159f

// Function-like macro
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define ABS(x) ((x) < 0 ? -(x) : (x))

// Multi-line macro
#define INIT_SENSOR(sensor, id, threshold) \
    do { \
        sensor.id = id; \
        sensor.threshold = threshold; \
        sensor.status = SENSOR_INACTIVE; \
    } while(0)

Conditional Compilation

// Platform-specific code
#ifdef ARM_CORTEX_M4
    #define CPU_FREQUENCY 168000000
#elif defined(ARM_CORTEX_M3)
    #define CPU_FREQUENCY 72000000
#else
    #define CPU_FREQUENCY 16000000
#endif

// Debug code
#ifdef DEBUG
    #define DEBUG_PRINT(msg) printf("DEBUG: %s\n", msg)
#else
    #define DEBUG_PRINT(msg) ((void)0)
#endif

🔧 Implementation

Complete Program Example

#include <stdint.h>
#include <stdbool.h>

// Constants
#define MAX_SENSORS 8
#define TEMPERATURE_THRESHOLD 30.0f

// Data structures
typedef struct {
    uint32_t id;
    float temperature;
    bool active;
} sensor_t;

typedef struct {
    sensor_t sensors[MAX_SENSORS];
    uint8_t sensor_count;
    bool system_active;
} system_state_t;

// Function prototypes
void initialize_system(system_state_t* state);
void read_sensors(system_state_t* state);
void process_data(system_state_t* state);
void update_outputs(system_state_t* state);

// Main function
int main(void) {
    system_state_t system;
    
    // Initialize system
    initialize_system(&system);
    
    // Main loop
    while (system.system_active) {
        read_sensors(&system);
        process_data(&system);
        update_outputs(&system);
    }
    
    return 0;
}

// Function implementations
void initialize_system(system_state_t* state) {
    state->sensor_count = 0;
    state->system_active = true;
    
    // Initialize sensors
    for (uint8_t i = 0; i < MAX_SENSORS; i++) {
        state->sensors[i].id = i;
        state->sensors[i].temperature = 0.0f;
        state->sensors[i].active = false;
    }
}

void read_sensors(system_state_t* state) {
    for (uint8_t i = 0; i < state->sensor_count; i++) {
        if (state->sensors[i].active) {
            // Simulate sensor reading
            state->sensors[i].temperature = 25.0f + (i * 2.0f);
        }
    }
}

void process_data(system_state_t* state) {
    for (uint8_t i = 0; i < state->sensor_count; i++) {
        if (state->sensors[i].active && 
            state->sensors[i].temperature > TEMPERATURE_THRESHOLD) {
            // Handle high temperature
            activate_cooling();
        }
    }
}

void update_outputs(system_state_t* state) {
    // Update system outputs based on processed data
    update_display();
    send_status_report();
}

⚠️ Common Pitfalls

1. Uninitialized Variables

Problem: Using variables before they’re initialized Solution: Always initialize variables

// ❌ Bad: Uninitialized variable
uint32_t counter;
printf("Counter: %u\n", counter);  // Undefined behavior

// ✅ Good: Initialized variable
uint32_t counter = 0;
printf("Counter: %u\n", counter);

2. Buffer Overflows

Problem: Writing beyond array boundaries Solution: Always check array bounds

// ❌ Bad: Buffer overflow
uint8_t buffer[10];
for (int i = 0; i < 20; i++) {
    buffer[i] = 0;  // Buffer overflow!
}

// ✅ Good: Bounds checking
uint8_t buffer[10];
for (int i = 0; i < 10; i++) {
    buffer[i] = 0;
}

3. Memory Leaks

Problem: Not freeing allocated memory Solution: Always free allocated memory

// ❌ Bad: Memory leak
void bad_function(void) {
    uint8_t* buffer = malloc(1024);
    // Use buffer...
    // Forgot to free!
}

// ✅ Good: Proper cleanup
void good_function(void) {
    uint8_t* buffer = malloc(1024);
    if (buffer != NULL) {
        // Use buffer...
        free(buffer);
    }
}

4. Dangling Pointers

Problem: Using pointers after memory is freed Solution: Set pointers to NULL after freeing

// ❌ Bad: Dangling pointer
uint8_t* ptr = malloc(100);
free(ptr);
*ptr = 42;  // Use-after-free!

// ✅ Good: Null pointer after free
uint8_t* ptr = malloc(100);
free(ptr);
ptr = NULL;  // Prevent use-after-free

Best Practices

1. Code Organization

2. Memory Management

3. Error Handling

4. Performance

5. Safety

🎯 Interview Questions

Basic Questions

  1. What are the key characteristics of C programming?
    • Static typing, manual memory management, low-level access
    • Procedural programming, direct hardware access
    • Efficiency, portability, mature ecosystem
  2. What is the difference between stack and heap memory?
    • Stack: Automatic allocation, LIFO, limited size, scope-based
    • Heap: Manual allocation, flexible size, slower access, manual deallocation
  3. What are pointers and why are they important in C?
    • Pointers store memory addresses
    • Provide indirect access to data
    • Essential for dynamic memory allocation
    • Enable efficient array and function operations

Advanced Questions

  1. How would you implement a memory pool in C?
    • Pre-allocate memory in fixed-size blocks
    • Maintain a free list of available blocks
    • Implement O(1) allocation and deallocation
    • Handle pool exhaustion gracefully
  2. How would you design a function pointer system for callbacks?
    • Define function pointer types
    • Pass function pointers as parameters
    • Implement callback registration
    • Handle NULL function pointers
  3. How would you optimize a C program for embedded systems?
    • Use appropriate data types
    • Minimize memory usage
    • Optimize critical loops
    • Use compiler optimizations

Implementation Questions

  1. Write a function to reverse a string in place
  2. Implement a simple memory allocator
  3. Write a function to find the nth Fibonacci number
  4. Design a structure for a linked list node

📚 Additional Resources

Books

Online Resources

Tools

Standards


Next Steps: Explore Memory Management to understand memory allocation strategies, or dive into Pointers and Memory Addresses for low-level memory manipulation.