Skip to content
Academia.
ELEmbedded LinuxT550077101 · Fall 2026
CourseFall 2026

Friday · 12:00–16:00 · Odense U174

Microcontrollers and Distributed Embedded Nodes

Lecture 05: This chapter introduces microcontrollers and distributed embedded nodes, covering MCU architecture, memory, peripherals, interrupts, real-time behavior, RTOS and bare-metal designs, Linux–MCU partitioning, message framing, versioned protocol contracts, authentication, freshness, synchronization, watchdogs, low-energy operation, bootloaders, firmware updates, debugging, logging, and Linux-to-microcontroller integration.

Learning objectives

✓By the end of this module, students should be able to:
✓• explain how a microcontroller differs from a microprocessor-based Linux computer;
✓• compare representative AVR, RP2040, ESP32, STM32, NXP, TI, and Microchip devices;
✓• select a controller from timing, memory, peripheral, power, environmental, lifecycle, security, and cost requirements;
✓• use interrupts, timers, DMA, ADC, PWM, communication peripherals, and low-power modes appropriately;
✓• partition sensing, control, safety, communication, storage, and user-interface responsibilities between a Linux device and an MCU;
✓• define a bounded, versioned, framed, and recoverable communication protocol;
✓• distinguish interrupt, cooperative, RTOS, and hardware-triggered execution models;
✓• design watchdog, brownout, restart, buffering, clock, and update behavior;
✓• validate a distributed embedded node under timing stress, malformed traffic, and disconnects.
Block 112:00–12:50content

Block 1 · 12:00–12:50 · Microcontroller Fundamentals, Families, and Architecture

CHAPTER 5

Microcontrollers and Distributed
Embedded Nodes

Learning objectives
By the end of this module, students should be able to:
  • explain how a microcontroller differs from a microprocessor-based Linux computer;
  • compare representative AVR, RP2040/RP2350, ESP, STM32, Nordic, NXP, TI, and Microchip devices;
  • select a controller from timing, memory, peripheral, power, environmental, lifecycle, security, and cost requirements;
  • use interrupts, timers, DMA, ADC, PWM, communication peripherals, and low-power modes appropriately;
  • partition sensing, control, safety, communication, storage, and user-interface responsibilities across Linux and MCU nodes;
  • define a bounded, versioned, framed, and recoverable communication protocol;
  • distinguish error detection from authentication and freshness protection;
  • design watchdog, brownout, reset, startup, buffering, clock, and update behavior; and
  • validate a distributed embedded node under timing stress, malformed traffic, reset, disconnection, and power interruption.
A microcontroller is not a small Raspberry Pi
A microcontroller integrates processor core, memories, timers, converters, communication peripherals, and control logic for direct interaction with hardware. It normally runs firmware with tightly bounded resources, using internal or external nonvolatile memory depending on the device. A Raspberry Pi-class computer uses a much richer processor and memory system and normally runs Linux. The correct architecture often contains both, with an explicit contract between them.

5.1Microcontrollers and Microprocessors

A microcontroller unit (MCU) typically combines a CPU, flash memory, SRAM, clocks, reset logic, timers, GPIO, analog conversion, and communication controllers on one chip. Firmware starts shortly after reset and interacts closely with hardware. An MCU may run a simple superloop, interrupt-driven firmware, or a real-time operating system.

A Linux single-board computer normally uses a microprocessor or system-on-chip with external dynamic memory, caches, a memory-management unit, high-performance peripherals, and a complex boot chain. Linux provides protected processes, virtual memory, storage, and rich networking, but startup, scheduling, and power use are less tightly bounded.

58 Embedded Linux – Fall 2026
EMBEDDED LINUX Fall 2026
Property Typical MCUsystem Typical embedded Linuxsystem
Startup Microseconds to milliseconds,
depending on initialization
Usually seconds through firmware,
kernel, and services
Memory KiB to MiB of on-chip SRAM
and flash
Hundreds of MiB or GiB of RAM
and large storage
Scheduling Superloop, interrupts, or RTOS
with designed priorities
General-purpose multitasking;
real-time options require
engineering
Hardware control Direct registers and
deterministic peripherals
Kernel drivers and user-space
APIs
Isolation Often one shared address space;
MPU on some devices
Per-process virtual address spaces
and permissions
Power Very low sleep modes possible Higher baseline power and longer
wake/boot time
Software ecosystem Compact firmware, HALs,
RTOS, vendor SDKs
Packages, languages, containers,
databases, full network stack
Typical
responsibility
Sampling, timing, motor control,
safety, power management
UI, storage, vision, planning,
networking, fleet management

An MCU is not automatically real-time. Determinism depends on firmware structure, interrupt priorities, blocking calls, shared resources, memory behavior, clock configuration, peripheral use, and verified worst-case execution. Likewise, Linux can meet many practical deadlines, but a normal user-space process should not be assumed to satisfy a hard safety deadline.

5.2Representative Microcontroller Families

Table 5.2 provides representative families rather than a purchasing specification. Exact memory, package, voltage, peripheral count, wireless support, temperature rating, security functions, and availability vary by part number and board. Always verify the current manufacturer datasheet, errata, and lifecycle status. Manufacturer documentation is the starting point for Pico, ESP32, and STM32 selection [21, 22, 23].

