Microcontrollers and Interfacing

Chapter 10
Real-Time Firmware and Embedded Control

Bachelor Program in Mechatronics Engineering
Microcontrollers and Interfacing   •   Bachelor

Real-Time Firmware and Embedded Control

Introduction and Context

A microcontroller-based mechatronic product is not merely a collection of sensors, actuators, and software routines. It is a time-dependent control system. The firmware must acquire physical measurements, compute decisions, update actuators, communicate with other devices, and detect faults within specified time limits. A result that is mathematically correct but delivered too late may be functionally wrong.

Real-time firmware therefore combines three concerns:

  1. Functional correctness — the computation produces the intended result.
  2. Temporal correctness — computations complete before their deadlines.
  3. Safety and robustness — abnormal conditions are detected and controlled safely.

This chapter develops finite-state machines, cyclic and priority-based schedulers, real-time operating-system (RTOS) mechanisms, timing analysis, concurrency control, sampled-data feedback, and fault-handling logic. The emphasis is on design reasoning that can be transferred to motor drives, robotic mechanisms, autonomous systems, industrial controllers, and embedded instrumentation.

Learning Objectives

By the end of this chapter, you should be able to:

  • model embedded behavior with finite-state machines;
  • distinguish periodic, sporadic, and event-driven activities;
  • select an appropriate scheduler or RTOS architecture;
  • use tasks, queues, semaphores, mutexes, and event flags correctly;
  • estimate processor utilization and reason about deadlines;
  • explain priority inversion and methods for limiting it;
  • implement a sampled-data feedback controller;
  • design watchdog, sensor-validation, and actuator-fallback logic;
  • evaluate an embedded design for timing, concurrency, resource, and safety risks.

1. Real-Time Firmware as a Control System

A real-time system has timing constraints associated with its computations. A hard real-time deadline must not be missed, as in a safety shutdown or overcurrent response. A firm real-time result is useless after its deadline, although an occasional miss may not cause catastrophic damage. A soft real-time task loses quality when late, as in a display refresh or data logger.

Important timing terms are:

  • Period, T: minimum or nominal interval between successive releases of a periodic task.
  • Execution time, C: processor time required by one task instance under stated conditions.
  • Release time: time at which an instance becomes ready.
  • Response time: time from release until completion.
  • Relative deadline, D: maximum permitted completion time measured from release.
  • Jitter: variation in release or completion time.
  • Blocking time, B: delay caused by a lower-priority activity holding a needed resource.

A periodic task is often represented by the tuple τi = (Ti, Ci, Di), where the subscript identifies the task. The simple utilization contribution is

Ui = Ci / Ti

where both Ci and Ti use the same time unit. For n independent periodic tasks, total processor utilization is

U = ∑i=1n Ci / Ti

This is a workload estimate, not a complete schedulability proof. Interrupt execution, context switches, blocking, cache effects, DMA contention, and measurement uncertainty must also be considered.

Example 1: Utilization estimate

Suppose a controller executes every 1 ms and requires 0.20 ms, a communication task executes every 10 ms and requires 0.80 ms, and a diagnostic task executes every 100 ms and requires 2 ms. Then

U = 0.20/1 + 0.80/10 + 2/100 = 0.20 + 0.08 + 0.02 = 0.30.

The nominal CPU utilization is 30%. This leaves capacity, but it does not by itself prove that the 1 ms control task always meets its deadline; interrupt bursts and blocking must still be examined.

2. Finite-State Machines for Embedded Behavior

A finite-state machine (FSM) describes a system using a finite set of states, input events, transition conditions, and actions. It is particularly useful when the same input has different meanings in different operating modes.

A state can be understood as a stable mode of operation, such as OFF, INITIALIZING, READY, RUNNING, FAULT, or SHUTDOWN. A transition has the general form:

source state + event/condition → destination state + action

For example:

  • OFF + Start command and safe sensors → INITIALIZING
  • INITIALIZING + self-test passed → READY
  • READY + enable command → RUNNING
  • RUNNING + overcurrent → FAULT
  • Any state + emergency stop → SHUTDOWN
  • FAULT + reset command and fault cleared → READY

