6. Embedded Systems and Real-Time ComputingIntroduction and ContextMechatronic systems combine mechanical structures, sensors, actuators, power electronics, control algorithms, and computation. Embedded computing provides the decision-making layer that connects these elements. A controller in a robotic joint, an electronic control unit in a vehicle, a machine-vision module, and a digitally controlled motor drive are all embedded systems: computing systems designed for a specific physical function rather than general-purpose computing. In mechatronics, correctness has two dimensions. The computed result must be numerically and logically correct, and it must be produced at the required time. A control command calculated after the relevant mechanical event has passed may be equivalent to an incorrect command. This temporal requirement distinguishes real-time computing from ordinary computation. The central engineering task is therefore to design a platform and software architecture that satisfy functional, timing, reliability, energy, cost, and maintainability constraints simultaneously. This chapter examines microcontrollers, digital signal processors, field-programmable gate arrays, and system-on-chip platforms; their peripherals, memory, interrupts, timers, firmware, and operating-system support; and the methods used for hardware–software co-design. Learning ObjectivesAfter studying this chapter, the reader should be able to: 1. Explain the architecture and application domains of embedded computing platforms. 2. Distinguish hard, firm, and soft real-time requirements. 3. Select microcontroller, DSP, FPGA, or SoC solutions for mechatronic applications. 4. Design interrupt, timer, memory, peripheral, and firmware structures. 5. Analyse latency, jitter, schedulability, computational load, and energy consumption. 6. Apply RTOS concepts and hardware–software co-design methods. 7. Evaluate reliability, security, safety, and lifecycle issues in embedded products. The Embedded-System Design ProblemAn embedded system interacts continuously with a physical process. Its typical signal path is: sensor → signal conditioning and conversion → computation → actuation → mechanical response. Analogue-to-digital converters (ADCs) transform measured voltages or currents into numerical values, while digital-to-analogue converters (DACs), pulse-width modulation (PWM), or communication interfaces produce commands. The controller executes estimation, control, diagnostics, and communication tasks within a bounded time. A useful abstraction is a periodic control task with sampling period \(T_s\), execution time \(C\), and deadline \(D\). For a simple single task, a necessary utilization condition is approximately \[ U = C/T_s < 1. \] For several tasks, utilization alone is not a complete proof of schedulability because priorities, blocking, interrupts, and deadlines also matter. Timing analysis must therefore consider worst-case execution time (WCET), release time, response time, interrupt latency, communication delays, and jitter. A real-time system may be classified as: - Hard real-time: a missed deadline can cause unacceptable failure or a safety hazard.
- Firm real-time: a late result has no value, although occasional misses may be tolerated.
- Soft real-time: late results reduce quality or performance but do not invalidate the system.
A motor over-current trip is normally hard real-time; a supervisory display update is usually soft real-time. A production inspection image may be firm real-time because an image arriving after the part leaves the station is useless. Platform Architectures for MechatronicsMicrocontrollersA microcontroller unit (MCU) integrates a processor core, memory, timers, GPIO, serial interfaces, ADCs, PWM units, and sometimes motor-control or safety peripherals on one chip. MCUs are attractive because they are inexpensive, energy efficient, deterministic, and supported by mature development tools. They are widely used in compact controllers, instrument clusters, actuator modules, appliances, and distributed industrial nodes. An MCU is particularly suitable when the application requires moderate computational performance, close coupling to sensors and actuators, predictable interrupt response, and low power. Selection should consider clock frequency, instruction set, floating-point support, ADC resolution and sampling rate, PWM alignment, timer architecture, memory size, safety features, communication buses, and development support—not clock speed alone. Digital Signal ProcessorsA DSP is optimized for repetitive numerical operations such as multiply–accumulate, filtering, spectral analysis, and coordinate transformation. DSPs often provide specialized arithmetic units, circular addressing, parallel data paths, and predictable instruction execution. They are useful in active vibration control, audio and ultrasonic processing, power conversion, servo control, and machine vision. The distinction between an MCU and DSP is not absolute. Modern MCUs may include floating-point and digital-signal instructions, while many DSPs include general-purpose peripherals. The engineering choice depends on the dominant workload, timing requirement, software ecosystem, and required integration. Field-Programmable Gate ArraysAn FPGA consists of configurable logic blocks, routing resources, registers, memory blocks, clock-management units, and often high-speed transceivers. Hardware description languages or synthesis tools configure these resources to implement parallel datapaths and finite-state machines. FPGAs are valuable when high throughput, very low and predictable latency, multiple simultaneous data streams, or custom interfaces are required. A vision system may process several pixels per clock; a power converter may execute a protection path independently of a processor. The costs include design complexity, verification effort, resource management, power consumption, and longer development time. Unlike a processor, an FPGA does not execute one instruction stream. It realizes spatially parallel hardware. This provides performance, but errors in clock-domain crossing, reset design, arithmetic width, or synchronization can be difficult to diagnose. System-on-Chip PlatformsA system-on-chip (SoC) integrates processor cores with programmable logic, memory controllers, accelerators, and peripherals. It can partition control software, high-level operating-system functions, and deterministic hardware pipelines on one device. A heterogeneous SoC might run Linux on an application processor while a real-time core or programmable logic handles motor control. Such platforms offer high integration and flexibility but create more complex partitioning, communication, boot, verification, and security problems. A non-real-time operating system should not be assumed to provide deterministic control merely because it runs on a fast processor. Peripherals, Timing, and InterruptsPeripherals are not merely accessories; they determine how accurately a controller observes and influences the physical system. A timer can trigger ADC conversion at a precise instant, capture encoder edges, generate complementary PWM signals, or schedule a control task. Hardware triggering is generally more repeatable than starting conversions from software. Interrupts allow hardware events to request processor service. A well-designed interrupt service routine (ISR) performs only urgent, bounded work: capturing data, clearing the source, recording a timestamp, and notifying a task. Lengthy calculations, blocking communication, and dynamic memory allocation inside an ISR increase latency and jitter. Nested interrupts require deliberate priority design because a high-priority event can delay lower-priority service and create priority inversion indirectly. Direct memory access (DMA) transfers data between peripherals and memory without requiring the processor to move every word. Circular DMA buffers are useful for continuous ADC streams, serial reception, and sampled-data control. DMA improves processor availability but introduces coherency issues: the software must know when a buffer is complete, and caches may need explicit maintenance on systems with data caching. Common interfaces include UART, SPI, I²C, CAN, industrial Ethernet, USB, and memory-mapped buses. Interface selection depends on distance, bandwidth, topology, noise environment, synchronization, fault tolerance, and protocol overhead. CAN, for example, supports distributed control and arbitration, whereas SPI is simple and fast for short board-level connections. Memory and Firmware ArchitectureEmbedded memory usually includes non-volatile program storage, volatile data memory, and sometimes external memory. Flash retains firmware but has finite erase/write endurance. SRAM supports fast execution and temporary data. EEPROM or emulated non-volatile memory stores calibration and configuration. Memory-mapped peripherals occupy address spaces that must be accessed according to hardware rules. Firmware should separate hardware abstraction, device drivers, middleware, control algorithms, diagnostics, and application logic. This separation enables testing and replacement of hardware-specific components. A typical startup sequence initializes clocks, memory protection, pin multiplexing, communication channels, timers, and safety outputs before enabling the application. Static allocation is often preferred in safety-critical systems because it avoids fragmentation and unpredictable allocation time. Fixed-size queues and memory pools provide controlled alternatives. Defensive firmware checks range, plausibility, timeout, sequence, and communication integrity. Watchdogs detect failure to execute a required service pattern, but a watchdog is not a substitute for fault diagnosis: indiscriminate resetting can conceal a recurring defect. Numerical representation is a design decision. Floating-point simplifies modelling and provides dynamic range, while fixed-point arithmetic can reduce cost and provide predictable execution on suitable hardware. Fixed-point design requires scaling, saturation, overflow analysis, and careful treatment of quantization. Sensor resolution and ADC noise may make excessive numerical precision meaningless. Real-Time Scheduling and RTOS ConceptsA bare-metal superloop is often adequate for small systems. It repeatedly checks flags and executes functions. Its simplicity is valuable, but response time can become difficult to predict as functions accumulate. An interrupt-driven architecture assigns immediate events to ISRs and less urgent work to the main loop or deferred handlers. For larger systems, a real-time operating system (RTOS) provides tasks, priorities, timers, inter-task communication, synchronization, and resource management. A task is an independently schedulable execution unit; a semaphore signals or protects an event or resource; a mutex provides mutually exclusive access; and a queue transfers structured data between tasks. Pre-emptive fixed-priority scheduling gives urgent tasks priority over less urgent tasks. Rate-monotonic reasoning assigns higher priority to tasks with shorter periods, subject to assumptions such as independent periodic tasks and bounded execution. Earliest-deadline-first scheduling selects the task whose deadline is nearest, but implementation and certification considerations may favour fixed priorities. Priority inversion occurs when a high-priority task waits for a resource held by a low-priority task while a medium-priority task consumes the processor. Priority inheritance temporarily raises the holder’s priority; priority ceiling protocols restrict which tasks may acquire resources. Both approaches reduce unbounded blocking, but neither removes the need to measure and bound critical sections. A timing budget should include sensing, conversion, computation, communication, actuation, and operating-system overhead. The designer should measure worst-case paths rather than rely on average execution time. Instrumentation using trace pins, cycle counters, logic analysers, and RTOS tracing can reveal jitter and overload conditions. Hardware–Software Co-DesignHardware–software co-design treats the complete system as the design object. A useful process is: 1. Define physical functions, safety constraints, deadlines, data rates, and energy limits. 2. Partition functions according to latency, parallelism, numerical intensity, adaptability, and verification needs. 3. Prototype algorithms in a high-level environment and establish numerical and timing requirements. 4. Map functions to processor software, FPGA logic, dedicated peripherals, or accelerators. 5. Define interfaces, buffer ownership, synchronization, and fault behaviour. 6. Verify functionality, timing, numerical accuracy, thermal performance, and electromagnetic compatibility. 7. Validate the integrated system under nominal, transient, degraded, and fault conditions. A control loop with a strict deadline and modest arithmetic may be placed on an MCU. A high-rate filtering pipeline may be placed in an FPGA, while configuration, logging, and communications run on a processor. The partition should also consider update frequency: functions likely to change frequently are often better kept in software, whereas stable parallel datapaths may justify hardware implementation. The key trade-off is not simply speed versus cost. Hardware can reduce latency and increase parallelism but is less flexible. Software is easier to update and reuse but may have variable timing. A hybrid architecture often provides the best compromise. Energy, Reliability, and SecurityEnergy analysis includes active computation, memory accesses, peripheral operation, communication, leakage, and conversion losses. Dynamic power is broadly related to switching activity, capacitance, voltage, and frequency. Clock gating, sleep modes, event-driven operation, efficient data movement, and appropriate sampling rates can reduce energy. However, aggressive sleeping may increase wake-up latency and compromise deadlines. Reliability measures include watchdogs, brown-out detection, memory parity or error-correcting codes, redundant sensing, plausibility checks, safe-state outputs, and diagnostic coverage. Functional safety requires a hazard-based process, traceable requirements, independent verification, and evidence that faults are detected or controlled. The required rigor depends on the application and applicable standards. Connectivity exposes embedded devices to unauthorized access, malicious firmware, data manipulation, and denial of service. Secure boot establishes trust in the firmware image; signed updates protect the update process; hardware security modules can protect cryptographic keys. Least privilege, authenticated communication, vulnerability management, and controlled debug access should be designed from the beginning rather than added after deployment. Applied Case: Real-Time Control of an Automated Packaging AxisBackgroundThis illustrative case concerns a servo-driven packaging axis that positions a sealing head. An encoder measures shaft position, a current-controlled drive produces torque, and a supervisory controller coordinates motion with a photoelectric sensor. Situation and ProblemThe original prototype used a general-purpose processor and a periodic software loop. Position error was acceptable at low speed, but timing jitter increased during network communication. The sealing head occasionally arrived late, causing defective packages. The design also lacked a reliable over-current response. AnalysisThe position loop requires a fixed sampling period and bounded latency. The current protection path has a substantially tighter deadline than the supervisory interface. Network logging is non-critical and may be delayed. A timing analysis identified three classes of work: - urgent current protection and PWM shutdown;
- periodic encoder sampling and servo computation;
- soft real-time communication, logging, and diagnostics.
The processor’s average utilization appeared acceptable, but worst-case interference from communication caused excessive jitter. This illustrates why average load is not a sufficient real-time argument. Approach and SolutionA microcontroller with hardware PWM, encoder capture, ADC triggering, DMA, fast comparator inputs, and a watchdog was selected. The timer triggered synchronized ADC conversion and the control task. A high-priority hardware or interrupt path disabled PWM when the current threshold was exceeded. The servo algorithm ran as a bounded periodic task. Communication and logging were assigned lower-priority RTOS tasks with queue-based buffering. Calibration constants were stored in protected non-volatile memory, while control variables used static memory. The firmware included sensor plausibility checks, communication timeouts, a safe output state, and signed firmware updates. Timing was measured with a trace pin and cycle counter under maximum communication traffic and worst-case motion. OutcomeThe redesigned architecture separated safety-critical timing from non-critical communication. More importantly, it created evidence for deadline compliance rather than relying on nominal speed. The design could be extended with an FPGA if future requirements demanded simultaneous multi-axis high-rate filtering. Learning PointsThe case demonstrates that platform selection follows timing and fault requirements, not popularity. Hardware-triggered sampling reduces jitter; priority separation prevents low-value tasks from disturbing control; and protection functions should not depend solely on a heavily loaded software loop. Challenges, Limitations, and Common MistakesFrequent mistakes include selecting a processor from clock frequency alone, using floating-point without analysing execution time, placing long algorithms in ISRs, ignoring cache and DMA coherency, sharing data without synchronization, and testing only nominal operating conditions. Another error is treating an RTOS as a guarantee of real-time performance. An RTOS supplies mechanisms; the application designer must still bound execution, blocking, interrupts, and resource use. Timing models may be invalid when WCET is poorly known, hardware accelerators have contention, or external networks introduce unbounded delays. Simulation cannot fully reproduce electrical noise, thermal drift, mechanical backlash, and sensor faults. Hardware-in-the-loop testing and physical validation remain essential. Complex SoCs can create a second limitation: architectural power may exceed organizational capability. A platform requiring advanced FPGA verification, secure boot integration, and multiple toolchains may increase project risk even when it offers superior performance. Current Developments and Best PracticesCurrent embedded systems increasingly combine multicore processors, heterogeneous accelerators, edge analytics, model-based development, and network connectivity. Tiny machine-learning models can classify vibration or detect anomalies locally, reducing communication and latency. Digital twins and hardware-in-the-loop environments support earlier validation. Time-sensitive networking and improved industrial Ethernet provide more deterministic distributed coordination. Nevertheless, emerging technology should be adopted selectively. A sound practice is to maintain a requirements traceability matrix, define timing budgets early, isolate safety functions, automate unit and integration tests, use static analysis and code review, measure WCET and jitter, control configuration changes, and plan long-term firmware support. Reproducible builds, documented interfaces, calibration management, and secure update procedures are equally important. Chapter SummaryEmbedded systems form the computational foundation of mechatronic products. Their design must integrate sensing, computation, actuation, communication, and fault response under physical timing constraints. MCUs provide economical integrated control; DSPs support intensive numerical processing; FPGAs provide deterministic parallel hardware; and SoCs combine processors with programmable or specialized resources. Real-time performance depends on deadlines, WCET, latency, jitter, scheduling, interrupt design, and bounded resource access. Timers, DMA, memory organization, and hardware-triggered peripherals strongly influence behaviour. RTOS mechanisms assist task management but do not replace analysis. Hardware–software co-design partitions functions according to timing, parallelism, adaptability, energy, safety, and verification needs. Reliable products additionally require defensive firmware, secure updates, safety engineering, measured validation, and lifecycle governance. Key TermsEmbedded system: A computing system dedicated to a specific function within a larger product. Real-time system: A system whose correctness depends on both result accuracy and timing. Microcontroller: An integrated processor containing memory and application peripherals. DSP: A processor optimized for repetitive numerical and signal-processing operations. FPGA: Reconfigurable hardware implementing application-specific parallel logic. System-on-chip: An integrated device combining processors, memory interfaces, peripherals, and often programmable logic. Interrupt: A hardware or software event requesting processor service. Interrupt service routine: Code executed in response to an interrupt. DMA: Hardware-supported transfer of data between memory and peripherals. Jitter: Variation in the timing of an event relative to its intended time. Latency: Delay between an event and the corresponding response. WCET: The maximum execution time considered for a task under defined conditions. RTOS: An operating system providing scheduling and timing mechanisms for real-time applications. Priority inversion: A condition in which a high-priority task is delayed by lower-priority activity. Watchdog: A timer that detects failure to execute expected servicing activity. Hardware–software co-design: Joint partitioning and optimization of system functions across hardware and software. Schedulability: The ability of a task set to meet its timing constraints. Firmware: Persistent software controlling embedded hardware. Secure boot: A mechanism that verifies firmware authenticity before execution. Review QuestionsShort Answer Questions1. Distinguish hard, firm, and soft real-time systems. 2. What functions are commonly performed by a microcontroller timer? 3. Why should lengthy computation generally be avoided inside an ISR? 4. Define WCET and explain its importance. 5. What is the purpose of DMA in a sampled-data system? Long Answer Questions1. Compare MCU, DSP, FPGA, and SoC platforms for mechatronic applications. 2. Explain how an RTOS schedules tasks and manages shared resources. 3. Discuss memory organization and firmware architecture in a reliable embedded controller. 4. Describe a hardware–software co-design workflow for a closed-loop motion system. 5. Explain the relationship among latency, jitter, utilization, deadlines, and control quality. Analytical / Application Questions1. A controller has three periodic tasks with execution times of 0.4, 1.0, and 1.5 ms and periods of 2, 5, and 10 ms. Calculate total nominal utilization and identify why this calculation alone cannot prove schedulability. 2. Design an architecture for a motor drive requiring synchronized ADC sampling, emergency over-current shutdown, position control, and Ethernet logging. Justify the assignment of functions to hardware, ISRs, and RTOS tasks. 3. A system meets average deadlines but fails during simultaneous sensor traffic and firmware logging. Analyse the likely causes and propose a validation and redesign plan. 22. Multiple Choice Questions with AnswersQuestion 1Which characteristic most directly distinguishes a real-time embedded system from an ordinary computing system? A. It always uses a microcontroller B. Its correctness includes meeting specified timing constraints C. It cannot communicate over a network D. It must use fixed-point arithmetic Correct Answer: B. Its correctness includes meeting specified timing constraints Question 2Which platform is generally most appropriate for implementing a highly parallel, low-latency pixel-processing pipeline? A. FPGA B. Basic UART controller C. EEPROM D. Watchdog timer Correct Answer: A. FPGA Question 3What is the best practice for a lengthy calculation triggered by an interrupt? A. Perform it entirely inside the ISR B. Disable all interrupts until it finishes C. Capture the event and defer computation to a task D. Ignore the interrupt source Correct Answer: C. Capture the event and defer computation to a task Question 4A periodic task has an execution time of 2 ms and a period of 10 ms. Its nominal processor utilization is: A. 0.02 B. 0.2 C. 2 D. 20 Correct Answer: B. 0.2 Question 5Which mechanism is particularly useful for transferring a continuous ADC stream while minimizing processor intervention? A. DMA B. Secure boot C. Priority inheritance D. EEPROM wear levelling Correct Answer: A. DMA Question 6What problem does priority inheritance primarily address? A. ADC quantization B. Priority inversion C. Flash memory retention D. Clock frequency drift Correct Answer: B. Priority inversion Question 7In the illustrative packaging-axis case, why was communication assigned lower priority than servo control? A. Communication cannot use memory B. Servo timing was more critical to physical performance C. Communication always consumes less energy D. Servo control does not require deadlines Correct Answer: B. Servo timing was more critical to physical performance Question 8Which statement about an RTOS is correct? A. It automatically guarantees deadline compliance B. It eliminates the need for WCET analysis C. It provides scheduling and synchronization mechanisms that still require engineering analysis D. It prevents all data races without configuration Correct Answer: C. It provides scheduling and synchronization mechanisms that still require engineering analysis Question 9Which design choice most directly reduces sampling jitter? A. Starting ADC conversion from an unscheduled background loop B. Triggering ADC conversion from a hardware timer C. Increasing log-file size D. Adding non-volatile memory writes to the control ISR Correct Answer: B. Triggering ADC conversion from a hardware timer Question 10What is the main purpose of secure boot? A. To increase PWM frequency B. To verify firmware authenticity before execution C. To reduce ADC noise D. To schedule periodic tasks Correct Answer: B. To verify firmware authenticity before execution
|