Table 5.2. Representative microcontrollers and common engineering roles.
Family/example Coreclass Notablecapability Typical strengths, applications,and limitations
ATmega328P 8-bit AVR Timers, ADC, UART,
SPI, I²C-class TWI
Familiar Arduino Uno R3 ecosystem and simple registers. Limited RAM, flash, performance, and modern security; suitable for basic control and teaching.
ATmega4809/
AVR DA
8-bit AVR Improved
event/peripheral
systems in newer
AVR families
Low-complexity control and education. Still resource-constrained compared with 32-bit devices.
SAMD21 Arm
Cortex-M0+
USB, timers, ADC,
low-power peripherals
Common on Arduino-compatible boards; useful general embedded control. No integrated Wi-Fi and modest compute.
Embedded Linux – Fall 2026 59
EMBEDDED LINUX Fall 2026
Family/example Coreclass Notablecapability Typical strengths, applications,and limitations
RP2040 Dual
Cortex-M0+
Programmable I/O
(PIO), flexible clocks,
external flash
Raspberry Pi Pico generation; excellent deterministic custom digital interfaces and education. No ordinary Linux and no integrated radio in the IC.
RP2350 class Two active
Cortex-M33 or
Hazard3 RISC-V
cores
Selectable core
architecture, security
features, and PIO
Useful where flexible digital I/O and improved platform capability are needed. Verify selected execution architecture and board features.
ESP8266 32-bit Wi-Fi
MCU
Integrated 2.4 GHz
Wi-Fi
Low-cost connected nodes with mature community support. Older architecture, limited resources, ADC/peripheral constraints, and Wi-Fi power peaks.
ESP32 Dual-core 32-bit
MCU family
Wi-Fi, Bluetooth on
many variants, rich
peripherals
Connected sensing, gateways, and controls. Family variants differ significantly; radio coexistence, power, ADC quality, and timing under wireless load need testing.
ESP32-S3 Dual-core
Xtensa class
Wi-Fi/BLE, USB,
vector-oriented
acceleration
Useful for connected sensing, USB, audio, and small ML workloads. Not a Linux board; external flash/PSRAM behavior and radio timing remain design concerns.
ESP32-C3/C6
class
RISC-V MCU
variants
Wi-Fi/BLE;
variant-dependent
newer radio support
Cost-effective connected nodes with modern security features. Exact wireless and peripheral capability is variant-specific.
STM32F0/G0 Cortex-M0/M0+ Broad timers, ADC,
communication,
industrial packages
Cost-sensitive control and I/O. Requires careful part selection and clock/peripheral configuration.
STM32F4/G4 Cortex-M4 class DSP/FPU options,
advanced timers,
mixed-signal features
by family
Motor control, robotics, instrumentation, and industrial control. Large family makes names and peripheral differences easy to confuse.
STM32H7 High-performance
Cortex-M7;
some dual-core
variants
High compute, caches,
advanced timers,
Ethernet/USB on
selected parts
Vision-adjacent preprocessing and demanding control. Cache/DMA coherency, power, clock trees, and complexity require discipline.
STM32L/U class Low-power
Cortex-M
Deep low-power
modes and
energy-oriented
peripherals
Battery instruments and long-lived nodes. Wake sources, leakage, board components, and radio often dominate actual energy.
STM32WB/WL
class
Wireless
Cortex-M
families
Bluetooth/802.15.4 or
sub-GHz capability by
family
Integrated wireless nodes and metering. Protocol stacks consume memory and add concurrency and certification considerations.
nRF52840 Cortex-M4F Bluetooth LE,
802.15.4, USB,
strong low-power
ecosystem
Wearables, beacons, Thread/Zigbee-class nodes, and low-power sensing. No Wi-Fi; radio scheduling and antenna design matter.
nRF53/nRF54
class
Multi-core or
newer low-power
wireless MCU
class
Application/radio
partition and
advanced wireless
capability
Connected products requiring stronger isolation and performance. Toolchain and architecture are more complex.
60 Embedded Linux – Fall 2026
EMBEDDED LINUX Fall 2026
Family/example Coreclass Notablecapability Typical strengths, applications,and limitations
Teensy 4.1 /
i.MX RT1062
High-performance
Cortex-M7
crossover MCU
Very high MCU clock,
rich I/O, external
memory options
Audio, robotics, fast control, and data acquisition. High speed increases signal-integrity, power, cache, and timing complexity.
NXP LPC/MCX
class
Cortex-M
families
General control,
security, analog and
connectivity by part
Industrial and consumer embedded systems. Verify SDK, package, lifecycle, and peripheral instance carefully.
NXP S32K class Automotive
Cortex-M family
Automotive
communication,
timers, safety-oriented
ecosystem
Vehicle and mobile-machine control. Process and tool requirements are heavier than hobby platforms.
TI MSP430 16-bit
ultra-low-power
MCU
Low-power analog
and timer operation
Battery sensing and metering. Lower compute and ecosystem breadth than many modern 32-bit MCUs.
TI C2000 Real-time control
MCU/DSP class
High-resolution
PWM, fast
ADC/control
peripherals
Motor drives, power electronics, and control. Specialized architecture and safety-critical power stages demand expertise.
PIC16/18 8-bit Microchip
MCU
Broad low-cost
control portfolio
Simple appliances and legacy industrial products. Resource and tool limits depend strongly on device generation.
PIC32/SAM E
class
32-bit Microchip
families
CAN, Ethernet, USB,
timers, analog by
device
Industrial communication and control. Exact family and software ecosystem should match product lifecycle needs.
Raspberry Pi
Pico board
RP2040 or
RP2350 depending
on version
Board-level USB,
regulator, flash,
exposed PIO/GPIO
Convenient development board. Board is not the chip, and neither Pico generation runs ordinary Raspberry Pi OS/Linux.
PLC-class
controller
Vendor-specific
MCU/SoC
Certified I/O,
runtime, diagnostics,
industrial networks
Deterministic industrial automation and maintainability. Higher cost and less low-level freedom, but system qualification and tooling may dominate value.