A Moore machine produces outputs primarily from the current state. A Mealy machine allows outputs to depend on both state and input. Moore models are often easier to verify for safety because outputs do not change unexpectedly due to a transient input, while Mealy models can respond with lower latency.

Hierarchical and orthogonal state machines

A complex product may have independent modes. A robotic actuator could simultaneously have a power state, a motion state, and a communication state. Duplicating every combination creates a state explosion. Hierarchical state machines allow shared behavior to be placed in a parent state, while orthogonal regions represent genuinely independent behavior.

State-machine design should specify:

  • legal states and transitions;
  • entry, during, and exit actions;
  • default behavior for unexpected events;
  • reset behavior;
  • safe outputs in every state;
  • whether transitions are atomic with respect to concurrent tasks.

A useful implementation separates event generation from state transition processing. Interrupt service routines should normally record an event or set a flag, then return quickly. A firmware task processes the event in a controlled context. This reduces interrupt latency and avoids performing complex, blocking operations inside an interrupt.

3. Firmware Execution Architectures

Superloop architecture

In a superloop, initialization is followed by an endless loop that calls services in sequence:

initialize hardware
while true:
    sample inputs
    execute control logic
    service communication
    update outputs
    perform diagnostics

The approach has little overhead and is suitable for small systems. Its weaknesses are blocking calls, poor scalability, and timing that depends on the execution time of everything earlier in the loop.

Timer-interrupt and cyclic executive

A timer interrupt can establish a periodic time base. A cyclic executive divides work into frames. Each frame must contain only activities that can fit within its allotted time. This gives deterministic behavior but becomes difficult when tasks have unrelated periods or irregular execution times.

Event-driven firmware

Event-driven firmware sleeps until an interrupt or event occurs. It is energy efficient and responsive to asynchronous inputs. However, lengthy event handlers can delay other events. Event handlers should therefore do minimal urgent work and defer substantial processing.

RTOS-based architecture

An RTOS provides task scheduling, synchronization, inter-task communication, timers, and often memory-management facilities. It improves modularity but introduces context-switch overhead, configuration complexity, and new failure modes such as deadlock and priority inversion. An RTOS does not automatically make a system real-time; deadlines must still be analyzed and tested.

4. Tasks, Scheduling, and Deadlines

A task is an independently schedulable activity with its own stack and execution context. Tasks may be periodic, sporadic, or aperiodic.

  • A periodic task runs at regular intervals, such as a 1 kHz current controller.
  • A sporadic task responds to irregular events with a known minimum inter-arrival time, such as an emergency input.
  • An aperiodic task has no reliable arrival bound, such as a maintenance command.

A common fixed-priority policy is rate-monotonic scheduling (RMS): tasks with shorter periods receive higher priority. For ideal independent periodic tasks with deadlines equal to periods, a sufficient utilization bound is

U ≤ n(21/n − 1)

where n is the number of tasks. This is a sufficient, not necessary, condition: a task set above the bound may still be schedulable. For one, two, and many tasks, the bound approaches approximately 100%, 83%, and 69%, respectively.

For a task under fixed-priority preemptive scheduling, a response-time analysis can include interference from higher-priority tasks and blocking:

Ri = Ci + Bi + ∑j∈hp(i) ⌈Ri/Tj⌉ Cj

Here, Ri is the response-time estimate for task i, Bi is its blocking time, and hp(i) is the set of higher-priority tasks. The equation is solved by iteration, beginning with Ri(0) = Ci + Bi. It is applicable under assumptions such as fixed priorities, known execution times, preemption, and bounded task arrivals. The task is schedulable if the converged response time satisfies Ri ≤ Di.

Worked response-time example

Consider task A with CA = 1 ms, DA = TA = 5 ms, and no blocking. A higher-priority task B has CB = 0.5 ms and TB = 2 ms. Starting with

RA(0) = 1.

The first iteration gives RA(1) = 1 + ⌈1/2⌉(0.5) = 1.5 ms. The next gives RA(2) = 1 + ⌈1.5/2⌉(0.5) = 1.5 ms. The result converges to 1.5 ms, which is less than the 5 ms deadline. The ceiling function counts how many releases of task B can interfere during A's response interval.

Scheduling practice

