Internet of Things

Chapter 4
Embedded Systems and IoT Device Engineering

Bachelors Program in Computer Science Engineering
Internet of Things   •   Bachelor

Embedded Systems and IoT Device Engineering

Introduction and Context

An Internet of Things (IoT) device is a physical computing system that senses conditions, processes information, communicates with other systems, and often controls an actuator. Unlike desktop computers, IoT devices operate under severe constraints: limited memory and processing capacity, restricted energy, intermittent connectivity, small physical size, environmental exposure, and long maintenance lifetimes.

Embedded systems engineering therefore requires coordinated decisions about electronics, firmware, operating systems, communication protocols, mechanical packaging, power, security, testing, and deployment. A successful design is not simply functional; it must satisfy timing, energy, reliability, safety, cost, and maintainability requirements.

Learning Objectives

After studying this chapter, students should be able to:

  1. Explain the architecture and constraints of embedded IoT devices.
  2. Select microcontrollers, sensors, actuators, interfaces, and operating systems for a stated application.
  3. Analyze real-time behavior, interrupt response, scheduling, and communication timing.
  4. Estimate energy consumption and battery life with stated assumptions.
  5. Apply firmware engineering, reliability, security, and over-the-air update practices.
  6. Design and evaluate a prototype using a systematic engineering workflow.

1. Embedded IoT Architecture

A typical device contains five interacting layers:

LayerMain responsibilityExamples
Physical componentsSense, actuate, power, and connectSensors, motors, antenna, battery
Hardware controlExecute instructions and manage peripheralsMicrocontroller, timers, ADC, GPIO
FirmwareImplement device behaviorDrivers, scheduler, protocol stack
ConnectivityExchange data and commandsBLE, Wi-Fi, Ethernet, LoRaWAN, cellular
Cloud or edge serviceStore, analyze, visualize, and manage devicesBroker, database, dashboard, update server

The microcontroller (MCU) commonly integrates a processor core, flash memory, SRAM, timers, interrupt controller, serial interfaces, analog-to-digital converter (ADC), and power-management functions. A microprocessor-based system generally provides greater computational capability but normally requires external memory and power-management components. A system-on-chip (SoC) integrates still more functions, such as radio communication or security acceleration.

The central design trade-off is that greater processing and communication performance usually increases cost, power consumption, thermal output, and software complexity. Requirements should therefore be expressed quantitatively where possible: measurement accuracy, sampling period, maximum response time, battery life, radio range, data rate, operating temperature, and acceptable failure rate.

2. Microcontroller Resources and Hardware Interfaces

2.1 Memory and processing

Flash or non-volatile memory stores program code and persistent configuration. SRAM stores variables, stacks, buffers, and run-time data. Non-volatile data may be stored in EEPROM or emulated in flash. Designers must reserve space for bootloaders, diagnostic records, cryptographic keys, and future firmware updates rather than allocating all memory to the first release.

CPU frequency alone is not a sufficient performance measure. Interrupt latency, memory wait states, DMA support, peripheral architecture, compiler efficiency, and worst-case execution time also matter. A device that is fast on average but misses a deadline is unsuitable for a hard real-time control task.

2.2 Digital and analog interfaces

GPIO pins provide digital input and output. Pull-up and pull-down resistors establish a defined logic state when a switch or open-drain output is inactive. Debouncing is required because a mechanical switch can produce several rapid transitions during one physical action.

An ADC maps an analog voltage into a digital code. For an ideal N-bit ADC with reference voltage V_ref, the approximate voltage represented by code k is:

Vin ≈ kVref/(2N − 1)

Here, k ranges from 0 to 2^N − 1, and quantization, reference error, noise, and sensor error limit practical accuracy. The formula assumes a unipolar ideal ADC and does not include gain or offset errors.

Communication interfaces include UART, I²C, SPI, CAN, USB, and Ethernet. UART is simple and point-to-point. I²C uses addressable devices on two shared lines and is useful for low-to-moderate-speed peripherals. SPI usually provides higher throughput and deterministic framing but requires chip-select lines. CAN supports robust multi-node communication and fault handling, particularly in vehicles and industrial systems.

2.3 Sensor and actuator conditioning