Embedded Linux – Fall 2026 61
Block 213:00–13:50content

Block 2 · 13:00–13:50 · Peripherals, Interrupts, and Real-Time Embedded Control

Embedded Linux — Chapter 5 Part 2

5.3  Selecting a Microcontroller from Requirements

Begin with the workload and deployment environment. A defensible selection records:

  • maximum and typical execution load, deadline, jitter, and interrupt rate;
  • flash, SRAM, persistent data, stack, heap, and update-slot requirements with margin;
  • ADC channels and quality, DAC, comparators, timers, PWM, capture, encoder, and motor-control needs;
  • UART, I²C, SPI, CAN, USB, Ethernet, and wireless instances and simultaneous pin mapping;
  • voltage, current, power modes, wake time, battery, and radio-current peaks;
  • operating temperature, electromagnetic environment, package, connector, and enclosure;
  • secure boot, protected key storage, cryptographic acceleration, debug locking, and update support;
  • toolchain, debugger, RTOS or SDK maturity, documentation, errata, test support, and team competence;
  • component lifecycle, second sources, certification, unit volume, and total product cost.

ChatGPT Image Sep 20, 2026, 05_05_50 PMFigure 5.1. Conceptual comparison of microcontroller development-board classes. Regulators, USB interfaces, flash, antennas, and pin routing are board-level resources; exact features vary by model.

Headline CPU frequency is rarely decisive. A slower MCU with a suitable timer, DMA channel, encoder interface, and ADC trigger may outperform a faster part forced to implement those functions in software. Verify that required peripherals can be used simultaneously; development-board pin labels can conceal shared functions and conflicts.

61Embedded Linux – Fall 2026
5.4  Internal Architecture and Memory

MCU firmware interacts with memory-mapped peripheral registers. Flash stores executable code and constants; SRAM stores stacks, variables, buffers, and dynamic state. Some devices add caches, tightly coupled memory, external-memory controllers, EEPROM or emulated EEPROM, and memory-protection units.

Stack overflow and buffer overwrite can silently corrupt control state. Avoid unbounded recursion, unbounded queues, and unchecked copying. Measure high-water marks where supported. Dynamic allocation can be acceptable when bounded and designed, but uncontrolled allocation and fragmentation are difficult to justify in long-lived real-time firmware.

Flash has finite erase endurance. Persistent counters should use wear-aware storage, journaling, or a dedicated nonvolatile strategy. A power loss between erasing and rewriting configuration can destroy both old and new values unless redundant, checksummed, and committed atomically.

ChatGPT Image Sep 20, 2026, 02_47_00 PMFigure 5.2. Conceptual MCU architecture. Exact bus, cache, DMA, and peripheral relationships determine timing and concurrency behavior.

5.5  GPIO, Timers, ADC, PWM, and DMA

GPIO registers control direction, output state, pull devices, drive strength, and alternate peripheral functions. Configure the safe output level before enabling a pin as an output where hardware allows. At reset, pins may be inputs or have boot-related functions; external circuitry must keep actuators safe during this interval.

Timers provide periodic interrupts, input capture, output compare, quadrature decoding, PWM, and watchdog timing. Hardware capture timestamps an edge more accurately than a delayed software read. PWM controls average delivered energy or a driver’s command, but switching frequency, resolution, dead time, load dynamics, and filtering matter.

An ADC converts an analog input relative to a reference. Acquisition time, source impedance, reference stability, input range, sampling trigger, calibration, noise, and effective number of bits determine useful performance. Never connect a voltage outside the permitted input range.

Direct memory access (DMA) moves data between peripheral and memory without CPU action for every item. DMA reduces interrupt load and timing jitter but introduces ownership and coherency problems: firmware must know which buffer is being filled, which is ready, and whether caches require maintenance. DMA completion does not prove that data are physically valid.

62Embedded Linux – Fall 2026

5.6  Interrupts, Concurrency, and Real-Time Behavior

An interrupt service routine (ISR) should normally do the minimum bounded work needed: capture state, clear the correct source, place data into a safe buffer or signal a task, and return. Blocking network calls, long formatting, dynamic allocation, or unbounded loops inside an ISR increase latency and can starve lower-priority work.

Shared state between ISR and main code or tasks requires synchronization. volatile can prevent certain compiler optimizations but does not make a compound operation atomic, create a memory barrier for every architecture, or protect invariants. Use architecture and RTOS primitives deliberately.

Important timing quantities are:

  • period: intended interval between activations;
  • latency: delay from event to response;
  • jitter: variation in timing;
  • execution time: processor time required;
  • deadline: latest acceptable completion; and
  • worst-case execution time: justified upper bound under defined conditions.

Measure timing using a hardware timer, trace facility, or oscilloscope/logic-analyzer pin toggle. Serial printing changes timing and is not a neutral measurement technique.

5.7  Bare Metal, Superloops, and RTOS Designs

A cooperative superloop repeatedly executes bounded tasks:

Listing 5.1.  Non-blocking cooperative scheduling concept

