UNIT 5: ADVANCED PERIPHERALS & EMBEDDED COMMUNICATION
5.1 Serial Communication Interfaces
5.1.1 UART (Universal Asynchronous Receiver/Transmitter)
-
Theory: Asynchronous, full-duplex serial communication. No shared clock line. Data framed with 1 start bit (0), 5-9 data bits, optional parity bit, and 1 or 2 stop bits (1).
-
Baud Rate: Symbol rate (bits/sec). Must match at both ends. Generated from system clock using a divisor.
- 8051 Baud Rate Formula (Mode 1, 2, 3):
$$ \text{Baud Rate} = \frac{2^{SMOD} \times \text{OSC Freq}}{32 \times \text{Timer 1 Overflow Rate}} $$
For Timer 1 in mode 2 (auto-reload):
$$ \text{TH1} = 256 - \frac{\text{OSC Freq}}{384 \times \text{Baud Rate}} \quad (\text{SMOD}=0) $$
* **Common Pitfall:** SMOD bit (PCON.7) doubles baud rate when set.
-
Key Registers (8051):
-
SBUF: Serial Data Buffer (read for RX, write for TX).
-
SCON: Serial Control Register (defines mode, enables RX/TX, RI/TI flags).
-
PCON: Power Control Register (holds SMOD bit).
-
-
Programming Flow:
-
Initialize SCON (set mode, enable serial interrupt if used).
-
Initialize Timer 1 for baud rate (set TH1, start Timer).
-
Transmit: Write byte to
SBUF. PollTIflag or wait for TX interrupt. ClearTIafter transmission. -
Receive: Poll
RIflag or wait for RX interrupt. Read byte fromSBUF. ClearRIafter reading.
-
-
Lab Experiment: Serial Echo. MCU receives a character from PC (via UART-USB converter), sends it back. Verifies bidirectional link.
[!TIP] UART uses two wires (TX, RX) plus GND. It's ideal for long-distance, low-to-medium speed communication with PCs, GPS modules, or other MCUs.
5.1.2 SPI (Serial Peripheral Interface)
-
Theory: Synchronous, full-duplex, master-slave protocol. 4 wires: SCK (clock from master), MOSI (Master Out Slave In), MISO (Master In Slave Out), SS/CS (Slave Select, active low).
-
Clock Modes (CPOL, CPHA):
| CPOL | CPHA | Data Sampled On | Clock Idle | | :--- | :--- | :--- | :--- | | 0 | 0 | Rising edge | Low | | 0 | 1 | Falling edge | Low | | 1 | 0 | Falling edge | High | | 1 | 1 | Rising edge | High |
-
Key Registers (AVR/ARM examples):
-
SPCR: SPI Control Register (enable SPI, set master/slave, clock rate, CPOL/CPHA).
-
SPSR: SPI Status Register (SPIF flag, write collision).
-
SPDR: SPI Data Register (read/write byte).
-
-
Programming (Master Mode):
-
Configure SCK, MOSI, SS as outputs; MISO as input.
-
Set SPCR (enable SPI, master, clock rate, mode).
-
Transmit Byte: Write to
SPDR. Wait forSPIFflag inSPSR. ReadSPDR(dummy read for received byte). -
Receive Byte: Write dummy (0xFF) to
SPDRto generate clocks. Wait forSPIF. ReadSPDR.
-
-
Lab Experiment: Serial EEPROM (25LC1024) Interface. Send write enable command, then write data to specific address. Read back by sending read command + address. Verify data integrity.
[!TIP] SPI is full-duplex and fastest among common protocols. Use for short-distance, high-speed communication with sensors, EEPROMs, display drivers. SS line must be managed carefully to avoid bus contention.
5.1.3 I²C (Inter-Integrated Circuit)
-
Theory: Synchronous, multi-master/multi-slave, 2-wire (SDA data, SCL clock). Uses 7-bit or 10-bit addressing. Open-drain lines require pull-up resistors.
-
Frame Format:
-
START Condition (S): SDA falls while SCL high.
-
Slave Address + R/W bit: 7-bit address + 1-bit read(1)/write(0).
-
ACK/NACK: Receiver pulls SDA low during 9th clock pulse (ACK). High = NACK.
-
Data Byte(s): 8 bits, each followed by ACK.
-
STOP Condition (P): SDA rises while SCL high.
-
-
Key Registers (e.g., PIC18, LPC1768):
-
I2CxCR: Control Register (enable, start/stop, ACK, interrupt).
-
I2CxSR: Status Register (holds status code, BF, ACKSTAT flags).
-
I2CxDR: Data Register (read/write byte).
-
-
Programming (Master Transmitter to Slave):
-
Generate START condition.
-
Send Slave Address + W(0). Check for ACK from slave.
-
Send Data Byte(s). Check for ACK after each.
-
Generate STOP condition.
-
-
Lab Experiment: RTC (DS1307) or Temp Sensor (LM75) Read. Generate START, send slave write address, send register pointer, generate repeated START, send slave read address, read data byte(s), generate STOP. Display time/temperature on LCD/Serial.
[!TIP] I²C is address-based, allowing many devices on 2 wires. It's slower than SPI but uses fewer pins. Always check ACK after each byte to detect bus errors or missing slaves.
5.1.4 Comparison & Selection Criteria
| Feature | UART | SPI | I²C |
|---|---|---|---|
| Type | Asynchronous | Synchronous | Synchronous |
| Wires | 2 (TX, RX) + GND | 4 (SCK, MOSI, MISO, SS) | 2 (SDA, SCL) + GND |
| Duplex | Full | Full | Half (per transfer) |
| Topology | Point-to-Point | Master-Slave (1:many with SS) | Multi-Master/Slave (1:many) |
| Addressing | No | No (hardware SS) | Yes (7/10-bit) |
| Speed | Low-Medium (kbps-Mbps) | High (Mbps) | Medium (100kHz-3.4MHz) |
| Distance | Long (meters) | Short (cm) | Short-Medium |
| Complexity | Low | Low | Medium-High |
Selection Rule of Thumb:
-
PC link, GPS, long cable: UART
-
High-speed sensor/EEPROM, same PCB: SPI
-
Multiple sensors/EEPROMs on same 2 wires, moderate speed: I²C
5.2 Analog Output & Pulse Generation
5.2.1 DAC (Digital-to-Analog Converter)
-
Theory: Converts a digital binary number into a proportional analog voltage/current.
-
Resolution: Number of bits (n). $$\displaystyle 2^n $$ discrete levels.
-
Reference Voltage ($$\displaystyle V_{ref} $$): Sets full-scale output. $$\displaystyle V_{out} = \frac{D}{2^n - 1} \times V_{ref} $$ (for unipolar).
-
-
Interfacing (External DAC0808):
-
Parallel 8-bit data input (D0-D7).
-
Control pins: CS (Chip Select), WR (Write).
-
Output: Current ($$\displaystyle I_{out} $$). Requires I-to-V converter (op-amp) for voltage output.
-
-
Programming: Set data pins (PORTx), pulse WR low then high. Update value to generate waveforms.
-
Lab Experiment: Variable DC Voltage. Use potentiometer (via ADC) to set digital value, DAC converts to analog voltage. Measure with multimeter.
5.2.2 PWM (Pulse Width Modulation)
-
Theory: Digital technique to create analog-like output using a digital pin switching ON/OFF rapidly.
-
Frequency ($$\displaystyle f_{pwm} $$): $$\displaystyle f_{pwm} = \frac{F_{timer}}{Prescaler \times (PRx + 1)} $$
-
Duty Cycle (%): $$\displaystyle \frac{T_{ON}}{T_{ON} + T_{OFF}} \times 100\% $$
-
Average Voltage: $$\displaystyle V_{avg} = DutyCycle \times V_{dd} $$
-
-
Generation (Using Timer/Counter in PWM Mode):
-
Configure Timer for PWM mode (e.g., Timer2 in PIC, PWM mode in CCP module).
-
Set PRx register for period (frequency).
-
Set CCPRxL (and possibly CCPxCON<5:4>) for pulse width (duty cycle).
-
Enable PWM output pin.
-
-
Key Registers (PIC18):
-
T2CON: Timer2 Control (on, prescaler, postscaler).
-
PR2: Timer2 Period Register.
-
CCPxCON: CCP Control (PWM mode select).
-
CCPRxL: CCP Register LSB (duty cycle MSB).
-
-
Lab Experiment: LED Dimming / DC Motor Speed Control. Connect LED/motor driver (L293D) to PWM pin. Vary duty cycle using a potentiometer read by ADC. Observe brightness/speed change.
[!TIP] PWM is preferred over DAC for motor/LED control because it's more efficient (switching device, not linear) and uses built-in timer hardware. Frequency must be high enough (>~100Hz for LEDs, >~1kHz for motors) to avoid flicker/audible noise.
5.3 System Reliability & Management
5.3.1 Watchdog Timer (WDT)
-
Theory: Independent hardware timer that resets the MCU if not periodically "kicked" (cleared) by software. Recovers from software hangs, infinite loops, crashes.
-
Operation:
-
WDT is enabled (often via configuration bits or a register).
-
It increments a counter with a fixed time-out period (e.g., 2ms to 2s).
-
Software must execute a "CLRWDT" (Clear Watchdog Timer) instruction before the counter overflows.
-
If overflow occurs, WDT generates a reset.
-
-
Programming Pattern:
void main(void) { // Init code while(1) { // 1. Do critical task A // 2. Do critical task B CLRWDT(); // <-- FEED THE DOG HERE } }Critical: Place
CLRWDT()in all possible code paths, including interrupt service routines (ISRs) if they can be long. -
Lab Experiment: WDT Reset Demonstration. Write a program that feeds WDT normally. Add a conditional (e.g., if a button is pressed) that stops feeding. Press button, observe MCU reset (blink LED pattern restarts). Measure time between reset using oscilloscope/timer.
[!TIP] Never disable WDT in final production code unless absolutely necessary. A common pitfall is placing
CLRWDT()only in the main loop, forgetting long ISRs or blocking delays can cause timeout.
5.4 Advanced Interfacing & Applications
5.4.1 LCD Interfacing (HD44780 compatible, 4-bit mode)
-
Theory: Character LCD (16x2, 20x4). Controller: HD44780. 4-bit mode uses only D4-D7 (saves 4 I/O pins).
-
Pin Connections (4-bit):
-
RS (Register Select): 0=Command, 1=Data.
-
RW (Read/Write): 0=Write, 1=Read (usually tied to GND for write-only).
-
E (Enable): Falling edge triggers read/write.
-
D4-D7: 4-bit data.
-
-
Initialization Sequence (4-bit, after power-on delay):
-
Set D4-D7 as outputs. Wait >15ms.
-
Send
0x30(8-bit mode) -> wait >4.1ms. -
Send
0x30again -> wait >100µs. -
Send
0x30again -> wait >40µs. -
Send
0x20(set 4-bit mode). -
Now send upper nibble first, then lower nibble for each command/data byte.
-
-
Programming Functions:
-
LCD_Command(uint8_t cmd): Send command (RS=0). -
LCD_Data(uint8_t dat): Send data/char (RS=1). -
LCD_Init(): Run initialization sequence. -
LCD_String(char *str): Loop sending characters.
-
-
Lab Experiment: Sensor Value Display. Read ADC channel (potentiometer), convert to string, display voltage/temperature on LCD with rolling message.
5.4.2 Matrix Keypad Interfacing
-
Theory: Row-Column Scanning reduces I/O pins. For 4x4 keypad: 4 rows (outputs), 4 columns (inputs with pull-up).
-
Scanning Algorithm:
-
Set all rows high (or low, depending on design). Read columns to check for any key press (all should be high if no press).
-
To scan: Set one row low (others high). Read all columns.
-
If a column reads low, key at intersection (current row, that column) is pressed.
-
Debounce: Wait ~10-20ms, re-check to confirm.
-
Repeat for all rows.
-
-
Key Decoding: Map (row, col) to keycode (e.g., row0-col0 = '1', row0-col1 = '2'...).
-
Circuit: Columns connected to MCU pins with internal/external pull-up resistors. Rows connected to MCU output pins.
-
Lab Experiment: Password Entry System. 4x4 keypad + LCD. User enters 4-digit code. Compare with stored password. Correct -> "Access Granted" on LCD; Wrong -> "Access Denied".
5.4.3 Relay & Motor Interfacing (with Driver ICs)
-
Theory: MCU I/O pins cannot source/sink high current/voltage. Driver ICs provide isolation and power.
-
ULN2003/ULN2803: Darlington pair array. For relays, solenoids, stepper motors (up to 500mA/channel). Has built-in flyback diodes.
-
L293D / L298N: Dual H-bridge driver. For DC motor direction/speed control and stepper motors. Controls both direction (via H-bridge) and speed (via PWM enable pin).
-
-
Circuit (DC Motor with L293D):
-
MCU Pin -> L293D Input 1.
-
MCU PWM Pin -> L293D Enable 1 (for speed).
-
L293D Output 1/2 -> Motor terminals.
-
L293D Vss (logic) -> MCU Vcc (5V).
-
L293D Vs (motor) -> External motor supply (e.g., 9V).
-
-
Programming (L293D):
-
Direction: Set two input pins (IN1, IN2):
(1,0)= Forward,(0,1)= Reverse,(0,0)or(1,1)= Brake/Coast. -
Speed: Apply PWM signal to Enable pin (ENA). Duty cycle controls average voltage/speed.
-
-
Lab Experiment: Keypad-Controlled Motor. Use keypad (5.4.2) to select direction (F/R) and speed level (1-5). Display status on LCD (5.4.1). Use PWM (5.2.2) and L293D driver.
[!TIP] Always connect flyback diodes (across inductive loads like relays/motors) to protect driver ICs from voltage spikes. Never connect motor supply (Vs) to MCU Vcc.
5.5 Introduction to Real-Time Operating Systems (RTOS) Concepts
5.5.1 Need for RTOS
- Limitation of Superloop (Foreground/Background): Single infinite loop. Tasks must run to completion quickly. No prioritization, no timing guarantees. A slow task (e.g., LCD update) blocks all others. Unsuitable for complex, time-critical systems.
5.5.2 Core RTOS Concepts
| Concept | Definition | Purpose |
|---|---|---|
| Task/Thread | Independent program module with its own stack, context, and priority. | Encapsulates a specific function (e.g., "Read Sensor", "Update LCD"). |
| Scheduler | OS component that decides which task runs next based on priority and state. | Enforces real-time deadlines. Preemptive: Highest ready task always runs (interrupts lower task). Cooperative: Tasks yield control voluntarily. |
| Context Switching | Saving the complete state (registers, PC, stack pointer) of a running task and restoring the state of the next task. | Allows multiple tasks to share a single CPU. Overhead cost. |
| Semaphore | Counting or binary flag used for resource counting or task synchronization. | e.g., Binary semaphore to signal "Data Ready". Give()/Take() operations. |
| Mutex | Special binary semaphore with ownership. Task that Take()s must Give() it. |
Mutual Exclusion for shared resources (e.g., global variable, LCD). Prevents race conditions. |
| Message Queue | FIFO buffer that passes data (messages) between tasks. | Inter-Task Communication. Task A sends data, Task B receives. |
| Software Timer | Timer that calls a callback function after a set time (one-shot) or periodically. | Time-based events without blocking a task. Uses system tick. |
5.5.3 Popular Lightweight RTOS
-
FreeRTOS: Open-source, small footprint. Core APIs:
xTaskCreate(),vTaskDelay(),xQueueSend(),xSemaphoreTake(). -
μC/OS-II/III: Commercial (with free evaluation), highly deterministic, certifiable (for safety-critical).
-
Focus: Understand concepts (task, queue, mutex), not deep API syntax for exam.
5.5.4 Lab Experiment (Conceptual)
-
Model: Multi-task system on 8051/ARM (using cooperative scheduler or FreeRTOS).
-
Tasks:
-
Task_High: Blink LED at 2Hz (highest priority).
-
Task_Med: Read keypad every 100ms (medium priority).
-
Task_Low: Update LCD with last key pressed (lowest priority).
-
-
Implementation:
-
Without RTOS:
while(1) { Task_High(); Task_Med(); Task_Low(); }-> Blocking. LCD update delays keypad read. -
With RTOS (Cooperative): Each task calls
yield()after its work. Scheduler runs next ready task. -
With RTOS (Preemptive): Assign priorities. Keypad task (med) can preempt LCD task (low) when key pressed. High-priority LED task always preempts others.
-
-
Outcome: Demonstrates concurrency, prioritization, and structured design over monolithic superloop.
[!TIP] RTOS adds overhead (memory for stacks/Task Control Blocks, CPU for context switch). Use only when complexity, multiple timing constraints, or modularity justify it. For simple 2-3 task systems, a well-structured superloop may suffice.