C/C++ สำหรับระบบสมองกลฝังตัว

Pointers, memory, bit manipulation and program structure on microcontrollers

Last updated:

Overview

Almost every flight controller, ESC and sensor board runs a C or C++ program on a microcontroller (MCU) with somewhere between a few hundred kilobytes and a few megabytes of memory, and it must respond to hardware on time. ArduPilot and PX4 are written in C++. Both languages give direct access to memory and registers, which makes them powerful and easy to get wrong. This unit gathers what you should understand before writing code for a real board: program structure, data types, pointers, memory management and bit manipulation.

Program structure on a microcontroller

Most embedded programs have three parts:

  1. Initialisation: set up clocks, GPIO pins, timers and communication buses once after power-up.
  2. Main loop (super-loop): repeats forever, for example read sensors, compute, drive outputs.
  3. Interrupt service routines (ISRs): run when hardware raises an interrupt. Keep them as short as possible, such as setting a flag or storing data in a buffer, and let the main loop do the processing.

Larger systems use a real-time operating system (RTOS) to split work into prioritised tasks, as PX4 does on NuttX. Split code into header files (.h) that declare functions and types and source files (.c or .cpp) that implement them, so each part can be tested on its own.

Fixed-width types and overflow

The size of int depends on the chip: 16 bits on some 8-bit MCUs, 32 bits on Arm Cortex-M. Embedded code therefore uses the types from <stdint.h>, such as uint8_t, int16_t and uint32_t. Unsigned integers wrap silently when they exceed their range. Signed overflow is undefined behaviour in C, meaning the compiler may do anything, so designs must avoid it in the first place.

Example 1: converting an ADC reading to battery voltage with integer maths

Assume a 12-bit ADC, a 3.3 V reference and an 11 : 1 voltage divider (assumed). We want millivolts without floating point: VmV = raw × 3300 × 11 ÷ 4095.

  1. The ADC reads raw = 2,700.
  2. Product: 2,700 × 3,300 × 11 = 98,010,000.
  3. Divide by 4,095: 23,934 mV, about 23.93 V (fraction truncated).

The largest intermediate product, at raw = 4,095, is 148,648,500, still below the signed 32-bit maximum of 2,147,483,647. On a chip where int is 16 bits, however, 2,700 × 3,300 alone overflows, so cast before multiplying:

uint32_t batt_mv(uint16_t raw)
{
    return ((uint32_t)raw * 3300u * 11u) / 4095u;
}

Multiplying before dividing keeps resolution, but always check that the product fits the type.

Pointers and memory

A pointer is a variable that holds the address of other data, like a note with a house number rather than the house itself. &x gives the address of x, and *p reads or writes the data p points to. Embedded code uses pointers in three main ways:

  • Passing large data to functions without copying it, such as the address of a 64-byte buffer. Add const when the function must not modify it.
  • Reaching peripheral registers, which sit at fixed addresses in the memory map. Combine with volatile so every read and write really happens.
  • Walking through arrays by advancing the pointer, taking care never to go past the end.

MCU memory splits into flash, holding code and const data, and SRAM, holding global variables (data and bss), the heap for run-time allocation and the stack for function locals. The stack grows down and the heap grows up; if they meet, the program fails unpredictably. Safety-related systems therefore allocate everything at start-up and do not call malloc or new in flight.

A struct groups fields, but the compiler may insert padding for alignment. A struct holding uint8_t, uint32_t and uint16_t in that order is typically 12 bytes on Arm compilers, not 7. Sending a raw struct over a bus or radio can make the other side misread it; serialise field by field instead.

Bit manipulation

A single register packs many control bits, and changing one must not disturb the others. The four standard patterns:

TaskC pattern
Set bit kreg |= (1u << k);
Clear bit kreg &= ~(1u << k);
Toggle bit kreg ^= (1u << k);
Read a 3-bit field at bit 4(reg >> 4) & 0x7u

Another common technique is a ring buffer whose size is a power of two, such as 64 slots, so the next index is (i + 1) & 63 instead of a modulo division. The ISR writes at the head and the main loop reads from the tail, a pattern widely used for UART reception.

Example 2: an interrupt flag shared with the main loop

static volatile uint8_t imu_ready = 0u;   /* written by ISR, read by main loop */

void imu_drdy_isr(void) { imu_ready = 1u; }

int main(void)
{
    system_init();
    for (;;) {
        if (imu_ready != 0u) {
            imu_ready = 0u;
            imu_read_and_filter();
        }
    }
}

Without volatile, an optimising compiler may read imu_ready once and loop forever. A variable wider than the CPU can read in one instruction, such as a 32-bit value on an 8-bit chip, needs interrupts briefly disabled while it is read, because volatile does not make access atomic.

C++ on embedded targets and coding standards

C++ adds classes, namespaces and templates, which help keep a large codebase such as an autopilot organised. Embedded projects usually restrict some features, for example no dynamic allocation after start-up, and care with standard-library parts that allocate behind the scenes. MISRA C:2025 is used in safety-critical work, and BARR-C:2018 is a freely available style standard that makes a good starting point for a team. Turn compiler warnings up as far as they go and fix every one.

Common pitfalls

  • Using int without knowing its size on the target, and multiplying large values without casting first.
  • Uninitialised pointers or pointers past the end of an array, which silently overwrite other data.
  • Overwriting a whole register instead of changing one bit.
  • Forgetting volatile, or believing volatile makes access atomic.
  • Long work inside an ISR, such as printing or waiting on a bus.
  • Sending a raw struct over a bus without considering padding and byte order.
  • Repeated dynamic allocation, fragmenting the heap or colliding with the stack.

Continue in the lessons

Key references

  1. White, E. (2024). Making embedded systems: Design patterns for great software (2nd ed.). O'Reilly Media.
  2. Arm. Effect of the volatile keyword on compiler optimization. Arm Compiler for Embedded User Guide (version 6.24). link
  3. MISRA. (2025). MISRA C:2025 — Guidelines for the use of the C language in critical systems. link
  4. Barr Group. (2018). Embedded C coding standard (BARR-C:2018). link
  5. PX4 Autopilot. PX4 architectural overview. PX4 user guide (main). link

Used in courses

How to cite this page

Drone Institute, Rangsit University. (2026). C/C++ สำหรับระบบสมองกลฝังตัว. In UAS Technology Knowledge Hub (B.Tech.). https://rsu-uat.pk-research.work/en/kb/new/prog-cpp-embedded/