1
2
3
4
5
6
7
8
9
10
11
12
for (;;) {
    uint32_t now = monotonic_ms();

    if (deadline_reached(now, next_sample)) {
        next_sample += SAMPLE_PERIOD_MS;
        start_sensor_conversion();
    }
    service_sensor_state_machine(now);
    service_communication(now);
    service_actuator_state_machine(now);
    update_health_and_watchdog(now);
}

This listing is scheduling pseudocode: the platform must supply the named functions, initialize the first deadline, and define an overrun policy. A fixed-width counter wraps, so deadline_reached must use a documented wrap-safe comparison with intervals shorter than half the counter range. Decide whether a missed period is skipped or caught up; do not create an uncontrolled burst of conversions. This structure can be reliable when every activity is bounded and non-blocking.

An RTOS adds preemptive tasks, priorities, timers, queues, semaphores, and event mechanisms. It helps organize concurrency but does not automatically make firmware real-time or race-free. Priority inversion, deadlock, stack exhaustion, queue overflow, and starvation remain design concerns.

Assign task priorities according to deadlines and consequence, not organizational importance. Avoid allowing a low-priority diagnostic task to hold a resource required by a high-priority control task.

63Embedded Linux – Fall 2026
5.8  Heterogeneous Linux–MCU Architecture

A useful partition assigns the MCU deterministic and safety-adjacent work and Linux complex, changing, network-facing work.

Responsibility
Likely location
Reason
Fast current or motor loop
MCU
Bounded timer, ADC, and PWM behavior
Encoder capture
MCU hardware timer
Precise edge capture and reduced Linux jitter
Emergency hardware chain
Independent safety hardware plus MCU where justified
Must not depend solely on a Linux process
Sensor aggregation
MCU or Linux depending on rate/interface
Balance timing, driver availability, and data volume
Local safe state
MCU and hardware
Must survive Linux crash or link loss
Camera processing
Linux/accelerator
Memory, compute, and library requirements
Database and long-term logs
Linux
File systems and storage services
MQTT/HTTP/TLS and remote updates
Usually Linux; sometimes connected MCU
Protocol complexity, credentials, and lifecycle
Operator interface
Linux/web service
Rich UI and networking ecosystem

Partitioning does not contain faults unless authority is explicit. Define which node may command each actuator, whether the MCU can reject Linux commands, how command freshness is evaluated, and what happens during disagreement, restart, update, or corrupted communication.

5.9  Byte Streams Need Message Framing

UART, USB serial, and TCP present byte streams without inherent application message boundaries. One write can be received in fragments or combined with later writes. Newline-delimited text is convenient for diagnosis but requires escaping or forbidden characters. Binary framing is more compact but requires careful resynchronization.

Common strategies include fixed-length frames, delimiter plus escaping, Consistent Overhead Byte Stuffing (COBS), SLIP, length-prefixed frames, and standardized encodings. A robust frame commonly contains synchronization or delimiter, protocol version, message type, source, sequence, payload length, payload, and integrity check.

SYNCVERTYPESRCSEQLENPAYLOADCRC Header and payload integrity coverage is defined by the protocol Conceptual field order; widths are not byte counts

Figure 5.3. Example framed message: the protocol must specify field sizes, byte order, and CRC coverage.

The parser must bound length before allocation or copying, enforce a receive timeout, reject unsupported versions and types, recover after corrupt bytes, and never interpret a partial frame as a command. Define numeric size, signedness, byte order, scaling, units, and string encoding.

64Embedded Linux – Fall 2026
5.10  A Versioned Protocol Contract

The protocol specification should define:

  • physical and link settings, including voltage standard and baud rate;
  • byte-level framing and escaping;
  • byte order and exact field widths;
  • protocol and message version compatibility;
  • message types, direction, permissions, and response semantics;
  • units, scale factors, coordinate frames, valid ranges, and sentinel policy;
  • sequence behavior, acknowledgement, timeout, retry, and duplicate handling;
  • startup handshake and capability discovery;
  • maximum payload, rate, buffering, and overflow behavior;
  • error codes, diagnostics, reset reason, and health reporting; and
  • authentication and replay protection where commands cross a trust boundary.

Versioning should support an intentional compatibility policy. Rejecting an unknown version is safer than interpreting fields under the wrong meaning. Capability negotiation can allow old and new nodes to agree on a supported subset, but negotiation itself must be bounded and testable.

Listing 5.2.  Illustrative bounded frame header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

/* Implement from the protocol message-type table. */
bool message_type_is_supported(uint8_t type);

typedef struct {
    uint8_t  version;
    uint8_t  type;
    uint16_t source_id;
    uint32_t sequence;
    uint16_t payload_length;
} frame_header_t;

enum { MAX_PAYLOAD = 256 };

bool header_is_valid(const frame_header_t *h) {
    return h != NULL &&
           h->version == 1 &&
           h->payload_length <= MAX_PAYLOAD &&
           message_type_is_supported(h->type);
}

Do not transmit a C structure directly as a portable wire format. Padding, alignment, compiler behavior, and native byte order can differ. Serialize each field explicitly.

66Embedded Linux – Fall 2026
Block 314:00–14:50content

Block 3 · 14:00–14:50 · Linux–MCU Integration, Protocols, and Reliable Communication

Embedded Linux — Chapter 5 Part 3
5.11   CRC, Authentication, and Freshness

A checksum or cyclic redundancy check detects many accidental transmission errors. It does not prove who sent a message, because an attacker can modify the data and calculate a new CRC. Authentication requires a cryptographic message authentication code or digital signature with protected keys and a defined key-management process.

