Microcontrollers and Interfacing

Chapter 1
Microcontroller and Embedded-System Foundations

Bachelor Program in Mechatronics Engineering
Microcontrollers and Interfacing   •   Bachelor

Microcontroller and Embedded-System Foundations

Introduction and Context

A microcontroller is a compact computing system designed to sense, process, and control physical processes. It combines a processor core with memory, input/output interfaces, timers, communication peripherals, and clocking circuitry on one integrated circuit. In mechatronics, microcontrollers connect mechanical systems, electrical power stages, sensors, actuators, and software. Examples include motor controllers, robotic joints, automotive body controllers, medical instruments, and industrial automation nodes.

An embedded system is a computer system incorporated into a larger product or process. Unlike a general-purpose desktop computer, it is usually designed for a defined function, often under constraints of cost, size, energy consumption, reliability, and timing. A washing-machine controller, for example, must read switches and water-level sensors, control valves and motors, detect unsafe conditions, and execute its program predictably.

This chapter establishes the vocabulary and architectural concepts needed for later study of microcontroller programming and interfacing. It also distinguishes microcontrollers from related technologies and explains how information moves through a processor.

Learning Objectives

After studying this chapter, you should be able to:

  • define embedded-system and microcontroller terminology;
  • convert among binary, hexadecimal, and decimal representations;
  • explain digital logic and the relationship between bits, logic gates, and registers;
  • compare von Neumann and Harvard architectures and common CPU organizations;
  • describe instruction execution, registers, buses, memory maps, stacks, and endianness;
  • explain interrupt operation and latency;
  • distinguish microcontrollers, microprocessors, DSPs, SoCs, and programmable logic;
  • analyze a small embedded-control architecture and identify appropriate design choices.

Embedded-System Terminology

A plant is the physical process being controlled, such as a motor, robotic arm, or temperature chamber. A sensor converts a physical quantity into an electrical signal. An actuator converts an electrical command into physical action. The controller computes commands from sensor data and desired operating conditions. Firmware is the software stored in non-volatile memory that governs this operation.

Embedded systems may be classified as:

  • Standalone systems, which perform a dedicated function without a host computer.
  • Networked systems, which communicate with other devices or cloud services.
  • Real-time systems, in which correctness depends on both the result and the time at which it is produced.
  • Safety-critical systems, in which failure can cause injury, environmental damage, or major economic loss.

A hard real-time deadline must always be met; missing it is a system failure. A soft real-time deadline is desirable, but occasional lateness degrades performance rather than necessarily causing catastrophe. Determinism, bounded interrupt latency, watchdog recovery, and careful resource budgeting are therefore central engineering concerns.

A microcontroller typically contains a CPU, program memory such as flash, data memory such as SRAM, general-purpose input/output, timers, serial interfaces, analog peripherals, and interrupt logic. Integration reduces component count and often reduces energy and cost, but it does not eliminate the need for external drivers, power electronics, memory, isolation, or signal conditioning.

Information Representation and Number Systems

Digital hardware represents information using discrete logic states, conventionally 0 and 1. A bit is one binary digit. A group of 8 bits is a byte. A 16-bit word contains 2 bytes, while a 32-bit word contains 4 bytes. The terms word, half-word, and double-word are architecture-dependent and must be interpreted from the processor documentation.

A binary number uses positional weights that are powers of 2. For an n-bit unsigned number with bits bₙ₋₁ through b₀, the value is:

V = ∑ᵢ₌₀ⁿ⁻¹ bᵢ2ⁱ, bᵢ ∈ {0,1}

Here, V is the decimal value and each bᵢ is a bit. The range of an n-bit unsigned representation is 0 through 2ⁿ − 1. For example, 1011012 equals 32 + 8 + 4 + 1 = 45₁₀.

Hexadecimal notation uses sixteen symbols, 0–9 and A–F. One hexadecimal digit represents exactly four binary bits, so 0x2D corresponds to 0010\ 11012, or 45₁₀. Hexadecimal is compact and particularly useful for addresses, register values, machine instructions, and bit masks.

