Chapter 13
Embedded Systems, IoT and Edge Intelligence
Bachelors Program in Electrical Engineering
Electrical & Electronics Engineering Laboratory
•
Bachelor
Embedded Systems, IoT and Edge Intelligence
Introduction and Context
An embedded system is a computer designed to perform a specific function within a larger electrical or mechanical product. Unlike a general-purpose computer, it is usually constrained by cost, power, memory, physical size, timing requirements and environmental conditions. A microcontroller-based laboratory prototype may combine a processor core, memory, timers, analog-to-digital converters (ADCs), communication peripherals and digital input/output on one integrated circuit.
The Internet of Things (IoT) extends embedded systems by connecting sensors, actuators and computational devices to local or wide-area networks. Edge intelligence adds data analysis or machine-learning inference near the point where data are produced rather than sending all raw data to a distant cloud service. This reduces latency, communication bandwidth and exposure of sensitive data. It also permits useful operation when network connectivity is intermittent.
In this laboratory-oriented chapter, the emphasis is on designing, programming and evaluating complete systems. A successful prototype must not merely read a sensor. It must satisfy electrical, timing, communication, cybersecurity, safety and maintainability requirements.
Learning Objectives
After studying and completing the laboratory work in this chapter, students should be able to:
Explain the architecture and operating constraints of microcontroller-based embedded systems.
Configure timers, interrupts, ADCs, sensors, actuators and serial communication buses.
Design a networked monitoring or control prototype using appropriate edge and cloud responsibilities.
Analyse sampling, timing, latency, power and data-quality requirements.
Apply basic cybersecurity, privacy, safety and responsible-AI principles.
Implement a lightweight diagnostic algorithm and evaluate its limitations.
Test a prototype systematically and document engineering decisions.
1. Embedded-System Architecture
A typical embedded node contains the following functional blocks:
Processing unit: a CPU core, often with hardware support for interrupts, arithmetic and low-power modes.
Program and data memory: non-volatile flash or ROM stores firmware; RAM stores variables, buffers and stack data.
Digital I/O: configurable pins interface with switches, LEDs, relays and digital sensors.
Analog interface: an ADC converts a sensor voltage into a digital code; a digital-to-analog converter (DAC) may generate an analog output.
Timing resources: timers and counters generate periodic events, measure pulse widths and produce pulse-width-modulated (PWM) signals.
Communication peripherals: UART, SPI, I²C, CAN, USB, Ethernet, Wi-Fi, Bluetooth Low Energy and other interfaces.
Power and protection: voltage regulation, decoupling, reset circuitry, watchdog timers and electrical protection.
The firmware commonly contains a hardware-abstraction layer, device drivers, application logic and communication/security services. A simple application may use a foreground loop, whereas a larger system may use a real-time operating system (RTOS) with scheduled tasks.
Embedded IoT edge system architecture
Figure: Embedded IoT edge system architecture
Figure: Functional relationship among sensors, the embedded edge node, actuators and network services.
2. Timers, Interrupts and Real-Time Operation
A timer increments or decrements a counter from a clock source. It can generate an interrupt when the counter reaches a compare value, overflow occurs or an input transition is detected. Timers support periodic sampling, event timestamps, motor control and timeout supervision.
For a timer clock frequency ftimer and a prescaler N, the timer tick period is:
Ttick = N / ftimer
Here, Ttick is in seconds, N is dimensionless, and ftimer is in hertz. If a compare event occurs after C timer counts, the event interval is approximately:
Tevent = C N / ftimer
The exact expression depends on whether the hardware counts from zero, whether the compare value is inclusive, and whether an auto-reload register adds one count. These details must be checked in the device reference manual.
Worked example. A timer is clocked at 16 MHz with a prescaler of 64. The tick period is 64/(16×106) = 4 μs. To obtain a 1 ms interrupt, the required number of tick intervals is 1 ms/4 μs = 250. A compare value of 249 may be required on a zero-based counter. The final register value is therefore hardware-dependent, even though the physical interval is 1 ms.
An interrupt temporarily transfers processor control to an interrupt service routine (ISR). An ISR should be short and deterministic: capture a timestamp, copy a received byte, set a flag or place data in a buffer, then return. Lengthy calculations, blocking communication and dynamic memory allocation inside an ISR can cause missed deadlines.
A hard real-time task must meet every deadline. A soft real-time task can tolerate occasional deadline misses with degraded quality. A useful timing budget is:
Each term is a non-negative time interval. The equation applies to a defined event path; it does not automatically include uncertain network delay or operating-system scheduling unless those terms are added. For a hard deadline, the worst-case response time, not merely the average, must be below the required limit.
Race conditions occur when an ISR and foreground code access shared data without an appropriate synchronization method. Depending on the processor, shared variables may require atomic access, interrupt masking, lock-free queues or RTOS synchronization primitives. The volatile qualifier can prevent unwanted compiler optimization for memory-mapped registers, but it does not by itself make a multi-byte operation atomic or provide mutual exclusion.
A watchdog timer resets or otherwise supervises a system that fails to service it within a configured interval. It should be refreshed only after essential tasks have completed; refreshing it unconditionally in a frequently running loop can conceal a stalled subsystem.
3. Sensors, ADCs and Actuators
A sensor converts a physical quantity into an electrical signal. Important specifications include range, sensitivity, offset, linearity, hysteresis, response time, resolution, repeatability and environmental dependence. A sensor interface must also consider grounding, shielding, impedance, protection and calibration.
For an ideal unipolar ADC with reference voltage Vref and n bits, the code for an input voltage Vin is commonly approximated by:
D = floor((2n − 1)Vin / Vref)
where D is the integer output code, 0 ≤ Vin ≤ Vref, and floor means round downward. The nominal voltage represented by one least-significant bit is:
VLSB = Vref / (2n − 1)
Some data sheets define ADC resolution using Vref/2n instead. The data-sheet convention should therefore be used when calculating accuracy. Quantization is only one error source; reference tolerance, noise, nonlinearity and sensor error may be larger.
Worked example. A 12-bit ADC uses a 3.3 V reference and receives 1.65 V. The ideal code is approximately (4095)(1.65/3.3) = 2047.5, so the quantized result is about 2047 or 2048 depending on the converter’s rounding rule. The nominal code step is 3.3/4095 ≈ 0.806 mV. This does not imply that the complete measurement accuracy is 0.806 mV.
Sampling must be fast enough to represent the signal of interest. For a band-limited signal with highest frequency fmax, the Nyquist condition requires:
fs > 2 fmax
where fs is the sampling frequency. This is a theoretical condition; practical systems use filtering and margin because noise, transients and non-ideal sampling can produce aliasing. An analog anti-alias filter should attenuate frequency components above the usable bandwidth before ADC conversion.
Actuators convert electrical commands into physical action. LEDs require current limiting; motors require suitable drivers, flyback protection and separate power considerations; relays may require transistor or MOSFET switching and isolation. A microcontroller pin must not directly drive a load beyond its rated voltage or current. PWM controls average power by varying duty ratio. For an ideal low-pass load, the average voltage of a unipolar PWM waveform is approximately:
Vavg = d Vsupply
where d is duty ratio between 0 and 1. This relation does not predict instantaneous motor current, torque or LED brightness exactly.
4. Communication Buses and Data Integrity
UART is an asynchronous point-to-point serial interface. Both ends must agree on baud rate, data bits, parity and stop bits. It is simple and useful for debugging, but a conventional UART link does not inherently provide message addressing or strong error recovery.
I²C uses open-drain/open-collector signaling with pull-up resistors, normally called SDA and SCL. Devices share the bus through addresses. Pull-up selection must satisfy voltage, bus capacitance, rise-time and sink-current requirements. Address conflicts and inadequate level shifting are common laboratory faults.
SPI commonly uses a clock, master-out/slave-in, master-in/slave-out and one chip-select line per selected device. It is fast and full duplex, but clock polarity, clock phase, word order and chip-select timing must match the peripheral.
CAN uses differential signaling, arbitration and error handling, making it valuable in vehicles and industrial systems. Message priority is represented by identifier arbitration; a numerically dominant identifier wins arbitration without corrupting the lower-priority transmission.
Reliable application protocols add framing, length information, sequence numbers, timestamps, checksums or message authentication, depending on requirements. A checksum can detect many accidental errors but is not a security mechanism against an intentional attacker.
5. IoT Architecture and Edge Intelligence
An IoT solution commonly has four logical layers:
Device layer: sensors, actuators, microcontroller firmware and local protection.
Edge/gateway layer: protocol conversion, buffering, filtering, local rules and inference.
Network/service layer: authentication, message transport, device management and storage.
Application layer: dashboards, alarms, reports, control policies and maintenance workflows.
The partition should be based on latency, bandwidth, privacy, reliability, energy and computational cost. A safety shutdown belongs locally because cloud round-trip delay and loss of connectivity are unacceptable. Long-term trend analysis may be placed in a cloud database because it benefits from large storage and fleet-wide data.
Edge intelligence means executing a trained model or diagnostic rule close to the sensor. Common lightweight methods include thresholding, moving averages, standard-deviation scores, linear regression, decision trees and small quantized neural networks. A moving average over N samples is:
x̄k = (1/N) ∑_(i=0)^(N−1) x_(k−i)
where xk is the current sample and x̄k is the filtered output. It reduces independent random noise but introduces delay and can hide abrupt faults. A larger N gives stronger smoothing and greater response delay.
For a signal with baseline mean μ and standard deviation σ, a simple standardized score is:
z = (x − μ) / σ
This assumes that the baseline statistics are representative and that σ > 0. A rule such as |z| > 3 is a heuristic, not a universal proof of failure. Non-Gaussian data, drift and correlated samples affect its false-alarm rate.
A practical edge diagnostic pipeline is: acquire → validate → calibrate → filter → extract features → infer → apply confidence and persistence rules → log and communicate. Feature examples include mean, RMS value, peak-to-peak value, temperature slope and vibration-band energy. The diagnostic output should include confidence, timestamp, model version and sensor-quality status rather than only a binary label.
6. Cybersecurity, Privacy and Safety
Connected laboratory systems have an expanded attack surface: debug ports, default passwords, wireless interfaces, firmware-update mechanisms, web dashboards and physical access. Security should be designed into the system rather than added after deployment.
Important controls include:
unique device identity and strong authentication;
encrypted communication using appropriately configured protocols;
authorization based on least privilege;
secure boot and signed firmware where supported;
protected and tested update procedures;
removal or locking of production debug interfaces;
input validation, rate limiting and replay protection;
event logging without unnecessary personal data;
backup, recovery and vulnerability-response plans.
Confidentiality, integrity and availability have different priorities. A temperature reading may require integrity and availability more urgently than confidentiality, whereas an occupancy sensor may reveal sensitive behavioral information. Data minimization, purpose limitation, retention limits and access control support privacy. Students should never place real personal data or production credentials in a public repository.
Safety is distinct from cybersecurity. A secure system can still be electrically unsafe, and a safe enclosure can still accept malicious commands. Define fail-safe states, energy isolation, current limits, emergency stops and manual overrides. For a control prototype, loss of communication should have a specified local response rather than an accidental one.
7. Engineering Workflow and Testing
A disciplined workflow is:
State functional, timing, electrical, environmental, security and safety requirements.
Select components using data-sheet limits and lifecycle information.
Build the smallest hardware and firmware test needed to retire the largest risk.
Verify each interface independently before integration.
Instrument timestamps, supply voltage, bus traffic, reset causes and error counters.
Test normal, boundary, disconnected, noisy and malicious-input conditions.
Record calibration data, firmware version, wiring, assumptions and unresolved limitations.
A useful test distinguishes verification—whether the system was built according to its specification—from validation—whether it solves the intended practical problem. For example, a node may transmit every five seconds as specified but still fail validation if its alarm is too slow for the application.
Measurements should be repeatable. Report test conditions, sample count, uncertainty or tolerance where meaningful, and pass/fail criteria established before examining results. Do not silently discard inconvenient observations.
8. Illustrative Case Study: Edge-Based Motor-Fan Monitor
Background. The following is a fictional instructional case. A small laboratory motor drives a fan. A temperature sensor measures the bearing housing, while a current sensor measures electrical load. The objective is to detect abnormal operation locally and report status to a dashboard.
Problem. A cloud-only design could miss a rapid over-temperature event when Wi-Fi is unavailable. Raw high-rate current data would also consume bandwidth and expose unnecessary operational information.
Analysis. The microcontroller samples temperature once per second and current at a higher rate for local feature extraction. It controls a warning LED and a relay driver. The emergency response must not depend on the network. The diagnostic baseline is established during known healthy operation, but the baseline must be recalibrated if the motor, load or environment changes.
Approach and solution. A timer creates the one-second supervisory task. An ADC reads the temperature sensor, while a timer-triggered sampling routine gathers current samples into a ring buffer. The firmware calculates the current RMS value, temperature slope and standardized scores relative to healthy-operation statistics. A warning requires abnormal temperature for three consecutive supervisory cycles, reducing nuisance alarms. A critical temperature threshold causes local shutdown through a hardware-compatible control path. A secure authenticated message transmits timestamp, state, selected features and firmware version; raw current samples remain local unless a maintenance mode is explicitly authorized.
The current RMS value for a set of N equally spaced samples is estimated by:
IRMS = √((1/N) ∑_(k=1)N ik²)
where ik is the kth current sample in amperes and IRMS is in amperes. This formula assumes samples represent the measurement interval adequately and that sensor offset has been removed or accounted for.
Outcome. In normal testing, the system reports healthy operation and the dashboard displays trends. When airflow is deliberately restricted, current and temperature rise; the local warning appears before the dashboard message. When Wi-Fi is disconnected, local protection continues and records an unsent event for later upload. Tests also reveal that a blocked sensor tube can produce a false-normal reading, demonstrating the need for sensor plausibility checks.
Learning points. Edge processing is not a substitute for sound instrumentation. Local protection should have a deterministic path. Diagnostics require a representative baseline, drift management and clear alarm semantics. Security and privacy decisions influence what data are collected, not merely how data are transmitted.
9. Contemporary Developments and Limitations
Modern microcontrollers increasingly include low-power wireless radios, hardware cryptography, secure enclaves, vector instructions and neural-processing accelerators. TinyML tools can quantize models, reduce memory use and generate optimized inference code. Digital-twin approaches combine field data with physical models for maintenance and commissioning.
These developments do not remove fundamental limitations. Small models may underfit changing conditions; training data may contain bias or leakage; quantization can reduce accuracy; and model drift can make a deployed diagnostic unreliable. Cloud dependence may create vendor lock-in and operational risk. Wireless coexistence, electromagnetic interference, battery aging and supply-chain vulnerabilities remain engineering concerns.
A responsible design therefore reports uncertainty, supports human review for consequential decisions and provides a way to update, disable or roll back an edge model. Students should compare a simple transparent rule with a more complex model and justify complexity using measured improvement, not novelty.
Chapter Summary
Embedded systems combine computation, sensing, actuation, timing and communication for a defined purpose. Timers and interrupts enable periodic and event-driven operation, but real-time behavior must be analysed using worst-case timing and careful synchronization. ADCs require attention to reference voltage, quantization, sampling and analog signal conditioning. UART, I²C, SPI and CAN provide different trade-offs in wiring, speed, addressing and robustness.
IoT systems distribute responsibilities among devices, edge nodes, networks and cloud services. Edge intelligence can reduce latency, bandwidth and privacy exposure through filtering, feature extraction and lightweight diagnostics. Such algorithms require representative data, validated assumptions and monitoring for drift. Cybersecurity, privacy, electrical safety and fault handling are integral design requirements. A professional prototype is verified through structured tests, documented limitations and evidence that it solves the intended problem.
Key Terms
Embedded system: A computer integrated into a larger product to perform a dedicated function.
Microcontroller: An integrated device containing a processor, memory and peripheral interfaces.
Timer: Hardware that counts clock events for timing, measurement or waveform generation.
Interrupt: An event that temporarily transfers processor execution to a service routine.
Real-time system: A system whose correctness includes producing results within specified time limits.
ADC: An analog-to-digital converter that represents an analog signal numerically.
Quantization: The mapping of continuous-valued amplitudes to discrete digital codes.
PWM: Pulse-width modulation, in which duty ratio controls the average effect of a switched waveform.
UART: An asynchronous serial communication interface.
I²C: A shared, addressed serial bus using clock and data lines with pull-up devices.
SPI: A synchronous serial bus commonly using clock, data and chip-select signals.
CAN: A robust multi-node differential bus with arbitration and error handling.
IoT: A networked system of physical devices that sense, communicate and sometimes actuate.
Edge computing: Processing performed near the data source.
TinyML: Deployment of machine-learning inference on resource-constrained embedded devices.
Watchdog timer: A supervisory timer that detects software failure or lack of progress.
Secure boot: A process that verifies firmware authenticity before execution.
Aliasing: Misrepresentation of signal frequency caused by inadequate sampling.
RMS value: The square root of the mean of squared signal samples, representing effective magnitude.
Sensor drift: Gradual change in sensor output or calibration over time.
Review Questions
Short Answer Questions
What distinguishes an embedded system from a general-purpose computer?
Why should an interrupt service routine usually be short?
State two electrical precautions when connecting an actuator to a microcontroller.
What is the purpose of an anti-alias filter?
Give two reasons for performing diagnostic processing at the edge.
Long Answer Questions
Explain how timers, interrupts and watchdogs cooperate in a reliable embedded application.
Compare UART, I²C, SPI and CAN in terms of topology, addressing, wiring and typical applications.
Explain ADC resolution, quantization and the practical factors that limit measurement accuracy.
Describe a secure and privacy-aware architecture for an IoT monitoring system.
Discuss the benefits and limitations of deploying a lightweight machine-learning diagnostic model on a microcontroller.
Analytical / Application Questions
Design a timing and data path for a motor monitor that samples temperature once per second, calculates current RMS locally and shuts down safely when a critical condition occurs. Identify which functions must remain local and justify your decision.
A sensor produces noisy measurements and occasional missing samples. Propose a validation, filtering and alarm-persistence strategy, and explain how you would test false alarms and missed faults.
An IoT prototype works correctly in the laboratory but fails when Wi-Fi is disconnected and accepts commands using a shared default password. Analyse the technical and security failures and propose a prioritized corrective plan.
Multiple Choice Questions with Answers
Question 1
Which resource is most appropriate for generating a periodic sampling event in a microcontroller?
A. Timer peripheral
B. LED resistor
C. Pull-up resistor alone
D. Mechanical relay contact
Correct Answer: A. Timer peripheral
Question 2
For a timer clocked at 16 MHz with a prescaler of 64, what is the timer tick period?
A. 4 μs
B. 64 μs
C. 250 ns
D. 1 ms
Correct Answer: A. 4 μs
Question 3
What is the principal purpose of an interrupt service routine?
A. Respond promptly to a hardware or software event
B. Store all historical sensor data permanently
C. Replace the power supply
D. Increase ADC reference voltage
Correct Answer: A. Respond promptly to a hardware or software event
Question 4
Which statement about the volatile qualifier is correct?
A. It guarantees mutual exclusion between tasks
B. It prevents every possible race condition
C. It can prevent inappropriate compiler optimization of hardware-shared data
D. It encrypts variables in RAM
Correct Answer: C. It can prevent inappropriate compiler optimization of hardware-shared data
Question 5
An ideal unipolar 12-bit ADC uses a 3.3 V reference. Approximately what voltage step corresponds to one code using 3.3 V ÷ 4095?
A. 0.806 mV
B. 8.06 mV
C. 80.6 mV
D. 806 mV
Correct Answer: A. 0.806 mV
Question 6
Which bus commonly uses open-drain signaling and pull-up resistors on shared clock and data lines?
A. SPI
B. I²C
C. UART
D. Analog VGA
Correct Answer: B. I²C
Question 7
Why is local edge protection preferable to cloud-only protection for a fast hazardous event?
A. It eliminates the need for sensors
B. It avoids dependence on network latency and connectivity
C. It guarantees perfect machine-learning accuracy
D. It makes actuators require no power
Correct Answer: B. It avoids dependence on network latency and connectivity
Question 8
What does a watchdog timer primarily detect?
A. A lack of expected software progress
B. The exact chemical composition of a sensor
C. The network provider’s billing rate
D. The color of an indicator LED
Correct Answer: A. A lack of expected software progress
Question 9
What is a major limitation of a simple z-score alarm?
A. It requires no baseline data
B. It is always valid for nonstationary data
C. Its usefulness depends on representative baseline statistics
D. It can only be calculated in the cloud
Correct Answer: C. Its usefulness depends on representative baseline statistics
Question 10
Which measure is most directly associated with preventing unauthorized firmware from executing at startup?
A. Secure boot
B. PWM duty ratio
C. ADC oversampling alone
D. A larger motor heatsink
Correct Answer: A. Secure boot
Electrical & Electronics Engineering Laboratory
Chapter 13
of 15