Sleep modes help microcontrollers save power by pausing most activities while keeping essential functions ready.
0
0
Sleep modes overview in Embedded C
Introduction
When your device runs on battery and you want to extend battery life.
When the device waits for a button press or sensor input before doing work.
When you want to reduce heat and power consumption in always-on devices.
When the device only needs to work at certain times and can rest in between.
Syntax
Embedded C
/* Example to enter sleep mode in embedded C */ #include <avr/sleep.h> void enter_sleep_mode() { set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Choose sleep mode sleep_enable(); // Enable sleep mode sleep_cpu(); // Enter sleep mode sleep_disable(); // Disable sleep after waking up }
set_sleep_mode() selects the type of sleep mode.
sleep_cpu() puts the CPU to sleep until an interrupt wakes it.
Examples
This mode stops the CPU but keeps peripherals running.
Embedded C
set_sleep_mode(SLEEP_MODE_IDLE);
This mode saves power but keeps timer running for wake-up.
Embedded C
set_sleep_mode(SLEEP_MODE_PWR_SAVE);
This mode saves the most power by stopping almost everything.
Embedded C
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
Sample Program
This program puts the microcontroller into the deepest sleep mode to save power. It wakes up only when an external interrupt (like a button press) happens. After waking, it toggles an LED to show it is awake.
Embedded C
#include <avr/io.h> #include <avr/sleep.h> #include <avr/interrupt.h> // Interrupt service routine for external interrupt INT0 ISR(INT0_vect) { // This will wake the MCU from sleep } int main(void) { // Configure INT0 (external interrupt 0) to trigger on falling edge EICRA |= (1 << ISC01); EICRA &= ~(1 << ISC00); EIMSK |= (1 << INT0); // Enable INT0 interrupt sei(); // Enable global interrupts // Set sleep mode to power down set_sleep_mode(SLEEP_MODE_PWR_DOWN); while (1) { // Prepare to sleep sleep_enable(); sleep_cpu(); // MCU sleeps here until INT0 interrupt sleep_disable(); // After waking up, toggle an LED connected to PORTB0 DDRB |= (1 << PORTB0); // Set PORTB0 as output PORTB ^= (1 << PORTB0); // Toggle LED } return 0; }
OutputSuccess
Important Notes
Sleep modes vary by microcontroller; check your device datasheet for details.
Interrupts are usually needed to wake the device from sleep.
Always disable sleep after waking to avoid unintended behavior.
Summary
Sleep modes reduce power by stopping CPU and peripherals.
Choose sleep mode based on how much power you want to save and what needs to stay active.
Use interrupts to wake the device from sleep safely.