For signed integers, a common representation is two's complement. In an n-bit two's-complement system, the range is −2ⁿ⁻¹ through 2ⁿ⁻¹ − 1. To form a negative value, invert every bit and add 1. For example, in 8 bits, +5 is 00000101; −5 is 11111011. Two's complement permits the same binary adder to perform signed and unsigned addition, but software must interpret the result according to the declared data type.

A bit mask selects or modifies individual bits. To set bit k, software commonly performs OR with 1 << k; to clear it, it performs AND with the complement of that mask. Such operations must be used carefully when a register contains reserved or write-one-to-clear bits, because the peripheral reference manual defines the permitted access behavior.

Digital Logic and Data Paths

Digital circuits are built from logic gates. AND produces 1 only when all inputs are 1; OR produces 1 when at least one input is 1; NOT inverts a value; XOR produces 1 when its inputs differ. NAND and NOR are functionally complete, meaning any Boolean function can be built from them.

A combinational circuit has outputs determined by current inputs. Adders, multiplexers, decoders, and comparators are examples. A sequential circuit includes storage, so its output depends on present inputs and previous state. Flip-flops, counters, registers, and finite-state machines are sequential circuits. A clock provides a timing reference, although asynchronous interfaces and metastability require additional design techniques.

A register is a small, fast storage location inside the CPU or a peripheral. A register may hold an operand, an address, a status flag, or a control field. A data path includes registers, arithmetic and logic units, multiplexers, and connections that transport and transform data. The control unit produces signals that cause the data path to perform instruction operations.

For a Boolean expression such as Y = (A\ AND\ B)\ OR\ C, Y is 1 whenever C is 1 or both A and B are 1. Boolean simplification and truth tables are useful when designing enable signals, safety interlocks, and peripheral-selection logic.

Processor Architectures

Von Neumann and Harvard Organizations

In a von Neumann architecture, instructions and data share one memory system and usually one principal path to memory. This simplifies hardware and permits code and data to be treated uniformly, but instruction fetches and data transfers can compete for bandwidth.

In a Harvard architecture, instruction and data memories or paths are separate. Instructions may be fetched while data is accessed, potentially improving throughput. Many modern microcontrollers use a modified Harvard organization: program flash and data SRAM are physically distinct, but the programmer may see a unified or partially unified address model. Some architectures also provide separate instruction and data caches.

RISC and CISC

Reduced Instruction Set Computer (RISC) designs generally use a relatively regular instruction set, many registers, and instructions that execute efficiently in a pipeline. Complex Instruction Set Computer (CISC) designs provide more elaborate instructions and addressing modes. These labels describe design philosophies rather than absolute performance. A modern processor may combine RISC-like encoding with sophisticated pipelines, caches, and specialized instructions.

CPU Organization

A CPU includes an arithmetic and logic unit (ALU), control unit, registers, and an interface to memory and peripherals. The program counter (PC) contains the address of the next instruction, subject to changes caused by branches, calls, exceptions, and interrupts. The instruction register or equivalent internal logic holds the current instruction during decoding. A status register stores flags such as zero, negative, carry, and overflow.

A load/store architecture performs arithmetic primarily on registers. Memory is accessed explicitly through load and store instructions. Other architectures permit arithmetic instructions to access memory operands directly. In either case, the programmer must understand alignment, data width, privilege rules, and peripheral side effects.

Instruction Execution and Timing

Instruction processing is often described as a fetch–decode–execute sequence. During fetch, the CPU obtains an instruction from program memory using the PC. During decode, it identifies the operation, operands, and addressing mode. During execution, the ALU, registers, memory system, or peripheral interface performs the requested action. The PC is then advanced or replaced by a branch target.

This description is conceptual. Pipelined processors overlap stages, so several instructions may be in different stages simultaneously. A branch, cache miss, wait state, or memory contention can interrupt the ideal flow. Therefore, an instruction's nominal cycle count may not equal its complete execution time in every system.

If a clock frequency is f₍clk₎, the clock period is:

