Amrita 23ECE313: Embedded Systems Exam Master Portal

Professor Giriraja C. V.'s Exam Pattern • Full Unit I & II + Lab Peripherals (50 Marks)

Official Exam Pattern Solved 3 Practice Papers with Interactive Dropdown Answers Every Slide Diagram & PPT Cited Deployed on Cloudflare Pages

🧬 Professor Giriraja C. V.'s Exam Pattern DNA

50-Mark Blueprint

Based on the official September 2026 examination paper, here is the exact question structure and marking formula:

Question Type & Marks Topics Tested Evaluation Criteria (How to Get 50/50)
Part 1: Theory & Advantages [5M]
(Q1: BTL1)
Cortex-M Processor Family Advantages, Architecture overview. List 5 crisp points from 1 23ECE313_ES_Ch4 Text 1.pdf (Low power/WIC, Thumb-2, NVIC 12-cycle latency, OS support with MSP/PSP, CoreSight debug).
Part 2: Assembly & Stack Trace [5M]
(Q2: BTL2)
Instruction execution (LDR, MOVS flags, IT blocks, STMDB/LDMIA, Full Descending Stack, ICI bits). Calculate exact register hex values, draw 4-byte memory map addresses, explain EPSR ICI bits preventing multi-cycle restart.
Part 3: Hardware Interfacing [5M]
(Q3: BTL2)
JTAG vs SWD, CoreSight host connection, SWJ-DP, DAP, AHB-AP. Draw host-to-core DAP interconnect diagram from 5 23ECE313_ES_Ch15_Txt 1a.pdf. Explain non-intrusive memory access while CPU runs.
Part 4: Timing Waveforms [15M]
(Q4, Q5, Q6: 5M each, BTL2)
1. SysTick task switching timeline.
2. Interrupt pending & activation state machine.
3. Context switch IRQ blocking & PendSV solution.
"With the help of a neat timing diagram" is mandatory. Must draw the exact waveforms from Ch12 and Ch_Txt1 slides with timeline states.
Part 5: Low Power / Core Feature [5M]
(Q7: BTL2)
Wake-Up Interrupt Controller (WIC) in Deep Sleep, Sleep-on-Exit. Draw WIC always-on power domain block diagram and list the 7-step sequence of events restoring CPU clocks.
Part 6: Applied Coding & Circuit [15M]
(Q8: 5M + Q9: 10M, BTL3)
• Q8: PWM Duty Cycle control (MOSFET, 3V from 5V DC).
• Q9: Analog sensor (PA0), Relay Fan (PA5), UART PuTTY display.
Must draw both Circuit Diagram AND write complete C code with exact registers (MODER, AFR, ARR, CCR1, ADC1->SQR3, CR2, BRR).

📋 Official September 2026 Mid-Term Paper (50 Marks)

Reference Paper Solved

Click on any question below to expand the complete 50/50 model answer, exact circuit schematics, and slide diagram citations:

1. Briefly explain any five advantages of the Cortex-M processors.
[5 Marks] [CO1, BTL1] PPT: Ch4 Slide 16

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slide 16)

  • 1. Low Power Consumption & High Energy Efficiency: Dedicated sleep modes (Sleep, Deep Sleep, Sleep-on-Exit) and the autonomous Wake-up Interrupt Controller (WIC), making it ideal for battery-operated IoT and wearable devices.
  • 2. High Performance & Code Density (Thumb-2 Technology): Blends 16-bit and 32-bit instructions to achieve high performance (1.25 DMIPS/MHz) without state-switching penalties or memory bloat.
  • 3. Deterministic, Low-Latency Interrupt Handling (Integrated NVIC): Hardware vector fetches, automatic context stacking/unstacking, tail-chaining, and late-arriving preemption achieve a deterministic 12-cycle interrupt latency.
  • 4. Comprehensive OS Support: Features dual banked stack pointers (MSP and PSP), two operation modes (Thread and Handler), two privilege levels (Privileged and Unprivileged), SysTick timer, and dedicated OS software exceptions (SVC and PendSV).
  • 5. Advanced Debug & Trace Capabilities (CoreSight Architecture): Integrates standard Serial Wire Debug (SWD - 2 pins) and JTAG, hardware breakpoints (FPB), data watchpoints (DWT), and non-intrusive real-time software tracing (ITM/ETM).
2. Assembly Execution, Memory State, IT Block & ICI Bits Trace.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slides 30, 42 & 57
Given Assembly Sequence:
LDR R0, =0x40000000
LDR SP, =0x800000F0
LDR R1, =0x12349876
LDR R2, =0xABCDEF12
MOVS R3, 0x00
IT EQ
STMDB SP!, {R0-R2}
STOP B STOP

Step-by-Step Instruction Execution Trace:

  1. LDR R0, =0x40000000 -> R0 = 0x40000000.
  2. LDR SP, =0x800000F0 -> SP = 0x800000F0.
  3. LDR R1, =0x12349876 -> R1 = 0x12349876.
  4. LDR R2, =0xABCDEF12 -> R2 = 0xABCDEF12.
  5. MOVS R3, 0x00 -> Moves 0 into R3. Because the instruction has the 'S' suffix, it updates the condition flags in APSR. Since result is 0, the Z (Zero) flag is set to 1.
  6. IT EQ -> If-Then block with condition EQ (Equal / Z == 1). Since Z == 1, the condition evaluates to TRUE. The following instruction executes!
  7. STMDB SP!, {R0-R2} -> Store Multiple Decrement Before with write-back (!).
    • Registers pushed in order: Lowest register number at lowest memory address (Full Descending Stack).
    • Total registers = 3 (12 bytes = 0x0C).
    • Final SP = 0x800000F0 - 0x0C = 0x800000E4.

(a) Contents of Registers R0-R2 and Stack Pointer [2 Marks]:

RegisterFinal ValueExplanation
R00x40000000Unchanged by STMDB
R10x12349876Unchanged by STMDB
R20xABCDEF12Unchanged by STMDB
SP0x800000E4Decremented by 12 bytes (3 words)

(b) Contents of Memory Locations from 0x800000E0 to 0x800000F0 [2 Marks]:

AddressStored 32-bit ValueStored Register
0x800000F0Unmodified DataOriginal SP Base
0x800000EC0xABCDEF12R2 (Highest register at highest address)
0x800000E80x12349876R1
0x800000E40x40000000R0 (Lowest register at lowest address) ← New SP
0x800000E0Unmodified DataBelow current SP

(c) How ICI (Interruptible-Continuable Instruction) is Used [1 Mark]:

(Directly from Slide Deck 1: Ch4 Text 1, Slide 42)
STMDB is a multi-cycle store instruction. If an interrupt occurs halfway through executing STMDB (e.g. after pushing R2 and R1, but before R0), the processor saves the transfer progress into the ICI bits inside the Execution Program Status Register (EPSR). Upon return from the interrupt via EXC_RETURN, the processor inspects the saved ICI bits and resumes execution directly from the remaining transfer (storing R0) instead of restarting the entire instruction from the beginning. This reduces interrupt latency and prevents duplicate bus transactions.

3. Explain how JTAG or SWD facilitates communication between a debug host and Cortex-M3.
[5 Marks] [CO2, BTL2] PPT: Ch15 Slides 5-8
Debug Host Connection
Diagram: Connection from Debug Host (PC) to Cortex-M3 Core
Cited from: 5 23ECE313_ES_Ch15_Txt 1a.pdf (Slide 5)

Key Points to Write in Exam:

  • 1. Physical Pins:
    • JTAG (IEEE 1149.1): Uses 4-5 pins (TCK, TMS, TDI, TDO, optional nTRST) to interface with the on-chip Test Access Port (TAP) controller.
    • SWD (Serial Wire Debug): ARM alternative requiring only 2 pins: SWCLK (clock) and SWDIO (bidirectional data), with an optional SWO (Serial Wire Output) pin for trace data.
  • 2. SWJ-DP: On-chip Serial Wire/JTAG Debug Port that detects and switches between JTAG and SWD protocols upon reset.
  • 3. DAP (Debug Access Port) Bus: Internal debug bus that translates JTAG/SWD packet commands into internal bus transactions.
  • 4. AHB-AP (AHB Access Port): Bridges the DAP directly to the internal AHB System Bus Interconnect.
  • 5. Non-Intrusive Live Memory Access: Because AHB-AP is an independent master on the AHB bus matrix, the host debugger can read and write memory, Flash, and peripheral registers on the fly even while the Cortex-M3 core is running at full speed!
4. Explain a scenario where SysTick switches between two tasks with a neat timing diagram.
[5 Marks] [CO1, BTL2] PPT: Ch12 Slide 36
SysTick Timeline
Diagram: A Simple Scenario Using SysTick to Switch between Two Tasks
Cited from: 3 23ECE313_ES_Ch12_Txt1.pdf (Slide 36)

Step-by-Step Context Switching Operation:

  • 1. Initial State: Task A is running in Thread mode using the Process Stack Pointer (PSP).
  • 2. Timer Expiry: The 24-bit SysTick down-counter reaches 0, sets COUNTFLAG, and asserts Exception 15 (SysTick).
  • 3. Automatic Context Save: Hardware automatically pushes caller-saved registers (R0-R3, R12, LR, PC, xPSR) onto Task A's stack (PSP). The processor switches to Handler mode using the Main Stack Pointer (MSP).
  • 4. Software Context Save: The SysTick ISR pushes the remaining callee-saved registers (R4-R11) onto Task A's stack and saves Task A's updated SP in its Task Control Block (TCB).
  • 5. Scheduler Execution: The OS scheduler selects Task B as the next task to run and retrieves Task B's SP from its TCB.
  • 6. Context Restore: Software pops R4-R11 from Task B's stack.
  • 7. Exception Exit: Executing BX LR with EXC_RETURN = 0xFFFFFFFD triggers hardware unstacking of R0-R3, R12, LR, PC, xPSR from Task B's stack. The CPU resumes execution of Task B in Thread mode.
5. Explain the interrupt pending and activation behavior with a neat timing diagram.
[5 Marks] [CO1, BTL2] PPT: Ch_Txt1 Slides 44 & 47
Interrupt Pending State
Diagram: Interrupt Pending and Activation Timing Behavior
Cited from: 2 23ECE313_ES_Ch_Txt1.pdf (Slide 44)

Key Points to Write in Exam:

  • 1. Inactive State: The interrupt request signal is de-asserted; interrupt status in NVIC is inactive and not pending.
  • 2. Pending State: When a peripheral pulses an interrupt request line, the NVIC latches this into the Interrupt Set-Pending Register (NVIC_ISPR). The interrupt is now Pending.
  • 3. Arbitration & Acceptance: The processor accepts the pending interrupt if:
    • The interrupt is enabled in NVIC_ISER.
    • Its priority is higher than the currently executing context and the BASEPRI / PRIMASK registers.
  • 4. Active State: When the core enters the exception entrance sequence (stacking), hardware automatically transitions the interrupt from Pending to Active. The pending flag is cleared unless a new pulse has arrived.
  • 5. Multiple Pulses Latching: If multiple request pulses occur while the interrupt is already pending or active, the NVIC latches the pending state only once, ensuring exactly one subsequent ISR execution.
