Embedded Controllers and Real-Time SoftwareIntroduction and ContextA mechatronic product combines mechanical structure, sensors, actuators, electronics, and computation. The computational element must not only produce correct results; it must produce them at the correct time. A controller that calculates a motor command accurately but delivers it too late may cause vibration, instability, collision, or product failure. This chapter introduces the principal computational platforms used in mechatronics and the software principles required for dependable real-time operation. An embedded controller is a computer integrated into a larger product for a specific function. Unlike a general-purpose desktop computer, it is usually constrained by cost, memory, energy, physical size, and timing requirements. Typical examples include a motor drive, robotic joint controller, washing-machine controller, automated inspection unit, and autonomous vehicle subsystem. The central design question is therefore: What computation must be performed, with what timing certainty, on what hardware, and under what failure constraints? Learning ObjectivesBy the end of this chapter, a student should be able to: - Explain the architectures and applications of microcontrollers, programmable logic controllers, and embedded computers.
- Distinguish hard, firm, and soft real-time requirements.
- Select sampling periods and explain aliasing, latency, jitter, and deadline utilization.
- Describe polling, interrupts, timers, direct memory access, and task scheduling.
- Design finite-state machines and modular control software.
- Analyse a small embedded-control application and identify reliability, safety, and cybersecurity issues.
1. Embedded-System ArchitectureA typical embedded mechatronic system contains five interacting layers: - Physical process: the motor, valve, robot, conveyor, or thermal plant.
- Sensors and signal conditioning: transducers, amplifiers, filters, analogue-to-digital converters (ADCs), and communication interfaces.
- Controller hardware: processor, memory, timers, input/output peripherals, and power interfaces.
- Real-time software: device drivers, scheduling logic, control algorithms, diagnostics, and communications.
- Engineering and safety layer: watchdogs, limits, fault handling, safe states, testing, and cybersecurity.
The controller observes a process through sampled measurements, computes an action, and commands an actuator. A simplified discrete-time loop is u[k] = C(r[k], y[k]) where r[k] is the reference at sample k, y[k] is the measured output, u[k] is the control command, and C represents the control algorithm. The sample index k is dimensionless; the corresponding time is tk = kTs, where Ts is the sampling period in seconds. 1.1 MicrocontrollersA microcontroller unit (MCU) integrates a processor core, non-volatile program memory, volatile data memory, timers, digital input/output, ADCs, serial interfaces, and often pulse-width-modulation (PWM) generators on one chip. It is well suited to dedicated, low-cost control tasks. An MCU normally executes firmware from flash memory. The processor reads peripheral registers, handles interrupts, and executes a main loop or a real-time operating system (RTOS). Its advantages include low power consumption, predictable peripheral access, fast start-up, and low cost. Limitations include modest memory, limited graphical capability, and restricted computational performance compared with an application processor. A useful MCU design separates: - hardware abstraction and device drivers;
- sensing and signal validation;
- control and estimation algorithms;
- sequencing and state management;
- communications and diagnostics;
- safety and fault response.
1.2 Programmable Logic ControllersA programmable logic controller (PLC) is an industrial controller designed for reliable operation in electrically noisy environments and for convenient maintenance by automation engineers. A conventional PLC repeatedly performs a scan cycle: - Read or image the inputs.
- Execute the user program.
- Update outputs.
- Perform diagnostics and communications.
The scan period is approximately Tscan = Tinput + Tprogram + Toutput + Tdiagnostic where each term is a time in seconds. The equation is a planning approximation; actual PLC implementations may use task priorities, asynchronous communications, and immediate I/O instructions. PLCs commonly use ladder diagram, function block diagram, structured text, and sequential function chart languages. Their strengths are maintainability, standardized industrial interfaces, diagnostics, and integration with supervisory control and data acquisition (SCADA). Their limitations can include higher cost per unit, less flexibility for advanced numerical computation, and scan-related timing variation. 1.3 Embedded ComputersAn embedded computer usually employs a microprocessor or system-on-chip with substantially greater processing capacity than a small MCU. It may run Linux, a real-time Linux variant, Android, or another full operating system. Typical hardware includes dynamic RAM, mass storage, Ethernet, USB, display interfaces, and high-speed networking. Embedded computers are appropriate for machine vision, trajectory planning, data logging, human-machine interfaces, and artificial-intelligence inference. They are less inherently deterministic than a bare-metal MCU because caches, virtual memory, background services, drivers, and operating-system scheduling can introduce timing variation. A common architecture therefore assigns fast, safety-critical loops to an MCU or dedicated drive, while assigning planning, vision, and user-interface tasks to an embedded computer. 1.4 Comparison of Platforms| Characteristic | MCU | PLC | Embedded computer |
|---|
| Primary strength | Low-cost dedicated control | Industrial automation and maintainability | High-level computation and connectivity | | Typical software | Bare metal or RTOS | PLC languages and cyclic tasks | Full operating system or RTOS | | Timing | Often highly deterministic | Deterministic when properly configured | Depends strongly on OS and configuration | | Typical use | Motor control, appliances, instruments | Conveyors, process cells, safety logic | Vision, planning, dashboards, edge analytics | | Main concern | Resource limitations | Cost and scan behavior | Complexity and timing uncertainty |
2. Real-Time ConceptsA real-time system is one whose correctness depends on both logical results and temporal behavior. “Real-time” does not necessarily mean “very fast.” It means that specified timing constraints are met. - A hard real-time deadline must never be missed, or a missed deadline can cause unacceptable danger or failure.
- A firm real-time result has no value after its deadline, but occasional misses may be tolerated without catastrophe.
- A soft real-time task degrades in quality when late, but remains useful.
For example, an emergency shutdown signal may be hard real-time; a machine-vision frame may be firm real-time; and a production dashboard may be soft real-time. Important timing quantities are: - Execution time: time required by a task.
- Period: time between successive releases of a periodic task.
- Deadline: latest acceptable completion time.
- Response time: release-to-completion time, including waiting.
- Latency: delay between an event and its service or resulting action.
- Jitter: variation in latency or task release time.
- Throughput: amount of work completed per unit time.
For a periodic task i, define utilization as Ui = Ci / Ti where Ci is its worst-case execution time in seconds and Ti is its period in seconds. The total utilization is U = ∑i=1n Ci / Ti This is a necessary workload measure, not a universal proof of schedulability. Context switches, interrupt service routines, blocking, communication, and operating-system overhead must also be included. Under idealized conditions, a single processor cannot sustain a workload with U greater than 1. For fixed-priority scheduling, additional response-time analysis is required. Worked Example: Timing BudgetA controller has three periodic tasks: | Task | Execution time | Period |
|---|
| Current control | 0.20 ms | 1 ms | | Position control | 0.50 ms | 5 ms | | Diagnostics | 2 ms | 100 ms |
The utilization is U = 0.20/1 + 0.50/5 + 2/100 = 0.20 + 0.10 + 0.02 = 0.32. Thus the nominal processor workload is 32%. This leaves 68% for other work and overhead, but it does not prove that every deadline is met. A high-priority interrupt could still delay a task, and a long non-preemptive section could cause deadline failure. 3. Sampling and Timing of Control SoftwareDigital control converts continuous physical behavior into discrete measurements and commands. The sampling period Ts must be selected in relation to the dynamics of the plant, sensor noise, actuator bandwidth, and processor capacity. The sampling frequency is fs = 1/Ts where fs is in hertz and Ts is in seconds. The Nyquist frequency is fs/2. A sinusoidal component above this frequency can be represented incorrectly as a lower-frequency component, a phenomenon called aliasing. An anti-aliasing low-pass filter is therefore normally placed before the ADC. The Nyquist condition alone is not a complete control-design rule. It only states that a band-limited signal with highest frequency fmax requires fs > 2fmax for ideal reconstruction. Practical control systems sample faster than this minimum to provide phase margin, account for computational delay, and represent transients adequately. A complete sample-and-control cycle may include sensor conversion, filtering, algorithm execution, output update, and actuator response. If the measurement is taken at time tk and the command becomes effective at tk + Td, then Td is computational and actuation delay. Delay reduces phase margin and can destabilize a feedback loop, particularly when the plant is fast. Example: Choosing a Sampling RateSuppose the relevant closed-loop bandwidth is approximately 20 Hz. A first engineering choice might be a sampling frequency between 200 Hz and 400 Hz, corresponding to sampling periods of 5 ms to 2.5 ms. This is not a theorem or universal rule; the final choice must be validated using the plant model, controller design, noise level, execution-time measurements, and stability margins. If a 5 ms period is selected, fs = 1/0.005 = 200 Hz. Sampling should be synchronized where possible. In motor control, the ADC may sample at a known point in the PWM cycle to reduce switching-noise effects. Unsynchronized sampling can produce beat patterns and variable measurement delay. 4. Interrupts, Timers, and Data Movement4.1 Polling and InterruptsIn polling, the main program repeatedly tests a condition. Polling is simple and predictable when events are frequent and timing is relaxed, but it can waste processor time and respond slowly to rare events. An interrupt temporarily suspends the current execution and invokes an interrupt service routine (ISR). Interrupts are suitable for timer ticks, ADC completion, encoder edges, communication reception, and fault inputs. An ISR should be short: capture essential data, acknowledge hardware, set a flag or place data in a buffer, and defer substantial processing to a scheduled task. An ISR that performs lengthy calculations can block other interrupts, increase jitter, and create priority inversion or data loss. Shared variables must be protected using atomic operations, brief critical sections, lock-free designs where appropriate, or RTOS synchronization primitives. 4.2 Timers and WatchdogsHardware timers generate periodic events independently of application-code progress. A timer can trigger ADC conversion, PWM update, or a control task. A watchdog timer resets or places the system in a safe response if software fails to refresh it within a defined interval. The watchdog must be designed carefully: indiscriminate refreshing from a low-level interrupt can conceal a failed main application. 4.3 Direct Memory AccessDirect memory access (DMA) transfers data between peripherals and memory with limited processor intervention. DMA is valuable for high-rate ADC streams, network packets, and audio or vibration data. It reduces CPU load but introduces buffer ownership, cache coherency, and synchronization issues. Software must define clearly when a buffer is being written, when it is complete, and when it may be processed. 5. Real-Time Software ArchitectureA robust software architecture makes timing and responsibility explicit. A small system may use a super-loop: initialize hardware
initialize variables and safety outputs
while true:
service fast flags
read and validate sensors
execute state machine
execute non-critical communications
run diagnosticsA super-loop is easy to inspect but can suffer from variable response time if one function blocks. A cooperative scheduler improves organization by releasing tasks without allowing them to pre-empt one another. An RTOS provides tasks, priorities, timers, queues, semaphores, and event flags. These facilities improve modularity but do not automatically guarantee determinism. A periodic control task commonly follows this pattern: - Acquire a time-stamped measurement.
- Check range, plausibility, and sensor status.
- Apply calibration and filtering.
- Calculate control error and command.
- Enforce saturation and rate limits.
- Update the actuator at the defined instant.
- Record execution time and fault status.
The software should distinguish control mode from fault mode. A fault must not merely print an error while continuing to command an actuator. Depending on the hazard analysis, the system may disable power, apply a brake, hold position, or move to a verified safe state. Modular Design Principles- Give each module one clear responsibility.
- Define interfaces using units, ranges, ownership, and timing assumptions.
- Avoid hidden global state.
- Separate hardware-dependent code from algorithms.
- Make saturation, invalid data, and timeout behavior explicit.
- Use version control, code review, static analysis, and automated tests.
- Measure worst-case execution time on representative hardware.
- Log faults without allowing logging to block safety functions.
6. Finite-State MachinesA finite-state machine (FSM) represents a system using a finite set of states, events, transitions, guards, and actions. It is especially useful for startup, homing, sequencing, interlocks, and fault recovery. A transition can be represented as (current state, event, guard) → (next state, action) For a motorized axis, possible states are OFF, INITIALIZING, HOMING, READY, RUNNING, and FAULT. The transition from READY to RUNNING may require a start command and confirmation that the emergency stop is released. A limit-switch event may cause RUNNING → FAULT or RUNNING → HOMING depending on the safety design. A state should define: - entry actions, such as resetting a timer;
- continuous or periodic actions, such as maintaining speed;
- exit actions, such as disabling a command;
- permitted events and guards;
- behavior when an unexpected event occurs.
A state table is often clearer than deeply nested conditional statements. | Current state | Event or guard | Next state | Action |
|---|
| OFF | Enable and safe conditions | INITIALIZING | Enable diagnostics | | INITIALIZING | Checks pass | HOMING | Drive toward home | | INITIALIZING | Check fails | FAULT | Disable actuator | | HOMING | Home detected | READY | Stop and zero position | | READY | Start command | RUNNING | Begin motion | | RUNNING | Stop command | READY | Controlled stop | | Any active state | Emergency stop | FAULT | Remove hazardous energy |
FSMs prevent contradictory commands and make verification more systematic. They do not replace continuous control algorithms; rather, they supervise modes in which those algorithms operate. 7. Control Algorithms and Numerical DetailsA discrete proportional-integral-derivative controller can be written in one practical form as e[k] = r[k] − y[k] u[k] = Kp e[k] + I[k] + Kd (e[k] − e[k−1]) / Ts I[k] = I[k−1] + Ki Ts e[k] Here e[k] is the error, Kp is the proportional gain, Ki is the integral gain, Kd is the derivative gain, I[k] is the integral contribution, and Ts is the fixed sampling period. Units depend on the selected input and output units. This approximation assumes a sufficiently regular sampling interval and a derivative based on measured or filtered signals in practical implementations. Actuator saturation creates integral windup: the integrator continues accumulating error while the actuator cannot produce the requested command. Anti-windup methods include conditional integration and back-calculation. A rate limiter may also be required because a command that is within amplitude limits can still change too rapidly for the actuator or mechanism. Numerical implementation requires attention to data type, overflow, quantization, scaling, and execution time. Fixed-point arithmetic can be efficient on small MCUs but requires explicit range analysis. Floating-point arithmetic simplifies modeling but may be slower or unavailable on some devices. Sensor values should be stored with documented units, not merely unexplained integer counts. 8. Applied Case: Conveyor Inspection and Reject SystemBackgroundConsider an illustrative packaging line that conveys products past a camera and ejects defective packages using a pneumatic actuator. An embedded computer performs image classification, while an MCU handles encoder measurement, timing, solenoid control, emergency-stop input, and safety interlocks. ProblemThe camera requires variable processing time, while the reject actuator must fire at the correct position. A software-only delay based on image-arrival time is unreliable because conveyor speed changes and image processing has jitter. AnalysisThe MCU receives encoder pulses and timestamps the product detection event. If the conveyor position is estimated from encoder counts, the reject decision can be associated with a target position rather than a fixed time. Let N be counts per revolution, D be roller circumference, and n be measured counts. The travelled distance is x = nD/N assuming no slip and consistent count interpretation. If the product must travel distance xr after detection, the MCU schedules the solenoid when the accumulated position increment reaches xr. Approach and SolutionThe MCU FSM includes OFF, READY, TRACKING, REJECTING, and FAULT. The embedded computer sends a product identifier and defect decision through a message queue. Each message includes a sequence number and validity timeout. The MCU rejects stale or malformed messages, while a watchdog and emergency-stop circuit provide independent protection. The reject pulse is generated by a hardware timer, not by a busy-wait delay. Encoder input is captured by hardware or a high-priority interrupt. A diagnostic task records missed messages, excessive conveyor speed, actuator feedback failure, and timing margins. OutcomeThis architecture separates high-level, variable-time classification from low-level, position-based actuation. The system remains responsive even when image processing time varies. It also provides a clear fault response if communication fails or the encoder becomes implausible. Learning Points- Timing should be tied to the physical requirement: position, angle, or deadline—not merely processor convenience.
- A heterogeneous architecture can combine high computational performance with deterministic control.
- Communication must include validation, freshness, and fault behavior.
- Safety functions should not depend solely on complex application software.
9. Verification, Safety, and CybersecurityTesting should proceed from individual functions to integrated behavior. Unit tests check algorithms and boundary cases. Hardware-in-the-loop testing connects real controller hardware to a simulated plant. Stress testing examines maximum interrupt rates, communication bursts, sensor faults, and processor load. Timing instrumentation should measure not only average execution time but also worst-case and high-percentile behavior. Safety engineering begins with hazard identification and risk reduction. Typical measures include physical guarding, emergency-stop circuits, redundant sensing, safe torque-off, limit switches, watchdogs, and controlled restart. The appropriate measures depend on the machine risk assessment and applicable legislation and standards; software alone is not automatically a safety function. Connected controllers also face cybersecurity threats. Attackers may alter firmware, commands, calibration data, or network messages. Good practice includes authenticated updates, signed firmware, least-privilege interfaces, secure boot where appropriate, network segmentation, credential management, event logging, and a vulnerability-response process. Security controls must be implemented without compromising hard real-time behavior. Ethically, engineers are responsible for communicating limitations honestly. A controller should not be described as safe merely because it passed nominal tests. Assumptions about sensor validity, communication availability, environmental conditions, and operator behavior must be documented. 10. Contemporary Developments and Best PracticeModern mechatronic systems increasingly use multicore processors, model-based design, time-sensitive networking, edge machine learning, and digital twins. These technologies can improve capability, but they also increase software complexity. Machine-learning inference should be treated as a bounded computational task with validated inputs, monitored confidence, and a deterministic fallback where safety requires it. A practical development workflow is: - Specify physical behavior, deadlines, failure responses, and units.
- Partition functions among sensors, MCU, PLC, embedded computer, and safety hardware.
- Establish task periods and worst-case timing budgets.
- Design interfaces and FSMs before writing extensive code.
- Implement drivers and algorithms separately.
- Add range checks, watchdogs, diagnostics, and safe defaults.
- Test nominal, boundary, fault, restart, and communication-loss cases.
- Measure timing on target hardware and revise the design.
- Document configuration, calibration, assumptions, and maintenance procedures.
Chapter SummaryEmbedded controllers connect computational decisions to physical machines. MCUs provide economical and deterministic peripheral control; PLCs provide maintainable industrial automation; and embedded computers provide high-level computation, networking, and data processing. Real-time correctness depends on deadlines as well as numerical results. Sampling frequency, aliasing, delay, jitter, execution time, and processor utilization must therefore be considered together. Interrupts and timers support precise event handling, while DMA reduces data-transfer overhead. Super-loops, cooperative schedulers, and RTOS architectures offer different balances of simplicity, modularity, and determinism. Finite-state machines make operating modes, interlocks, and fault behavior explicit. Modular software should separate hardware drivers, sensing, control, sequencing, communications, diagnostics, and safety functions. Reliable mechatronic software is verified through timing measurement, fault testing, hardware-in-the-loop simulation, code review, and documented safety analysis. Contemporary systems may combine deterministic low-level controllers with powerful embedded computers, but increased computational capability does not remove the need for explicit deadlines, bounded behavior, secure interfaces, and safe failure modes. Key TermsEmbedded controller: A computer integrated into a larger product for a dedicated function. Microcontroller unit (MCU): A processor, memory, timers, and peripherals integrated on one chip. Programmable logic controller (PLC): An industrial controller designed for reliable automation and programmable sequencing. Embedded computer: A higher-capability computer integrated into a product or machine. Real-time system: A system whose correctness depends on both result and timing. Hard real-time: A timing requirement for which a missed deadline is unacceptable. Soft real-time: A timing requirement where lateness degrades performance but does not necessarily cause failure. Sampling period: Time between successive measurements or control updates. Aliasing: Misrepresentation of signal frequency caused by insufficient sampling. Latency: Delay between an event and its service or response. Jitter: Variation in timing from one event or task instance to another. Interrupt service routine: Code executed in response to a hardware or software interrupt. Watchdog timer: A timer that initiates recovery when software fails to respond correctly. Direct memory access: Hardware-assisted transfer between memory and peripherals. Finite-state machine: A model of discrete states, events, guards, transitions, and actions. Utilization: Fraction of processor capacity demanded by scheduled tasks. Worst-case execution time: Maximum execution duration considered for a task under specified conditions. Anti-windup: A method that prevents excessive integral accumulation during actuator saturation. Hardware-in-the-loop: Testing in which real controller hardware interacts with a simulated plant. Safe state: A defined condition that reduces risk after a fault or hazardous event. Review QuestionsShort Answer Questions- What distinguishes an embedded computer from a general-purpose desktop computer?
- Define hard real-time, firm real-time, and soft real-time behavior.
- Why is an anti-aliasing filter used before an ADC?
- What information should be specified for an FSM state?
- Why should an interrupt service routine usually be short?
Long Answer Questions- Compare MCU, PLC, and embedded-computer architectures for a robotic production cell. Recommend a suitable partition of functions and justify it.
- Explain how sampling period, computational delay, and jitter can influence closed-loop control performance.
- Describe a real-time software architecture for a motorized axis, including sensing, control, sequencing, diagnostics, and fault handling.
- Explain the PLC scan cycle and analyse its advantages and limitations for time-critical control.
- Discuss how safety engineering and cybersecurity requirements affect embedded-controller design.
Analytical / Application Questions- A controller has tasks of 0.25 ms every 1 ms, 0.8 ms every 10 ms, and 3 ms every 100 ms. Calculate nominal processor utilization and explain why the result alone does not prove schedulability.
- Design an FSM for an automated door with CLOSED, OPENING, OPEN, CLOSING, and FAULT states. Specify at least two guards, two fault events, and safe actions.
- A conveyor speed varies during operation. Explain why a fixed time delay is inferior to encoder-based position scheduling for a reject actuator, and identify two sensor or communication faults that must be handled.
Multiple Choice Questions with AnswersQuestion 1Which platform most commonly integrates a processor, timers, ADCs, and communication peripherals on one chip? A. Microcontroller unit B. Programmable logic controller C. Desktop workstation D. Mechanical relay panel Correct Answer: A. Microcontroller unit Question 2A task executes for 0.4 ms every 2 ms. What is its nominal processor utilization? A. 5% B. 20% C. 40% D. 80% Correct Answer: B. 20% Question 3What is the principal purpose of an anti-aliasing filter before an ADC? A. Increase actuator torque B. Prevent all sensor noise C. Reduce frequency components that could alias D. Guarantee zero sampling delay Correct Answer: C. Reduce frequency components that could alias Question 4Which statement best describes a hard real-time deadline? A. It is preferred but may always be ignored B. Its occasional violation may reduce display quality only C. Its result remains useful indefinitely after completion D. Missing it can cause unacceptable failure or danger Correct Answer: D. Missing it can cause unacceptable failure or danger Question 5What is generally the best practice for an interrupt service routine? A. Perform all application processing inside it B. Keep it short and defer substantial work C. Disable every other interrupt permanently D. Wait for slow network communication to finish Correct Answer: B. Keep it short and defer substantial work Question 6Which element is most characteristic of a finite-state machine? A. States and guarded transitions B. Only continuous differential equations C. Unbounded random memory allocation D. A requirement for a graphical display Correct Answer: A. States and guarded transitions Question 7What is the main purpose of a watchdog timer? A. Measure motor position directly B. Filter analogue sensor noise C. Recover from software that fails to respond correctly D. Increase the ADC resolution Correct Answer: C. Recover from software that fails to respond correctly Question 8Why can an embedded computer running a full operating system be less deterministic than a small MCU? A. It cannot perform arithmetic B. Operating-system scheduling, caches, and background services can add timing variation C. It has no memory D. It cannot communicate with sensors Correct Answer: B. Operating-system scheduling, caches, and background services can add timing variation Question 9In the conveyor case, why is encoder-based scheduling preferable to a fixed time delay? A. It relates actuation to physical position despite speed variation B. It eliminates the need for any safety circuit C. It guarantees image classification is correct D. It removes all sensor noise Correct Answer: A. It relates actuation to physical position despite speed variation Question 10What problem occurs when a PID integrator continues accumulating error during actuator saturation? A. Aliasing B. Deadlock C. Integral windup D. Quantization-free control Correct Answer: C. Integral windup
|