T₍clk₎ = 1 / f₍clk₎

The period is in seconds when frequency is in hertz. If an operation takes N clock cycles under specified memory and pipeline conditions, its ideal duration is:

t = N T₍clk₎ = N / f₍clk₎

For example, at 48 MHz, one clock period is approximately 20.83 ns. A four-cycle operation takes approximately 83.3 ns, assuming no wait states, stalls, or interrupt interference. In real-time design, worst-case execution time is more important than the average time.

Registers, Buses, and Memory Maps

A bus is a collection of signals used to transfer information. The data bus carries values, the address bus identifies locations, and control signals indicate operations such as read, write, byte enable, or interrupt acknowledgment. In modern devices, these may be implemented as internal point-to-point interconnects rather than one shared physical bus, but the logical roles remain useful.

The width of an address bus affects the number of uniquely addressable locations. With A address bits, the number of distinct addresses is 2ᴬ. If each address identifies one byte, the addressable byte capacity is 2ᴬ bytes. This is a theoretical address-space limit; the implemented memory may be smaller and may contain gaps.

A memory map assigns address ranges to physical resources. A typical map may contain flash for program storage, SRAM for variables and stack, and memory-mapped peripheral registers. Reading or writing a peripheral address may initiate an action rather than simply retrieve or store ordinary memory. Some addresses are reserved and must not be accessed.

ResourceTypical roleImportant engineering concern
Flash/ROMProgram and constantsErase/write endurance and programming time
SRAMVariables, buffers, stackVolatility and limited capacity
Peripheral registersConfiguration and statusSide effects and access width
Boot or system memoryStartup and programming supportProtection and recovery behavior
Memory-mapped external deviceExpansion or interfaceTiming, voltage, and bus contention

A 32-bit address field can represent 2³² byte addresses, or 4 GiB, in an abstract byte-addressed space. A particular microcontroller may implement only a fraction of that space and may divide it into regions with different permissions and bus behavior.

Stack Operation and Calling Conventions

The stack is a last-in, first-out (LIFO) memory structure. It stores return addresses, saved registers, function parameters, local variables, and sometimes interrupt context. The stack pointer (SP) identifies the current stack position. On a function call, the processor or software convention saves enough information to return to the caller. On return, that information is restored.

Stacks may grow toward lower addresses or higher addresses, depending on the architecture. The terms full and empty also describe whether SP points to the last occupied item or the next free location. These details must be obtained from the processor manual; they should never be assumed.

An interrupt often causes hardware to save a return address and status information, after which an interrupt service routine (ISR) executes. The ISR must preserve any registers required by the calling convention and clear or acknowledge the interrupt source correctly. Excessive ISR computation can delay other events, so lengthy processing is usually deferred to the main loop or a scheduled task.

Stack overflow occurs when execution uses more stack space than allocated, potentially corrupting variables, return addresses, or control structures. Recursion, large automatic arrays, nested interrupts, and deep call chains increase risk. Stack watermarking, static analysis, and worst-case testing are practical safeguards.

Endianness and Data Layout

Endianness describes the order in which the bytes of a multi-byte value are stored in increasing memory addresses. In little-endian representation, the least significant byte is stored at the lowest address. In big-endian representation, the most significant byte is stored first.

For the 32-bit value 0x12345678, little-endian byte order is 78 56 34 12, whereas big-endian byte order is 12 34 56 78. Endianness does not change the mathematical value; it changes its memory representation. It matters when communicating binary data between processors, interpreting files, mapping peripheral registers, or serializing structures.

Byte order is distinct from bit numbering within a byte. A data sheet may label the least significant bit as bit 0 regardless of physical signal routing. Portable communication software should define field widths, signedness, alignment, padding, and byte order explicitly rather than copying compiler-specific structures blindly.

Interrupts and Exceptions

An interrupt is an event that temporarily diverts the CPU from normal program execution to an interrupt service routine. Sources include timers, received communication data, ADC completion, GPIO transitions, faults, and watchdog events. An interrupt controller commonly provides enable bits, pending flags, priorities, masking, and vector addresses.

