UNIT 3: Microcontroller & Embedded System
I. Embedded System Fundamentals
Definition and Core Concept
An embedded system is a dedicated computer system designed to perform specific control functions within a larger mechanical or electrical system. It is typically embedded as an integral part of the device.
Key Distinction from General-Purpose Computing:
- Embedded System: Single-purpose, resource-constrained, real-time, often reactive to environment. Example: Microwave oven controller.
- General-Purpose System: Multi-purpose, high resources (CPU, memory, I/O), user-programmable for diverse tasks. Example: Desktop PC.
Characteristics of Embedded Systems
-
Single-functioned: Executes a specific program repeatedly.
-
Tightly constrained: Limited by cost, size, power, performance.
-
Reactive & Real-time: Must respond to external events within strict deadlines (hard/soft real-time).
-
Often operates in harsh environments.
-
Low power consumption is critical for battery-operated devices.
-
No standard user interface (often no keyboard/monitor).
Quality Attributes (Non-Functional Requirements)
| Attribute | Description | Example Metric |
|---|---|---|
| Reliability | Probability of failure-free operation over time. | MTBF (Mean Time Between Failures) |
| Real-time Performance | Ability to meet task deadlines. | Worst-case execution time (WCET) |
| Power Efficiency | Energy consumed per operation. | mW/MIPS, battery life |
| Cost | Total manufacturing cost. | Bill of Materials (BOM) cost |
| Size | Physical footprint. | PCB area, volume |
| Memory | On-chip/off-chip storage capacity. | ROM (KB), RAM (KB) |
Design Metrics (Quantifiable Goals)
Primary trade-offs exist between:
-
Performance (MIPS, MHz)
-
Power (mW)
-
Cost (USD)
-
Size (mm²)
-
Memory (KB)
Classification Based on Performance & Complexity
| Class | Complexity | Performance | Typical Clock | Example Applications |
|---|---|---|---|---|
| Small-Scale | 8-bit MCU | Low | < 20 MHz | Remote controls, toys, sensors |
| Medium-Scale | 16/32-bit MCU, low-end DSP | Medium | 20-200 MHz | Automotive (ECU), industrial controllers, mobile phones |
| Large-Scale | 32-bit RISC, high-end DSP, SoC, multi-core | High | > 200 MHz | Networking routers, set-top boxes, advanced multimedia, aerospace |
Major Application Areas
-
Automotive: Engine control, ABS, airbags, infotainment.
-
Consumer Electronics: TVs, cameras, washing machines, wearables.
-
Industrial: PLCs, robotics, process control, instrumentation.
-
Telecom: Switches, routers, modems, mobile phones.
-
Aerospace & Defense: Flight control, radar, missile guidance.
-
Medical: Pacemakers, imaging systems, patient monitors.
II. 8051 Microcontroller
A. Timer/Counter Operations
Core Concept: Two independent 16-bit timers/counters (Timer 0, Timer 1). Can be configured in 4 modes.
-
Mode 0 (13-bit): Legacy mode, THx holds upper 8 bits, TLx holds lower 5 bits.
-
Mode 1 (16-bit): Full 16-bit timer/counter (THx:TLx as 16-bit register). Most common.
-
Mode 2 (8-bit auto-reload): TLx holds count, THx holds reload value. Used for baud rate generation.
-
Mode 3 (Split Timer): Timer 0 splits into two 8-bit timers; Timer 1 stops (can be used as baud rate generator).
Programming Timer 0 in Mode 1 for Square Wave Generation (11.0592 MHz Crystal):
Goal: Generate 1 kHz square wave on P2.3.
Formula:
Frequency = Crystal Freq / (12 * (65536 - TH0_TL0))
- Calculate reload value:
TH0_TL0 = 65536 - (11059200 / (12 * 1000)) = 65536 - 921.6 ≈ 64574 = 0xFC66.
- Initialize TMOD:
TMOD = 0x01(Timer0 Mode1).
- Load TH0, TL0:
TH0 = 0xFC; TL0 = 0x66;.
- Start timer:
TCON = 0x10(TR0=1).
- Toggle P2.3 in ISR (TF0 interrupt) or poll TF0 flag.
B. Serial Communication
Modes of Operation (SCON register bits SM0, SM1):
| Mode | SM0 | SM1 | Description | Baud Rate |
|---|---|---|---|---|
| 0 | 0 | 0 | Shift Register (UART mode) | Fixed = fosc/12 |
| 1 | 0 | 1 | 8-bit UART, variable baud | Timer1 overflow / 32 |
| 2 | 1 | 0 | 9-bit UART, fixed baud | fosc/64 or /32 |
| 3 | 1 | 1 | 9-bit UART, variable baud | Timer1 overflow / 32 |
Detailed Comparison: Mode 1 vs Mode 3
| Feature | Mode 1 (8-bit UART) | Mode 3 (9-bit UART) |
|---|---|---|
| Data Bits | 8 | 9 (TB8/RB8 used as 9th bit) |
| Start/Stop | 1 start, 1 stop | 1 start, 1 stop |
| Baud Rate Source | Timer1 overflow rate / 32 | Timer1 overflow rate / 32 |
| TB8/RB8 | Not used (set to 0) | Used for address/data identification or parity |
| Typical Application | Standard asynchronous serial comms (e.g., PC link) | Multi-processor communication, address byte recognition |
Programming Serial Transmission in Embedded C (Mode 1, 11.0592 MHz, 9600 baud):
#include <reg51.h>
void serial_init() {
SCON = 0x50; // 8-bit UART, enable receiver
TMOD &= 0x0F; // Clear Timer1 bits
TMOD |= 0x20; // Timer1 Mode2 (8-bit auto-reload)
TH1 = 0xFD; // Reload value for 9600 baud @ 11.0592MHz
TL1 = 0xFD;
TR1 = 1; // Start Timer1
TI = 0; // Clear transmit flag
}
void serial_tx_char(char c) {
SBUF = c;
while(!TI); // Wait for transmission complete
TI = 0;
}
void main() {
serial_init();
serial_tx_char('H');
serial_tx_char('E');
serial_tx_char('L');
serial_tx_char('L');
serial_tx_char('O');
while(1);
}
C. Interfacing and Applications
1. DAC Interfacing (e.g., DAC0800)
-
Circuit: 8051 P0 (8-bit data) → DAC0800 inputs. DAC reference voltage (Vref) sets output range. Output current
Iout = (D/256) * (Vref/ R). Requires current-to-voltage op-amp converter at output. -
Timing Diagram: Data valid →
CS&WRlow pulse (min 500ns) → analog output settles. -
Application: Waveform generation (sine, square), analog control signals, audio output.
2. Stepper Motor Interfacing
-
Circuit: 8051 port pins → Driver IC (e.g., ULN2003/ULN2803) → Stepper motor coils (4-phase or 2-phase).
-
Sequence: Full-step (4-phase sequence) or Half-step (8-phase sequence) pulses generated by software delay loops.
-
Control: Speed by delay between steps, direction by sequence order.
-
Application: Printers, plotters, CNC machines, robotics.
3. Design of 8051-based Data Acquisition System (DAS)
Block Diagram & Components:
-
Sensor/Transducer: Converts physical parameter (temp, pressure) to analog signal.
-
Signal Conditioning: Amplifier, filter (anti-aliasing) to bring signal to ADC range.
-
Analog-to-Digital Converter (ADC): e.g., ADC0804 (8-bit). Controlled by 8051
WR,RD,CSpins. -
8051 Microcontroller: Controls ADC start, reads data, processes, stores.
-
Memory: External EEPROM/Flash for data logging.
-
Display/Output: LCD (via P0/P2) or serial to PC.
-
Power Supply: Regulated 5V for MCU & logic, isolated supply for analog front-end.
Operation: MCU triggers ADC → waits for conversion → reads digital data → processes (calibration, scaling) → stores/displays.
III. 8096 Microcontroller
A. Architecture and Overview
Functional Block Diagram Explanation:
-
CPU (16-bit): Central processing unit with 16-bit data bus & ALU.
-
Register ALU (RAL): High-speed arithmetic unit for multiply/divide.
-
Memory Interface: Generates control signals for external memory.
-
I/O Ports: 4 x 8-bit parallel ports (P0-P3), multiplexed with address/data bus.
-
Timer/Counter: 16-bit timer with 4 modes, event counter.
-
Serial Port: Full-duplex UART.
-
A/D Converter: 10-bit, 8-channel multiplexed ADC.
-
Watchdog Timer: For system recovery.
-
High-Speed I/O Section: Special pins for PWM, pulse measurement.
-
Interrupt Controller: 5 interrupt sources with priority.
Superiority over 8051:
-
16-bit data path & ALU vs 8-bit → faster arithmetic.
-
On-chip 10-bit ADC (8051 requires external ADC).
-
Register ALU (RAL) for fast 16x16 multiply/divide in 3.5-7 µs.
-
More I/O pins (40-pin vs 8051's 40-pin but more multiplexing options).
-
Enhanced timer with capture/compare.
-
Higher clock speed (up to 12 MHz vs 8051's 12-24 MHz typical).
-
More memory address space (64KB data, 64KB program).
B. Registers and I/O
Control and Status Register (CSR)
-
Function: Controls I/O port modes (input/output), serial port mode, and indicates status of interrupts, A/D conversion.
-
Key Bits:
-
PORT-MODEbits (PM0-PM3): Configure P0-P3 as I/O or address/data bus. -
SERIAL-MODEbits (SM0, SM1): UART mode select. -
A/D CONVERSION COMPLETEflag. -
TIMER OVERFLOWflag. -
INTERRUPT PENDINGbits.
-
I/O Ports Structure
-
P0-P3: 8-bit ports. Function determined by CSR
PMbits.-
PMx = 0: Port acts as I/O (quasi-bidirectional like 8051). -
PMx = 1: Port used for address/data bus multiplexing (external memory access).
-
-
Operation: Writing
1to port bit makes it input (high-impedance). Writing0drives low.
Register ALU (RAL)
-
Significance: Dedicated hardware for 16x16 multiplication and 32/16 division.
-
Operation: Uses registers
R0(multiplicand),R1(multiplier),R2(product high),R3(product low).MPY&DIVinstructions execute in fixed cycles (~3.5-7 µs at 12 MHz), much faster than software loops on 8051. -
Overflow:
DIVinstruction causes software trap if divisor is zero or result > 16 bits.
C. Memory Organization
-
Separate Program & Data Spaces: Harvard-like but can be unified.
-
Address Spaces:
-
64KB Program Memory (PMEM): Addresses 0000H-FFFFH. Can be internal ROM/EPROM or external.
-
64KB Data Memory (DMEM): Addresses 0000H-FFFFH. Internal RAM (256 bytes) + external.
-
-
Internal RAM (256 bytes):
-
00H-7FH: General-purpose registers, bit-addressable area.
-
80H-FFH: Special Function Registers (SFRs) including ports, timer, CSR, etc.
-
-
External Memory: Accessed via multiplexed P0/P1 bus when
PMx=1.
D. Addressing Modes (with Code Examples)
| Mode | Syntax | Description | Example |
|---|---|---|---|
| Immediate | LD R1, #05H |
Operand is immediate data. | LD R1, #0FFH |
| Direct | LD R1, 0200H |
Operand address in instruction. | LD R1, CSR |
| Register | ADD R1, R2 |
Operand in register. | INC R1 |
| Register Indirect | LD R1, @R2 |
Address in register (R2/R3/R4/R5). | LD R1, @R2 |
| Indexed | LD R1, 0200H[R2] |
Effective address = Base + Index. | JMP 1000H[R4] |
| Relative | JBC R1, LABEL |
PC-relative jump for branches. | JBS R1, LOOP |
Analysis of Past Paper Code:
LD R1, #05H ; R1 = 0x0005 (Immediate)
LD R2, #03H ; R2 = 0x0003 (Immediate)
MPY R1, R2 ; R1 = R1 * R2 = 0x0005 * 0x0003 = 0x000F (R2:R1 = 32-bit product)
ST R1, 0200H ; Store R1 (0x000F) at memory 0200H
i) Value at 0200H: 0x000F (15 decimal).
ii) If MPY replaced by DIV: DIV R1, R2 → R1 = R1 / R2 = 5 / 3 = 1 (quotient), R2 = remainder = 2. Store would be 0x0001.
iii) Overflow Risk in DIV: Yes. If divisor (R2) is zero → software trap (non-maskable interrupt). If dividend > 0xFFFF (16-bit) → quotient > 16 bits → overflow flag set and result undefined.
E. Instruction Set Classification
| Category | Purpose | Example Instructions |
|---|---|---|
| Data Transfer | Move data between registers/memory. | LD, ST, PUSH, POP, LDB, STB |
| Arithmetic | Math operations. | ADD, SUB, MPY, DIV, INCR, DECR |
| Logical | Bitwise operations. | AND, OR, XOR, NOT, TEST |
| Branch | Program flow control. | JMP, JBC, JBS, JZ, JNZ, CALL, RET |
| Control | CPU & system control. | NOP, DI, EI, SINGLE, SINGLE |
IV. Processor Architectures for Embedded Systems
A. Architecture Types
Von Neumann vs Harvard
| Feature | Von Neumann | Harvard |
|---|---|---|
| Memory Structure | Single memory for data & instructions. | Separate memories for data & instructions. |
| Bus Structure | Single bus for both data & instructions. | Two separate buses (data & instruction). |
| Performance | Bottleneck: Can't fetch instruction & data simultaneously. | Higher: Simultaneous fetch of instruction & data. |
| Complexity/Cost | Simpler, cheaper. | More complex, costlier. |
| Implication | Simpler programming model. | Used in modern MCUs/DSPs for speed (e.g., ARM, PIC, 8096 uses modified Harvard). |
| Example | Intel x86 (early), 8051 (modified). | ARM Cortex-M, PIC, DSPs (e.g., TI C5000). |
RISC vs CISC
| Feature | RISC (Reduced Instruction Set Computer) | CISC (Complex Instruction Set Computer) |
|---|---|---|
| Instruction Set | Small, simple, fixed-length. | Large, complex, variable-length. |
| Instructions/ Cycle | 1 (most). | Many (1+). |
| Registers | Many general-purpose registers (16-32). | Fewer, specialized. |
| Memory Access | Load/Store architecture (only load/store access memory). | Memory access allowed in many instructions. |
| Pipelining | Easy, highly pipelined. | Harder, complex. |
| Control Unit | Hardwired (fast). | Microcoded (flexible). |
| Code Density | Lower (larger code size). | Higher (smaller code size). |
| Examples | ARM, MIPS, RISC-V, PIC, AVR. | x86, 8051, 8096. |
B. Specific Processors
ARM Processor Architecture
-
RISC Features: Load/Store architecture, fixed 32-bit (ARM state) or 16-bit (Thumb state) instructions, large register file (R0-R15), conditional execution.
-
Pipeline: Classic 3-stage (fetch, decode, execute) or advanced (e.g., ARM7: 3-stage, ARM9: 5-stage).
-
Use in Mobile: Dominant due to power efficiency, high performance/Watt, licensable core (SoC integration), extensive ecosystem. Found in >95% of smartphones.
DSP Processors (Digital Signal Processors)
-
Role: Optimized for high-speed numeric processing, especially multiply-accumulate (MAC) operations on streaming data (audio, video, telecom).
-
Special Features vs GPP:
-
Harvard Architecture: Separate program/data buses → simultaneous instruction/data fetch.
-
Deep Pipelines: 6-10 stages for high clock rates.
-
Hardware MAC Unit: Single-cycle multiply-accumulate.
-
Zero-Overhead Looping: Hardware support for repetitive DSP algorithms.
-
Special Addressing Modes: Bit-reversed, circular buffering for FFT.
-
Fixed-Point Arithmetic: Native support, fast.
-
-
Example: TI TMS320C5000 (C55x), ADI SHARC, Freescale (NXP) DSP56k.
C. Processor Classifications & Selection Criteria
| Type | Description | When to Use | Example |
|---|---|---|---|
| GPP | General-purpose, programmable for many tasks. | Complex control, varied I/O, need OS (Linux, RTOS). | ARM Cortex-A, x86, 8051. |
| ASP | Optimized for a specific application class. | High-volume, performance-critical, cost-sensitive. | Network processor, GPU, DSP. |
| SPP | Hardwired for a single function. | Ultra-high speed, lowest power, simplest. | ASIC for MPEG decode, UART chip. |
16-bit PIC & 32-bit dsPIC (Microchip):
-
16-bit PIC (e.g., PIC24): 16-bit data path, RISC, rich peripherals (ADC, PWM, CAN), low power. Apps: Industrial control, consumer, automotive body.
-
32-bit dsPIC: Combines 16-bit DSP engine (MAC, barrel shifter) with PIC24 MCU core. Apps: Motor control (FOC), digital power, audio processing.
V. Peripheral Interfaces and Controllers
A. Watchdog Timer (WDT)
-
Operation: Independent timer that must be periodically "kicked" (reset) by software. If software hangs (fails to kick), WDT times out and generates a reset or interrupt to recover system.
-
Timing Diagram:
Software Kick ----> WDT Reset ----> (Timeout Period) ----> Reset/Interrupt -
Role in Reliability: Fault detection & automatic recovery from software lock-ups, electromagnetic interference (EMI) glitches. Critical in safety-critical systems (automotive, medical).
-
Implementation: Can use a regular timer/counter with a long timeout, configured to trigger system reset on overflow. Software writes a specific sequence to a control register to clear it.
B. Keyboard Controller (8279)
Internal Block Diagram & Explanation:
-
Keyboard Section: Scans matrix (e.g., 8x8) for key closures. Debounces in hardware/software. Encodes key position to scan code.
-
Display Section: Drives multiplexed LED/LCD displays (up to 16 digits/segments). Stores display RAM.
-
FIFO (8-byte): Stores key codes (with shift/control status). CPU reads via data bus.
-
Control Unit: Registers for mode setting (encoded/decoded, scan rate), interrupt generation on FIFO not empty/not full.
Key-Press Scanning (Matrix Scanning):
-
Drive one row line low (others high).
-
Read column lines. Low on any column → key pressed at (row, column).
-
Repeat for all rows.
-
Debouncing: Hardware (RC filter) or software (sample key state multiple times over 10-20ms).
Processing Key Codes & Modes:
-
Encoded Mode: 8279 returns scan code (row+col). CPU needs lookup table for ASCII.
-
Decoded Mode: 8279 returns ASCII code directly (requires 8279 to be programmed with key map). Simpler for CPU.
C. Interrupt Controllers
Functional Block Diagram & Explanation:
-
Purpose: Manage multiple interrupt sources, prioritize, and present single interrupt line to CPU.
-
Blocks:
-
Interrupt Request (IRQ) Lines: Inputs from peripherals.
-
Priority Encoder: Determines highest priority pending interrupt.
-
Interrupt Service Register (ISR): Bits set when IRQ active, cleared by CPU on ISR entry.
-
Interrupt Mask Register (IMR): Masks (disables) specific interrupts.
-
Cascade Buffer: For cascading multiple controllers (e.g., 8259A).
-
Interrupt Output: Single
INTline to CPU.
-
Types of Interrupts & Microprocessor Interface:
| Type | Source | Generation | CPU Handling |
|---|---|---|---|
| Hardware | External pin (e.g., INT0, INT1). |
External device signals. | CPU finishes current instruction, pushes PC/PSW, jumps to ISR address (from vector table or controller). |
| Software | INT instruction. |
Program execution. | Same as hardware, but triggered by software. Used for system calls. |
| Trap/Exception | Internal CPU events. | Divide-by-zero, invalid opcode, NMI. | Highest priority, non-maskable (NMI) or maskable. CPU handles immediately. |
How CPU Checks: After each instruction cycle, CPU checks interrupt flags (in status register) and interrupt controller's output. If enabled and pending, it initiates interrupt acknowledge cycle.
D. Serial Communication Standards: RS-232
-
Role: Standard for serial binary data exchange between DTE (Data Terminal Equipment, e.g., PC) and DCE (Data Circuit-terminating Equipment, e.g., modem).
-
Voltage Levels: Mark (logic 1): -3V to -15V. Space (logic 0): +3V to +15V. (Inverted, opposite of TTL/CMOS).
-
Main Signals:
-
TXD (Transmit Data): DTE → DCE.
-
RXD (Receive Data): DTE ← DCE.
-
RTS (Request To Send): DTE → DCE, requests permission to send.
-
CTS (Clear To Send): DCE → DTE, grants permission.
-
DTR (Data Terminal Ready): DTE → DCE, DTE is powered on.
-
DSR (Data Set Ready): DCE → DTE, DCE is powered on.
-
GND: Signal ground.
-
Handshaking Signals Purpose:
-
Hardware Flow Control: Uses RTS/CTS to prevent data overflow. DTE asserts RTS when its buffer has space; DCE asserts CTS when it can receive.
-
Modem Control: DTR/DSR indicate modem readiness. DCD (Data Carrier Detect) indicates carrier signal from remote modem.
E. Other Peripherals
Real-Time Clock (RTC)
-
Functionality: Keeps track of current time (seconds, minutes, hours, date, month, year) independently of main CPU. Often battery-backed (CMOS RAM + crystal).
-
Interfacing: Typically via I²C (e.g., DS1307) or SPI serial bus. MCU reads/writes time/date registers and configures alarm/interrupt.
-
Application: Data logging with timestamp, scheduled events, time-sensitive control.
Exam Tips & Common Pitfalls:
- 8051 Timer Mode 1: Always remember reload value = 65536 - (Crystal/(12 * Desired_Freq)). For 1kHz @ 11.0592MHz, it's 64574 (0xFC66).
- 8096 MPY/DIV:
MPYstores 32-bit product in R2:R1.DIVquotient in R1, remainder in R2. DIV by zero causes trap.
- RS-232 Voltage: Negative = logic 1, Positive = logic 0. NOT TTL compatible – requires MAX232 level shifter.
- Watchdog: Must be "kicked" periodically in main loop. If ISR takes too long, WDT may expire – place
kickin main loop, not ISR.
- Harvard vs Von Neumann: Key is separate vs unified memory/buses. Most modern MCUs are Modified Harvard (separate buses but can access program memory as data).
- RISC vs CISC: RISC = simple, load/store, many regs, pipelined. CISC = complex, memory access in many instructions, variable length.
- 8279 Modes: Encoded = scan code (CPU decodes). Decoded = ASCII (8279 decodes).