UNIT 2: CORE PERIPHERAL INTERFACING & REAL-TIME CONTROL
2.1 Review & Foundation: From Theory to Lab
-
Microcontroller Architecture: Core components are CPU (executes instructions), Memory (ROM/Flash for code, RAM for data), and Buses (Address, Data, Control) for internal communication.
-
Target MCU Familiarity: Must know the specific pin diagram (function of each pin: VCC, GND, GPIO, specialized peripherals) and core registers (e.g., Accumulator, B, DPTR for 8051; General Purpose Registers R0-R15 for ARM).
-
Development Toolchain:
-
IDE (Integrated Development Environment): Keil uVision (8051/ARM), MPLAB X (PIC), Arduino IDE, STM32CubeIDE.
-
Compiler: Converts C/Assembly code to machine code (hex/elf file).
-
Programmer/Debugger: Hardware interface (USBasp, J-Link, ST-Link) to flash code to MCU and often debug.
-
-
Workflow: Write Source Code (
.c) → Compile → Link → Generate Hex → Flash to MCU → Run.
[!TIP] First Program: Blinking an LED (
LED = ~LED;with delay) validates toolchain, hardware power, and basic GPIO output.
2.2 General Purpose Input/Output (GPIO) - The Fundamental Interface
-
Configuration:
-
Direction: Set pin as Input (read external signal) or Output (drive external device). Done via Data Direction Register (DDR) or specific configuration bits.
-
Pull-up/Pull-down: Internal resistors (enable via register) to keep pin at known state (High/Low) when not driven externally. Essential for clean switch reading.
-
-
Output Operations:
-
LED: Connect LED + current-limiting resistor (220Ω-1kΩ) between GPIO pin and VCC/GND. Calculate resistor: $$\displaystyle R = \frac{V_{CC} - V_{LED}}{I_{LED}} $$.
-
Relay/Buzzer: MCU pin cannot drive directly. Use transistor driver circuit (e.g., NPN BJT or MOSFET) as a switch, with a flyback diode across relay coil.
-
-
Input Operations:
-
Switch Reading: Simple read of input pin. Debouncing is mandatory to avoid multiple detections from mechanical bounce.
-
Hardware: RC low-pass filter (e.g., 10kΩ + 0.1µF).
-
Software: Sample pin at intervals (e.g., 10-50ms) or require stable state for N consecutive reads.
-
-
Digital Sensors: PIR, IR receiver modules output digital HIGH/LOW signals. Connect to GPIO input with pull-up if required.
-
-
Practical Lab: Interface LED matrix or multiple LEDs; implement a state machine (e.g., sequence control) triggered by push buttons.
2.3 Timers/Counters - The Heart of Timing and Measurement
-
Timer Basics:
-
Clock Source: Internal system clock (F_CPU) or external pin.
-
Prescaler: Divides clock source (e.g., /8, /64, /256) to extend counting range.
-
Counting Modes:
| Mode | Description | | :--- | :--- | | Normal | Counts up to TOP (0xFFFF or OCR), then resets. | | CTC (Clear Timer on Compare) | Counts to value in Compare Register (OCR/TOP), resets, triggers interrupt/flag. | | PWM (Fast/Phase Correct) | Special modes for generating Pulse Width Modulation. |
-
-
Applications - Generating Delays:
-
Software Delay:
forloops. Limitations: Inaccurate, blocks CPU, depends on clock & compiler optimization. -
Hardware Timer Interrupt (Preferred):
-
Calculate timer tick time: $$\displaystyle t_{tick} = \frac{Prescaler}{F_{CPU}} $$.
-
Set compare value for desired delay $$\displaystyle t_{delay} $$: $$\displaystyle OCR = \frac{t_{delay}}{t_{tick}} - 1 $$.
-
Enable Timer interrupt. ISR toggles a flag or performs action.
\boxed{OCR = \frac{t_{delay} \times F_{CPU}}{Prescaler} - 1}
-
-
-
Applications - Measuring Events:
-
Input Capture: Timer counts on every tick. On external pin edge (rising/falling), current timer value (TCNT) is latched to Input Capture Register (ICR). Used to measure pulse width or period/frequency.
-
Output Compare/PWM:
-
Concept: Timer counts. When TCNT = OCRx, pin toggles/clears/sets.
-
PWM Duty Cycle: $$\displaystyle Duty\% = \frac{OCR_{x}}{TOP} \times 100\% $$ (for Fast PWM).
-
Frequency: $$\displaystyle f_{PWM} = \frac{F_{CPU}}{Prescaler \times TOP} $$.
-
Applications: LED dimming, DC motor speed control, servo motor position control.
-
-
-
Practical Lab: Generate precise 1s interrupt blink; measure unknown frequency using Input Capture; generate variable PWM (0-100%) on an oscilloscope.
2.4 Interrupts - The Mechanism for Real-Time Response
-
Concept:
-
Interrupt: Event that causes CPU to suspend current main program, execute a dedicated Interrupt Service Routine (ISR), then return.
-
Polling: CPU continuously checks status flags. Inefficient, misses fast events.
-
Priority & Nesting: Some MCUs allow higher-priority interrupt to preempt lower-priority ISR.
-
-
Interrupt Sources: External (INT0/INT1 pins), Timer Overflow/Compare Match, ADC Conversion Complete, UART Rx/Tx Complete, I2C/SPI events.
-
Interrupt Service Routine (ISR) - Best Practices:
-
Keep it SHORT: Do minimal work (set flag, increment counter). Avoid
delay(),printf(). -
Use
volatile: Global variables shared with main loop must be declaredvolatileto prevent compiler optimization issues. -
Protect Critical Sections: Disable interrupts briefly (
cli()/sei()or specific bits) when accessing multi-byte shared variables. -
Clear Interrupt Flag: Often must be cleared manually in ISR to allow next interrupt.
-
Structure: No parameters, no return value.
ISR(TIMER1_COMPA_vect) { // Short code: toggle pin, increment volatile counter PORTB ^= (1 << PB0); volatile_count++; }
-
-
Practical Lab: External button press (INT0) toggles LED while main loop counts. Timer interrupt toggles another LED at fixed rate.
2.5 Analog-to-Digital Conversion (ADC) - Bridging the Analog World
-
ADC Fundamentals:
-
Resolution (n-bit): $$\displaystyle 2^n $$ discrete levels. e.g., 10-bit → 1024 levels (0-1023 or 0-1023).
-
Reference Voltage (Vref): Maximum analog voltage corresponding to maximum digital value (e.g., 1023 for 10-bit). Vref can be VCC, internal bandgap, or external pin.
-
Sampling Rate: Conversions per second (sps). Limited by ADC clock and acquisition time.
-
Conversion Time: Time to complete one conversion. $$\displaystyle t_{conv} = \frac{Sample\ Cycles}{ADC_{clock}} $$.
-
Digital Output: $$\displaystyle ADC_{value} = \frac{V_{in}}{V_{ref}} \times (2^n - 1) $$.
-
-
Configuration Steps:
-
Select ADC Channel (MUX input).
-
Set Reference Voltage (Vref).
-
Set ADC Clock Prescaler (within recommended range, e.g., 50-200kHz for 10-bit).
-
Set Trigger Source: Software (manual start) or Hardware (Timer event, external pin).
-
Set Acquisition Time (sample & hold): Time for input capacitor to charge. Depends on source impedance.
-
-
Reading Data:
-
Start Conversion (write to ADCSRA/ADSC bit or set trigger).
-
Wait for Completion: Poll
ADIFflag or use ADC Complete Interrupt. -
Read Result from ADC Data Register (ADCL/ADCH). Read ADCL first, then ADCH.
-
-
Applications:
-
Potentiometer: Voltage divider. $$\displaystyle V_{out} = V_{CC} \times \frac{R_{2}}{R_{1}+R_{2}} $$.
-
LM35 Temperature Sensor: Output = 10mV/°C. $$\displaystyle Temp(°C) = \frac{ADC_{value} \times V_{ref}}{1024 \times 0.01} $$ (for 10-bit, Vref=5V).
-
LDR with Voltage Divider: Resistance changes with light → voltage changes.
-
-
Practical Lab: Read potentiometer, map value (0-1023) to 0-5V or 0-100%, display on LCD or LED bar graph.
2.6 Serial Communication Protocols - Interfacing Modules & Networks
-
UART (Universal Asynchronous Receiver/Transmitter) / RS-232:
-
Concepts: Asynchronous (no shared clock). Frame: Start Bit (0) + Data Bits (5-8) + Parity Bit (Optional) + Stop Bit(s) (1 or 2).
-
Baud Rate: Symbol rate (bits/sec). Must match on both ends. Generated from system clock via UBRR register: $$\displaystyle UBRR = \frac{F_{CPU}}{16 \times Baud} - 1 $$ (for normal mode).
-
Loopback Test: Connect TX pin to RX pin internally/externally. Send data, verify received data matches.
-
PC Communication: Use USB-to-Serial converter (FTDI, CP2102). Terminal software (PuTTY, Tera Term) set to correct baud, format.
-
-
I2C (Inter-Integrated Circuit) / Two-Wire Interface:
-
Concepts: Multi-master, multi-slave. Only two wires: SDA (data), SCL (clock). Each slave has a 7-bit address.
-
Operation: Master initiates, generates clock. Data transferred in 8-bit bytes with ACK/NACK from receiver.
-
Clock Stretching: Slave can hold SCL low to delay master (for slow processing).
-
Common Peripherals: EEPROM (24Cxx), RTC (DS1307), OLED (SSD1306), IO Expander (PCF8574).
-
-
SPI (Serial Peripheral Interface):
-
Concepts: Full-duplex, single-master, multiple-slaves. Four wires: MOSI (Master Out Slave In), MISO (Master In Slave Out), SCK (Clock), SS/CS (Slave Select, active low).
-
Clock Polarity/Phase (CPOL/CPHA): Defines clock idle state and data sampling edge. Modes 0-3.
-
Chip Select: Master pulls specific slave's SS low to select it.
-
Common Peripherals: Sensors (ADXL345 accelerometer), Display (ILI9341 TFT), Flash Memory, ADC/DAC.
-
-
Comparison Table:
| Feature | UART | I2C | SPI | | :--- | :--- | :--- | :--- | | Type | Async, Point-to-Point | Sync, Multi-master/multi-slave | Sync, Single-master/multi-slave | | Wires | 2 (TX, RX) | 2 (SDA, SCL) | 4 (MOSI, MISO, SCK, SS) | | Speed | Medium (~115kbps common) | Medium (100kHz-3.4MHz) | High (10-50+ MHz) | | Addressing | No | Yes (7/10-bit) | No (hardware SS) | | Duplex | Half | Half | Full |
-
Practical Lab: UART echo program (read char, send back); I2C: write/read byte from 24Cxx EEPROM; SPI: read WHO_AM_I register from ADXL345.
2.7 Integrated Lab Projects & System Integration
-
Project 1: Digital Data Logger
-
Goal: Sample analog sensor (temp/Light) → Store in EEPROM → Retrieve via UART.
-
Peripherals: ADC (sample), I2C (write to 24Cxx), UART (read out).
-
Key Skill: Sequencing, I2C page write/read, data formatting.
-
-
Project 2: Multi-Function Meter
-
Goal: Measure frequency, voltage, display on LCD.
-
Peripherals: Timer Input Capture (frequency), ADC (voltage via divider), LCD (16x2 parallel or I2C).
-
Key Skill: Input capture calculation, ADC scaling, LCD library integration.
-
-
Project 3: Motor Control System
-
Goal: PC controls DC motor speed via UART commands. Feedback from potentiometer.
-
Peripherals: UART (command decode), Timer PWM (motor driver), ADC (potentiometer feedback).
-
Key Skill: PWM duty cycle update, command parsing, closed-loop concept (pot read vs. set speed).
-
-
Emphasis: Modular Code (separate
.c/.hfiles for each peripheral), clear function APIs, globalvolatilevariables for ISR-main communication.
2.8 Debugging, Troubleshooting & Best Practices
-
On-Chip Debugging (OCD/JTAG):
-
Stepping: Execute code line-by-line (
Step Over,Step Into). -
Breakpoints: Halt execution at specific line.
-
Watch Variables: Monitor global/register values in real-time.
-
Register View: Inspect/modify peripheral registers (e.g., check if
ADCSRAADIF flag is set).
-
-
Common Hardware Issues:
-
No Power/Reset: Check VCC/GND connections, decoupling capacitors (0.1µF near VCC pin).
-
No Communication (UART/I2C/SPI): Verify baud/address, pull-up resistors (I2C needs 4.7kΩ), wiring (MOSI/MISO not swapped), SS pin logic.
-
Intermittent Behavior: Loose connections, long wires (noise), missing ground reference.
-
Overcurrent: LED/resistor value wrong, relay driver missing transistor/base resistor.
-
-
Common Software Issues:
-
ISR Not Firing: Global interrupt enable (
sei()) missing, wrong vector name, interrupt flag not cleared. -
Garbage Values: Non-
volatileshared variables, reading multi-byte ADC result incorrectly (must read ADCL first). -
Race Condition: Main and ISR modify same variable without protection. Disable interrupts briefly during access.
-
Bus Contention: Two output pins shorted together (e.g., two ports driving same line).
-
-
Documentation (Lab Report):
-
Circuit Diagram: Clear schematic with component values.
-
Code Explanation: Flowchart or step-by-step logic of main program and ISRs.
-
Results: Oscilloscope/logic analyzer captures for PWM, UART, I2C. Screenshots of terminal output.
-
Observations: Challenges faced, solutions, performance limits (max ADC sampling rate, max UART baud without error).
-