The general sequence is:

  1. A peripheral asserts an interrupt request.
  2. The controller determines whether the source is enabled and permitted by priority and masking rules.
  3. The CPU completes or suspends an instruction according to architectural rules.
  4. Context is saved, automatically or by software.
  5. The vector associated with the source identifies the ISR.
  6. The ISR services or acknowledges the source and returns.
  7. Context is restored and normal execution resumes.

Interrupt latency is the time from an event to the start of its service. It depends on instruction completion, disabled-interrupt intervals, higher-priority ISRs, synchronization, vectoring, and memory wait states. Jitter is variation in timing from one event to another. Motor-control and communication applications often require both bounded latency and bounded jitter.

Polling repeatedly checks a status condition in software. It is simple and predictable for slow tasks but can waste CPU time or miss short events. Interrupts improve responsiveness and efficiency but introduce concurrency, priority, reentrancy, and shared-data problems. Shared variables between an ISR and main code should use appropriate atomic access, synchronization, and, where required, volatile qualification. Volatile alone does not make a multi-byte operation atomic.

Related Computing Technologies

TechnologyMain characteristicTypical strengthsTypical limitations
MicrocontrollerCPU, memory, and peripherals on one chipLow cost, low power, deterministic controlLimited computing and memory resources
MicroprocessorPrimarily a high-performance CPU requiring external supportOperating systems, large applications, high performanceGreater power, cost, and system complexity
DSPProcessor optimized for signal-processing operationsFast filtering, transforms, multiply–accumulate operationsLess convenient for general control unless integrated with peripherals
SoCHighly integrated system containing CPU cores and many subsystemsComplex applications, connectivity, graphics, accelerationVerification, software, and power-management complexity
Programmable logicHardware configured to implement parallel logicMassive parallelism, custom interfaces, deterministic pipelinesDesign complexity, configuration resources, and often higher development effort

These categories overlap. A modern SoC may contain microcontroller cores, DSP accelerators, graphics processors, and programmable logic. A microcontroller may include DSP instructions. The correct choice depends on timing, computational workload, interfaces, power, safety, development tools, production volume, and certification requirements.

Applied Case: Illustrative Closed-Loop Conveyor Controller

Background

Consider an illustrative small conveyor system that moves products past a sensor. A brushed DC motor is driven by a pulse-width-modulated power stage. An optical sensor detects products, and a rotary encoder measures shaft speed. The controller must maintain speed, count products, stop safely when a guard opens, and report faults to a supervisory system.

Problem and Analysis

A microprocessor running a large operating system could perform the task, but it would add cost and startup complexity. A small microcontroller is suitable because the workload is modest, timing is important, and timers, capture inputs, PWM, GPIO, and serial communication are needed. The guard input is safety-relevant; software alone may not provide the required safety integrity, so an independent hardware interrupt, motor-enable circuit, emergency stop, and suitable safety design are required.

The encoder generates edges that must be counted accurately. A timer/counter peripheral can count them in hardware, avoiding missed transitions while the CPU performs other work. A periodic timer interrupt can sample speed and execute a control algorithm. The optical sensor can generate an interrupt, while product counting is debounced or validated according to the sensor characteristics.

Approach and Solution

The memory map reserves flash for firmware, SRAM for control variables and communication buffers, and peripheral ranges for timers, GPIO, PWM, ADC, and serial communication. At startup, firmware configures clocks, safe GPIO states, timer modes, interrupt priorities, and watchdog operation before enabling motor drive.

A high-priority guard interrupt immediately disables the motor command and records a fault. A periodic control interrupt reads the encoder count, calculates speed, updates PWM within safe limits, and places a compact status record in a buffer. The main loop handles diagnostics and communication. Shared records are protected by short critical sections or an atomic exchange mechanism.

Outcome and Learning Points

The architecture provides responsive control without requiring a general-purpose computer. Its reliability depends not merely on selecting a processor, but on correct memory access, bounded interrupt behavior, electrical isolation, watchdog recovery, validation of sensor signals, and safe failure states. The case demonstrates that hardware peripherals often provide more deterministic behavior than equivalent software polling.