6. Explain the problem associated with context switching during an IRQ with a neat timing diagram.
[5 Marks] [CO1, BTL2] PPT: Ch12 Slides 40 & 42
Context Switch Problem
Diagram: Context Switch Problem inside SysTick Blocking Peripheral IRQ
Cited from: 3 23ECE313_ES_Ch12_Txt1.pdf (Slide 40)

Detailed Operational Explanation:

  • Scenario: Task A is executing normally in Thread mode. A periodic SysTick timer interrupt triggers to initiate a task switch.
  • The Conflict: While the SysTick handler is executing the context switch sequence, an urgent external peripheral interrupt (e.g., UART communication or Motor Control IRQ) arrives.
  • The Failure: Because the processor is already executing inside an ISR (SysTick handler), and both have equal or configurable priorities, the external IRQ is blocked and delayed until the lengthy context switch operation completes.
  • Consequence: Crucial real-time peripheral deadlines are missed, creating unacceptable interrupt latency.
  • The Solution (PendSV): To resolve this, the OS delegates context switching to the Pendable Service Call (PendSV), which is programmed to the lowest possible interrupt priority. SysTick simply sets the PENDSVSET bit and exits immediately, allowing the external IRQ to run with zero delay. PendSV executes only after all pending IRQs complete!
7. How does the Wake-Up Interrupt Controller (WIC) help in low-power deep sleep? Explain the sequence.
[5 Marks] [CO1, BTL2] PPT: Ch14 Slide 11
WIC in Deep Sleep
Diagram: Wake-up Interrupt Controller (WIC) in Deep Sleep Mode
Cited from: 4 23ECE313_ES_Ch14_Txt 1a.pdf (Slide 11)

Sequence of Events:

  1. Entering Deep Sleep: Software sets SLEEPDEEP in SCR and executes WFI.
  2. Clock Gating: The Power Management Unit (PMU) shuts down high-speed system oscillators, gating clocks to the core and NVIC (NVIC is completely powered down).
  3. WIC Monitoring: The Wake-Up Interrupt Controller (WIC) remains active in an ultra-low-power, always-on voltage domain, mirroring the enabled interrupt lines.
  4. External Event Detection: An external interrupt signal arrives at a pin. The WIC detects the signal edge/level.
  5. Waking PMU: The WIC asserts a wake-up signal to the Power Management Unit (PMU).
  6. Restoring Clocks: The PMU restarts oscillators and restores power to the core and NVIC.
  7. NVIC Vectoring: The NVIC resumes normal operation, detects the pending interrupt, and vectors the core to execute the ISR.
8. C Program & Circuit to generate 3V average output from 5V DC supply via STM32 PWM.
[5 Marks] [CO2, BTL3] PPT: Mazidi PWM Slides 1-2 & TIM2 Slides 11-12
Calculations:
Supply Voltage V_supply = 5.0 V. Target Average Voltage V_avg = 3.0 V.
Duty Cycle D = V_avg / V_supply = 3.0 V / 5.0 V = 0.60 = 60%.
Using STM32F446RE Timer 2 Channel 1 on Pin PA5 (16 MHz clock, 1 kHz PWM frequency):
• PSC = 0 -> Timer Clock = 16 MHz.
• ARR = 15999 -> f_PWM = 16 MHz / 16000 = 1 kHz.
• CCR1 = 60% * 16000 = 9600.

Circuit Interfacing Diagram:

STM32F446RE Nucleo-64 Board ┌────────────────────────────────────────┐ │ │ │ PA5 (TIM2_CH1) ────────────────────┐ │ │ [3.3V Logic PWM] │ │ │ │ │ │ GND ───────────────────────────┐ │ │ └──────────────────────────────────┼───┘ │ ┌───────────────────────┴───────────────────────┐ │ MOSFET Driver Circuit (External 5V Domain) │ │ │ │ +5V DC Supply ───────────────────────┐ │ │ │ │ │ ┌────────┴─────┐ │ │ │Output Device │ │ │ │(Fan / Heater)│ │ │ └────────┬─────┘ │ │ │ │ │ Drain ─────┘ │ │ PA5 ────[ 1kΩ Resistor ]── Gate │ │ ───[ 10kΩ Pull-down]─ Source ───┐ │ │ │ │ └───────────────────────────────────────┼───────┘ │ Common Power GND

Complete Embedded C Program:

#include "stm32f4xx.h"

int main(void) {
    // 1. Enable AHB1 clock for GPIOA and APB1 clock for TIM2
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;

    // 2. Configure PA5 as Alternate Function Mode ('10')
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (2U << (5 * 2));

    // 3. Connect PA5 to AF1 (TIM2_CH1) via AFR[0] (Bits [23:20] = 0001)
    GPIOA->AFR[0] &= ~(0xFU << (5 * 4));
    GPIOA->AFR[0] |=  (1U << (5 * 4)); // 0x1 selects AF1

    // 4. Set Timebase: 1 kHz PWM frequency at 16 MHz clock
    TIM2->PSC = 0;     // Clock = 16 MHz
    TIM2->ARR = 15999; // Period = 16 MHz / 16000 = 1 ms (1 kHz)

    // 5. Set 60% Duty Cycle for 3V average output from 5V supply: CCR1 = 9600
    TIM2->CCR1 = 9600;

    // 6. Configure Channel 1 for PWM Mode 1 (OC1M = 110) with Preload Enable
    TIM2->CCMR1 |= (6U << 4) | TIM_CCMR1_OC1PE;

    // 7. Enable Output on Channel 1
    TIM2->CCER |= TIM_CCER_CC1E;

    // 8. Enable Auto-Reload Preload and start counter
    TIM2->CR1 |= TIM_CR1_ARPE | TIM_CR1_CEN;

    while (1) {
        // Continuous 60% PWM waveform generated autonomously by hardware
    }
}
9. Analog Sensor (PA0), Relay Fan (PA5), ADC 12-Bit, UART Serial Monitor + Circuit.
[10 Marks] [CO2, BTL3] PPT: Lab Exp 1, 3 & TIM/ADC Slides
Calculations & Thresholds:
Reference Voltage V_REF = 3.3 V, 12-bit ADC Resolution -> 4095 levels.
Threshold Voltage = 2.2 V.
Threshold Digital Code = (2.2 V / 3.3 V) * 4095 = (2/3) * 4095 = 2730.
Control Logic: When ADC >= 2730 (V >= 2.2 V), turn ON Relay on PA5. When ADC < 2730 (V < 2.2 V), turn OFF Relay.

Circuit Interfacing Diagram:

STM32F446RE Microcontroller Board ┌─────────────────────────────────────────────────────────┐ │ │ │ PA0 (ADC1_IN0) ◄────── Analog Sensor Output │ │ │ │ PA2 (USART2_TX) ─────► TX Pin ──► USB / PuTTY Monitor │ │ │ │ PA5 (GPIO_OUT) ──────┐ │ │ │ │ │ GND ─────────────┐ │ │ └───────────────────┼───┼─────────────────────────────────┘ │ │ │ └────────────┐ │ │ │ ┌────┴───────────────────────────┐ │ │ Relay Module Driver Circuit │ │ │ │ │ │ PA5 ──[ 1kΩ ]── Base (NPN) │ │ │ Emitter ──┐ │ │ │ +5V ────┐ Collector │ │ │ │ │ │ │ │ │ │ ┌───┴────┐ │ │ │ │ │ │ Relay │─────┘ │ │ │ │ │ Coil │ │ │ │ │ └───┬────┘ │ │ │ │ │ │ │ │ │ [Flyback Diode] │ │ │ └──────────┼─────────────────┼───┘ │ │ │ └──────────────────────┴─────────────────┘ Common GND

Complete Embedded C Program:

#include "stm32f4xx.h"
#include 

void USART2_Init(void);
void USART2_SendChar(char c);
void USART2_SendString(char *str);
void ADC1_PA0_Init(void);
uint32_t ADC1_Read(void);

void delay_ms(uint32_t ms) {
    uint32_t count = (SystemCoreClock / 10000) * ms;
    for (volatile uint32_t i = 0; i < count; i++) { __NOP(); }
}