Authentication alone does not stop replay of an old valid command. Include a sequence, nonce, session context, or timestamp under authenticated protection, and define restart and resynchronization behavior. Encryption protects confidentiality but is not a substitute for authorization or safe command validation.

5.12   Sequence Numbers, Acknowledgement, and Duplicates

Sequence numbers reveal gaps, repetition, and order within a defined source and session. They do not prove delivery or integrity. Sequence values wrap and may reset when a node loses state, so combine them with persistent device identity and boot/session identifier.

An acknowledgement should state what has been accepted: bytes received, frame validated, command accepted, command completed, or data durably stored. These are different guarantees. If an acknowledgement is lost, the sender may repeat the request, so command handling must be idempotent or deduplicated.

“Set motor target to zero with command ID 482” is an idempotent state-setting request: repeating it leaves the same target. Deduplication additionally requires remembering accepted IDs within a defined source/session and retention window; storing only the most recent ID cannot reject every delayed older request. “Move forward 10 cm” can repeat physical motion unless defined as a unique operation with remembered completion state.

5.13   Watchdogs, Brownout, Reset, and Safe Startup

A hardware watchdog resets or constrains a controller that fails to demonstrate health within a configured interval. Refresh it only after critical tasks have met their health conditions. A dedicated low-priority “watchdog task” that always refreshes can conceal a deadlocked control task.

Select the watchdog interval above justified worst-case healthy execution but below the maximum tolerable uncontrolled time. Test it by deliberately blocking or disabling critical work. Record reset cause, firmware version, boot count, and persistent fault count before evidence is overwritten.

Brownout detection prevents execution at inadequate supply voltage. Supply dips can corrupt computation, communication, flash operations, and actuator outputs before a complete reset occurs. External supervisors may provide stronger guarantees than internal brownout circuits.

At reset:

  1. external hardware must keep dangerous outputs inactive;
  2. firmware sets safe output levels before enabling drivers;
  3. reset cause and persistent state are validated;
  4. peripherals and communication are initialized;
  5. self-tests and configuration checks run;
  6. the node reports identity, version, capability, and health; and
  7. command authority is accepted only after READY criteria pass.

Embedded Linux – Fall 202667
5.14   Time, Clock Drift, and Synchronization

MCU oscillators have frequency error that varies with tolerance, temperature, voltage, and aging. If relative frequency error is ε, accumulated time error grows approximately as

Δt ≈ εT .

A 20 ppm clock can accumulate about 1.7 seconds per day under the conditions corresponding to that error. Synchronization corrects or estimates clock relationship; it does not make message latency disappear.

Possible sources include Linux host time, GNSS pulse-per-second and time messages, network synchronization, an RTC, or a local monotonic counter. For precise multi-sensor work, estimate offset and drift and timestamp close to hardware acquisition. Pair timestamps with sequences and a synchronization-quality indicator.

Never use adjustable wall time directly for control intervals. Use a monotonic hardware counter for deadlines and durations, and translate to global time with an explicit clock model.

5.15   Buffering and Store-and-Forward

Buffers absorb differences between production and consumption rates, but a finite buffer only postpones overload. Define capacity, item size, maximum age, ordering, durability, overflow policy, and diagnostic counters.

Overflow policy
Advantage
Risk and suitable context
Discard newest
Preserves older sequence/history
Current state may become increasingly stale
Discard oldest
Preserves most recent state
Loses historical continuity and event evidence
Stop acquisition
Makes loss explicit
May violate monitoring or control requirement
Reduce rate/aggregate
Extends outage endurance
Removes detail and may hide transient events
Spill to durable storage
Supports longer interruption
Adds wear, power-loss, and recovery complexity

Report dropped count, oldest queued age, high-water mark, and current depth. On reconnection, prevent backlog transmission from starving current safety traffic or overloading the receiver.

5.16   Power and Low-Energy Operation

Average current is not sufficient for design. Wi-Fi transmission, motor-driver switching, sensor heaters, and flash writes create peaks that can reset the MCU. Include regulator transient response, capacitor behavior, wiring resistance, battery impedance, and temperature.

Low-power firmware coordinates sleep state, wake source, retained memory, sensor warm-up, radio association, measurement duty cycle, and clock accuracy. A development board may consume far more than the MCU because of regulators, power LEDs, USB interface chips, and pull resistors.

68Embedded Linux – Fall 2026

An energy budget for repeated states can be estimated as

Ecycle = ∑i Vi Ii ti , Iavg = ∑i Ii ti ∑i ti ,

where the states partition one complete cycle and each voltage and current are approximately constant within a state. The average-current expression applies to currents measured at the same supply boundary; currents on different voltage rails must first be converted to input power using regulator efficiency. Battery usable capacity, conversion losses, pulse capability, self-discharge, and temperature must also be considered.

5.17   Bootloaders and Safe Firmware Updates

An update mechanism must address artifact authenticity, integrity, target compatibility, version policy, interruption, rollback, and key lifecycle. A CRC detects accidental corruption; signed metadata or images establish origin when verification keys are trusted.

A robust dual-slot process is:

  1. download or receive into the inactive slot;
  2. check format, target identity, size, version policy, signature, and hash;
  3. mark the candidate without destroying the confirmed image;
  4. reboot into the candidate with a limited trial counter;
  5. perform self-tests and communicate health;
  6. confirm the image only after defined success; and
  7. automatically return to the known-good image if boot or confirmation fails.

