suspend.c
2614 bytes
1#include <stdbool.h>
2#include <avr/sleep.h>
3#include <avr/wdt.h>
4#include <avr/interrupt.h>
5#include "suspend.h"
6#include "action.h"
7#include "timer.h"
8
9#ifdef PROTOCOL_LUFA
10# include "lufa.h"
11#endif
12#ifdef PROTOCOL_VUSB
13# include "vusb.h"
14#endif
15
16// TODO: This needs some cleanup
17
18#if !defined(NO_SUSPEND_POWER_DOWN) && defined(WDT_vect)
19
20// clang-format off
21#define wdt_intr_enable(value) \
22__asm__ __volatile__ ( \
23 "in __tmp_reg__,__SREG__" "\n\t" \
24 "cli" "\n\t" \
25 "wdr" "\n\t" \
26 "sts %0,%1" "\n\t" \
27 "out __SREG__,__tmp_reg__" "\n\t" \
28 "sts %0,%2" "\n\t" \
29 : /* no outputs */ \
30 : "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \
31 "r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \
32 "r" ((uint8_t) ((value & 0x08 ? _WD_PS3_MASK : 0x00) | _BV(WDIE) | (value & 0x07))) \
33 : "r0" \
34)
35// clang-format on
36
37/** \brief Power down MCU with watchdog timer
38 *
39 * wdto: watchdog timer timeout defined in <avr/wdt.h>
40 * WDTO_15MS
41 * WDTO_30MS
42 * WDTO_60MS
43 * WDTO_120MS
44 * WDTO_250MS
45 * WDTO_500MS
46 * WDTO_1S
47 * WDTO_2S
48 * WDTO_4S
49 * WDTO_8S
50 */
51static uint8_t wdt_timeout = 0;
52
53/** \brief Power down
54 *
55 * FIXME: needs doc
56 */
57static void power_down(uint8_t wdto) {
58 wdt_timeout = wdto;
59
60 // Watchdog Interrupt Mode
61 wdt_intr_enable(wdto);
62
63 // TODO: more power saving
64 // See PicoPower application note
65 // - I/O port input with pullup
66 // - prescale clock
67 // - BOD disable
68 // - Power Reduction Register PRR
69 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
70 sleep_enable();
71 sei();
72 sleep_cpu();
73 sleep_disable();
74
75 // Disable watchdog after sleep
76 wdt_disable();
77}
78
79/* watchdog timeout */
80ISR(WDT_vect) {
81 // compensate timer for sleep
82 switch (wdt_timeout) {
83 case WDTO_15MS:
84 timer_count += 15 + 2; // WDTO_15MS + 2(from observation)
85 break;
86 default:;
87 }
88}
89
90#endif
91
92/** \brief Suspend power down
93 *
94 * FIXME: needs doc
95 */
96void suspend_power_down(void) {
97#ifdef PROTOCOL_LUFA
98 if (USB_DeviceState == DEVICE_STATE_Configured) return;
99#endif
100#ifdef PROTOCOL_VUSB
101 if (!vusb_suspended) return;
102#endif
103
104 suspend_power_down_quantum();
105
106#ifndef NO_SUSPEND_POWER_DOWN
107 // Enter sleep state if possible (ie, the MCU has a watchdog timeout interrupt)
108# if defined(WDT_vect)
109 power_down(WDTO_15MS);
110# endif
111#endif
112}
113
114/** \brief run immediately after wakeup
115 *
116 * FIXME: needs doc
117 */
118void suspend_wakeup_init(void) {
119 // clear keyboard state
120 clear_keyboard();
121
122 suspend_wakeup_init_quantum();
123}