int main(void) {
    char buffer[80];
    uint32_t adc_val = 0;
    float voltage = 0.0f;

    // 1. Initialize Peripherals
    USART2_Init();
    ADC1_PA0_Init();

    // 2. Configure PA5 as General Output for Relay Control
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (1U << (5 * 2)); // Output mode '01'

    USART2_SendString("--- Sensor & Relay Monitoring System Online ---
");

    while (1) {
        // Read 12-bit ADC value
        adc_val = ADC1_Read();

        // Convert code to voltage: V = (ADC / 4095) * 3.3
        voltage = ((float)adc_val / 4095.0f) * 3.3f;

        // Relay Control Logic: Threshold 2.2V corresponds to code 2730
        if (adc_val >= 2730) {
            GPIOA->ODR |= (1U << 5); // Relay ON (Fan runs)
        } else {
            GPIOA->ODR &= ~(1U << 5); // Relay OFF (Fan stopped)
        }

        // Transmit readings over UART to PuTTY Serial Monitor
        snprintf(buffer, sizeof(buffer), "ADC: %lu | Volt: %.2f V | Fan: %s
",
                 adc_val, voltage, (adc_val >= 2730) ? "ON" : "OFF");
        USART2_SendString(buffer);

        delay_ms(500); // 500 ms sampling period
    }
}

// USART2 Configuration: PA2 as TX (AF7), 9600 Baud at 16 MHz
void USART2_Init(void) {
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    RCC->APB1ENR |= RCC_APB1ENR_USART2EN;

    GPIOA->MODER &= ~(3U << (2 * 2));
    GPIOA->MODER |=  (2U << (2 * 2)); // Alternate Function '10'

    GPIOA->AFR[0] &= ~(0xFU << (2 * 4));
    GPIOA->AFR[0] |=  (7U << (2 * 4)); // AF7 for USART2

    USART2->BRR = 0x0683; // 9600 Baud at 16 MHz
    USART2->CR1 = USART_CR1_TE | USART_CR1_UE; // Transmitter Enable & Module Enable
}

void USART2_SendChar(char c) {
    while (!(USART2->SR & USART_SR_TXE)); // Wait for TX data register empty
    USART2->DR = c;
}

void USART2_SendString(char *str) {
    while (*str) { USART2_SendChar(*str++); }
}

// ADC1 Configuration on PA0 (Channel 0)
void ADC1_PA0_Init(void) {
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;

    GPIOA->MODER |= (3U << (0 * 2)); // PA0 Analog Mode '11'

    ADC1->SQR1 = 0; // 1 conversion
    ADC1->SQR3 = 0; // Channel 0 first

    // Sample time: 84 cycles for Channel 0 (SMPR2 bits [2:0] = 100)
    ADC1->SMPR2 |= (4U << 0);

    ADC1->CR2 |= ADC_CR2_ADON; // Power ON ADC
}

uint32_t ADC1_Read(void) {
    ADC1->CR2 |= ADC_CR2_SWSTART;     // Trigger conversion
    while (!(ADC1->SR & ADC_SR_EOC)); // Wait for End Of Conversion
    return ADC1->DR;                  // Read 12-bit value (clears EOC)
}

📝 Practice Question Paper - Set 1 (50 Marks)

Model Exam Set 1

Mirroring the exact difficulty, BTL taxonomy, and question pattern of Professor Giriraja C. V. Click to reveal complete solutions and slide citations:

1. Briefly explain the four Memory Access Attributes in Cortex-M3 architecture.
[5 Marks] [CO1, BTL1] PPT: Ch_Txt1 Slide 11

Direct Reference: 2 23ECE313_ES_Ch_Txt1.pdf (Slide 11)

  • 1. Bufferable: Write transfers to memory can be handled by an internal write buffer while the processor continues executing subsequent instructions without stalling. (Nuance: Write buffers can cause Imprecise Bus Faults if the bus later returns an error!)
  • 2. Cacheable: Data or instruction reads from memory can be copied into high-speed local cache memories to accelerate subsequent accesses.
  • 3. Executable (XN - Execute Never): Defines whether instructions can be fetched and executed from the region. Attempting to fetch code from an XN region (like Peripherals or System Space) triggers an immediate MemManage Fault.
  • 4. Shareable: Indicates that memory is accessible by multiple bus masters (e.g. DMA and CPU core). The memory system enforces hardware coherency protocols across shared masters.
2. Assembly Execution, Reverse Subtract, IT Block & Full Descending Stack Trace.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slides 30, 48 & 57
Given Assembly Sequence:
LDR R0, =0x20000000
LDR SP, =0x20000200
LDR R1, =0x11223344
LDR R2, =0x55667788
SUBS R3, R1, R2
IT MI
STMDB SP!, {R0, R2}
STOP B STOP

Step-by-Step Execution Analysis:

  1. LDR R0, =0x20000000 -> R0 = 0x20000000.
  2. LDR SP, =0x20000200 -> SP = 0x20000200.
  3. LDR R1, =0x11223344 -> R1 = 0x11223344.
  4. LDR R2, =0x55667788 -> R2 = 0x55667788.
  5. SUBS R3, R1, R2 -> Subtracts R2 from R1. Since R1 < R2, the result is negative. The N (Negative) flag in APSR is set to 1.
  6. IT MI -> If-Then block with condition MI (Minus / Negative: N == 1). Since N = 1, condition evaluates to TRUE.
  7. STMDB SP!, {R0, R2} -> Pushes 2 registers (8 bytes = 0x08).
    • Final SP = 0x20000200 - 0x08 = 0x200001F8.
    • R2 is placed at 0x200001FC, R0 is placed at 0x200001F8.

Final State:

Register / AddressValue
R00x20000000
R10x11223344
R20x55667788
SP0x200001F8
0x200001FC0x55667788 (R2)
0x200001F80x20000000 (R0)
3. Explain the CoreSight On-Chip Debug Architecture and Differentiate Halt vs Debug Monitor Modes.
[5 Marks] [CO2, BTL2] PPT: Ch15 Slides 4, 15 & 16
Trace Architecture
Diagram: Cortex-M3 Debug & Trace Architecture
Cited from: 5 23ECE313_ES_Ch15_Txt 1a.pdf (Slide 10)

Functions of Key CoreSight Units:

  • DWT (Data Watchpoint and Trace): Monitors data address accesses, provides cycle counting, and event profiling.
  • FPB (Flash Patch and Breakpoint): Hardware breakpoint comparator (6 instruction breakpoints, 2 literal slots).
  • ITM (Instrumentation Trace Macrocell): Software printf debugging via Serial Wire Output (SWO) pin.
  • ETM (Embedded Trace Macrocell): Instruction tracing streamed out via TPIU.

Comparison of Debug Modes:

FeatureHalt ModeDebug Monitor Mode
CPU StateCompletely stopped (halted)Executes Exception 12 handler
SysTick TimerStoppedContinues running
InterruptsMasked/pendedHigher-priority interrupts can still preempt
ApplicationBare-metal firmware debuggingSafety-critical motor control / RTOS
4. With a neat timing diagram, explain the Cortex-M3 Reset Sequence and initial vector fetches.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slides 76 & 77
Reset Sequence
Diagram: Reset Sequence Vector Fetch Flow
Cited from: 1 23ECE313_ES_Ch4 Text 1.pdf (Slide 76)

Step-by-Step Reset Sequence:

  1. Step 1: System reset signal is de-asserted; clock stabilizes.
  2. Step 2 (Fetch Vector 0): Hardware fetches the 32-bit word from memory address 0x00000000 and loads it directly into the Main Stack Pointer (MSP). This ensures a valid stack exists before executing any code!
  3. Step 3 (Fetch Vector 1): Hardware fetches the 32-bit word from memory address 0x00000004 and loads it directly into the Program Counter (PC). This word contains the address of the Reset_Handler function. Bit 0 of this address must be 1 to specify Thumb state.
  4. Step 4: Processor begins instruction execution at Reset_Handler in Privileged Thread Mode.
5. With a neat diagram, explain Preempt Priority and Sub-Priority splitting in the NVIC.
[5 Marks] [CO1, BTL2] PPT: Ch_Txt1 Slide 32
AIRCR PRIGROUP
Diagram: AIRCR PRIGROUP Preempt vs Sub-Priority Splitting
Cited from: 2 23ECE313_ES_Ch_Txt1.pdf (Slide 32)

Priority Rules:

  • Each interrupt priority level register holds an 8-bit priority value (microcontrollers implement top 3 to 8 bits). Smaller numerical values indicate higher logical priority (0 is highest).
  • The PRIGROUP field in the Application Interrupt and Reset Control Register (AIRCR) splits the priority bits into two fields:
    • Preemption Priority: Determines whether an arriving interrupt can interrupt (nest inside) an currently executing ISR.
    • Sub-Priority: When two pending interrupts have the identical preemption priority, the one with the smaller sub-priority value executes first. Sub-priority does NOT cause preemption!
6. Explain the 4 Fault Exceptions in Cortex-M3 and Fault Escalation to HardFault.
[5 Marks] [CO1, BTL2] PPT: Ch12 Slides 5 & 20
Fault Table
Diagram: ARMv7-M Fault Exceptions Summary Table
Cited from: 3 23ECE313_ES_Ch12_Txt1.pdf (Slide 5)

Fault Descriptions:

  • MemManage (Exc #4): MPU permission violation, unprivileged task accessing privileged memory, or executing from Execute-Never (XN) regions.
  • Bus Fault (Exc #5): Bus error response during read/write. Precise (immediate) vs Imprecise (buffered write).
  • Usage Fault (Exc #6): Undefined instruction, division by zero, unaligned memory access, or clearing Thumb bit (T=0).
  • HardFault (Exc #3): Fixed priority -1. Caused by:
    • Fault Escalation: When a configurable fault occurs while its handler is disabled in SHCSR.
    • A fault occurring inside an active fault handler with equal or higher priority.
    • Bus error during vector table fetch.
7. Explain Sleep-on-Exit and Multiprocessor Synchronization (SEV & WFE) with neat flowcharts.
[5 Marks] [CO1, BTL2] PPT: Ch14 Slides 7 & 16
Sleep on Exit
Diagram: Sleep-on-Exit Operation
Cited from: 4 23ECE313_ES_Ch14_Txt 1a.pdf (Slide 7)

Sleep-on-Exit Working:

Configured by setting SLEEPONEXIT in System Control Register (SCR). After ISR completes, the processor skips Thread Mode and returns directly to sleep, eliminating stack restore overhead in interrupt-only systems.

Multiprocessor Event
Diagram: Multiprocessor Task Synchronization Using Event Signals
Cited from: 4 23ECE313_ES_Ch14_Txt 1a.pdf (Slide 16)

Multiprocessor Signals:

SEV instruction pulses TXEV pin to wake other cores. WFE (Wait For Event) sleeps until RXEV is asserted.

8. C Program & Circuit to generate an accurate 2-second delay using TIM5 to toggle an LED on PA5.
[5 Marks] [CO2, BTL3] PPT: Lab Exp 2
Calculations:
Clock f_sys = 16 MHz. Prescaler PSC = 15999 -> f_timer = 16 MHz / 16000 = 1 kHz (1 ms tick).
For 2 seconds: ARR = (2 * 1000) - 1 = 1999.

Circuit Interfacing Diagram:

STM32F446RE Nucleo Board ┌────────────────────────────────────────┐ │ │ │ PA5 (GPIO_OUT) ──[ 220Ω Resistor ]───┼──► [Anode] Green LED [Cathode] ──┐ │ │ │ │ GND ─────────────────────────────────┴──────────────────────────────────┘ └────────────────────────────────────────┘

Complete Embedded C Code:

#include "stm32f4xx.h"

void delay_seconds(uint32_t seconds) {
    RCC->APB1ENR |= RCC_APB1ENR_TIM5EN; // Enable TIM5 clock
    TIM5->PSC = 15999;                  // 1 ms tick (16 MHz / 16000)
    TIM5->ARR = (seconds * 1000) - 1;   // Reload value
    TIM5->CNT = 0;                      // Reset count
    TIM5->CR1 |= TIM_CR1_CEN;           // Start timer
    while (!(TIM5->SR & TIM_SR_UIF));   // Wait for overflow UIF flag
    TIM5->SR  &= ~TIM_SR_UIF;           // Clear flag
    TIM5->CR1 &= ~TIM_CR1_CEN;          // Stop timer
}

int main(void) {
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (1U << (5 * 2)); // Output mode '01'

    while (1) {
        GPIOA->ODR ^= (1U << 5); // Toggle LED
        delay_seconds(2);        // 2-second delay
    }
}
9. External Interrupt (EXTI13) System Design on PC13 toggling LED on PA5 + Circuit Diagram.
[10 Marks] [CO2, BTL3] PPT: Mazidi EXTI Slide 3 & Lab Exp 1
Hardware Design: External Push Button on PC13 (Active-Low with internal/external pull-up). Green LED on PA5. SYSCFG routes Port C to EXTI line 13. Falling-edge detection triggers EXTI15_10_IRQHandler.

Circuit Interfacing Diagram:

STM32F446RE Microcontroller ┌───────────────────────────────────────────────────┐ │ │ │ PC13 (EXTI13) ◄───┬───[ Push Button ]─── GND │ │ │ │ │ [ 10kΩ Pull-up ] │ │ │ │ │ +3.3V │ │ │ │ PA5 (GPIO_OUT) ───[ 220Ω ]──► LED (Green) ──┐ │ │ │ │ │ GND ────────────────────────────────────────┴───┘ └───────────────────────────────────────────────────┘

Complete Embedded C Program:

#include "stm32f4xx.h"

void EXTI13_Init(void) {
    // 1. Enable Clocks for GPIOA (LED), GPIOC (Button), and SYSCFG
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOCEN;
    RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;

    // 2. PA5 as Output (LED), PC13 as Input (Button)
    GPIOA->MODER |= (1U << (5 * 2));
    GPIOC->MODER &= ~(3U << (13 * 2));

    // 3. Connect EXTI13 to Port C in SYSCFG_EXTICR4 (bits [7:4] = 0010)
    SYSCFG->EXTICR[3] &= ~(0xFU << 4);
    SYSCFG->EXTICR[3] |=  (0x2U << 4); // Port C

    // 4. Configure Falling-edge Trigger in FTSR (Button press pulls to 0)
    EXTI->FTSR |= (1U << 13);
    EXTI->RTSR &= ~(1U << 13);

    // 5. Unmask interrupt line 13 in IMR
    EXTI->IMR |= (1U << 13);

    // 6. Enable in NVIC
    NVIC_SetPriority(EXTI15_10_IRQn, 2);
    NVIC_EnableIRQ(EXTI15_10_IRQn);
}

void EXTI15_10_IRQHandler(void) {
    if (EXTI->PR & (1U << 13)) {
        GPIOA->ODR ^= (1U << 5); // Toggle LED
        EXTI->PR = (1U << 13);   // Clear pending bit (WRITE 1 TO CLEAR!)
    }
}

int main(void) {
    EXTI13_Init();
    while (1) {
        __WFI(); // Sleep until button press interrupt
    }
}

📝 Practice Question Paper - Set 2 (50 Marks)

Model Exam Set 2

Comprehensive coverage of Unit 1, Unit 2, and Peripheral Interfacing. Click any question to reveal complete step-by-step solutions, slide citations, register breakdowns, and schematics:

1. Explain the Operating Modes (Thread vs Handler), Privilege Levels, and Dual Stack Pointers (MSP vs PSP) with the CONTROL Register.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slides 19, 23, 27

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slides 19, 23, 27)

Operating Modes and Privilege Levels
Figure 2.1: Cortex-M3 Operating Modes & States (Ch 4 Slide 19)
1. Two Operating Modes:
  • Thread Mode: The default mode entered upon reset. Used to execute regular application tasks / main program code. Can run in either Privileged or Unprivileged state.
  • Handler Mode: Automatically entered whenever an exception or interrupt occurs. Always executes in Privileged state (cannot be switched to unprivileged). Returns to Thread mode upon exception completion via EXC_RETURN.
2. Two Privilege Levels:
  • Privileged Level: Software has full access to all memory ranges and all core control registers (NVIC, MPU, SCB, SysTick). Allowed to switch to unprivileged state by modifying the CONTROL register.
  • Unprivileged (User) Level: Restricts software from accessing System Control Space (PPB: 0xE0000000 - 0xE00FFFFF), and restricts MPU regions marked privileged-only. Prevents user bugs from crashing the operating system. Cannot directly switch back to privileged mode; must execute an SVC (Supervisory Call).
CONTROL Register
Figure 2.2: CONTROL Register Bit Layout (Ch 4 Slide 27)
3. The CONTROL Register (Bits [1:0]):
  • CONTROL[0] (nPRIV):
    • 0 = Privileged thread execution.
    • 1 = Unprivileged thread execution.
  • CONTROL[1] (SPSEL):
    • 0 = Use Main Stack Pointer (MSP) in Thread mode.
    • 1 = Use Process Stack Pointer (PSP) in Thread mode.
    • Note: Handler mode always uses MSP regardless of SPSEL setting!
4. Dual Stack Pointers (MSP vs PSP):
  • MSP (Main Stack Pointer): Used by the OS kernel, exception handlers, and interrupts. Configured at boot from vector table index 0 (`0x00000000`).
  • PSP (Process Stack Pointer): Dedicated stack pointer assigned to individual user application tasks in an RTOS.
  • Key Advantage: If a user task overflows its stack (PSP), the system kernel and interrupt handlers (using MSP) remain completely uncorrupted and can safely catch the fault!
2. Derive the Bit-Banding memory mapping formula. Calculate the exact alias address for Bit 5 of GPIOA_ODR (0x40020014) and explain its real-time advantages.
[5 Marks] [CO1, BTL3] PPT: Ch_Txt1 Slide 12

Direct Reference: 2 23ECE313_ES_Ch_Txt1.pdf (Slide 12)

Bit Band Memory Map
Figure 2.3: Bit-Band Region & Alias Region Mapping (Ch_Txt1 Slide 12)
1. Mathematical Derivation of the Formula:

Cortex-M3 provides two 1 MB bit-band regions mapped to 32 MB alias regions:

  • SRAM Bit-Band: 0x20000000 - 0x200FFFFF ──► Alias: 0x22000000 - 0x23FFFFFF
  • Peripheral Bit-Band: 0x40000000 - 0x400FFFFF ──► Alias: 0x42000000 - 0x43FFFFFF

In the alias region, every single bit in the bit-band region is mapped to an entire 32-bit (4-byte) word. Therefore:

  • 1 byte in the bit-band region contains 8 bits, requiring 8 × 4 = 32 bytes in the alias region.
  • Each individual bit n within that byte is offset by n × 4 bytes.
General Bit-Band Alias Address Formula:
Bit_Word_Addr = Alias_Base + (Byte_Offset × 32) + (Bit_Number × 4)
Where: Byte_Offset = Target_Address - Bit_Band_Base
2. Step-by-Step Numerical Calculation for Bit 5 of GPIOA_ODR (0x40020014):
  1. Target Address: 0x40020014 (Peripheral Region)
  2. Bit Number (n): 5
  3. Peripheral Base: 0x40000000
  4. Peripheral Alias Base: 0x42000000
  5. Byte Offset:
    0x40020014 - 0x40000000 = 0x00020014 (in decimal: 131,092 bytes)
  6. Calculate (Byte_Offset × 32):
    Multiplying by 32 in hex is shifting left by 5 bits:
    0x00020014 × 0x20 = 0x00400280 (decimal: 131,092 × 32 = 4,194,944 = 0x400280)
  7. Calculate (Bit_Number × 4):
    5 × 4 = 20 = 0x00000014
  8. Total Alias Address:
    0x42000000 + 0x00400280 + 0x00000014 = 0x42400294
Final Answer: The bit-band alias address is 0x42400294. Writing 1 to this address sets PA5; writing 0 clears PA5.
3. Real-Time & Multitasking Advantages:
  • Atomic Operation: Performs atomic read-modify-write entirely in hardware without disabling interrupts.
  • Eliminates Race Conditions: If an interrupt occurs between a read and write of a shared port register, software bit operations (ODR |= (1<<5)) corrupt adjacent bits. Bit-banding prevents this completely!
  • Code Density & Speed: Replaces 3 assembly instructions (LDR, ORR, STR) with a single atomic STR instruction.
3. Contrast Precise vs Imprecise Bus Faults. Explain the Write Buffer mechanism and how to diagnose imprecise faults using ACTLR.
[5 Marks] [CO2, BTL2] PPT: Ch12 Slides 10–14, 23

Direct Reference: 3 23ECE313_ES_Ch12_Txt1.pdf (Slides 10–14, 23)

Feature Precise Bus Fault Imprecise Bus Fault
Cause Synchronous bus error (Instruction fetch, data read, or non-buffered write). Asynchronous bus error caused by the Write Buffer during buffered writes.
Stacked PC Value Exact: Stacked PC points directly to the instruction that triggered the bus error. Inaccurate: The processor moved on while the write buffer was writing. Stacked PC points to an arbitrary later instruction!
Fault Address Register (BFAR) Valid: BFSR->BFARVALID = 1. BFAR register contains the exact faulting memory address. Invalid: BFSR->BFARVALID = 0. The memory address that triggered the fault is lost.
Status Flag in BFSR PRECISERR (Bit 1) = 1 IMPRECISERR (Bit 2) = 1
Mechanism of the Imprecise Bus Fault (The Write Buffer Trap):

To maximize execution throughput, Cortex-M incorporates an internal Write Buffer on the system bus. When a program writes to memory, the write data is queued in the buffer, and the CPU immediately proceeds to execute subsequent instructions without waiting for bus acknowledgement. If the bus later rejects the transaction (e.g. invalid peripheral address, slave timeout), the error arrives cycles later. By then, the CPU is already executing unrelated code!

Diagnostic Method using ACTLR (Auxiliary Control Register):

Because imprecise bus faults make debugging nearly impossible (unknown PC and unknown address), ARM provides a hardware override:

// Set DISDEFWBUF bit (Bit 1) in ACTLR (Address: 0xE000E008)
SCB->ACTLR |= SCB_ACTLR_DISDEFWBUF_Msk; // Disables Write Buffer

Effect: Disabling the write buffer forces all write operations to complete synchronously before the next instruction executes. When the faulty write occurs, it immediately triggers a Precise Bus Fault, allowing the developer to inspect the exact stacked PC and read the faulty address from BFAR!

4. With a neat timing diagram, explain the 3-Stage Pipeline in Cortex-M3 and analyze the Branch Flush penalty.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slide 17

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slide 17)

3 Stage Pipeline
Figure 2.4: Cortex-M3 3-Stage In-Order Pipeline (Ch 4 Slide 17)
1. The Three Pipeline Stages:
  • Stage 1 (Fetch): Fetches the 16-bit or 32-bit Thumb-2 instruction from memory (Flash/SRAM) via the I-Code or System bus and places it into the instruction buffer.
  • Stage 2 (Decode): Decodes the instruction opcode, identifies register operands, and generates internal datapath control signals.
  • Stage 3 (Execute): Executes the operation in the ALU, performs barrel shifter operations, updates status flags, or accesses memory (Load/Store).
2. Normal Sequential Execution (1 Instruction per Cycle Throughput):
Clock Cycle:     | T1 | T2 | T3 | T4 | T5 |
Instr 1 (ADD):   | Fe | De | Ex |    |    |
Instr 2 (SUB):   |    | Fe | De | Ex |    |
Instr 3 (MOV):   |    |    | Fe | De | Ex |
3. Branch Hazard & Pipeline Flush Penalty:

When a branch instruction (e.g., B label, BL, BX) reaches the Execute stage and the branch is taken, the instructions already fetched and decoded in stages 1 and 2 are invalid and must be flushed (discarded).

Clock Cycle:       | T1 | T2 | T3   | T4    | T5    |
Instr 1 (B target):| Fe | De | Ex   |       |       |  <-- Branch target computed in Ex
Instr 2 (Next):    |    | Fe | De   | FLUSH |       |  <-- Discarded!
Instr 3 (Next+1):  |    |    | Fe   | FLUSH |       |  <-- Discarded!
Target Instr 1:    |    |    |      | Fe    | De    | Ex  <-- 2 cycle branch penalty!
4. Mitigation in Cortex-M Architecture:
  • Branch Speculation: Speculative prefetching fetches the target address early.
  • Thumb-2 IT (If-Then) Blocks: Conditional execution allows up to 4 instructions to execute conditionally without taking a branch, completely eliminating branch flush penalties in short decision trees!
5. Explain the Supervisory Call (SVC) exception mechanism, hardware stack frame, and how the C handler extracts the SVC immediate number.
[5 Marks] [CO2, BTL3] PPT: Ch12 Slides 28–34

Direct Reference: 3 23ECE313_ES_Ch12_Txt1.pdf (Slides 28–34)

SVC Stack Frame
Figure 2.5: Hardware Stack Frame & Parameter Passing in SVC (Ch 12 Slide 30)
1. Purpose of SVC:

The SVC (Supervisory Call) instruction generates a synchronous software exception used by unprivileged user application tasks to request privileged operating system services (file system, hardware drivers, memory allocation).

2. Step-by-Step Hardware Execution:
  1. User task executes SVC #number (e.g. SVC #3).
  2. Hardware automatically saves the standard 8-word stack frame on the current stack (PSP):
    [SP+0] = R0, [SP+4] = R1, [SP+8] = R2, [SP+12] = R3, [SP+16] = R12, [SP+20] = LR, [SP+24] = Return PC, [SP+28] = xPSR.
  3. Processor switches to Handler Mode (Privileged) and loads EXC_RETURN into LR.
  4. Processor branches to SVC_Handler using the vector fetched from vector table entry 11 (offset 0x0000002C).
3. Assembly Trampoline to Detect Stack Pointer (MSP vs PSP):
__asm void SVC_Handler(void) {
    TST LR, #4          // Test Bit 2 of EXC_RETURN (0 = MSP, 1 = PSP)
    ITE EQ
    MRSEQ R0, MSP       // Stack pointer was MSP, pass in R0
    MRSNE R0, PSP       // Stack pointer was PSP, pass in R0
    B SVC_Handler_C     // Branch to C handler with stack frame pointer in R0
}
4. Extracting the SVC Number in C:
void SVC_Handler_C(uint32_t *svc_args) {
    // svc_args[6] is the stacked Return PC!
    // Since Thumb-2 SVC is a 2-byte opcode [0xDF, SVC_#],
    // subtract 2 bytes from Return PC to point directly to the SVC instruction!
    uint8_t svc_number = ((uint8_t *)svc_args[6])[-2];

    switch (svc_number) {
        case 0: // Read Service
            svc_args[0] = OS_Read(svc_args[1], svc_args[2]); // Return in R0
            break;
        case 1: // Write Service
            svc_args[0] = OS_Write(svc_args[1], svc_args[2]);
            break;
        default:
            break;
    }
}
Exam Trap: Notice that return values are passed back to the user task by modifying svc_args[0] (stacked R0), which hardware automatically restores into register R0 upon unstacking!
6. Compare the Interrupt Masking Registers: PRIMASK, FAULTMASK, and BASEPRI. Write the assembly instructions to control them.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slides 31–33

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slides 31–33)

Register Width Effective Priority Level Exceptions Blocked Assembly Instructions
PRIMASK 1 bit 0 (Highest configurable priority) Blocks all interrupts with configurable priority. NMI and HardFault still execute! CPSID i (Disable IRQs)
CPSIE i (Enable IRQs)
FAULTMASK 1 bit -1 (HardFault priority level) Blocks all interrupts and all configurable faults (MemManage, BusFault, UsageFault) plus HardFault. Only NMI can execute! Cleared automatically on exception exit. CPSID f (Disable All)
CPSIE f (Enable All)
BASEPRI Up to 8 bits Configurable threshold N Blocks only interrupts with priority level ≥ N (numerically equal or lower priority). Leaves higher priority interrupts (< N) active. When set to 0, masking is disabled. MSR BASEPRI, R0
MRS R0, BASEPRI
Why RTOS Kernels Prefer BASEPRI over PRIMASK:

In hard real-time systems, critical tasks (e.g. emergency motor stop, radar timing) must never experience interrupt latency. By setting BASEPRI to a mid-level threshold (e.g. priority 3), the OS scheduler can protect its internal queues without blocking ultra-high-priority hard real-time interrupts (priorities 0, 1, and 2)!

7. Explain the NVIC Advanced Mechanisms: Tail-Chaining and Late-Arrival with cycle-accurate timing comparisons.
[5 Marks] [CO2, BTL2] PPT: Ch_Txt1 Slides 25–28

Direct Reference: 2 23ECE313_ES_Ch_Txt1.pdf (Slides 25–28)

1. Tail-Chaining Mechanism:

Occurs when an interrupt arrives while the processor is already servicing another interrupt, or during the completion phase of an ISR.

  • Traditional Microcontroller Flow: Unstacking previous registers (16 cycles) ──► Re-stacking registers for next interrupt (16 cycles) = 32+ clock cycles wasted!
  • Cortex-M3 Tail-Chaining Flow: The NVIC skips the unstacking and re-stacking completely! It reuses the existing stack frame and transitions directly from the finishing ISR to the pending ISR in just 6 clock cycles.
Traditional: [ ISR 1 ] ──► [ Unstack (16c) ] ──► [ Restack (16c) ] ──► [ ISR 2 ] (32+ cycles)
Cortex-M3:   [ ISR 1 ] ──► [ Tail-Chain (6 cycles) ] ───────────────► [ ISR 2 ] (6 cycles!)
2. Late-Arrival Mechanism:

Occurs when a higher-priority interrupt arrives while the processor is in the middle of stacking registers for an earlier, lower-priority interrupt.

  • Behavior: The processor does NOT abort or restart the stacking process. It completes the 12-cycle register stacking in progress, updates the vector fetch address to point to the higher-priority interrupt handler, and enters the high-priority ISR immediately!
  • Result: Zero cycles wasted. When the high-priority ISR completes, the original lower-priority interrupt is serviced immediately via tail-chaining in 6 cycles.
8. Hardware Interfacing & C Program to generate a 10 kHz PWM signal with 75% duty cycle on PA5 (TIM2_CH1) to drive a DC motor via MOSFET.
[5 Marks] [CO3, BTL3] PPT: Mazidi Timers & PWM Slides 4–9

Direct Reference: STM32F446RE_Timers_PWM_ADC_Mazidi.pdf (Slides 4–9)

1. Circuit Interfacing Schematic:
+3.3V System GND +12V DC Supply │ │ │ ├──[ + DC Motor - ]──┐ │ │ │ │ └───[◄───(1N4007)───]┤ (Flyback Diode) │ │ STM32F446RE ┌───┴───┐ ┌─────────────┐ │ Drain │ │ │ 100 Ω │ │ │ PA5 ├─────────[====]──────────┬───────────────────────────────┤ Gate │ N-Channel Logic MOSFET │ (TIM2_CH1) │ │ │ │ (e.g. IRLZ44N) │ │ [10kΩ] Pulldown │ Source│ │ GND ├─────────────────────────┴───────────────────────────────┴───┬───┘ └─────────────┘ │ GND (Common)
2. Mathematical Calculations (System Clock = 16 MHz HSI):
  • Target PWM Frequency: f_PWM = 10 kHz
  • Timer Clock: 16 MHz
  • Set Prescaler: PSC = 0 (Counter frequency = 16 MHz / 1 = 16 MHz)
  • Calculate Auto-Reload: ARR = (16,000,000 / 10,000) - 1 = 1600 - 1 = 1599
  • Duty Cycle (75%): CCR1 = 0.75 × (ARR + 1) = 0.75 × 1600 = 1200
3. Complete CMSIS Register C Program:
#include "stm32f4xx.h"

void PWM_TIM2_PA5_Init(void) {
    // 1. Enable Clock for GPIOA (AHB1) and TIM2 (APB1)
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;

    // 2. Configure PA5 as Alternate Function mode (MODER bits [11:10] = '10')
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (2U << (5 * 2));

    // 3. Set Alternate Function to AF1 (TIM2_CH1) in AFR[0] (Bits [23:20] = 0x01)
    GPIOA->AFR[0] &= ~(0xFU << (5 * 4));
    GPIOA->AFR[0] |=  (1U   << (5 * 4));

    // 4. Configure TIM2 Time Base: 10 kHz
    TIM2->PSC = 0;       // Prescaler = 0 (16 MHz timer clock)
    TIM2->ARR = 1599;    // Auto-reload value (Period = 1600 cycles = 100 us)

    // 5. Configure 75% Duty Cycle
    TIM2->CCR1 = 1200;   // Compare match value (75% of 1600)

    // 6. Set PWM Mode 1 (OC1M = '110') and enable Preload (OC1PE = 1) in CCMR1
    TIM2->CCMR1 &= ~(7U << 4);
    TIM2->CCMR1 |=  (6U << 4);   // PWM Mode 1: High until counter > CCR1
    TIM2->CCMR1 |=  TIM_CCMR1_OC1PE;

    // 7. Enable Channel 1 Output in CCER (CC1E = 1, Active High polarity)
    TIM2->CCER |= TIM_CCER_CC1E;

    // 8. Enable Main Counter in CR1 (CEN = 1)
    TIM2->CR1 |= TIM_CR1_CEN;
}

int main(void) {
    PWM_TIM2_PA5_Init();
    while (1) {
        // Hardware timer generates 10 kHz 75% PWM automatically!
    }
}
9. Interfacing & C Program: Read analog temperature on PA0 (ADC1), trigger 12V cooling fan on PA5 when V > 2.0V, and send serial alert over USART2 at 115200 baud.
[10 Marks] [CO3, BTL3] PPT: Mazidi ADC Slides 11–17, UART Slides

Direct Reference: STM32F446RE_Timers_PWM_ADC_Mazidi.pdf (Slides 11–17)

1. Complete Circuit Interfacing Diagram:
+3.3V +12V DC Supply │ │ ┌─┴─────────┐ ├──[ + 12V Fan - ]──┐ │ Analog │ │ │ │ Temp │ └───[◄───(1N4007)───]┤ (Flyback Diode) │ Sensor │ │ │ (LM35) │ ┌──┴──┐ └─┬────┬────┘ STM32F446RE │ C │ NPN Transistor │ └──────► PA0 (ADC1_IN0) 1 kΩ │ │ (e.g. BD139 / TIP120) GND PA5 (Fan Control) ───[====]─────────┤ B │ PA2 (USART2_TX) ───► RX (PuTTY) │ E │ GND ──────────────────┴──┬──┘ │ GND (Common)
2. Mathematical Calculations:
  • ADC Resolution: 12-bit (0 to 4095 counts for 0V to 3.3V).
  • Quantization Step: 3.3V / 4095 ≈ 0.8058 mV/count.
  • Threshold Voltage: V_th = 2.0V.
  • Threshold Digital Count: Threshold = (2.0V / 3.3V) × 4095 = 2481.8 ≈ 2482.
  • USART2 Baud Rate: 16 MHz / (16 × 115200) = 8.6805.
    Mantissa = 8 = 0x08, Fraction = 0.6805 × 16 ≈ 11 = 0x0B.
    USART2->BRR = 0x008B.
3. Complete Embedded C Program:
#include "stm32f4xx.h"

void System_Init(void) {
    // 1. Enable Peripheral Clocks
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;  // GPIOA clock
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;   // ADC1 clock (APB2)
    RCC->APB1ENR |= RCC_APB1ENR_USART2EN; // USART2 clock (APB1)

    // 2. Configure PA0 as Analog Mode for ADC1_IN0 (MODER[1:0] = '11')
    GPIOA->MODER |= (3U << (0 * 2));

    // 3. Configure PA5 as General Purpose Output for Fan Control (MODER[11:10] = '01')
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (1U << (5 * 2));

    // 4. Configure PA2 as Alternate Function AF7 for USART2_TX (MODER[5:4] = '10')
    GPIOA->MODER &= ~(3U << (2 * 2));
    GPIOA->MODER |=  (2U << (2 * 2));
    GPIOA->AFR[0] &= ~(0xFU << (2 * 4));
    GPIOA->AFR[0] |=  (7U   << (2 * 4)); // AF7 = USART2

    // 5. Configure ADC1
    ADC1->CR1 = 0;                        // 12-bit resolution
    ADC1->SMPR2 |= (4U << (0 * 3));       // 84 cycles sample time for Channel 0
    ADC1->SQR1 = 0;                       // 1 conversion in regular sequence
    ADC1->SQR3 = 0;                       // 1st conversion is Channel 0 (PA0)
    ADC1->CR2 |= ADC_CR2_ADON;            // Enable ADC1 power

    // 6. Configure USART2 (115200 Baud @ 16 MHz, 8-N-1)
    USART2->BRR = 0x008B;                 // 115200 baud
    USART2->CR1 |= USART_CR1_TE | USART_CR1_UE; // Transmitter enable & USART enable
}

uint16_t ADC1_Read(void) {
    ADC1->CR2 |= ADC_CR2_SWSTART;         // Start software conversion
    while (!(ADC1->SR & ADC_SR_EOC));     // Wait until End Of Conversion flag is set
    return ADC1->DR;                      // Read 12-bit data (clears EOC flag)
}

void UART2_SendString(char *str) {
    while (*str) {
        while (!(USART2->SR & USART_SR_TXE)); // Wait for Transmit Data Register Empty
        USART2->DR = (*str++ & 0xFF);         // Transmit byte
    }
}

int main(void) {
    System_Init();
    
    while (1) {
        uint16_t adc_val = ADC1_Read();

        // Check if analog voltage > 2.0V (ADC Count > 2482)
        if (adc_val > 2482) {
            GPIOA->ODR |= (1U << 5);           // Turn ON Fan
            UART2_SendString("ALERT: HIGH TEMP! FAN ACTIVATED
");
        } else {
            GPIOA->ODR &= ~(1U << 5);          // Turn OFF Fan
        }

        // Small software delay between readings
        for (volatile int i = 0; i < 500000; i++);
    }
}

📝 Practice Question Paper - Set 3 (50 Marks)

Model Exam Set 3

Final master preparation set covering deep architectural traps, vector alignments, MPU sub-regions, and multi-peripheral integration:

1. Explain the Memory Protection Unit (MPU) Architecture, Region Registers, Sub-Region Disable (SRD) Bits, and MemManage Faults.
[5 Marks] [CO1, BTL2] PPT: Ch_Txt1 Slides 14–18

Direct Reference: 2 23ECE313_ES_Ch_Txt1.pdf (Slides 14–18)

MPU Subregion Breakdown
Figure 3.1: MPU 8 Sub-Regions & SRD Masking (Ch_Txt1 Slide 18)
1. MPU Architecture Overview:

The MPU divides the 4 GB memory map into up to 8 programmable regions (numbered 0 to 7). A background region with default privileged access permissions can be enabled via PRIVDEFENA.

2. Key MPU Control Registers:
  • MPU->CTRL: Enables MPU (ENABLE bit), enables default memory map in privileged mode (PRIVDEFENA), and enables MPU during HardFault and NMI (HFNMIENA).
  • MPU->RNR: Region Number Register (0 to 7) to select active region.
  • MPU->RBAR: Region Base Address Register (must be aligned to region size).
  • MPU->RASR: Region Attribute and Size Register:
    • SIZE bits [5:1]: Region size = 2^(SIZE+1) bytes (minimum 32 bytes).
    • AP bits [26:24]: Access Permissions (Privileged RW / User None, Privileged RO / User RO, etc.).
    • XN bit [28]: Execute Never (prevents code execution from data/stack).
    • TEX, C, B bits: Cache and write buffer memory attributes.
    • SRD bits [15:8]: Sub-Region Disable field.
3. Sub-Region Disable (SRD) Mechanism:
  • Any MPU region of size ≥ 256 bytes is automatically split into 8 equal-sized sub-regions.
  • The SRD field contains 8 bits (one bit for each sub-region).
  • Writing a 1 to bit k disables sub-region k, allowing that slice to fall through to lower priority region rules or the background region.
  • Exam Benefit: Allows carving out unprivileged memory "holes" without consuming multiple precious MPU region slots!
4. MemManage Fault Violation:

When an instruction fetch or data access violates MPU permissions (or attempts to execute in an XN region), the processor aborts the transaction and triggers a MemManage Fault. The fault address is stored in MMFAR, and status flags are set in MFSR.

2. Assembly Branch Execution & The EPSR Thumb-Bit (T-Bit) Rule: Explain why branching to an even address causes an immediate UsageFault (INVSTATE).
[5 Marks] [CO1, BTL3] PPT: Ch4 Slides 25, 48

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slides 25, 48)

xPSR Register Layout
Figure 3.2: Execution Program Status Register (EPSR) & Thumb T-Bit (Ch 4 Slide 25)
1. The EPSR T-Bit (Bit 24) Rule:

ARM Cortex-M processors exclusively execute the Thumb-2 instruction set. They do NOT possess a 32-bit ARM instruction decoder state. Therefore, the T-bit (Bit 24) in the EPSR MUST ALWAYS BE 1 during instruction execution.

2. Function Pointers and Indirect Branches (BX / BLX):

In the ARM architecture, when executing an indirect branch via a register (e.g. BX R0, BLX R3, or loading PC via LDR PC, [R1]), Bit 0 of the target address is used by hardware to update the T-bit:

  • If Bit 0 of target address = 1 ──► Sets EPSR T-bit to 1 (Thumb State). Target instruction executed at Address & ~1.
  • If Bit 0 of target address = 0 ──► Attempts to clear EPSR T-bit to 0 (ARM State).
3. Why an Even Address Triggers UsageFault:
// Example: Function resides at Flash address 0x08001000
void (*my_func)(void) = (void (*)(void))0x08001000; // EVEN ADDRESS (Bit 0 = 0)
my_func(); // Executes BX R0 with R0 = 0x08001000

Hardware attempts to switch the CPU into ARM state by clearing the T-bit to 0. Since Cortex-M does not support ARM state, the core detects an illegal state transition and immediately triggers a UsageFault with INVSTATE (Invalid State) bit set in UFSR!

The Golden Rule for 50/50 Marks: In Cortex-M, all vector table handler addresses and C function pointers MUST have their LSB set to 1 (e.g., 0x08001001 for a function physically located at 0x08001000).
3. Vector Table Offset Register (VTOR) Sizing & Alignment Derivation: Calculate the minimum table size and power-of-2 alignment boundary for an MCU with 32 and 75 external IRQs.
[5 Marks] [CO1, BTL3] PPT: Ch_Txt1 Slides 20, 34–37

Direct Reference: 2 23ECE313_ES_Ch_Txt1.pdf (Slides 20, 34–37)

Vector Table Architecture
Figure 3.3: Vector Table Memory Structure (Ch_Txt1 Slide 20)
1. Mathematical Formula for Vector Table Size:

Every Cortex-M vector table begins with 16 system exception vectors (Vectors 0 to 15), followed by N external interrupt vectors (IRQ0 to IRQ N-1). Each vector entry is a 32-bit (4-byte) pointer.

Total Vector Table Size = (16 System Exceptions + N External IRQs) × 4 bytes
2. ARMv7-M VTOR Alignment Rule:

The base address programmed into VTOR (Address: 0xE000ED08) must be aligned to a power-of-2 boundary that is greater than or equal to the total table size, with an absolute minimum hardware alignment of 128 bytes (32 words).

3. Calculation for Case A: Microcontroller with 32 External IRQs:
  • Total Vector Entries: 16 + 32 = 48 words.
  • Memory Size: 48 × 4 = 192 bytes.
  • Required Power-of-2 Alignment: The smallest power of 2 ≥ 192 is 256 bytes (0x100).
  • Conclusion: Base address in VTOR must end in 0x00 (Bits [7:0] = 0).
4. Calculation for Case B: Microcontroller with 75 External IRQs (e.g. STM32F446RE):
  • Total Vector Entries: 16 + 75 = 91 words.
  • Memory Size: 91 × 4 = 364 bytes.
  • Required Power-of-2 Alignment: The smallest power of 2 ≥ 364 is 512 bytes (0x200).
  • Conclusion: Base address in VTOR must end in a multiple of 0x200 (Bits [8:0] = 0).
4. Explain the CoreSight On-Chip Debug Architecture and Contrast the 4 Trace Units: DWT, ITM, ETM, and TPIU.
[5 Marks] [CO2, BTL2] PPT: Ch14 Slides 5–12; Ch15 Slides 4–10

Direct Reference: 4 23ECE313_ES_Ch14_Txt 1a.pdf (Slides 5–12); 5 23ECE313_ES_Ch15_Txt 1a.pdf (Slides 4–10)

CoreSight Architecture
Figure 3.4: CoreSight On-Chip Debug & Trace Architecture
1. Non-Intrusive Tracing vs Intrusive Debugging:
  • Intrusive Debugging (Halt Mode): Halts the CPU clock. Breaks hard real-time systems (e.g., motor drive shorts out, CAN bus communication times out).
  • Non-Intrusive Trace: CoreSight monitors execution in real-time at full CPU speed without halting the CPU, transmitting trace packets through external pins.
2. Detailed Functions of the Four CoreSight Trace Units:
Trace Unit Full Name Primary Function & Exam Keywords
DWT Data Watchpoint and Trace Contains 4 hardware watchpoint comparators. Monitors data memory accesses (triggering trace on read/write to a specific variable). Measures cycle counts (CYCCNT) for profiling.
ITM Instrumentation Trace Macrocell Enables high-speed software printf debugging without UART hardware. Application writes directly to ITM stimulus registers (e.g. ITM->PORT[0]), which outputs data over the 1-pin SWO (Serial Wire Output) line.
ETM Embedded Trace Macrocell Reconstructs the exact instruction execution history in real time. Captures every branch taken/not-taken and exception entry to provide full instruction trace back in time.
TPIU Trace Port Interface Unit Acts as a hardware multiplexer and serializer. Formats and combines data streams from ITM and ETM, outputting them to external debug hardware (e.g. Keil ULINKpro, Segger J-Trace) via SWO or multi-pin Trace Port.
5. Draw and explain the Cortex-M Bus Architecture (I-Code, D-Code, and System Bus) and the AHB-Lite Bus Matrix.
[5 Marks] [CO1, BTL2] PPT: Ch4 Slides 14–15

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slides 14–15)

Bus Interfaces
Figure 3.5: Cortex-M3 Bus Interconnect & Harvard Architecture (Ch 4 Slide 15)
1. The Three Primary AHB-Lite Buses:
  • I-Code Bus (Instruction Fetch): 32-bit AHB-Lite bus dedicated to fetching instructions from the Code space (0x00000000 - 0x1FFFFFFF), primarily Flash/ROM.
  • D-Code Bus (Data Fetch from Code Space): 32-bit AHB-Lite bus used to fetch literal pools, constants, and table data stored within the Code space (0x00000000 - 0x1FFFFFFF).
  • System Bus (S-Bus): 32-bit AHB-Lite bus used for all data accesses to SRAM (0x20000000), Peripherals (0x40000000), and External Memories (0x60000000). Can also fetch instructions from SRAM.
2. The Multi-Layer AHB Bus Matrix Advantage:

Cortex-M uses a Harvard architecture enabled by a multi-layer AHB matrix. Because instruction fetches (on I-Code) and data accesses (on System Bus or D-Code) travel over independent physical buses simultaneously, the processor can fetch an instruction and perform a data load/store in the exact same clock cycle without bus contention!

3. The APB (Advanced Peripheral Bus) Bridge:

Connects the high-speed AHB system bus to lower-power peripherals (USART, SPI, I2C, Timers, ADC). The APB bridge translates AHB burst transfers into simplified APB read/write cycles and operates at lower clock frequencies to save power.

6. Explain the Three Reset Types in Cortex-M and Self-Reset Control using the AIRCR Register (VECTKEY and SYSRESETREQ).
[5 Marks] [CO2, BTL2] PPT: Ch4 Slide 75; Ch12 Slide 44

Direct Reference: 1 23ECE313_ES_Ch4 Text 1.pdf (Slide 75); 3 23ECE313_ES_Ch12_Txt1.pdf (Slide 44)

1. Three Reset Types in Cortex-M Architecture:
  1. Power-on Reset (POR): Cold reset initiated when power is first applied. Resets the entire microcontroller: processor core, system control logic, all peripherals, and debug blocks.
  2. System Reset: Warm reset initiated by the external reset pin (NRST), independent watchdog timer, or software command (SYSRESETREQ). Resets processor core and all peripherals, but preserves debug logic so active debug sessions are not dropped.
  3. Processor Reset: Resets only the processor core (internal registers, pipeline, and NVIC). Peripherals and bus bridges continue active operation. Driven by debuggers via VECTRESET.
2. Self-Reset Control via AIRCR (Address: 0xE000ED0C):

The Application Interrupt and Reset Control Register allows software to trigger a clean system reboot:

Self Reset Features
Figure 3.6: Self-Reset & AIRCR Control Bits (Ch 14 Slide 18)
3. The VECTKEY Security Protection:

To prevent accidental system resets caused by errant software or stack corruption, writes to AIRCR MUST write the secret unlock key 0x05FA into bits [31:16] (VECTKEY field). If any other value is written, the entire write is rejected by hardware!

4. CMSIS Register Implementation:
void System_SelfReset(void) {
    __DSB(); // Ensure all outstanding memory transactions finish
    SCB->AIRCR = (0x05FA << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk;
    __DSB(); // Wait for reset to assert
    while (1); // Trap until hardware reset executes
}
7. Compare Low-Power Modes (Sleep, Deep Sleep, Standby), SCR Register Control Bits, and the Wakeup Interrupt Controller (WIC).
[5 Marks] [CO2, BTL2] PPT: Ch12 Slides 38–42

Direct Reference: 3 23ECE313_ES_Ch12_Txt1.pdf (Slides 38–42)

Mode Core Clock Peripherals & Clocks Voltage Regulator Wakeup Sources & Latency
Sleep Mode Gated (Off) Running (HSI, HSE, PLL, Timers active) Main Regulator ON Any interrupt. Fast wakeup (< 10 cycles).
Deep Sleep (Stop) Gated (Off) High-speed clocks stopped. SRAM and register contents retained. Low-power regulator mode EXTI, RTC alarm, WIC. Medium wakeup (~few microseconds).
Standby Mode Off Entire core domain powered down. SRAM lost! Only Backup Domain active. Regulator Powered Down Wakeup pin (WKUP), RTC alarm, NRST. Cold boot reset sequence.
WIC Deep Sleep Sequence
Figure 3.7: Wakeup Interrupt Controller (WIC) Sequence in Deep Sleep (Ch 12 Slide 40)
1. SCR (System Control Register - Address: 0xE000ED10) Control Bits:
  • Bit 1 (SLEEPONEXIT): When set to 1, processor automatically enters sleep mode immediately upon exiting the lowest-priority ISR, without executing thread background code. Perfect for purely interrupt-driven sensor nodes!
  • Bit 2 (SLEEPDEEP): 0 = Enter standard Sleep mode on WFI; 1 = Enter Deep Sleep / Stop mode on WFI.
  • Bit 4 (SEVONPEND): If 1, even disabled/masked pending interrupts generate an event to wake processor from WFE.
2. Wakeup Interrupt Controller (WIC):

In Deep Sleep mode, the main core power domain and NVIC clocks are shut down to achieve microamp currents. The WIC is a small, ultra-low-power shadow controller that stays powered. When an external line asserts an interrupt, the WIC signals the Power Management Unit to wake the main voltage regulator, restore clocks, and hand off the pending interrupt directly to the NVIC!

8. Write a CMSIS Register C Function to generate a millisecond hardware delay using the SysTick Timer (16 MHz clock) without interrupts.
[5 Marks] [CO3, BTL3] PPT: Ch12 Slides 35–37; Lab Code systick.c

Direct Reference: 3 23ECE313_ES_Ch12_Txt1.pdf (Slides 35–37); lab/systick.c

SysTick Registers
Figure 3.8: SysTick 24-Bit Down-Counter Registers (Ch 14 Slide 3)
1. Mathematical Derivation for 1 Millisecond Delay:
  • Processor Clock: f_CPU = 16 MHz = 16,000,000 Hz
  • Time for 1 millisecond: T = 1 ms = 0.001 s
  • Number of clock cycles required: N = 16,000,000 × 0.001 = 16,000 cycles
  • Since counter counts from LOAD down to 0 (a total of LOAD + 1 states):
  • SysTick->LOAD = 16,000 - 1 = 15,999 (0x3E7F)
2. Complete CMSIS Register Implementation:
#include "stm32f4xx.h"

void SysTick_Delay_ms(uint32_t ms) {
    // 1. Disable SysTick during configuration
    SysTick->CTRL = 0;

    // 2. Load count value for 1 ms (16,000 cycles at 16 MHz)
    SysTick->LOAD = 15999;

    // 3. Clear current value register and clear COUNTFLAG
    SysTick->VAL = 0;

    // 4. Enable SysTick with Processor Clock (Bit 2: CLKSOURCE = 1, Bit 0: ENABLE = 1)
    // No interrupt enable (TICKINT = 0)
    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk;

    // 5. Loop for the requested number of milliseconds
    for (uint32_t i = 0; i < ms; i++) {
        // Wait until COUNTFLAG (Bit 16) is set to 1 by hardware
        while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk));
    }

    // 6. Disable SysTick after delay finishes
    SysTick->CTRL = 0;
}