Firmware version, protocol version, hardware revision, bootloader version, and configuration schema are separate. An update can be cryptographically authentic and still be incompatible or defective.

Embedded Linux – Fall 202669
ChatGPT Image Sep 21, 2026, 12_52_39 AM

Figure 5.4. Conceptual A/B update sequence. Slot A remains active while the candidate is written to inactive slot B. Failed verification leaves A selected; only a verified candidate proceeds to trial boot. Confirmation accepts B, while failed trial health checks trigger fallback to A.

Block 415:00–15:50content

Block 4 · 15:00–15:50 · Watchdogs, Synchronization, Firmware Updates, and Laboratory

Embedded Linux — Chapter 5 Part 4

5.18   Debugging, Logging, and Production Diagnostics

Useful tools include serial logs, logic analyzers, oscilloscopes, multimeters, SWD/JTAG debuggers, trace, GPIO timing markers, compiler warnings, static analysis, sanitizers in host tests, and hardware-in-the-loop testing. Each observes a different layer.

Logs must be bounded and non-blocking relative to critical work. Record boot count, reset reason, firmware/protocol/configuration versions, watchdog events, queue overflow, communication error counters, sensor validity, retry answers, and last accepted command identity. Avoid printing secret keys or overwhelming a low-speed UART.

Debug interfaces and test firmware can become security vulnerabilities. Production policy should control readout protection, debug unlocking, recovery, and manufacturing access without making legitimate repair impossible.

5.19   Guided Laboratory: Linux-to-Microcontroller Link

Laboratory objective
Connect a Linux target to a Raspberry Pi Pico, ESP32/ESP8266, STM32, or comparable MCU. Implement a versioned framed protocol carrying measurements, health, and bounded commands. Demonstrate correct behavior under malformed data, lost bytes, duplication, reset, host restart, and reconnection, and measure end-to-end timing.

Part A—responsibility allocation. Produce a table assigning sensor acquisition, actuation, safety response, timekeeping, buffering, protocol parsing, networking, storage, and UI. State the deadline and failure response for each.

Part B—physical link. Specify connector, voltage levels, grounding or isolation, UART/USB/RS-485 settings, cable limits, and protection. Confirm electrical compatibility before connection.

Part C—protocol. Specify framing, escaping or length, byte order, version, message types, source/session, sequence, payload limits, CRC, units, acknowledgements, timeout, retries, and duplicate behavior. Include valid and invalid frame examples.

Part D—firmware state machine. Initialize outputs safely, validate configuration, report boot/reset reason, require a handshake before accepting commands, and expire stale command authority. Refresh the watchdog only after critical health conditions.

Part E—fault injection. Test noise bytes before sync, truncated and oversized frames, bad CRC, unsupported version, lost bytes, duplicates, sequence gap, Linux restart, MCU reset, unplug/reconnect, buffer overflow, and blocked critical task. Record parser recovery time and physical output state.

Part F—timing. Measure acquisition-to-Linux latency, jitter, maximum sustainable message rate, queue high-water mark, and command-to-output latency using appropriate instrumentation. Explain measurement uncertainty and probe effect.

Portfolio evidence
Include the MCU selection matrix, node-responsibility table, electrical interface, complete protocol specification, and state diagrams, firmware and host revisions, timing method and results, malformed-input tests, watchdog test, reset evidence, buffer policy, and justification for every function assigned to Linux or the MCU.
5.20   Self-Assessment and Job-Interview Preparation

These questions support Module 5 and future interviews in firmware, embedded Linux, robotics, IoT, automotive, industrial control, and mechatronics. Strong answers connect hardware features to timing, safety, testability, and lifecycle rather than naming a favorite development board.

Questions

Q1. Why is a Raspberry Pi Pico not an embedded Linux computer?

Q2. Compare an 8-bit AVR, RP2040, ESP32-S3, STM32G4/H7-class device, and nRF52840 for representative applications.

Q3. Why is CPU clock frequency an inadequate basis for MCU selection?

Q4. What is DMA, and what new failure modes can it introduce?

Q5. Why should an ISR be short and bounded?

Q6. Does declaring a shared variable volatile make access thread-safe? Explain.

Q7. Compare a non-blocking superloop with an RTOS design.

Q8. Define period, latency, jitter, execution time, deadline, and worst-case execution time.

Q9. What functions should remain operational if the Linux computer crashes in a mobile robot?

Q10. Why does a byte stream require framing even when each sender uses one write call per message?

Q11. Compare delimiter, length-prefix, fixed-length, and COBS-style framing.

Q12. What should a versioned MCU protocol specify beyond the byte layout?

Q13. What does a sequence number reveal that a CRC does not? What does a CRC reveal that a sequence number does not?

Q14. Why can a valid CRC not authenticate a motor command?

Q15. When an acknowledgement is received, what exactly has been proven?

Q16. How can a watchdog be refreshed incorrectly?

Q17. What should happen to actuator outputs immediately after MCU reset?

Q18. Compare discard-oldest and discard-newest buffer policies.

Q19. A 20 ppm clock is used without synchronization. Estimate one day of possible accumulated error at that rate.

Q20. Why should control durations use a monotonic counter rather than wall-clock time?

Q21. Describe a power-loss-safe dual-image firmware update.

Q22. An MCU resets whenever Wi-Fi transmits. Give a layered investigation.

