Bachelors Program in Mechnical Engineering
Mechatronics & Industrial Automation
•
Bachelor
Embedded Systems and Real-Time Control
Introduction
Mechatronic products increasingly depend on embedded computers that sense physical variables, execute control algorithms, communicate with other devices, and command actuators. An embedded system is a computer designed as part of a larger product rather than as a general-purpose desktop system. In industrial automation, embedded controllers appear in motor drives, programmable automation components, robotic joints, safety systems, data-acquisition units, and smart sensors.
The central engineering challenge is not merely to make a controller compute the correct answer. It must compute that answer at the correct time, under electrical, mechanical, thermal, safety, and resource constraints. This chapter develops the principles needed to design microcontroller-based systems with digital and analog interfaces, data acquisition, interrupts, real-time scheduling, firmware, edge computing, and hardware–software integration.
Learning Objectives
By the end of this chapter, the reader should be able to:
Explain the architecture and operating constraints of embedded systems.
Select and interface digital and analog sensors and actuators.
Design basic data-acquisition chains and assess sampling limitations.
Explain interrupts, timers, latency, jitter, and real-time scheduling.
Develop structured firmware for reliable control applications.
Integrate hardware and software through systematic verification.
Evaluate edge-computing architectures, safety concerns, and cybersecurity risks.
1. Embedded-System Architecture
A typical embedded control system contains a physical process, sensors, signal-conditioning circuits, a microcontroller, communication interfaces, actuators, and power supplies. The microcontroller commonly integrates a processor core, flash memory for program storage, RAM for variables and stacks, timers, pulse-width-modulation (PWM) units, analog-to-digital converters (ADCs), serial interfaces, and interrupt controllers.
The control loop can be represented as:
Embedded control loop architecture
Figure: Embedded control loop architecture
Figure: The sensing, computation, actuation, and feedback elements of an embedded control loop.
A design begins with requirements: controlled variables, allowable error, response time, sample period, environmental conditions, energy budget, communication needs, and safety integrity. These requirements determine processor performance, memory capacity, interface circuitry, operating system choice, and development method.
Microcontroller and microprocessor
A microcontroller (MCU) combines processing, memory, and peripherals on one integrated circuit. It is usually economical, energy efficient, and well suited to deterministic control. A microprocessor generally requires external memory and peripheral devices but can provide substantially greater computational capacity, often running a full operating system. A system-on-chip may combine both approaches.
Important resources include:
Resource
Engineering significance
Flash or ROM
Non-volatile program storage
RAM
Run-time data, buffers, and stack
Timer/counter
Time measurement, scheduling, and PWM
ADC/DAC
Conversion between analog and digital domains
GPIO
Binary input and output
UART, SPI, I²C, CAN, Ethernet
Device and network communication
Watchdog timer
Recovery from software failure
DMA
Transfers data without continuous CPU involvement
A resource budget should include worst-case execution time, peak RAM use, interrupt load, communication bandwidth, and power consumption. Designing only for average demand can cause failure during exceptional but legitimate operating conditions.
2. Digital Interfaces
A digital signal is interpreted within voltage ranges rather than as an exact continuous value. A digital input must satisfy input-low and input-high voltage specifications, while an output must supply or sink the required current. Logic thresholds, pull-up or pull-down resistors, input leakage, propagation delay, and electrical noise must be considered.
A mechanical pushbutton illustrates a common problem: contact bounce can produce multiple rapid transitions. Debouncing may be performed in hardware using an RC network and a Schmitt trigger, or in firmware by requiring the signal to remain stable for a specified interval. Firmware debouncing must not block urgent control tasks.
Open-drain or open-collector outputs can pull a shared line low but require a pull-up resistor to produce a high level. The resistor must be chosen so that the rising-time requirement and output-current limit are both satisfied. Excessively small resistance wastes current; excessively large resistance makes the line susceptible to noise and slow transitions.
Common digital buses include:
UART: asynchronous point-to-point serial communication.
SPI: synchronous, usually high-speed communication with separate chip-select lines.
I²C: two-wire addressed bus using open-drain signaling and pull-up resistors.
CAN: robust multi-master bus widely used in vehicles and industrial systems, with arbitration and error detection.
Industrial Ethernet: high-bandwidth networking, often supplemented by real-time protocols.
Electrical compatibility must be established before connecting devices. Logic voltage, grounding, isolation, termination, cable length, common-mode range, and electromagnetic compatibility are system-level concerns.
3. Analog Interfaces and Data Acquisition
Physical quantities such as temperature, pressure, position, and force are often analog. A data-acquisition chain normally includes a sensor, excitation or bias circuit, amplifier, anti-aliasing filter, ADC, digital processing, and calibration procedure.
For an ideal unipolar ADC with reference voltage Vref and resolution of N bits, the code range is 0 to 2N - 1. The ideal voltage represented by code k is approximately:
Vin ≈ k Vref / (2N − 1)
Here, Vin and Vref are in volts, k is the integer ADC code, and N is the number of bits. The approximation ignores offset, gain error, noise, and nonlinearity. The nominal quantization interval is often described as:
q = Vref / 2N
where q is in volts. The quantization uncertainty for rounding is ideally approximately ±q/2, assuming a signal sufficiently independent of the ADC sampling pattern.
For a linear sensor with output V = V0 + Sx, the measured physical quantity is:
x = (V − V0) / S
where x is the measurand, V is measured voltage, V₀ is zero-input voltage, and S is sensitivity in volts per unit of x. This relationship is valid only over the sensor’s calibrated linear range.
Sampling and aliasing
If a continuous signal contains frequency components up to fmax, ideal uniform sampling requires:
fs > 2 fmax
where fs is sampling frequency in hertz. This is the Nyquist condition for band-limited signals. In practice, the sampling rate is selected with margin, and an analog low-pass anti-aliasing filter is placed before the ADC. Once aliasing occurs, digital processing cannot reliably reconstruct the original frequency component.
Worked example: ADC measurement
An 8-bit ADC uses a 5.00 V reference. For code k = 153:
Vin ≈ 153 × 5.00 / 255 = 3.00 V
The nominal quantization interval is:
q = 5.00 / 256 = 0.0195 V ≈ 19.5 mV
Thus the ideal conversion indicates approximately 3.00 V, with quantization effects on the order of several millivolts, before sensor and circuit errors are included.
Signal conditioning
Signal conditioning may provide amplification, attenuation, isolation, filtering, linearization, or level shifting. An amplifier must remain within its input common-mode and output-voltage limits. A sensor connected directly to an ADC can produce incorrect results if its source impedance is too high for the ADC acquisition time. Ground loops and switching currents can also corrupt low-level measurements.
Calibration establishes the relationship between measured code and physical value. Two-point calibration commonly estimates offset and slope, but temperature drift, hysteresis, aging, and sensor nonlinearity may require multi-point calibration or compensation.
4. Timing, Interrupts, and Real-Time Behavior
A real-time system is one in which correctness depends on both computed values and the times at which they are produced. A hard real-time deadline must not be missed; a soft real-time deadline permits occasional misses with degraded performance.
A timer can trigger periodic sampling and control execution more reliably than a software delay. An interrupt requests processor attention when an event occurs. Typical interrupt sources include timer overflow, ADC completion, communication reception, encoder transitions, and fault inputs.
Interrupt service routines (ISRs) should be short, deterministic, and limited to urgent work. A good ISR records data, clears the hardware flag, and signals a task. Lengthy calculations, formatted printing, dynamic memory allocation, and blocking communication inside an ISR can increase latency and cause missed deadlines. Shared data between an ISR and main code requires atomic access or suitable synchronization.
Important timing terms are:
Latency: time from an event to the beginning of its response.
Execution time: time required to perform a task.
Jitter: variation in task start or completion time.
Period: intended interval between successive executions.
Deadline: latest acceptable completion time.
For a periodic task with execution time C and period T, its processor utilization is:
U = C / T
C and T must use the same time units, and U is dimensionless. For several independent periodic tasks:
Utotal = ∑(Ci / Ti)
This utilization is a useful screening measure, not a universal schedulability proof. Interrupt overhead, blocking, context switching, nonperiodic tasks, and scheduling policy must also be considered.
Scheduling approaches
A cyclic executive repeatedly executes a fixed sequence of tasks. It is simple and predictable but inflexible when task periods differ or requirements change. A pre-emptive real-time operating system (RTOS) allows higher-priority tasks to interrupt lower-priority tasks. Rate-monotonic scheduling assigns higher priority to tasks with shorter periods. Earliest-deadline-first scheduling dynamically prioritizes the nearest deadline.
For a single processor under ideal assumptions, the classic sufficient utilization bound for n independent periodic tasks under rate-monotonic scheduling is:
Utotal ≤ n(2^(1/n) − 1)
The assumptions include independent tasks, fixed priorities based on periods, negligible context-switch cost, and deadlines equal to periods. Passing this bound is sufficient but not necessary; a system above the bound may still be schedulable. Exact response-time analysis is preferred for safety-critical designs.
Worked scheduling example
Task A has C₁ = 1 ms and T₁ = 10 ms. Task B has C₂ = 2 ms and T₂ = 20 ms. Task C has C₃ = 1 ms and T₃ = 50 ms. Therefore:
The processor demand is 22%, leaving nominal capacity for overhead and additional work. This calculation alone does not prove that all deadlines will be met.
5. Firmware Design
Firmware is the software stored in an embedded device. Reliable firmware is structured around clear states, explicit interfaces, bounded execution, defensive error handling, and traceable requirements.
A common architecture is:
Startup: initialize clocks, memory, peripherals, safety outputs, and diagnostics.
Self-test: verify memory, sensors, communication, and actuator feedback.
Scheduler or main loop: execute periodic and event-driven functions.
Control layer: calculate commands from measured values and references.
Communication layer: exchange validated messages.
Fault manager: place the system in a defined safe state.
Watchdog service: refresh only when essential tasks are healthy.
A finite-state machine is useful for modes such as OFF, INITIALIZING, READY, RUNNING, FAULT, and SHUTDOWN. State transitions should be triggered by explicit events and guarded by conditions. For example, a motor should not enter RUNNING unless enable status, emergency-stop status, drive feedback, and sensor validity have been verified.
Control firmware should avoid unbounded loops and uncontrolled dynamic memory allocation. Fixed-size buffers, range checks, timeout monitoring, and input validation improve predictability. Version control, code review, static analysis, unit testing, hardware-in-the-loop testing, and documented calibration are professional best practices.
6. Embedded Control Algorithms
A basic discrete proportional-integral-derivative (PID) controller uses the error between a reference r[k] and measured output y[k]:
e[k] = r[k] − y[k]
A practical discrete form is:
u[k] = Kp e[k] + I[k] + Kd (e[k] − e[k−1]) / Ts
I[k] = I[k−1] + Ki Ts e[k]
Here, u is the controller output, Kp is proportional gain, Ki is integral gain, Kd is derivative gain, Ts is sample period, and k is the sample index. The equations assume a fixed sample period and consistent units. Derivative action is sensitive to measurement noise, and the integral term can wind up when the actuator saturates. Anti-windup methods, output limiting, derivative filtering, and bumpless transfer are therefore important.
The controller must be implemented with actuator constraints. If a PWM command is limited to 0–100%, the software must detect saturation and prevent the integral state from accumulating in a direction that cannot be realized. Controller tuning must consider plant dynamics, sampling delay, computation delay, sensor filtering, and actuator bandwidth.
7. Hardware–Software Integration
Hardware and software should be developed as one engineered system. An interface specification should identify signal names, voltage levels, units, scaling, update rates, connector pin assignments, timing requirements, failure behavior, and ownership of each resource.
Integration proceeds from simple tests to complete operation:
verify power rails and clock frequencies;
test each GPIO and communication peripheral;
inject known analog voltages and compare measured codes;
test sensor plausibility and open-circuit detection;
verify timer periods and interrupt latency;
test actuators with current and motion limits;
perform closed-loop tests under controlled conditions;
conduct fault-injection and recovery tests.
A logic analyzer or oscilloscope can measure pulse width, bus timing, interrupt response, and jitter. A hardware-in-the-loop setup connects the real controller to a simulated plant, allowing dangerous or expensive conditions to be tested safely.
8. Edge Computing and Connected Automation
Edge computing places data processing near the machine rather than sending all raw data to a remote server. Benefits include reduced latency, lower bandwidth demand, improved operation during network loss, and greater control over sensitive data. An edge node may filter sensor data, detect anomalies, estimate machine condition, and transmit only events or summaries to a supervisory system.
Edge processing does not eliminate the need for deterministic local control. A networked dashboard should not be placed in the safety-critical path unless its timing, availability, and cybersecurity properties have been rigorously demonstrated. A useful architecture separates fast control, supervisory control, and enterprise analytics.
Artificial-intelligence techniques can support anomaly detection or predictive maintenance, but training data may be biased, machine conditions may change, and model decisions may be difficult to explain. Safety decisions should have validated fallback logic. Model updates require configuration control, testing, rollback capability, and cybersecurity protection.
9. Safety, Security, and Governance
Embedded automation can cause physical injury or equipment damage. Safety design should use risk assessment, independent protective functions where required, emergency-stop circuits, safe-state definitions, diagnostics, and validated safety standards applicable to the industry. A software flag alone should not be assumed to provide emergency protection when an independent hardwired or safety-rated function is required.
Cybersecurity threats include unauthorized firmware modification, spoofed sensor data, denial of service, and compromised communication networks. Good practice includes secure boot, signed firmware, least-privilege access, unique credentials, encrypted communication where appropriate, network segmentation, logging, patch management, and controlled maintenance ports. Security controls must be balanced with real-time performance and availability.
Ethical engineering requires honest reporting of test results, disclosure of known limitations, protection of operator data, and refusal to bypass safety controls for convenience. Regulatory compliance is not a substitute for engineering judgment; it establishes a minimum framework for responsible design.
Consider an illustrative packaging line that uses a conveyor, an optical sensor, an encoder, and a pneumatic reject actuator. The controller must detect defective packages and activate the reject mechanism at the correct conveyor position.
Problem
The conveyor speed varies. A fixed time delay between detection and rejection causes positional errors. Electrical noise also produces occasional false sensor transitions.
Analysis
The encoder provides position increments, while the optical sensor identifies a package. The controller must timestamp or position-stamp each detection, calculate the required travel distance, and command the actuator when the encoder count reaches the target. If the encoder resolution is R counts per revolution and the conveyor moves a distance L per revolution, the nominal distance per count is:
dc = L / R
If the reject point is D metres downstream, the required count increment is approximately:
ND = D / dc = D R / L
R and N_D are dimensionless counts, while D and L use the same length units. Rounding and mechanical backlash must be included in calibration.
Solution
A timer interrupt samples the optical input and encoder interface. A validated package-detection event is placed in a fixed-size queue with its encoder count. The control task compares the current count with each queued target. A watchdog supervises task execution, and a fault state disables rejection if encoder feedback is missing or the queue overflows. The pneumatic valve is driven through an electrically suitable output stage, with a pressure and valve-response test performed during commissioning.
Outcome
Position-based triggering remains accurate when conveyor speed changes, provided the encoder signal is reliable and the mechanical response is calibrated. Debouncing and plausibility checks reduce false detections. The queue and fault manager prevent silent loss of packages or uncontrolled actuator behavior.
Learning points
The case demonstrates why real-time control must combine sensing, timing, computation, actuation, diagnostics, and mechanical calibration. A correct algorithm cannot compensate for poor signal conditioning, missed encoder pulses, or an actuator whose response time has been ignored.
Challenges and Limitations
Embedded designs face finite memory, processor capacity, power, and communication bandwidth. Electromagnetic interference, temperature variation, vibration, component aging, and manufacturing tolerances affect reliability. Simulation does not reveal every hardware fault, while laboratory tests may not reproduce field conditions. Real-time scheduling calculations can be invalidated by blocking calls, priority inversion, unmeasured interrupt load, or underestimated worst-case execution time. Finally, connected devices enlarge the cybersecurity attack surface and require maintenance throughout their operational life.
Best-Practice Design Checklist
Convert system requirements into measurable timing, accuracy, safety, and environmental specifications.
Use calibrated sensors and document units and scaling at every interface.
Apply anti-aliasing and choose sampling rates with engineering margin.
Measure worst-case execution time, latency, jitter, and memory use.
Keep interrupt routines short and protect shared data.
Define startup, shutdown, fault, and recovery behavior explicitly.
Test normal operation, boundary conditions, communication loss, and sensor failure.
Use watchdogs, diagnostics, secure update procedures, and configuration control.
Separate safety functions from nonessential connectivity and analytics.
Preserve traceability from requirement to design, test, and released firmware.
Chapter Summary
Embedded systems combine computation, sensing, actuation, communication, and physical processes. Microcontrollers provide integrated resources that are particularly suitable for deterministic industrial control. Digital interfaces require attention to thresholds, current, noise, and signal integrity; analog interfaces require conditioning, calibration, quantization analysis, and anti-aliasing.
Real-time correctness includes both value and timing. Interrupts, timers, task periods, execution times, latency, jitter, and deadlines must be analyzed using realistic worst-case assumptions. Firmware should use explicit states, bounded operations, defensive validation, watchdog supervision, and systematic testing. PID control and other algorithms must account for sampling, saturation, noise, and actuator limitations.
Hardware–software integration is verified progressively with instruments, fault injection, and hardware-in-the-loop testing. Edge computing can reduce latency and bandwidth use, but safety-critical control should remain locally deterministic. Secure, ethical, and standards-aware engineering is essential because embedded automation directly affects people, equipment, and production continuity.
Key Terms
Embedded system: A computer integrated into a larger product or process.
Microcontroller: An integrated circuit containing a processor, memory, and peripherals.
GPIO: A configurable general-purpose digital input or output.
ADC: A circuit that converts an analog voltage into a digital code.
DAC: A circuit that converts a digital value into an analog signal.
Quantization: Representation of a continuous value by discrete digital levels.
Aliasing: Misrepresentation of signal frequency caused by inadequate sampling.
Interrupt: A hardware or software event that requests processor service.
Interrupt service routine: Code executed in response to an interrupt.
Latency: Time between an event and the start of its response.
Jitter: Variation in the timing of an event or task.
Deadline: Latest acceptable completion time for a task.
Real-time system: A system whose correctness depends on logical and temporal results.
RTOS: Operating system providing scheduling and synchronization facilities for real-time tasks.
PWM: Pulse-width modulation used to control average power or represent a command.
Firmware: Software stored in and executed by an embedded device.
Watchdog timer: Timer that resets or reports a system if software fails to service it.
Edge computing: Processing data near the physical source rather than only in a remote cloud.
Hardware-in-the-loop: Testing in which real hardware interacts with a simulated plant.
Anti-windup: A method that limits integral-controller accumulation during actuator saturation.
Review Questions
Short Answer Questions
What distinguishes a microcontroller from a general-purpose microprocessor?
Why is an anti-aliasing filter used before an ADC?
Define interrupt latency and jitter.
State two reasons why an ISR should be short.
What is the purpose of a watchdog timer?
Long Answer Questions
Explain the complete signal path from a physical sensor to a digital control decision, including conditioning, sampling, conversion, and calibration.
Compare a cyclic executive with a pre-emptive RTOS for industrial control applications.
Explain the sources of error and instability that can arise in a discrete PID implementation.
Describe a systematic hardware–software integration and verification strategy.
Discuss how safety and cybersecurity requirements influence embedded automation architecture.
Analytical / Application Questions
An ADC has 12 bits and a 3.3 V reference. Calculate its nominal quantization interval and explain which practical errors are not represented by that value.
Three periodic tasks have execution times and periods of (0.5 ms, 5 ms), (1 ms, 20 ms), and (2 ms, 100 ms). Calculate total utilization and discuss why the result alone does not prove schedulability.
Design a fault response for a conveyor controller that loses encoder feedback while an actuator command is active. Identify detection, safe-state action, operator indication, and recovery conditions.
Multiple Choice Questions with Answers
Question 1
Which peripheral is most directly suited to generating a periodic control-task trigger?
A. Timer/counter
B. Flash memory
C. GPIO pull-up resistor
D. Watchdog output only
Correct Answer: A. Timer/counter
Question 2
An ideal 8-bit ADC with a 5 V reference has a nominal quantization interval closest to:
A. 1.25 mV
B. 19.5 mV
C. 39.1 mV
D. 256 mV
Correct Answer: B. 19.5 mV
Question 3
What is the principal purpose of an anti-aliasing filter?
A. Increase processor clock speed
B. Prevent high-frequency signal components from folding into sampled data
C. Provide non-volatile program storage
D. Replace actuator feedback
Correct Answer: B. Prevent high-frequency signal components from folding into sampled data
Question 4
Which statement best describes a hard real-time requirement?
A. Average response time must be low
B. A missed deadline is always harmless
C. A specified deadline must not be missed
D. The system must use an RTOS
Correct Answer: C. A specified deadline must not be missed
Question 5
A well-designed interrupt service routine normally:
A. Performs lengthy formatted printing
B. Contains unbounded loops
C. Records urgent information and defers lengthy work
D. Allocates dynamic memory repeatedly
Correct Answer: C. Records urgent information and defers lengthy work
Question 6
For tasks with execution times 1 ms and 2 ms and periods 10 ms and 20 ms, total processor utilization is:
A. 0.05
B. 0.10
C. 0.20
D. 0.30
Correct Answer: C. 0.20
Question 7
What problem does anti-windup address in a PID controller?
A. ADC aliasing
B. Integral accumulation while the actuator is saturated
C. Loss of flash memory
D. Incorrect serial parity
Correct Answer: B. Integral accumulation while the actuator is saturated
Question 8
Which feature most directly improves recovery from a firmware lockup?
A. Watchdog timer
B. Larger connector
C. Lower sensor sensitivity
D. Open-drain output
Correct Answer: A. Watchdog timer
Question 9
What is a principal advantage of edge computing in automation?
A. It guarantees perfect sensor accuracy
B. It can reduce latency and dependence on a remote network
C. It eliminates the need for local control
D. It removes all cybersecurity risks
Correct Answer: B. It can reduce latency and dependence on a remote network
Question 10
In the conveyor case, encoder-based triggering is superior to a fixed time delay because it:
A. Ignores conveyor speed
B. Tracks physical position despite speed variation
C. Requires no sensor validation
D. Eliminates actuator response time
Correct Answer: B. Tracks physical position despite speed variation
Mechatronics & Industrial Automation
Chapter 5
of 15