Sensors may require amplification, filtering, biasing, linearization, isolation, or level translation. An analog low-pass filter can reduce high-frequency noise, but filtering introduces delay. Actuators may require transistor drivers, flyback diodes for inductive loads, current limiting, or galvanic isolation. A microcontroller pin must never be assumed capable of directly driving a motor, relay, heater, or high-current lamp.

3. Firmware Architecture

Firmware is the software permanently or semi-permanently installed in the device. A maintainable architecture separates hardware-dependent code from application logic:

  1. Boot and hardware initialization configure clocks, memory protection, pins, and safety defaults.
  2. Board-support and driver layers control timers, ADCs, sensors, radios, storage, and actuators.
  3. Middleware provides networking, cryptography, file systems, logging, and device management.
  4. Application logic implements sensing, control, alarms, and user requirements.
  5. Diagnostics record faults, reset causes, health measures, and communication status.

A hardware abstraction layer improves portability, but excessive abstraction can obscure timing and memory costs. Interfaces should specify units, valid ranges, error behavior, timeout rules, and ownership of buffers.

Super-loops, interrupts, and RTOSs

A super-loop repeatedly executes tasks. It is inexpensive and predictable for simple systems, but a long task can delay every other activity. Interrupt service routines (ISRs) respond quickly to hardware events. ISRs should be short: capture essential state, clear the interrupt condition, and defer substantial processing to a task or queue.

A real-time operating system (RTOS) supplies tasks, scheduling, synchronization, timers, queues, and sometimes memory protection. It does not automatically make a system real-time. The designer must still establish bounded execution times, priorities, resource ownership, and deadline analysis.

Priority inversion occurs when a high-priority task waits for a resource held by a low-priority task while a medium-priority task prevents the low-priority task from running. Priority inheritance temporarily raises the holder’s priority and can reduce this problem. Mutexes protect shared resources; semaphores commonly signal events or count available resources; queues transfer data between execution contexts.

4. Real-Time Behavior and Scheduling

A real-time system is judged by whether results are produced within required deadlines, not merely by average speed. A periodic task has execution time C, period T, and deadline D. Its utilization is:

U = ∑(Ci/Ti)

where the sum is over periodic tasks and C_i and T_i use the same time unit. For rate-monotonic scheduling on independent periodic tasks with deadlines equal to periods, a sufficient—not necessary—schedulability bound for n tasks is:

U ≤ n(2^(1/n) − 1)

This bound assumes fixed priorities, independent tasks, negligible context-switch overhead, no blocking, and suitable periodic behavior. A utilization above the bound does not prove failure; exact response-time analysis may still show schedulability.

For a fixed-priority task i, a commonly used response-time recurrence is:

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

B_i is blocking time and hp(i) is the set of higher-priority tasks. The recurrence is iterated until it converges or exceeds the deadline. It assumes known execution-time bounds and a specified priority model.

Worked scheduling example

Suppose two independent periodic tasks have (C₁, T₁) = (1 ms, 5 ms) and (C₂, T₂) = (2 ms, 10 ms). Their utilization is:

U = 1/5 + 2/10 = 0.2 + 0.2 = 0.4

For two tasks, the sufficient rate-monotonic bound is 2(2^(1/2) − 1) ≈ 0.828. Since 0.4 ≤ 0.828, the task set passes this sufficient test under the stated assumptions. Interrupt overhead, blocking, and non-periodic work must still be measured or bounded.

5. Energy Management and Battery Estimation

Battery-powered design begins with an energy budget. For a sequence of operating modes, average current is:

Iavg = (∑ Ii ti)/T

I_i is the current in mode i, t_i is time spent in that mode, and T = ∑t_i. The result is valid when currents are measured under the relevant voltage and operating conditions. Battery life in hours can be approximated by:

tb ≈ Cb/Iavg

where C_b is usable battery capacity in mAh. This is an approximation: temperature, discharge rate, regulator losses, aging, self-discharge, and the required minimum voltage reduce usable capacity. With a regulator efficiency η and load voltage V_L, the battery-side current must account for power conversion; a first approximation is I_b ≈ V_L I_L/(ηV_b), assuming a relatively stable battery voltage V_b.

Corrected worked energy example

An IoT node operates for a 60-second cycle:

  • Sleep: 0.020 mA for 59 s
  • Measurement: 8 mA for 0.5 s
  • Radio transmission: 120 mA for 0.5 s

The charge consumption per cycle is:

Q = (0.020 × 59) + (8 × 0.5) + (120 × 0.5)