Q23. A protocol works on the bench but corrupts frames near a motor. What physical and software evidence would you collect?

Q24. Design a test proving that loss of the Linux–MCU connection leads to a safe and observable state.

Answers and discussion

A1. Pico boards use an RP-series microcontroller and execute firmware from flash with limited SRAM. They do not provide the processor/memory-management/storage architecture required for ordinary Raspberry Pi OS or desktop/server Linux.

A2. AVR suits simple low-cost control and sensing; RP2040 offers dual cores and PIO for custom deterministic digital I/O; ESP32-S3 adds Wi-Fi/BLE, USB, and higher connected/ML capability; STM32G4/H7 classes support advanced control or high compute and rich peripherals; nRF52840 is strong for low-power BLE/802.15.4. Exact part and system requirements determine the answer.

A3. Peripherals, memory, DMA, timers, ADC quality, radio, latency, power, temperature, security, tools, lifecycle, and simultaneous pin mapping may dominate. Frequency does not state work per cycle or deterministic I/O capability.

A4. DMA transfers data between peripheral and memory without CPU work per item. Incorrect lengths, stale buffers, ownership races, cache incoherency, overwriting unread data, and premature reuse can corrupt results.

A5. A long ISR delays equal or lower-priority interrupts, increases jitter, risks missed events, and makes worst-case timing difficult. Capture essential state, signal deferred work, and return.

A6. No. volatile affects compiler access but does not make read-modify-write atomic, protect multi-field invariants, or provide complete synchronization. Use atomic operations, critical sections, queues, or RTOS/architecture primitives.




A7. A superloop is compact and analyzable when tasks are bounded and non-blocking. An RTOS organizes concurrent activities with priorities and IPC but adds scheduling, stack, deadlock, priority-inversion, and configuration complexity. Neither is automatically correct.

A8. Period is activation interval; latency is event-to-response delay; jitter is timing variation; execution time is required CPU time; deadline is latest acceptable completion; WCET is a justified upper bound under stated conditions.

A9. Independent emergency and hardware safety functions, command timeout, safe actuator state, fast control loops, essential sensing, watchdog, and local fault reporting should remain. Exact functions follow risk analysis.

A10. Stream transport do not preserve application write boundaries; bytes may be fragmented or combined. Receiver needs an explicit way to identify complete messages and resynchronize after loss or corruption.

A11. Fixed length is simple but inflexible; delimiters are readable but require escaping; length prefixes are efficient but corrupted lengths can misframe until recovery; COBS reserves a delimiter with bounded encoding overhead and reliable resynchronization at the next delimiter.

A12. Specify physical layer, timing, versions, types, units, scale, ranges, authority, maximum rates, acknowledgements, timeouts, retries, duplicate handling, startup, health, errors, compatibility, and security.

A13. Sequence reveals order, gaps, and duplicates within context; CRC detects many accidental bit errors in covered bytes. Neither authenticates a sender or proves physical correctness.

A14. CRC algorithms are public and unkeyed, so an attacker may modify payload and compute a matching CRC. Authentication requires a protected cryptographic key and MAC or signature, plus freshness/replay design.

A15. Only the documented acknowledgement stage: perhaps frame validation, acceptance, completion, or durable storage. Transport receipt does not automatically prove physical actuation or persistent application state.

A16. An independent task may continue refreshing while the critical control task is deadlocked. Refresh only after all required health evidence has advanced within deadline.

A17. External circuitry and reset defaults must keep them safe; firmware then explicitly writes safe levels before enabling output drivers. Commands are rejected until configuration, health, and authority checks pass.

A18. Discard-oldest retains current state but loses history; discard-newest preserves historical sequence but becomes stale. Choose from the application’s value of freshness versus continuity and report every loss.

A19. 20 × 10-6 × 86400 seconds is approximately 1.728 seconds. Actual error varies with conditions and sign.

A20. Wall time can step forward or backward during synchronization or manual change. A monotonic counter advances consistently and is appropriate for deadlines, timeouts, and control intervals.

A21. Write the candidate into an inactive slot, verify target/version/signature/hash, retain the confirmed image, trial boot with limited attempts, run health checks, confirm only after success, and automatically fall back if boot or confirmation fails.

A22. Inspect reset reason and brownout flags, supply voltage at the MCU during radio peaks, regulator current/transient response, wiring and ground drop, decoupling, battery impedance, RF layout, watchdog timing, heap/stack use, and software logs. Do not assume it is solely a software crash.

A23. Measure supply and ground, observe differential/single-ended waveforms and motor transients, inspect shielding/routing/termination/reference, count framing and CRC errors, capture raw bytes and timestamps, test reduced baud and motor-off cases, and verify parser resynchro- nization. Separate physical corruption from firmware buffer loss.

A24. Define expected timeout and safe outputs; operate normally; interrupt the link at controlled times and command states; measure detection and safe-transition latency; verify no stale command replay after reconnection; record MCU state, fault code, Linux logs, and physical output; repeat across resets and load conditions.


Chapter summary
Microcontrollers provide direct, resource-bounded control of sensing, timing, communication peripherals, power, and actuation. Linux provides rich networking, storage, computation, and management. Dependable distributed nodes emerge only when responsibility and authority are explicit; time and memory are bounded; streams are recoverable versioned framing; sequences, CRC, authentication, and freshness are not confused; watchdog and brownout behavior are tested; buffers expose overload; clocks and resets are modeled; and firmware updates preserve a verified recovery path. These principles apply across Pico, ESP, STM32, Nordic, NXP, TI, Microchip, and industrial-controller platforms.

