UNIT 4: ADVANCED PERIPHERAL INTERFACING & COMMUNICATION PROTOCOLS
4.1 Serial Communication Protocols (Asynchronous & Synchronous)
4.1.1 Universal Asynchronous Receiver/Transmitter (UART/USART)
-
Objective: Full-duplex serial communication between MCU & PC/another MCU.
-
Key Concepts:
-
Asynchronous: No shared clock line; synchronization via start/stop bits.
-
Data Frame: 1 Start bit (low), 5-9 Data bits (LSB first), optional Parity bit, 1-2 Stop bits (high).
-
Baud Rate: Symbol rate (bits/sec). Must match on both ends.
-
Voltage Levels: MCU uses TTL (0-5V/0-3.3V); PC uses RS-232 (±3V to ±15V). MAX232/MAX3232 IC required for level shifting.
-
-
Baud Rate Calculation (Common 8051/AVR style):
$$ \text{Baud Rate} = \frac{F_{\text{CPU}}}{16 \times (\text{UBRR} + 1)} $$
Where `UBRR` is a register value. *Exact formula varies by MCU family.*
-
Programming Steps:
-
Configure TX (output) and RX (input) pins.
-
Set baud rate by writing to
UBRR/BAUDregister. -
Enable UART transmitter and/or receiver.
-
Polling: Wait for
UDRE(Data Reg Empty) flag to send; wait forRXCflag to receive. -
Interrupt-Driven: Enable
TXCIE/RXCIE; write ISR to handleUDR(Data Register).
-
-
Common Errors & Troubleshooting:
[!TIP] Incorrect Baud Rate is the #1 issue. Double-check
F_CPUand UBRR formula for your specific MCU. Use an oscilloscope to verify.-
Wrong voltage levels (no MAX232).
-
Buffer overflow in interrupt-driven code (ISR too slow).
-
Mismatched data frame format (bits, parity).
-
4.1.2 Serial Peripheral Interface (SPI)
-
Objective: High-speed, synchronous, full-duplex master-slave communication.
-
Key Concepts:
-
4-Wire Interface: MOSI (Master Out Slave In), MISO (Master In Slave Out), SCLK (Serial Clock from Master), SS/CS (Slave Select, active low).
-
Clock Modes (CPOL, CPHA): Defines clock polarity (idle state) and data sampling edge.
| Mode | CPOL (Clock Polarity) | CPHA (Clock Phase) | Data Sampled On | | :--- | :--- | :--- | :--- | | 0 | 0 (Idle Low) | 0 (Leading Edge) | Rising Edge | | 1 | 0 | 1 (Trailing Edge) | Falling Edge | | 2 | 1 (Idle High) | 0 | Falling Edge | | 3 | 1 | 1 | Rising Edge |
-
Full-Duplex: Simultaneous send/receive. MISO line provides data from slave while master sends on MOSI.
-
-
Hardware Setup:
-
Master controls SCLK and SS.
-
Each slave needs a dedicated SS line from master (or daisy-chained with logic).
-
Pull-up resistors on MISO if multiple slaves share line (tri-state when SS high).
-
-
Programming Steps (Master Mode):
-
Configure MOSI, SCK, SS as outputs; MISO as input.
-
Set clock polarity & phase (
CPOL,CPHAbits). -
Set clock frequency (usually
F_CPU/2,/4, etc.). -
Enable SPI (
SPEbit). -
To Transfer: Pull target slave's SS low. Write byte to
SPDR(Data Register). Wait forSPIF(Transfer Complete) flag. Read received byte fromSPDR. Pull SS high.
-
-
Viva Focus: SPI is full-duplex and faster than I2C but uses more pins (no addressing). Master always generates clock.
4.1.3 Inter-Integrated Circuit (I2C/TWI)
-
Objective: Multi-master, multi-slave, 2-wire bus for addressable peripherals.
-
Key Concepts:
-
2-Wire Bus: SDA (Serial Data), SCL (Serial Clock). Both open-drain outputs.
-
Pull-up Resistors: Mandatory on both SDA and SCL lines (typically 1kΩ-10kΩ) to pull lines high.
-
Start/Stop Conditions:
START= SDA HIGH→LOW while SCL HIGH.STOP= SDA LOW→HIGH while SCL HIGH. Bus is busy after START until STOP. -
Data Transfer: 8-bit bytes + 1 ACK/NACK bit from receiver. MSB first.
-
Addressing: 7-bit slave address + R/W bit (total 8 bits). 10-bit addressing also exists.
-
Clock Stretching: Slave can hold SCL low to delay master (for slow processing).
-
-
Hardware Setup: All SDA lines tied together, all SCL lines tied together. Pull-ups to Vcc.
-
Programming Steps (Master Transmitter):
-
Initialize TWI peripheral, set bit rate.
-
Generate
STARTcondition. -
Send
(Slave_Address << 1) | 0(Write). -
Wait for slave
ACK(TWINT flag &TWSRstatus check). -
Send data byte(s), wait for ACK after each.
-
Generate
STOPcondition.
-
-
Common Issues:
[!TIP] Bus Contention occurs if two masters try to control simultaneously. I2C protocol has arbitration. Missing ACK means wrong address, slave not powered, or bus error. Check pull-ups and wiring.
4.2 Advanced Input/Output Interfacing
4.2.1 Liquid Crystal Display (LCD) Interfacing (16x2/20x4)
-
Objective: Display alphanumeric data using HD44780 compatible controller.
-
Key Concepts:
-
4-bit vs. 8-bit Mode: 4-bit uses only D4-D7 pins, saving 4 I/O pins. Higher nibble sent first.
-
Control Pins:
RS(Register Select: 0=Command, 1=Data),RW(Read/Write: usually 0=Write),E(Enable: pulse high for 450ns min). -
Busy Flag (BF): Bit 7 of data bus when
RS=0. Check BF before writing to avoid waiting fixed delays.
-
-
Hardware Setup: Contrast pin (V0) to potentiometer wiper (adjusts LCD contrast).
-
Programming Steps (4-bit Mode Init):
-
Wait >15ms after Vcc rises.
-
Send
0x30(Function Set: 8-bit) 3 times with delays. -
Send
0x20(Function Set: 4-bit). -
Configure display (e.g.,
0x28for 2-line, 5x8 dots). -
Display control (
0x0Cfor cursor off, blink off). -
Clear display (
0x01), set entry mode (0x06for increment, no shift).
-
-
Custom Characters: Write to CGRAM (addresses 0x00-0x07). 5x8 pixel matrix per char.
4.2.2 Matrix Keypad Interfacing (4x4)
-
Objective: Scan 16 keys using 8 I/O pins (4 rows + 4 columns).
-
Key Concepts:
-
Row-Column Scanning: Rows configured as outputs (scan one low at a time). Columns configured as inputs with internal/external pull-ups.
-
Debouncing: Mechanical bounce causes multiple detections. Use software delay (10-20ms) after first detection or hardware RC filter.
-
-
Hardware Setup: Keypad rows to MCU output pins. Columns to MCU input pins (enable pull-up). Common keypad pins to ground.
-
Scanning Algorithm:
-
Set all rows HIGH (inactive).
-
For each row
i:-
Set row
iLOW. -
Read all column pins.
-
If any column
jreads LOW, key at(row i, col j)is pressed. -
Small delay for debounce.
-
Set row
iHIGH.
-
-
-
Key Mapping: Store key codes in a 2D array
keypad[row][col].
4.2.3 Real-Time Clock (RTC) Interfacing (DS1307/DS3231)
-
Objective: Maintain accurate time/date with battery backup (typically coin cell).
-
Key Concepts:
-
I2C Slave: Fixed address (DS1307:
0xD0write,0xD1read). -
BCD Format: Each register stores seconds, minutes, etc., in BCD. e.g.,
0x59= 59 seconds. -
Registers: 00h-06h (Seconds to Year), 07h (Control), 08h-3Fh (RAM).
-
Battery: Maintains time when main power off. CH (Clock Halt) bit in seconds register (bit 7) stops oscillator.
-
-
Programming Steps:
-
Initialize I2C master.
-
Set Time: Write to registers 00h-06h. Convert decimal to BCD. Set CH=0.
-
Read Time: Generate START, send write address, send register 00h, generate repeated START, send read address. Read 7 bytes. Convert BCD to decimal.
-
-
Viva Focus: RTC has its own battery and crystal; independent of MCU's system timer. DS3231 is more accurate (temperature-compensated).
4.3 Analog Signal Processing & Generation
4.3.1 Advanced ADC Applications
-
Objective: Convert analog sensor voltage to digital value with calibration.
-
Key Concepts:
-
Resolution:
nbits → $$\displaystyle 2^n $$ levels. ADC Value = $$\displaystyle \frac{V_{\text{in}}}{V_{\text{ref}}} \times (2^n - 1) $$. -
Reference Voltage (
Vref): Can be internal (e.g., 1.1V, 2.56V) or external (AVcc, precise external ref). Affects accuracy & range. -
Sampling Rate: Determined by ADC clock prescaler. Must satisfy Nyquist criterion ($$\displaystyle f_s > 2 f_{\text{signal max}} $$).
-
Averaging/Filters: Take multiple samples and average to reduce noise.
-
-
Programming Steps:
-
Select ADC channel, reference voltage.
-
Enable ADC, start conversion (or single conversion mode).
-
Wait for conversion complete (
ADIFflag) or use interrupt. -
Read
ADCL/ADCH(10-bit result). -
Convert to Physical Quantity: Use sensor's transfer function. e.g., LM35: $$\displaystyle V_{\text{out}} = 10 \text{ mV/°C} $$ → $$\displaystyle \text{Temp} = \frac{\text{ADC\_Value} \times V_{\text{ref}}}{1024 \times 0.01} $$.
-
-
Calibration: Measure known voltage (e.g., precise 1.024V) and adjust calculation offset/gain.
4.3.2 Digital-to-Analog Converter (DAC) Interfacing
-
Objective: Generate variable analog voltage or waveforms.
-
Key Concepts:
-
External DAC IC (e.g., MCP4725): I2C interface, 12-bit resolution, internal reference. Write 16-bit command (12-bit data + config).
-
PWM-based DAC: Low-pass filter (RC) smooths PWM to DC. Resolution = Timer resolution (e.g., 8-bit). Settling Time = RC time constant.
-
Waveform Generation: Update DAC value in loop or timer interrupt with pre-calculated sine/square table.
-
-
Hardware Setup (PWM DAC): PWM pin → RC filter (e.g., R=1kΩ, C=10µF) → Output. Cutoff freq $$\displaystyle f_c = \frac{1}{2\pi RC} $$ must be << PWM frequency.
-
Programming Steps (External I2C DAC):
-
Initialize I2C.
-
Send START, slave write address.
-
Send configuration byte (e.g.,
0x40for normal mode, output not buffered). -
Send 12-bit data as two bytes (MSB first, lower 4 bits of LSB=0).
-
Send STOP.
-
4.4 Actuator & Motor Control
4.4.1 DC Motor Control using PWM
-
Objective: Control motor speed via average voltage.
-
Key Concepts:
-
PWM: Fast on/off switching. Duty Cycle (%) = $$\displaystyle \frac{T_{\text{on}}}{T_{\text{period}}} \times 100 $$. Controls average voltage.
-
H-Bridge (L293D/SN754410): Allows bidirectional current flow. 4 control inputs (IN1, IN2, IN3, IN4) + 2 enable pins (EN1, EN2).
-
Flyback Diodes: Internal in driver IC or external across motor terminals. Clamp back EMF spikes.
-
-
H-Bridge Truth Table (Single Motor):
| IN1 | IN2 | Motor Direction | EN (PWM) | Speed | | :-- | :-- | :--- | :--- | :--- | | 0 | 0 | Coast/Stop | X | 0 | | 1 | 0 | Forward | PWM | Variable | | 0 | 1 | Reverse | PWM | Variable | | 1 | 1 | Brake | X | 0 |
-
Programming Steps:
-
Configure timer for PWM on EN pin (e.g., Fast PWM, 8-bit).
-
Set motor direction pins (IN1, IN2).
-
Write duty cycle to
OCRregister (0=0%, 255=100%). -
Speed Control: Read potentiometer via ADC → map to 0-255 → update
OCR.
-
4.4.2 Stepper Motor Interfacing (Unipolar, 5-wire)
-
Objective: Precise angular steps (e.g., 1.8°/step).
-
Key Concepts:
-
Coils: Typically 4 or 5 wires (common center tap). Energize coils in sequence.
-
Step Sequence:
-
Full-Step (Wave Drive): One coil on at a time. Less torque.
-
Full-Step (Standard): Two coils on at a time. More torque.
-
Half-Step: Alternates 1-coil and 2-coil. Finer resolution (0.9°), smoother.
-
-
Driver IC (ULN2003): Darlington array, sinks current from coils.
-
-
Programming Steps:
-
Connect 4 control pins to MCU.
-
Store sequence array (e.g.,
uint8_t seq[4] = {0x01, 0x02, 0x04, 0x08};for wave drive). -
Loop through sequence with
delay_ms()between steps. Delay controls speed. -
Reverse loop for opposite direction.
-
-
Applications: Robotics, CNC, printers.
4.4.3 Servo Motor Control
-
Objective: Set angular position (0-180°) precisely.
-
Key Concepts:
-
PWM Control: Not for speed, but for position. Pulse width determines angle.
-
Timing: 20ms period (50Hz). Pulse width:
-
0.5ms → 0°
-
1.5ms → 90°
-
2.5ms → 180°
-
-
Internal Potentiometer & Control Circuit: Servo has feedback; applies torque to reach position.
-
-
Programming Steps:
-
Configure timer for Fast PWM, TOP = 20ms period. (e.g., ICR1 = 20ms count).
-
Set
OCR1Afor pulse width (e.g., 1.5ms count value for 90°). -
Update
OCR1Ato change position.
-
-
Viva Focus: Servo expects repeating pulses every 20ms. No power to hold position? Most servos "jitter" without pulses.
4.5 System Integration & Mini-Project Concepts
4.5.1 Combining Multiple Peripherals
-
Example: Data Logger
-
Flow: ADC reads temperature sensor → store value in external EEPROM (I2C) every N seconds → display current temp on LCD.
-
Challenges:
-
Timing Conflicts: ADC conversion time vs. I2C write time vs. LCD update. Use state machine or RTOS/scheduler.
-
Memory Management: EEPROM wear (limit write cycles). Use circular buffer.
-
ISR Priority: UART debug messages vs. time-critical ADC sampling. Set interrupt priorities correctly.
-
-
4.5.2 Interrupt-Driven Design
-
Scenario: UART RX interrupt (store char in ring buffer) + External INT0 (keypad interrupt) + Timer0 overflow (system tick).
-
Critical Sections: Shared variables (e.g.,
volatile uint8_t buffer_index) accessed by both main loop and ISR.-
Problem: Main reads
buffer_indexwhile ISR modifies it → corrupted value. -
Solution: Disable interrupts briefly around access:
cli(); // Disable all interrupts temp = buffer_index; sei(); // Enable interrupts -
Keep critical section as short as possible.
-
4.5.3 Power Management Considerations
-
Sleep Modes: From idle to power-down. Select lowest mode that keeps required peripherals active (e.g., keep UART for wake-up).
-
Peripheral Shutdown: Disable clocks to unused modules (ADC, SPI, I2C) in power control register.
-
Battery Operated: Use low-power mode between events (e.g., wake on external interrupt from keypad or RTC alarm).
4.6 Common Viva/Theory Questions for Unit 4
-
Compare UART, SPI, and I2C:
| Feature | UART | SPI | I2C | | :--- | :--- | :--- | :--- | | Type | Asynchronous | Synchronous | Synchronous | | Wires | 2 (TX, RX) | 4 (MOSI, MISO, SCLK, SS) | 2 (SDA, SCL) | | Topology | Point-to-Point | Master-Slave (multi-slave) | Multi-Master, Multi-Slave | | Speed | Low (kbps) | Very High (Mbps) | Medium (100kHz-3.4MHz) | | Addressing | No | No (hardware SS) | Yes (7/10-bit) | | Duplex | Full | Full | Half (but multi-master) | | Use Case | PC comm, debug | High-speed sensors, flash | Many sensors on bus (RTC, EEPROM) |
-
Pull-up Resistors in I2C: Open-drain outputs can only pull LOW; they float HIGH. Pull-ups provide the HIGH logic level and limit current. Value chosen to balance rise time (speed) and power (lower R = more power).
-
ADC Accuracy: Depends on: Reference voltage stability (use precise external ref), Noise (filter, averaging), Integral Nonlinearity (INL) & Differential Nonlinearity (DNL) of ADC, Sampling rate vs. input impedance.
-
Stepper vs. Servo:
-
Stepper: Open-loop. Sends step pulses. Can lose steps if overloaded. High holding torque. No position feedback.
-
Servo: Closed-loop. Sends PWM pulse for position. Has internal feedback (pot). More precise, can correct for load. Limited rotation (usually 180°).
-
-
I2C Write Timing Diagram:
DiagramSEARCH: "i2c write timing diagram start condition slave address ack data stop"-
START condition.
-
Send Slave Address + W (0).
-
Slave sends ACK (SDA low during SCL high).
-
Send Data Byte 1.
-
ACK from master (or NACK from master to stop).
-
Repeat for more bytes.
-
STOP condition.
-
-
PWM Motor Speed Control: Varies average voltage to motor. Faster switching (higher PWM freq) reduces audible noise and motor inductance effects. Limitation: At very low duty cycles, motor may stall due to insufficient torque to overcome static friction.
-
I2C Bus Contention: Two masters try to control SDA/SCL simultaneously. Avoided by: Clock synchronization (wired-AND), arbitration (masters monitor SDA while transmitting; lose arbitration if send 1 but read 0). Losing master becomes slave.
-
Critical Section in Interrupt System: Code segment where a non-atomic access (e.g., 16-bit variable on 8-bit MCU) to a shared resource (global variable, hardware register) must be protected from interruption to prevent corruption. Protect by disabling interrupts around the access.