int main(void) {
    // Enable GPIOA clock and configure PA5 as output
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (1U << (5 * 2));

    while (1) {
        GPIOA->ODR ^= (1U << 5);      // Toggle PA5 LED
        SysTick_Delay_ms(500);        // Accurate 500 ms delay
    }
}
9. Complete Peripheral Integration: Interfacing PC13 Pushbutton (EXTI13), PA0 Analog Sensor (ADC1), and PA5 PWM LED (TIM2_CH1). Write C code where button press updates LED brightness.
[10 Marks] [CO3, BTL3] PPT: Mazidi EXTI, ADC & PWM Chapters

Direct Reference: 7 23ECE313_ES_ Mazidi.pdf & STM32F446RE_Timers_PWM_ADC_Mazidi.pdf

1. Complete Multi-Peripheral Circuit Diagram:
+3.3V System Supply ├──[ Pushbutton ]── PC13 (Active-Low with internal pull-up) │ ├──[ 10k LDR ]──┬── PA0 (ADC1_IN0 Analog Input) │ │ │ [ 10k Resistor ] │ │ │ GND │ └── STM32F446RE PA5 (TIM2_CH1 PWM) ───[ 220 Ω ]───►| (LED) ─── GND
2. System Architecture & Operation Flow:
  1. Standby State: System operates in low-power sleep (__WFI()) while TIM2 continuously outputs PWM on PA5.
  2. Interrupt Event: User presses PC13 button, asserting falling edge on EXTI13.
  3. ISR Execution (EXTI15_10_IRQHandler):
    • Trigger software conversion on ADC1 (SWSTART).
    • Poll until EOC flag is set in ADC1->SR.
    • Read 12-bit ADC result (0 to 4095).
    • Scale and write the ADC result directly to TIM2->CCR1.
    • Clear pending bit by writing 1: EXTI->PR = (1U << 13);.