Q = 1.18 + 4 + 60 = 65.18 mA·s

Therefore:

Iavg = 65.18/60 ≈ 1.0863 mA

For an ideal 2000 mAh battery, estimated life is:

tb = 2000/1.0863 ≈ 1841 h

This is approximately 76.7 days. In practice, the estimate must be reduced for regulator losses, battery derating, radio retries, leakage, and the cutoff-voltage requirement.

Energy can also be expressed as power integrated over time:

E = ∫P(t)dt

For approximately constant voltage, P ≈ VI. Charge-based calculations are convenient when current is specified; energy-based calculations are preferable when voltage changes significantly.

Energy-saving methods include deep sleep, event-driven wake-up, batching measurements, reducing radio airtime, adaptive sampling, efficient regulators, local processing, and selecting sensors with low standby current. A lower-power design must not compromise safety or measurement validity.

6. Reliability, Safety, and Security

Reliability is the probability that a device performs its required function for a specified time under stated conditions. Common engineering practices include watchdog timers, brownout detection, input validation, bounded retries, fail-safe actuator states, redundant or plausibility checks, thermal derating, environmental sealing, and persistent fault logs.

A watchdog is useful only if the software cannot regularly service it while malfunctioning. The watchdog policy should identify which tasks must report health and what recovery action follows a timeout. Recovery levels may include restarting a task, resetting the MCU, reverting communication, or placing the actuator in a safe state.

Failure mode and effects analysis (FMEA) ranks possible failures by severity, occurrence, and detectability. The resulting risk priority is a screening aid, not a physical law; high-severity hazards require controls even if their numerical ranking is low.

Security begins with a threat model. Relevant controls include secure boot, signed firmware, unique device identity, protected keys, encrypted communication, least privilege, secure debug configuration, replay protection, rate limiting, and vulnerability monitoring. Encryption alone does not establish authenticity; authenticated encryption or a separate integrity mechanism is required.

Privacy must be considered when devices collect location, health, occupancy, or behavioral data. Data minimization, purpose limitation, retention controls, access logging, and lawful processing are important governance practices. Safety-critical devices may also be subject to sector-specific standards and radio-spectrum regulations.

7. Over-the-Air Updates

An OTA system consists of a build and signing pipeline, update repository, device bootloader, transport protocol, installation mechanism, and rollback strategy. A robust update process should provide:

  • authenticated image verification;
  • version and anti-rollback policy;
  • power-loss tolerance;
  • staged deployment and monitoring;
  • resumable transfer;
  • sufficient flash space for the active and candidate images;
  • recovery to a known-good image.

A common design uses two firmware slots. The device downloads the candidate image into the inactive slot, verifies its signature and integrity, marks it pending, and reboots. The bootloader selects the candidate only after validation. The new firmware reports successful self-tests; otherwise the bootloader rolls back. A cryptographic hash detects accidental corruption, while a digital signature establishes that the image came from an authorized signer.

OTA updates increase maintainability but also introduce risks: compromised signing keys, incomplete deployments, incompatible data schemas, and update-induced outages. Keys should be protected with controlled access and rotation procedures, and deployments should begin with a small cohort.

8. Prototyping and Engineering Workflow

A disciplined workflow reduces late failures:

  1. Define measurable requirements and operating conditions.
  2. Partition functions between hardware, firmware, edge, and cloud.
  3. Select components with lifecycle, supply, certification, and environmental constraints in mind.
  4. Build a proof of concept using development boards.
  5. Measure current, timing, thermal behavior, radio performance, and sensor accuracy.
  6. Design the schematic, PCB, enclosure, and production test strategy.
  7. Perform unit, integration, hardware-in-loop, environmental, security, and field tests.
  8. Document calibration, manufacturing programming, traceability, and service procedures.

A prototype board may hide electromagnetic interference, connector weakness, regulator instability, antenna detuning, or production-assembly problems. Verification should therefore use representative hardware and realistic workloads.

9. Applied Case: Battery-Powered Cold-Chain Monitor

Background

This illustrative case concerns a device that records the temperature of vaccine containers during transport. It must operate for at least 30 days, record temperature every minute, transmit summaries when cellular coverage is available, and raise an alarm when temperature remains outside its permitted range.

Problem analysis

The device faces competing requirements: accurate sensing, long battery life, intermittent connectivity, data integrity, tamper evidence, and safe operation across changing temperatures. Immediate transmission of every reading would increase energy use and fail in regions without coverage.

