Consider the following Arduino sketch that uses SLEEP_MODE_IDLE. What will be printed on the serial monitor?
#include <avr/sleep.h> void setup() { Serial.begin(9600); delay(1000); Serial.println("Before sleep"); set_sleep_mode(SLEEP_MODE_IDLE); sleep_enable(); sleep_mode(); sleep_disable(); Serial.println("After sleep"); } void loop() { // Empty loop }
Idle mode stops the CPU but keeps peripherals running, so the program continues after sleep.
In SLEEP_MODE_IDLE, the CPU stops but peripherals like the serial continue. So the program prints both lines.
Given this Arduino code using SLEEP_MODE_PWR_DOWN, what will be the output on the serial monitor?
#include <avr/sleep.h> void setup() { Serial.begin(9600); delay(1000); Serial.println("Start"); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_mode(); sleep_disable(); Serial.println("Wake up"); } void loop() { // Empty }
Power-down mode stops almost everything; without an interrupt, the device never wakes.
In SLEEP_MODE_PWR_DOWN, the CPU and most peripherals stop. Without an interrupt to wake it, the program never reaches the second print.
This Arduino code uses SLEEP_MODE_PWR_DOWN but never wakes up. What is the main reason?
#include <avr/sleep.h> void setup() { Serial.begin(9600); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_mode(); sleep_disable(); Serial.println("Awake"); } void loop() {}
Power-down mode requires an external or pin change interrupt to wake up.
Power-down mode stops the CPU and clocks. Without an interrupt, the MCU stays asleep indefinitely.
Choose the correct Arduino sleep mode that uses the least power and can only be exited by an external interrupt or reset.
Think about which mode stops almost all clocks and peripherals.
SLEEP_MODE_PWR_DOWN uses the least power by stopping the CPU and most peripherals. It requires an external interrupt or reset to wake.
Analyze this Arduino sketch that uses sleep and an interrupt to wake. How many times will the LED blink after pressing the button once?
#include <avr/sleep.h> volatile bool woke = false; void wakeUp() { woke = true; } void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), wakeUp, FALLING); Serial.begin(9600); delay(1000); Serial.println("Going to sleep"); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_mode(); sleep_disable(); if (woke) { for (int i = 0; i < 3; i++) { digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200); } Serial.println("Woke up and blinked LED"); } } void loop() {}
The interrupt sets a flag that triggers the blinking loop once after waking.
The interrupt sets woke to true. After waking, the code blinks the LED 3 times in setup().