3. Complete Embedded C Program:
#include "stm32f4xx.h"

void System_Peripherals_Init(void) {
    // 1. Enable Peripheral Clocks
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOCEN; // GPIOA & GPIOC
    RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN | RCC_APB2ENR_ADC1EN; // SYSCFG & ADC1
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;                        // TIM2

    // 2. Configure PC13 as Digital Input with Pull-Up (Pushbutton)
    GPIOC->MODER &= ~(3U << (13 * 2)); // Input mode ('00')
    GPIOC->PUPDR &= ~(3U << (13 * 2));
    GPIOC->PUPDR |=  (1U << (13 * 2)); // Pull-Up ('01')

    // 3. Configure PA0 as Analog Mode (ADC1_IN0)
    GPIOA->MODER |= (3U << (0 * 2));   // Analog mode ('11')

    // 4. Configure PA5 as Alternate Function AF1 (TIM2_CH1 PWM)
    GPIOA->MODER &= ~(3U << (5 * 2));
    GPIOA->MODER |=  (2U << (5 * 2));  // Alternate function ('10')
    GPIOA->AFR[0] &= ~(0xFU << (5 * 4));
    GPIOA->AFR[0] |=  (1U   << (5 * 4)); // AF1 = TIM2_CH1

    // 5. Configure EXTI13 for PC13
    SYSCFG->EXTICR[3] &= ~(0xFU << 4);
    SYSCFG->EXTICR[3] |=  (2U   << 4); // Port C = 0x2
    EXTI->FTSR |= (1U << 13);          // Falling trigger
    EXTI->IMR  |= (1U << 13);          // Unmask interrupt line 13

    NVIC_SetPriority(EXTI15_10_IRQn, 2);
    NVIC_EnableIRQ(EXTI15_10_IRQn);

    // 6. Configure ADC1 (Channel 0, PA0)
    ADC1->SMPR2 |= (4U << 0);          // 84 cycles sample time
    ADC1->SQR1 = 0;                    // 1 conversion
    ADC1->SQR3 = 0;                    // Channel 0
    ADC1->CR2 |= ADC_CR2_ADON;         // Turn on ADC

    // 7. Configure TIM2 for 1 kHz PWM with 12-bit range (ARR = 4095)
    TIM2->PSC = 3;                     // 16 MHz / 4 = 4 MHz timer clock
    TIM2->ARR = 4095;                  // Matches 12-bit ADC resolution!
    TIM2->CCR1 = 2048;                 // Initial 50% duty cycle
    TIM2->CCMR1 |= (6U << 4) | TIM_CCMR1_OC1PE; // PWM Mode 1
    TIM2->CCER  |= TIM_CCER_CC1E;      // Enable channel 1 output
    TIM2->CR1   |= TIM_CR1_CEN;        // Start counter
}