A practical design should:

  • assign the highest priorities to short-deadline, safety-critical work;
  • bound interrupt and critical-section durations;
  • measure worst-case execution time rather than relying on average time;
  • reserve margin for aging, compiler changes, communication bursts, and diagnostics;
  • avoid unbounded loops in deadline-critical tasks;
  • monitor deadline misses explicitly.

5. RTOS Communication and Synchronization

Queues

A queue transfers discrete data items between tasks, commonly using first-in, first-out order. A producer places a sensor sample or command in the queue; a consumer removes it. A queue decouples producer and consumer timing, but its capacity is finite. Overflow policy must be explicit: reject new data, overwrite the oldest data, discard low-priority data, or trigger a fault.

Queues are appropriate when the data itself must be transferred. A pointer queue can reduce copying, but ownership of the referenced buffer must be unambiguous.

Semaphores

A counting semaphore represents a quantity of available resources or pending events. For example, a DMA-completion interrupt may release a semaphore and a task may take it. A binary semaphore can signal an event, although event flags or direct task notifications may be more efficient in some RTOSs.

A semaphore generally does not express ownership. The task that takes it need not be the task that gives it. It is therefore usually not the best primitive for protecting a shared data structure.

Mutexes

A mutex provides mutual exclusion and ownership. Only the owning task should release it. Mutexes are appropriate for short critical sections involving shared buses, configuration structures, or peripheral drivers. They must not be held while waiting for an unrelated event or performing lengthy communication.

A mutex should support priority inheritance or priority ceiling where appropriate. Priority inheritance temporarily raises the priority of a low-priority mutex holder to that of a blocked higher-priority task. Priority ceiling assigns a resource a ceiling priority and can limit blocking and detect some incorrect access patterns.

Priority inversion and deadlock

Priority inversion occurs when a high-priority task waits for a resource held by a low-priority task while medium-priority tasks execute. The high-priority task is indirectly delayed by the medium-priority tasks. Priority inheritance reduces this unbounded delay.

Deadlock commonly requires four conditions: mutual exclusion, hold-and-wait, no preemption, and circular wait. Design strategies include consistent lock ordering, short lock durations, timeouts, avoiding nested locks, and using message passing instead of shared memory.

Interrupts and concurrency

Shared variables modified by both an interrupt and a task require careful treatment. volatile may prevent inappropriate compiler optimization, but it does not by itself make a multi-byte operation atomic or provide mutual exclusion. Atomic operations, interrupt masking, lock-free protocols, or a suitable RTOS primitive may be needed. Critical sections should be as short as possible because they increase interrupt latency.

6. Sampled-Data Feedback Control

A digital controller observes a physical process at discrete sampling instants. Let r[k] be the reference, y[k] the measured output, and e[k] = r[k] − y[k] the error at sample k. The sampling period is Ts seconds.

A discrete proportional-integral-derivative (PID) controller may be implemented as

u[k] = Kp e[k] + I[k] + Kd (e[k] − e[k−1]) / Ts

with integral update

I[k] = I[k−1] + Ki Ts e[k]

where Kp is proportional gain, Ki is integral gain, Kd is derivative gain, and u[k] is the commanded control effort. The gains depend on the plant and units. The derivative term shown is a backward-difference approximation and is sensitive to measurement noise.

The controller must account for actuator saturation. If the physical actuator permits only umin ≤ u ≤ umax, the command should be limited:

usat[k] = min(umax, max(umin, u[k]))

When saturation occurs, continued integration can cause integral windup. A simple conditional-integration strategy updates the integral only when the actuator is not saturated, or when the error would move the actuator back toward its allowable range. A back-calculation method instead feeds the saturation difference into the integrator; its exact form depends on the chosen sign convention and tuning.

Sampling must be sufficiently fast relative to the plant dynamics. Sampling too slowly causes delay, aliasing, and possible instability. An anti-aliasing filter should remove frequency components above the useful measurement bandwidth before analog-to-digital conversion. The sampling period, sensor latency, computation time, and zero-order-hold behavior together contribute phase delay.

A control task should have a deterministic release mechanism, commonly a hardware timer or RTOS periodic delay referenced to an absolute schedule. A relative delay after computation can cause drift because execution time is added to each period.

Control-task pseudocode

