aboutsummaryrefslogtreecommitdiff
path: root/common/avr/suspend.c
diff options
context:
space:
mode:
Diffstat (limited to 'common/avr/suspend.c')
-rw-r--r--common/avr/suspend.c117
1 files changed, 117 insertions, 0 deletions
diff --git a/common/avr/suspend.c b/common/avr/suspend.c
new file mode 100644
index 000000000..66a579fd7
--- /dev/null
+++ b/common/avr/suspend.c
@@ -0,0 +1,117 @@
1#include <stdbool.h>
2#include <avr/sleep.h>
3#include <avr/wdt.h>
4#include <avr/interrupt.h>
5#include "matrix.h"
6#include "action.h"
7#include "backlight.h"
8#include "suspend_avr.h"
9#include "suspend.h"
10#ifdef PROTOCOL_LUFA
11#include "lufa.h"
12#endif
13
14
15#define wdt_intr_enable(value) \
16__asm__ __volatile__ ( \
17 "in __tmp_reg__,__SREG__" "\n\t" \
18 "cli" "\n\t" \
19 "wdr" "\n\t" \
20 "sts %0,%1" "\n\t" \
21 "out __SREG__,__tmp_reg__" "\n\t" \
22 "sts %0,%2" "\n\t" \
23 : /* no outputs */ \
24 : "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \
25 "r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \
26 "r" ((uint8_t) ((value & 0x08 ? _WD_PS3_MASK : 0x00) | \
27 _BV(WDIE) | (value & 0x07)) ) \
28 : "r0" \
29)
30
31
32void suspend_idle(uint8_t time)
33{
34 cli();
35 set_sleep_mode(SLEEP_MODE_IDLE);
36 sleep_enable();
37 sei();
38 sleep_cpu();
39 sleep_disable();
40}
41
42/* Power down MCU with watchdog timer
43 * wdto: watchdog timer timeout defined in <avr/wdt.h>
44 * WDTO_15MS
45 * WDTO_30MS
46 * WDTO_60MS
47 * WDTO_120MS
48 * WDTO_250MS
49 * WDTO_500MS
50 * WDTO_1S
51 * WDTO_2S
52 * WDTO_4S
53 * WDTO_8S
54 */
55void suspend_power_down(uint8_t wdto)
56{
57#ifdef PROTOCOL_LUFA
58 if (USB_DeviceState == DEVICE_STATE_Configured) return;
59#endif
60
61 // Watchdog Interrupt Mode
62 wdt_intr_enable(wdto);
63
64 // TODO: more power saving
65 // See PicoPower application note
66 // - I/O port input with pullup
67 // - prescale clock
68 // - BOD disable
69 // - Power Reduction Register PRR
70
71 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
72 sleep_enable();
73 sei();
74 sleep_cpu();
75 sleep_disable();
76
77 // Disable watchdog after sleep
78 wdt_disable();
79}
80
81bool suspend_wakeup_condition(void)
82{
83 matrix_power_up();
84 matrix_scan();
85 matrix_power_down();
86 for (uint8_t r = 0; r < MATRIX_ROWS; r++) {
87 if (matrix_get_row(r)) return true;
88 }
89 return false;
90}
91
92// run immediately after wakeup
93void suspend_wakeup_init(void)
94{
95 // clear keyboard state
96 clear_keyboard();
97#ifdef BACKLIGHT_ENABLE
98 backlight_init();
99#endif
100}
101
102#ifndef NO_SUSPEND_POWER_DOWN
103/* watchdog timeout */
104ISR(WDT_vect)
105{
106 /* wakeup from MCU sleep mode */
107/*
108 // blink LED
109 static uint8_t led_state = 0;
110 static uint8_t led_count = 0;
111 led_count++;
112 if ((led_count & 0x07) == 0) {
113 led_set((led_state ^= (1<<USB_LED_CAPS_LOCK)));
114 }
115*/
116}
117#endif