// EXTI15_10 Interrupt Handler for Button Press
void EXTI15_10_IRQHandler(void) {
    if (EXTI->PR & (1U << 13)) {
        // Start ADC conversion on PA0
        ADC1->CR2 |= ADC_CR2_SWSTART;
        while (!(ADC1->SR & ADC_SR_EOC)); // Wait for conversion

        uint16_t adc_val = ADC1->DR;      // Read 12-bit analog value (0-4095)
        
        // Dynamically update PWM duty cycle (matches ARR = 4095)
        TIM2->CCR1 = adc_val;

        // Clear interrupt pending bit (WRITE 1 TO CLEAR)
        EXTI->PR = (1U << 13);
    }
}

int main(void) {
    System_Peripherals_Init();

    while (1) {
        __WFI(); // Sleep until button press interrupt arrives
    }
}

📚 Master PPT Diagram Vault & Visual Revision Gallery

All Slide Figures Indexed

Professor Giriraja C. V. prioritizes neat, properly labeled diagrams. Master every essential visual representation directly extracted from the course slides:

1. Operating Modes & Privilege States

1 23ECE313_ES_Ch4 Text 1.pdf (Slide 19)
Operating Modes

Key Exam Notes: Shows transitions between Thread Mode (Privileged/Unprivileged) and Handler Mode (Always Privileged). Reset enters Thread Privileged. Exceptions force transition to Handler Mode. Exit via EXC_RETURN.