Design Best Practices, Limitations, and Governance

Read the reference manual, device errata, compiler documentation, and electrical specifications as a coordinated set. Do not infer register behavior from names alone. Use fixed-width integer types when binary widths matter, define peripheral ownership clearly, and document assumptions about clock frequency and timing.

Separate hardware abstraction, device drivers, control logic, and application behavior. Keep ISRs short, measure worst-case timing with suitable instrumentation, and test startup, brownout, reset, communication errors, sensor disconnection, and invalid input conditions. Use watchdogs as recovery mechanisms, not as substitutes for debugging.

Embedded products may collect personal, industrial, or safety-related data. Secure boot, signed firmware, controlled debug ports, least-privilege access, encrypted communication where appropriate, vulnerability management, and traceable updates are increasingly important. Safety and cybersecurity requirements should be addressed during architecture, not added after implementation. Applicable standards depend on the industry and may include functional-safety, medical-device, automotive, industrial, or electromagnetic-compatibility requirements.

Contemporary microcontrollers increasingly include machine-learning accelerators, cryptographic engines, wireless radios, secure enclaves, and real-time operating-system support. These features can improve capability, but they increase configuration and verification complexity. Artificial intelligence at the edge is useful only when its computational cost, data quality, explainability, update process, and failure behavior are acceptable for the application.

Chapter Summary

Embedded systems combine computation with physical processes and must satisfy functional, timing, power, cost, reliability, and sometimes safety constraints. Microcontrollers integrate a CPU, memory, and peripherals for dedicated control applications. Binary and hexadecimal representations support direct reasoning about data, addresses, and registers; two's complement provides a common signed-integer representation.

Digital logic consists of combinational and sequential circuits. The CPU uses registers, an ALU, control logic, buses, and memory interfaces to fetch, decode, and execute instructions. Clock frequency and cycle count provide ideal timing estimates, but pipelines, wait states, interrupts, and memory behavior determine actual performance. Memory maps assign address ranges to flash, SRAM, peripherals, and other resources. Stack behavior supports calls and interrupts, while endianness determines byte order in memory.

Interrupts provide responsive event handling but introduce concurrency and timing concerns. Microcontrollers, microprocessors, DSPs, SoCs, and programmable logic differ in integration, specialization, parallelism, and system complexity; many contemporary devices combine their characteristics. Sound engineering requires reference-manual discipline, measurement, defensive design, security, and consideration of safety and governance.

Key Terms

Microcontroller: An integrated circuit containing a processor, memory, and peripherals for embedded control.

Embedded system: A computer incorporated into a larger product or process for a defined function.

Real-time system: A system whose correctness includes meeting specified timing requirements.

Bit: A binary digit with value 0 or 1.

Byte: A group of eight bits.

Two's complement: A signed-integer representation using bit inversion and addition of one for negative values.

Register: Fast storage inside a CPU or peripheral.

ALU: Arithmetic and logic unit that performs computational operations.

Program counter: Register or state element identifying the next instruction address.

Bus: Logical or physical signals used to transfer data, addresses, and control information.

Memory map: Assignment of address ranges to memory and peripheral resources.

Stack pointer: Register identifying the active position of a LIFO stack.

Endianness: The byte order used to store multi-byte values.

Interrupt: An event that diverts execution to an interrupt service routine.

Interrupt latency: Time between an interrupt event and commencement of its service.

Polling: Repeated software testing of a status condition.

DSP: Digital signal processor optimized for numerical signal-processing workloads.

SoC: System-on-chip integrating multiple computing and peripheral subsystems.

Programmable logic: Configurable hardware used to implement custom digital circuits.

Firmware: Software stored in a device and responsible for its embedded behavior.

Review Questions

Short Answer Questions

  1. What makes an embedded system different from a general-purpose computer?
  1. Why is hexadecimal notation convenient for representing binary data?
  1. What are the principal functions of the program counter and stack pointer?
  1. Define interrupt latency and identify two factors that affect it.
  1. State one important difference between a microcontroller and a microprocessor.

