Skip to content
EC-606 · MICROCONTROLLER & EMBEDDED SYSTEM LAB/Quick Revision Short Notes

MICROCONTROLLER & EMBEDDED SYSTEM LAB (EC-606) - Unit 4 Short Notes

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:

    1. Configure TX (output) and RX (input) pins.

    2. Set baud rate by writing to UBRR/BAUD register.

    3. Enable UART transmitter and/or receiver.

    4. Polling: Wait for UDRE (Data Reg Empty) flag to send; wait for RXC flag to receive.

    5. Interrupt-Driven: Enable TXCIE/RXCIE; write ISR to handle UDR (Data Register).

  • Common Errors & Troubleshooting:

    [!TIP] Incorrect Baud Rate is the #1 issue. Double-check F_CPU and 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):

    1. Configure MOSI, SCK, SS as outputs; MISO as input.

    2. Set clock polarity & phase (CPOL, CPHA bits).

    3. Set clock frequency (usually F_CPU/2, /4, etc.).

    4. Enable SPI (SPE bit).

    5. To Transfer: Pull target slave's SS low. Write byte to SPDR (Data Register). Wait for SPIF (Transfer Complete) flag. Read received byte from SPDR. 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):

    1. Initialize TWI peripheral, set bit rate.

    2. Generate START condition.

    3. Send (Slave_Address << 1) | 0 (Write).

    4. Wait for slave ACK (TWINT flag & TWSR status check).

    5. Send data byte(s), wait for ACK after each.

    6. Generate STOP condition.

  • 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):

    1. Wait >15ms after Vcc rises.

    2. Send 0x30 (Function Set: 8-bit) 3 times with delays.

    3. Send 0x20 (Function Set: 4-bit).

    4. Configure display (e.g., 0x28 for 2-line, 5x8 dots).

    5. Display control (0x0C for cursor off, blink off).

    6. Clear display (0x01), set entry mode (0x06 for 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:

    1. Set all rows HIGH (inactive).

    2. For each row i:

      • Set row i LOW.

      • Read all column pins.

      • If any column j reads LOW, key at (row i, col j) is pressed.

      • Small delay for debounce.

      • Set row i HIGH.

  • 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: 0xD0 write, 0xD1 read).

    • 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:

    1. Initialize I2C master.

    2. Set Time: Write to registers 00h-06h. Convert decimal to BCD. Set CH=0.

    3. 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: n bits → $$\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:

    1. Select ADC channel, reference voltage.

    2. Enable ADC, start conversion (or single conversion mode).

    3. Wait for conversion complete (ADIF flag) or use interrupt.

    4. Read ADCL/ADCH (10-bit result).

    5. 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):

    1. Initialize I2C.

    2. Send START, slave write address.

    3. Send configuration byte (e.g., 0x40 for normal mode, output not buffered).

    4. Send 12-bit data as two bytes (MSB first, lower 4 bits of LSB=0).

    5. 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:

    1. Configure timer for PWM on EN pin (e.g., Fast PWM, 8-bit).

    2. Set motor direction pins (IN1, IN2).

    3. Write duty cycle to OCR register (0=0%, 255=100%).

    4. 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:

    1. Connect 4 control pins to MCU.

    2. Store sequence array (e.g., uint8_t seq[4] = {0x01, 0x02, 0x04, 0x08}; for wave drive).

    3. Loop through sequence with delay_ms() between steps. Delay controls speed.

    4. 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:

    1. Configure timer for Fast PWM, TOP = 20ms period. (e.g., ICR1 = 20ms count).

    2. Set OCR1A for pulse width (e.g., 1.5ms count value for 90°).

    3. Update OCR1A to 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_index while 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"

    1. START condition.

    2. Send Slave Address + W (0).

    3. Slave sends ACK (SDA low during SCL high).

    4. Send Data Byte 1.

    5. ACK from master (or NACK from master to stop).

    6. Repeat for more bytes.

    7. 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.

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in