Engineering approach

The design uses a low-power MCU, a calibrated digital temperature sensor, non-volatile local storage, a cellular or low-power wide-area modem, a real-time clock, a protected battery, and a tamper switch. The MCU wakes once per minute, reads and validates the sensor, stores a timestamped record, and returns to sleep. It maintains a rolling summary and attempts transmission periodically or when an alarm is detected. Records are authenticated so that later analysis can identify modification.

The firmware uses a state machine with states such as INITIALIZE, SAMPLE, STORE, TRANSMIT, ALARM, and RECOVER. Sensor values outside the physically plausible range are marked invalid rather than silently accepted. If communication fails, exponential back-off limits repeated attempts while preserving the data locally. A watchdog and brownout detector protect against stalled execution and unstable supply voltage.

An energy estimate must include sleep, sensing, modem startup, transmission, retries, storage, regulator losses, and cold-temperature battery derating. Field tests should measure the worst expected communication pattern rather than relying only on a nominal laboratory cycle.

Outcome and learning points

The key outcome is not merely a working prototype but an auditable monitoring system with traceable measurements, alarms, recovery behavior, and update capability. The case demonstrates that IoT device engineering is a systems problem: sensor accuracy, firmware timing, power architecture, communications, security, and regulatory obligations interact.

10. Contemporary Developments and Professional Practice

Modern MCUs increasingly integrate hardware cryptography, secure enclaves, low-power radios, and machine-learning accelerators. TinyML can classify vibration, sound, or images locally, reducing bandwidth and privacy exposure, but model memory, inference energy, training-data bias, and update management must be evaluated.

Digital twins and fleet observability support predictive maintenance by combining device telemetry, firmware versions, fault codes, and environmental data. However, telemetry should be proportionate and protected. Edge computing reduces latency and dependence on cloud connectivity, while cloud services simplify fleet management. Neither is universally superior; the appropriate split follows latency, privacy, cost, and availability requirements.

Professional engineers should maintain configuration control, peer review, coding standards, reproducible builds, component bills of materials, vulnerability response plans, and evidence-based verification. Design decisions should record assumptions, measurements, residual risks, and rejected alternatives.

Challenges and Limitations

Embedded designs are constrained by incomplete component documentation, supply-chain substitutions, analog noise, radio interference, battery variability, environmental stress, and difficult field access. Simulation cannot replace measurement, and a successful laboratory demonstration does not prove fleet reliability. Real-time guarantees require defensible worst-case bounds, while battery predictions require representative duty cycles. Security is also a lifecycle property: a secure launch can become vulnerable if credentials, dependencies, or update infrastructure are neglected.

Chapter Summary

Embedded IoT devices combine sensing, computation, communication, actuation, and power management under strict resource constraints. MCU selection must consider memory, peripherals, timing, energy, environmental conditions, lifecycle, and security. Firmware should separate drivers, middleware, application behavior, and diagnostics. Interrupts, super-loops, and RTOSs provide different execution models, but real-time behavior depends on bounded execution and deadline analysis.

Energy estimation requires a duty-cycle calculation with consistent units; the corrected example gives 65.18 mA·s per 60-second cycle, 1.086 mA average current, and approximately 1,841 hours for an ideal 2000 mAh battery. Reliability requires watchdogs, brownout handling, fault detection, safe states, testing, and risk analysis. Secure OTA updates require authenticated images, rollback, staged deployment, and protected signing keys. Finally, successful IoT engineering depends on measurement, prototyping, lifecycle planning, privacy, security, and evidence-based verification.

Key Terms

Microcontroller: An integrated processor and peripheral device designed for embedded control.

Firmware: Software that controls embedded hardware and its device behavior.

GPIO: A general-purpose digital input/output pin.

ADC: A circuit that converts an analog quantity into a digital code.

Interrupt: A hardware or software event that requests processor attention.

RTOS: An operating system providing task scheduling and real-time services.

ISR: Interrupt service routine executed in response to an interrupt.

Deadline: The latest permitted completion time for a task.

Priority inversion: Delay of a high-priority task by lower-priority resource ownership.

DMA: Direct memory access that transfers data without continuous CPU involvement.

Duty cycle: The fraction of time a device operates in a particular mode.

Watchdog: A timer that initiates recovery when software fails to report health.