Long Answer Questions

  1. Explain the fetch–decode–execute process and discuss why pipeline and memory effects make simple cycle estimates incomplete.
  1. Compare von Neumann and Harvard architectures, including their effects on memory access and implementation.
  1. Explain memory maps, memory-mapped peripherals, and the engineering risks of treating peripheral registers like ordinary RAM.
  1. Describe stack operation during function calls and interrupts, and discuss causes and prevention of stack overflow.
  1. Compare microcontrollers, DSPs, SoCs, and programmable logic for an industrial control application.

Analytical / Application Questions

  1. A processor operates at 48 MHz and an operation requires four clock cycles under stated ideal conditions. Calculate the ideal execution time and explain why measured time might differ.
  1. Design a high-level interrupt and polling strategy for a conveyor controller with an encoder, emergency stop, product sensor, and serial interface. Justify priorities and identify shared-data risks.
  1. A 32-bit value is stored beginning at address 0x1000 as bytes 78, 56, 34, and 12. Determine whether the storage is little-endian or big-endian for the value 0x12345678, and explain how a communication protocol should specify this issue.

Multiple Choice Questions with Answers

Question 1

Which feature most directly distinguishes a microcontroller from a typical microprocessor?

A. A microcontroller normally integrates memory and peripherals on the same chip.

B. A microcontroller cannot execute stored instructions.

C. A microcontroller always contains a graphical processing unit.

D. A microcontroller requires an external ALU for every operation.

Correct Answer: A. A microcontroller normally integrates memory and peripherals on the same chip.

Question 2

What is the decimal value of 0x2D?

A. 35

B. 45

C. fifty-five

D. 64

Correct Answer: B. 45

Question 3

Which architecture uses separate instruction and data memory paths?

A. Pure von Neumann architecture

B. Harvard architecture

C. Stack-only architecture

D. Polling architecture

Correct Answer: B. Harvard architecture

Question 4

At 48 MHz, what is the approximate duration of an ideal four-cycle operation?

A. 20.8 ns

B. 48 ns

C. 83.3 ns

D. 192 ns

Correct Answer: C. 83.3 ns

Question 5

What is the principal purpose of a memory map?

A. To define the physical size of the CPU package

B. To assign address ranges to memory and peripheral resources

C. To determine the number of logic gates in an ALU

D. To select the processor's programming language

Correct Answer: B. To assign address ranges to memory and peripheral resources

Question 6

Which statement about a stack is correct?

A. It is a first-in, first-out structure used only for flash memory.

B. It is a last-in, first-out structure that can store return addresses and local data.

C. It cannot be used during interrupt handling.

D. Its growth direction is identical on every processor.

Correct Answer: B. It is a last-in, first-out structure that can store return addresses and local data.

Question 7

For the value 0x12345678, which byte sequence represents little-endian storage from the lowest address?

A. 12 34 56 78

B. 78 56 34 12

C. 21 43 65 87

D. 87 65 43 21

Correct Answer: B. 78 56 34 12

Question 8

Which statement best describes an interrupt?

A. A permanent replacement of the main program

B. An event that can divert execution to a service routine

C. A method for increasing flash capacity

D. A Boolean gate with four inputs

Correct Answer: B. An event that can divert execution to a service routine

Question 9

Why is a hardware timer often preferable to software polling for counting rapid encoder transitions?

A. It can count events in hardware while the CPU performs other work.

B. It eliminates the need for electrical signal conditioning in all cases.

C. It converts every encoder signal into an analog voltage.

D. It guarantees that mechanical noise is impossible.

Correct Answer: A. It can count events in hardware while the CPU performs other work.

Question 10

Which technology is primarily optimized for implementing custom parallel digital hardware?

A. Programmable logic

B. A conventional hard disk

C. A linear voltage regulator

D. A passive sensor

Correct Answer: A. Programmable logic

Microcontrollers and Interfacing
Chapter 1 of 14