periodic_control_task:
    wait_until_next_release()
    raw = read_sensor()
    measurement = validate_and_filter(raw)
    error = reference - measurement
    provisional = compute_pid(error)
    command = saturate(provisional)
    update_anti_windup(provisional, command, error)
    write_actuator(command)
    record_timing_and_fault_status()

Sensor acquisition, control computation, and actuator update should have clearly defined timing relationships. In high-performance systems, timer-triggered ADC conversion and DMA can reduce sampling jitter, while the control task processes a completed sample.

7. Fault Handling and Safety Logic

Fault handling should be designed as deliberately as normal operation. Typical faults include sensor disconnection, out-of-range measurements, stale data, actuator disagreement, communication loss, watchdog expiration, overtemperature, overcurrent, and memory corruption.

A robust fault path includes:

  1. Detection — identify a violation using range, rate-of-change, timeout, plausibility, or redundancy checks.
  2. Classification — distinguish warning, recoverable fault, and hazardous fault.
  3. Containment — stop or limit the affected function and place outputs in a defined safe state.
  4. Notification — record diagnostic information and inform a supervising system.
  5. Recovery — retry, reset, reinitialize, or require an authorized manual reset.
  6. Verification — confirm that the fault has cleared before re-enabling operation.

A fault state should be latched when an automatic restart could be dangerous. For example, an emergency stop should normally require a deliberate reset and a fresh enable sequence, not merely disappearance of the input signal.

The watchdog is a last-resort mechanism, not a substitute for task supervision. A centralized watchdog service should receive health indications from critical tasks and refresh the hardware watchdog only when all required indications are valid. Otherwise, a task that is alive but malfunctioning could keep refreshing the watchdog.

A fail-safe design moves to a safe condition after a fault. A fail-operational design continues limited operation using redundancy or degraded modes. The correct choice depends on hazard analysis, energy, motion, environment, and applicable standards. Safety-related products may require processes and evidence aligned with standards such as IEC 61508, ISO 13849, or ISO 26262; the applicable standard depends on the industry and product.

8. Integrated Illustrative Case: Servo-Driven Safety Gate

The following is a fictional illustrative case.

Background

A small automated production cell uses a motor-driven guard gate. The controller reads a position encoder, a closed-limit switch, an open-limit switch, and an emergency-stop circuit. It commands a motor drive over a digital interface. The gate must stop promptly when an unsafe condition occurs.

Problem

An initial prototype used one superloop. During communication retries, the loop sometimes delayed position sampling. The gate could also restart immediately after a transient emergency-stop release, and a shared diagnostic buffer occasionally became corrupted.

Analysis

The required functions were separated into timing classes:

ActivityTypeRequirementProposed mechanism
Position/control updatePeriodic1 ms deadlineHigh-priority control task
Emergency input captureSporadicImmediate captureInterrupt plus safety task
Drive communicationPeriodic/event-driven10 ms serviceCommunication task and queue
DiagnosticsAperiodicNoncriticalLow-priority task
Watchdog supervisionPeriodic20 ms health windowSupervisor task

The FSM states were OFF, INITIALIZING, READY, OPENING, CLOSING, FAULT, and EMERGENCY_STOP. Motion commands were accepted only in the appropriate state, and the emergency input caused a transition from every state to EMERGENCY_STOP.

Approach and solution

The control task used a timer-based periodic release. The emergency interrupt disabled the drive-enable output through a hardware path where possible, latched an event, and notified the safety task. It did not attempt to perform logging or communication in interrupt context.

A queue carried motion commands from the user-interface task to the state-machine task. A mutex protected the communication driver because it was accessed by the control diagnostic service and the communication task. The mutex was configured with priority inheritance. Diagnostic records were placed in a bounded queue; overflow generated a counter and a warning rather than blocking the control task.

Sensor validation rejected impossible combinations, such as both limit switches being active during ordinary motion, and rejected encoder samples that exceeded a physically plausible rate. The actuator command was saturated and motion was inhibited when a limit or safety fault was detected.

Outcome

The architecture removed communication retries from the control loop, made emergency behavior explicit, and prevented an immediate restart. Timing instrumentation recorded task response times, queue high-water marks, mutex hold times, and missed releases. Testing included sensor disconnection, stuck inputs, queue overflow, repeated emergency stops, processor overload, and watchdog recovery.