2. CONTROL Register Bits

1 23ECE313_ES_Ch4 Text 1.pdf (Slide 27)
CONTROL Register

Key Exam Notes: Bit 0 = nPRIV (0: Privileged, 1: Unprivileged). Bit 1 = SPSEL (0: MSP, 1: PSP in Thread mode). Handler mode always forces MSP.

3. Bit-Band Memory Regions & Mapping

2 23ECE313_ES_Ch_Txt1.pdf (Slide 12)
Bit Band Memory Map

Key Exam Notes: SRAM: 0x20000000 (1MB) mapped to Alias 0x22000000 (32MB). Peripheral: 0x40000000 (1MB) mapped to Alias 0x42000000 (32MB). Formula: Alias = Base + (ByteOffset * 32) + (Bit * 4).

4. Bus Interfaces & Bus Matrix

1 23ECE313_ES_Ch4 Text 1.pdf (Slide 15)
Bus Interfaces

Key Exam Notes: I-Code (Instruction fetch from Flash), D-Code (Literal pool data from Flash), System Bus (SRAM & Peripherals). Harvard architecture allows concurrent code and data transfers.

5. Reset Sequence Vector Fetch

1 23ECE313_ES_Ch4 Text 1.pdf (Slide 76)
Reset Sequence

Key Exam Notes: Step 1: Read address 0x00000000 into MSP. Step 2: Read address 0x00000004 into PC (Reset Handler address). Step 3: Branch to Reset Handler. Bit 0 of PC must be 1 (Thumb state).