Summary

Microcontrollers provide direct, resource-bounded control of sensing, timing, communication, peripheral, power, and actuation tasks. Linux provides richer storage, networking, computation, and software services. This chapter explains how these capabilities can be partitioned and integrated through bounded interfaces, framed protocols, synchronization, watchdogs, bootloaders, firmware updates, diagnostics, and explicit safety behavior.

Course outline

What we will learn

From Linux foundations to physical interfaces, networking, security and a complete embedded system.

Linux foundationsKernel, users, processes and file systems
Command lineShells, scripting and automation
Embedded hardwareBoot, storage and device drivers
Physical I/OGPIO, sensors and actuators
Device busesUART, I²C and SPI
NetworkingTCP/IP, SSH and remote management
Distributed systemsMessage passing and cooperating nodes
Engineering practiceGit, testing, logging and deployment
SecurityLeast privilege, updates and secrets

Teaching method

Short introductions are followed by laboratory activities. Work is normally completed in teams of three. Each team develops an embedded Linux system; the examination portfolio is individual.

Project ideas

Applications you could build

Each project should begin with one reliable end-to-end function.

Automatic Raspberry Pi-based GPS trackerSample examination report available in PDF format
Environmental monitoring stationValidated sensing, local storage and dashboard
Energy monitoring systemMeasure, log and visualize equipment power use
Greenhouse automationClimate sensing, actuation and remote supervision
Field-robot telemetryLocation, operating state, measurements and faults
LoRaWAN sensor networkField nodes, TTN integration and private cloud
Intelligent irrigationSensing, decisions, valves and safe failure handling
Multi-node IoT gatewayProtocol translation, buffering and secure forwarding
ROS 2 communication systemDistributed nodes, QoS and service integration
Edge-AI monitoring systemLocal inference, measured performance and safe fallback

A complete project should demonstrate

NeedA clear user and purpose
Physical interfaceA sensor, actuator or device
Linux integrationPrograms, scripts or services
CommunicationA justified data-exchange method
ReliabilityLogging and failure handling
EvidenceTests, results and reflection

Contractor and client roles

Project groups

Each group develops a project for one client group and evaluates the project received from another contractor group.

Contractor

Heros

ProjectProject 01
Delivers to
Client not assigned
Receives from
Contractor not assigned

Fridays · four 50-minute slots · Odense

Fall 2026 lecture plan

The SDU timetable remains authoritative for dates, times and rooms.

Project progression

Project ideas and proposals begin in Module 1 and evolve throughout the course. Module 10 is the formal integration, architecture and verification review; Modules 11–12 complete implementation, demonstration and individual portfolio evidence.

Lecture 05 · participation

Student questions

Questions remain hidden until the student is called. Model answers are revealed separately.

Instructor classroom view

The roster, answers, attendance and participation records are available only to the authorized primary owner after sign-in.

Instructor sign in

Definitions

Essential course vocabulary

Plain-language definitions for the technical terms used throughout the course.

TermDefinitionExample
ActuatorA device that produces a physical action.Motor, valve, relay or fan
BootThe sequence that starts the hardware, kernel, services and applications.Starting an embedded computer
CLIA text interface that accepts commands.Windows Terminal or a Linux terminal
CommandAn instruction interpreted by a shell.pwd, ls or Get-Location
Device driverSoftware through which the operating system communicates with hardware.GPIO or camera driver
DirectoryA named container for files and other directories./home/student/eml
DistributionA complete operating system built around the Linux kernel.Ubuntu or Debian
Embedded systemA computer integrated into a larger product for a defined purpose.Greenhouse controller
File systemThe structure used to name, store and retrieve files.ext4
GPIOA configurable digital input or output pin.Reading a switch
I²CA two-signal serial bus for peripherals.Environmental sensor
KernelThe privileged core managing memory, processors, devices and processes.Linux kernel
MQTTA lightweight publish/subscribe messaging protocol.Sending sensor data
ProcessA running instance of a program.A data logger
PWMRapid switching used to control average power or a signal duty cycle.Motor speed
RootThe privileged Linux user or the top directory, depending on context.Administrative access
ScriptA file containing commands that automate work.A backup script
SensorA device that converts a physical quantity into data.Temperature sensor
ServiceA background program providing an ongoing function.SSH server
ShellA program that interprets commands and starts programs.Bash or PowerShell
SPIA synchronous bus commonly used for fast peripherals.Display or converter
SSHEncrypted remote command-line access.Managing a Raspberry Pi
TCP/IPThe principal protocol family used across computer networks.Device-to-server communication
UARTAn asynchronous serial interface.Debug console
User spaceThe environment where ordinary programs run outside the kernel.Application software
Version controlA system that records and manages file changes.Git

Official examination information · EKA T550077102

Individual portfolio examination

Form

Portfolio

Individual presentation portfolio submitted at semester end.

Grade

7-point scale

No second examiner.

Weighting

No split published

No separate written-exam or coursework percentages are stated.

Re-examination

Same form

Same form as the ordinary examination.

Team project and individual assessment

The team project creates practical evidence, but each student is assessed individually through the presentation portfolio. Classroom participation points support engagement and do not form part of the official grade.

Document from the beginning

  • Your own decisions and identifiable contribution
  • Commands, code, configuration and version history
  • Tests, results, failures and improvements
  • Reflection on trade-offs and learning

People and course systems

Contacts and official links