Learning points

The main improvement did not come from selecting an RTOS alone. It came from assigning timing requirements, ownership, state transitions, and safe behavior explicitly. The RTOS mechanisms supported the design; they did not replace engineering analysis.

9. Verification, Resource Use, and Professional Practice

Real-time verification should combine analysis, instrumentation, and fault injection. Useful measurements include worst observed execution time, response-time distribution, interrupt latency, deadline misses, stack high-water marks, queue occupancy, heap usage, and mutex blocking duration.

Dynamic memory allocation can be convenient but may introduce fragmentation, nondeterministic allocation time, and failure during long operation. Safety- or deadline-critical firmware commonly uses static allocation or bounded memory pools. Every task requires enough stack for its worst call path, interrupt nesting assumptions, and library behavior.

Code review should examine race conditions, timeout units, integer overflow, signedness, initialization order, and behavior after reset. Time values should have explicit units. Interfaces should document ownership, blocking behavior, maximum message size, and failure returns.

AI-assisted coding can help generate test scaffolding, explain APIs, or identify obvious defects, but generated code must be reviewed, compiled with warnings enabled, statically analyzed, tested on target hardware, and evaluated against safety and licensing requirements. An AI tool cannot establish that a deadline is met or that a fault response is safe.

Challenges and Limitations

No timing model is exact. Flash wait states, interrupts, DMA arbitration, compiler optimization, caches, thermal effects, and communication traffic can alter execution time. Average measurements are inadequate for hard deadlines. Similarly, an FSM can become difficult to maintain if state responsibilities are unclear, while an RTOS can encourage excessive task decomposition and synchronization.

Sampled-data control introduces discretization and delay. A controller that is stable in continuous time may become poorly damped or unstable after sampling and computation delays. Gains must therefore be validated with the actual sampling period, sensor filtering, actuator limits, and plant dynamics.

Finally, fault handling cannot be designed solely from software assumptions. The complete system includes wiring, power electronics, mechanical energy, human interaction, and external communication. Hazard analysis and independent safety mechanisms may be necessary.

Chapter Summary

Real-time firmware must satisfy functional, temporal, and safety requirements. Finite-state machines provide a disciplined representation of modes, events, transitions, and safe outputs. Superloops are simple, whereas cyclic executives and RTOS architectures offer stronger structure for multiple timing classes.

Tasks should be characterized by period, execution time, deadline, and blocking. Utilization is a useful first estimate, but response-time analysis and measurement are needed for credible deadline claims. Queues transfer data, semaphores signal events or count resources, and mutexes protect owned shared resources. Priority inversion, deadlock, race conditions, and unbounded blocking must be actively controlled.

Sampled-data feedback uses discrete measurements and updates. PID implementation requires attention to sampling, noise, saturation, integral windup, timing jitter, and actuator limits. Fault handling should detect, classify, contain, notify, recover, and verify. Watchdogs, validation checks, explicit fault states, and independent safety paths improve robustness. The integrated case demonstrates that reliable embedded control results from coordinated architecture, analysis, implementation, and testing.

Key Terms

Real-time system: A system whose correctness depends on both results and their timing.

Hard deadline: A deadline that must not be missed.

Period: The interval between releases of a periodic task.

Execution time: Processor time needed by one task instance.

Jitter: Variation in release or completion timing.

Finite-state machine: A model based on finite states, events, transitions, and actions.

Moore machine: A state machine whose output is primarily determined by state.

Mealy machine: A state machine whose output can depend on state and input.

Superloop: A repeatedly executed foreground firmware loop.

Task: An independently schedulable execution context.

Queue: A bounded mechanism for transferring ordered data between execution contexts.

Semaphore: A synchronization primitive representing events or resource counts.

Mutex: An ownership-based mutual-exclusion lock.

Priority inversion: Delay of a high-priority task because a lower-priority task holds a needed resource.

Deadlock: Permanent waiting caused by circular resource dependencies.

Sampling period: Time between successive digital control samples.

Integral windup: Excessive integrator accumulation during actuator saturation.

Watchdog: A hardware or software timer used to detect missing system service.

Fail-safe: A response that moves the system toward a defined safe condition.

Response time: Time from task release until task completion.

