Consider this embedded C code snippet simulating entering idle mode and waking up on an interrupt. What will be printed?
#include <stdio.h> #include <stdbool.h> volatile bool idle = false; void enter_idle_mode() { idle = true; printf("Entering idle mode...\n"); } void wake_up() { if (idle) { idle = false; printf("Woke up from idle mode!\n"); } } int main() { enter_idle_mode(); wake_up(); wake_up(); return 0; }
Think about the state of the idle variable after waking up once.
The code sets idle to true when entering idle mode. The first wake_up() call detects idle == true, prints the wake-up message, and sets idle to false. The second wake_up() call finds idle == false, so it prints nothing.
Choose the statement that correctly explains what happens when an embedded system enters idle mode.
Think about how the CPU can wake up from idle mode.
In idle mode, the CPU stops executing instructions to save power, but peripherals and interrupts remain active. This allows the CPU to wake up when an interrupt occurs.
Examine the code below. It is supposed to enter idle mode and wake up on an interrupt, but it never wakes up. What is the cause?
volatile bool idle = false; void enter_idle_mode() { idle = true; // CPU enters idle mode here } void interrupt_handler() { idle = false; } int main() { enter_idle_mode(); while (idle) { // wait for interrupt } printf("Woke up!\n"); return 0; }
Think about what is missing to actually stop the CPU.
The code sets the idle flag but never executes an instruction to halt the CPU (like __WFI() or __WFE()). Without halting, the CPU keeps running and the interrupt may never occur as expected.
Identify the error in this embedded C code snippet related to idle mode.
void enter_idle_mode() {
idle = true;
__WFI();
}
Check the line endings carefully.
The line idle = true is missing a semicolon at the end, causing a syntax error.
Given the code below, how many times will the CPU print "Woke up!" before the program ends?
#include <stdio.h> #include <stdbool.h> volatile bool idle = false; int wake_count = 0; void enter_idle_mode() { idle = true; // Simulate CPU halt } void interrupt_handler() { if (wake_count < 3) { idle = false; wake_count++; } } int main() { for (int i = 0; i < 5; i++) { enter_idle_mode(); interrupt_handler(); if (!idle) { printf("Woke up!\n"); } } return 0; }
Look at how wake_count limits waking up.
The interrupt handler only clears idle and increments wake_count if wake_count < 3. So the CPU wakes up exactly 3 times, printing "Woke up!" three times.