Brownout: A supply-voltage condition below reliable operating limits.

FMEA: A structured analysis of failure modes, effects, and controls.

Secure boot: Startup verification that permits only authorized firmware to run.

OTA update: Delivery and installation of firmware through a network.

Rollback: Restoration of a previously working firmware version.

Edge computing: Processing data near its source rather than exclusively in a cloud.

Review Questions

Short Answer Questions

  1. What are the main differences between flash memory and SRAM in an MCU?
  2. Why should an interrupt service routine generally be short?
  3. Define priority inversion and name one mitigation technique.
  4. Why does a battery-life calculation based only on nominal capacity overestimate field life?
  5. Distinguish a cryptographic hash from a digital signature in an OTA system.

Long Answer Questions

  1. Explain how a layered firmware architecture improves maintainability and testability.
  2. Compare a super-loop, interrupt-driven firmware, and an RTOS-based design for an IoT node.
  3. Derive and interpret the average-current equation for a multi-mode battery device.
  4. Describe a secure, power-loss-tolerant OTA update process using dual firmware slots.
  5. Explain how reliability, safety, security, and privacy requirements interact in a connected medical monitor.

Analytical / Application Questions

  1. A node draws 0.05 mA for 99 s and 80 mA for 1 s in a 100-second cycle. Calculate its average current and estimate ideal life with a 1600 mAh battery. State two reasons the field result may differ.
  2. Two periodic tasks have execution and period values (C₁,T₁) = (0.5 ms, 4 ms) and (C₂,T₂) = (1 ms, 8 ms). Calculate utilization and assess it using the two-task rate-monotonic sufficient bound, stating the assumptions.
  3. Design a recovery strategy for a remote sensor that experiences repeated modem failures and occasional power loss. Include local storage, retry policy, watchdog behavior, security, and OTA rollback.

Multiple Choice Questions with Answers

Question 1

Which memory normally stores executable firmware when power is removed?

A. SRAM

B. Flash memory

C. CPU register file

D. ADC sample-and-hold capacitor

Correct Answer: B. Flash memory

Question 2

For a 60-second cycle consuming 65.18 mA·s, what is the average current?

A. 0.1086 mA

B. 1.086 mA

C. 10.86 mA

D. 65.18 mA

Correct Answer: B. 1.086 mA

Question 3

Which practice best limits work performed inside an interrupt service routine?

A. Perform blocking network operations in the ISR

B. Disable all interrupts permanently

C. Capture essential state and defer processing to a task

D. Allocate unlimited dynamic memory in the ISR

Correct Answer: C. Capture essential state and defer processing to a task

Question 4

What does an authenticated firmware signature primarily establish?

A. The image was produced by an authorized signer and was not altered

B. The battery is fully charged

C. The radio signal is available

D. The firmware has zero defects

Correct Answer: A. The image was produced by an authorized signer and was not altered

Question 5

For two periodic tasks under the stated rate-monotonic sufficient test, the utilization bound is approximately:

A. 0.250

B. 0.500

C. 0.707

D. 0.828

Correct Answer: D. 0.828

Question 6

Which interface commonly uses separate clock, data-in, data-out, and chip-select signals?

A. SPI

B. UART

C. Single-wire GPIO

D. Analog voltage input

Correct Answer: A. SPI

Question 7

What is the principal purpose of a watchdog timer?

A. Increase ADC resolution

B. Recover from software that fails to operate correctly

C. Encrypt every sensor reading automatically

D. Measure antenna impedance

Correct Answer: B. Recover from software that fails to operate correctly

Question 8

In a dual-slot OTA design, where is a downloaded candidate image normally placed before activation?

A. The currently executing slot only

B. The inactive firmware slot

C. The CPU register file

D. The ADC calibration register

Correct Answer: B. The inactive firmware slot

Question 9

If a task has C = 2 ms and T = 10 ms, its utilization contribution is:

A. 0.02

B. 0.2

C. 2

D. 20

Correct Answer: B. 0.2

Question 10

Which technique most directly reduces radio energy for a sensor that does not need continuous connectivity?

A. Transmit every raw sample immediately

B. Increase retransmissions without a limit

C. Batch data and transmit during planned communication windows

D. Keep the radio permanently active

Correct Answer: C. Batch data and transmit during planned communication windows

Internet of Things
Chapter 4 of 15