Review Questions

5 Short Answer Questions

  1. Distinguish hard, firm, and soft real-time requirements.
  2. What information is represented by a finite-state-machine transition?
  3. Why is a mutex generally more appropriate than a semaphore for protecting a shared data structure?
  4. Define priority inversion.
  5. Why can a PID integrator wind up during actuator saturation?

5 Long Answer Questions

  1. Compare superloop, cyclic-executive, event-driven, and RTOS-based firmware architectures.
  2. Explain how queues, semaphores, mutexes, and event notifications differ in purpose and ownership.
  3. Derive and interpret the utilization estimate for a set of periodic tasks, and explain why it is not a complete schedulability proof.
  4. Describe a robust fault-handling sequence from detection through recovery and verification.
  5. Explain the effects of sampling period, sensor noise, computation delay, and actuator saturation on digital feedback control.

3 Analytical / Application Questions

  1. A task has C = 0.6 ms and T = 4 ms. Two higher-priority tasks have parameters (C1,T1) = (0.4,2) ms and (C2,T2) = (0.5,5) ms. Using iterative response-time reasoning and assuming no blocking, determine whether the task meets a 4 ms deadline.
  2. Design an FSM for a motorized door with OFF, READY, OPENING, CLOSING, FAULT, and EMERGENCY_STOP states. Specify at least two transitions from each motion state and define safe outputs after an emergency event.
  3. Propose an RTOS architecture for a sensor-controlled actuator with a 1 ms control loop, irregular emergency inputs, 10 ms communications, and low-priority logging. Identify task priorities, communication primitives, and two tests for timing or concurrency faults.

Multiple Choice Questions with Answers

Question 1

Which property distinguishes a hard real-time task?

A. It always uses the least processor time.

B. Its deadline must not be missed.

C. It never communicates with another task.

D. It runs only in an interrupt.

Correct Answer: B. Its deadline must not be missed.

Question 2

Which mechanism is primarily intended to transfer discrete data between tasks?

A. Queue

B. Mutex

C. Watchdog

D. Priority ceiling

Correct Answer: A. Queue

Question 3

A mutex differs from a counting semaphore because a mutex normally includes:

A. Analog filtering

B. Task ownership

C. A fixed sampling frequency

D. DMA conversion

Correct Answer: B. Task ownership

Question 4

For three independent periodic tasks, the nominal utilization is computed as:

A. ∑ T_i/C_i

B. ∑ C_iT_i

C. ∑ C_i/T_i

D. ∑(C_i+T_i)

Correct Answer: C. ∑ C_i/T_i

Question 5

What is the main purpose of priority inheritance?

A. To increase ADC resolution

B. To reduce priority inversion

C. To eliminate actuator saturation

D. To replace all queues

Correct Answer: B. To reduce priority inversion

Question 6

In a sampled controller, the error is commonly defined as:

A. e[k] = y[k] − r[k]

B. e[k] = r[k] − y[k]

C. e[k] = r[k]y[k]

D. e[k] = r[k]/y[k]

Correct Answer: B. e[k] = r[k] − y[k]

Question 7

What problem results when the integral term continues accumulating while the actuator is saturated?

A. Aliasing

B. Deadlock

C. Integral windup

D. Priority inheritance

Correct Answer: C. Integral windup

Question 8

Which action should normally be avoided in a time-critical interrupt service routine?

A. Capturing a timestamp

B. Setting an event flag

C. Performing lengthy blocking communication

D. Recording a hardware status bit

Correct Answer: C. Performing lengthy blocking communication

Question 9

Why should a watchdog supervisor require health indications from critical tasks?

A. To ensure a malfunctioning task cannot refresh the watchdog alone

B. To increase queue capacity

C. To tune proportional gain

D. To remove all interrupts

Correct Answer: A. To ensure a malfunctioning task cannot refresh the watchdog alone

Question 10

Which state-machine response is generally appropriate for an emergency-stop event?

A. Ignore it until the next communication cycle

B. Transition to a defined emergency state and inhibit hazardous actuation

C. Increase the motor command temporarily

D. Clear all diagnostic records

Correct Answer: B. Transition to a defined emergency state and inhibit hazardous actuation

Microcontrollers and Interfacing
Chapter 10 of 14