6. Initial MSP & PC Concrete Example

1 23ECE313_ES_Ch4 Text 1.pdf (Slide 77)
Initial SP PC Memory Values

Key Exam Notes: Visual memory layout of initial MSP (e.g. 0x20008000 top of SRAM) and Reset Handler vector with LSB=1 (e.g. 0x08000101 for code at 0x08000100).

7. AIRCR PRIGROUP Priority Splitting

2 23ECE313_ES_Ch_Txt1.pdf (Slide 27)
AIRCR PRIGROUP

Key Exam Notes: Shows how PRIGROUP bits [10:8] split 8-bit priority into Preempt Priority (determines nesting) and Sub-Priority (determines pending resolution when preemption is equal).

8. Interrupt Pending & Active Behavior

2 23ECE313_ES_Ch_Txt1.pdf (Slide 28)
Interrupt Pending Behavior

Key Exam Notes: Timing diagram showing interrupt pulse latching into pending state, transition from Pending to Active upon ISR entry, and clearing of pending bit.

9. Context Switching Problem & PendSV

3 23ECE313_ES_Ch12_Txt1.pdf (Slides 24–25)
PendSV Solution

Key Exam Notes: Without PendSV, SysTick preempting an external IRQ causes delayed IRQ completion. PendSV (lowest priority) defers context switching until all active IRQs complete!

10. SVC Hardware Stack Frame

3 23ECE313_ES_Ch12_Txt1.pdf (Slide 30)
SVC Stack Frame

Key Exam Notes: 8 words pushed by hardware: R0, R1, R2, R3, R12, LR, Return PC, xPSR. SVC immediate extracted from ((uint8_t*)stacked_pc)[-2].

11. WIC Deep Sleep Sequence

3 23ECE313_ES_Ch12_Txt1.pdf (Slide 40)
WIC Deep Sleep

Key Exam Notes: Core clock gated, PLL disabled. WIC stays powered, detects external edge, signals PMU to restore high-speed regulator and clocks, and transfers control to NVIC.

12. CoreSight On-Chip Debug Units

4 23ECE313_ES_Ch14_Txt 1a.pdf (Slide 8)
CoreSight Architecture

Key Exam Notes: DWT (Data watchpoints & cycle counting), ITM (printf via SWO pin), ETM (Instruction trace), TPIU (Trace packet serializer). Differentiates intrusive vs non-intrusive debug.

🎯 Professor Giriraja C.V.'s Secret 50/50 Rubric & Exam Traps

Must Read Before Entering Hall

Reviewed and audited by Senior Embedded Systems Faculty. These are the subtle technical corner cases where 90% of students lose marks:

🚨 Trap 1: The Vector Table Sizing & Alignment Formula

Question: "Calculate the vector table size and alignment for 75 external interrupts."

  • Wrong Student Answer: 75 * 4 = 300 bytes. (Loses 3 marks!)
  • Full Marks Answer: Must include the 16 system exceptions!
    Total Vectors = 16 (Core) + 75 (External) = 91 words.
    Table Size = 91 × 4 = 364 bytes.
    Alignment Rule: ARMv7-M VTOR requires alignment to the next power of 2 ≥ size.
    Next power of 2 ≥ 364 is 512 bytes (0x200 boundary). Bits [8:0] of VTOR must be 0!

🚨 Trap 2: Imprecise Bus Faults & BFAR Invalidity

Question: "Why is BFAR not always valid during a BusFault?"

  • Exam Trap: If the write was handled by the internal Write Buffer, the bus error is returned asynchronously after the CPU has already executed subsequent instructions.
  • Key Points:
    1. Stacked PC does NOT point to the faulty instruction (points to an arbitrary later instruction).
    2. BFSR->BFARVALID = 0 (Fault address in BFAR is completely invalid).
    3. Fix / Diagnosis: Set SCB->ACTLR |= SCB_ACTLR_DISDEFWBUF_Msk to disable write buffer. This forces precise faults where BFARVALID = 1!

🚨 Trap 3: The 3 EXC_RETURN Magic Codes

Question: "Explain how Cortex-M returns from an exception handler."

  • Hardware loads a special magic value into LR on exception entry. You MUST memorize these three:
    • 0xFFFFFFF9: Return to Thread Mode using MSP (Main Stack Pointer).
    • 0xFFFFFFFD: Return to Thread Mode using PSP (Process Stack Pointer).
    • 0xFFFFFFE9: Return to Handler Mode using MSP (Nested exception return).

🚨 Trap 4: The 8-Byte Stack Alignment Trap (STKALIGN in CCR)

Question: "Why does SP decrement by 0x24 (36 bytes) instead of 0x20 (32 bytes) during an interrupt?"

  • The ARM Architecture Procedure Call Standard (AAPCS) requires double-word (8-byte) stack alignment at public interfaces.
  • If SP was only 4-byte aligned when the interrupt arrived, hardware automatically inserts a 4-byte alignment dummy pad before pushing the 8 registers (32 bytes).
  • Total SP decrement = 32 + 4 = 36 bytes (0x24)! Controlled by CCR->STKALIGN. Bit 9 of stacked xPSR records if padding was added.

🚨 Trap 5: The Thumb-Bit LSB = 1 Rule in Branch Targets

Question: "What happens if a function pointer points to address 0x08002000?"

  • Immediate UsageFault (INVSTATE)! Cortex-M does not have an ARM state decoder. Indirect branches load Bit 0 of the target address into the EPSR T-bit.
  • If Bit 0 is 0, the core attempts to switch to ARM state, violating architecture rules and asserting UsageFault.
  • Full Marks Rule: All function pointers and vector table addresses MUST have Bit 0 = 1 (e.g. 0x08002001).

🚨 Trap 6: EXTI Write-1-to-Clear Register Logic

Coding Trap: In EXTI15_10_IRQHandler, how do you clear the interrupt?

  • Wrong Code: EXTI->PR &= ~(1U << 13); (Fails to clear! Writing 0 does nothing!).
  • Correct Code: EXTI->PR = (1U << 13); (Must write a 1 to clear pending status!).

🚨 Trap 7: Inductive Load Protection (Flyback Diode)

Circuit Design Trap: Whenever the question asks to interface a Relay or DC Motor:

  • You MUST draw a reverse-biased flyback diode (1N4007) in parallel with the motor or relay coil!
  • Explanation: When the transistor/MOSFET switches off, inductive kickback ($V = -L rac{di}{dt}$) creates hundreds of volts that will instantly destroy the switching transistor and MCU pin without the diode.

🚨 Trap 8: Enabling Peripheral Clocks FIRST

Coding Trap: Always enable clocks in RCC->AHB1ENR, RCC->APB1ENR, or RCC->APB2ENR before touching any peripheral register. Touching a peripheral register without its clock enabled triggers an immediate BusFault!