deep_sleep_example_main.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /* Deep sleep wake up example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <time.h>
  11. #include <sys/time.h>
  12. #include "freertos/FreeRTOS.h"
  13. #include "freertos/task.h"
  14. #include "esp_sleep.h"
  15. #include "esp_log.h"
  16. #include "esp32/ulp.h"
  17. #include "driver/touch_pad.h"
  18. #include "driver/adc.h"
  19. #include "driver/rtc_io.h"
  20. #include "soc/sens_periph.h"
  21. #include "soc/rtc.h"
  22. static RTC_DATA_ATTR struct timeval sleep_enter_time;
  23. #ifdef CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  24. #if CONFIG_IDF_TARGET_ESP32
  25. /*
  26. * Offset (in 32-bit words) in RTC Slow memory where the data is placed
  27. * by the ULP coprocessor. It can be chosen to be any value greater or equal
  28. * to ULP program size, and less than the CONFIG_ESP32_ULP_COPROC_RESERVE_MEM/4 - 6,
  29. * where 6 is the number of words used by the ULP coprocessor.
  30. */
  31. #define ULP_DATA_OFFSET 36
  32. _Static_assert(ULP_DATA_OFFSET < CONFIG_ESP32_ULP_COPROC_RESERVE_MEM/4 - 6,
  33. "ULP_DATA_OFFSET is set too high, or CONFIG_ESP32_ULP_COPROC_RESERVE_MEM is not sufficient");
  34. /**
  35. * @brief Start ULP temperature monitoring program
  36. *
  37. * This function loads a program into the RTC Slow memory and starts up the ULP.
  38. * The program monitors on-chip temperature sensor and wakes up the SoC when
  39. * the temperature goes lower or higher than certain thresholds.
  40. */
  41. static void start_ulp_temperature_monitoring(void);
  42. /**
  43. * @brief Utility function which reads data written by ULP program
  44. *
  45. * @param offset offset from ULP_DATA_OFFSET in RTC Slow memory, in words
  46. * @return lower 16-bit part of the word writable by the ULP
  47. */
  48. static inline uint16_t ulp_data_read(size_t offset)
  49. {
  50. return RTC_SLOW_MEM[ULP_DATA_OFFSET + offset] & 0xffff;
  51. }
  52. /**
  53. * @brief Utility function which writes data to be ready by ULP program
  54. *
  55. * @param offset offset from ULP_DATA_OFFSET in RTC Slow memory, in words
  56. * @param value lower 16-bit part of the word to be stored
  57. */
  58. static inline void ulp_data_write(size_t offset, uint16_t value)
  59. {
  60. RTC_SLOW_MEM[ULP_DATA_OFFSET + offset] = value;
  61. }
  62. #endif // CONFIG_IDF_TARGET_ESP32
  63. #endif // CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  64. #ifdef CONFIG_ENABLE_TOUCH_WAKEUP
  65. #if CONFIG_IDF_TARGET_ESP32
  66. #define TOUCH_THRESH_NO_USE 0
  67. static void calibrate_touch_pad(touch_pad_t pad);
  68. #endif
  69. #endif
  70. void app_main(void)
  71. {
  72. struct timeval now;
  73. gettimeofday(&now, NULL);
  74. int sleep_time_ms = (now.tv_sec - sleep_enter_time.tv_sec) * 1000 + (now.tv_usec - sleep_enter_time.tv_usec) / 1000;
  75. switch (esp_sleep_get_wakeup_cause()) {
  76. case ESP_SLEEP_WAKEUP_EXT1: {
  77. uint64_t wakeup_pin_mask = esp_sleep_get_ext1_wakeup_status();
  78. if (wakeup_pin_mask != 0) {
  79. int pin = __builtin_ffsll(wakeup_pin_mask) - 1;
  80. printf("Wake up from GPIO %d\n", pin);
  81. } else {
  82. printf("Wake up from GPIO\n");
  83. }
  84. break;
  85. }
  86. case ESP_SLEEP_WAKEUP_TIMER: {
  87. printf("Wake up from timer. Time spent in deep sleep: %dms\n", sleep_time_ms);
  88. break;
  89. }
  90. #ifdef CONFIG_ENABLE_TOUCH_WAKEUP
  91. case ESP_SLEEP_WAKEUP_TOUCHPAD: {
  92. printf("Wake up from touch on pad %d\n", esp_sleep_get_touchpad_wakeup_status());
  93. break;
  94. }
  95. #endif // CONFIG_ENABLE_TOUCH_WAKEUP
  96. #ifdef CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  97. #if CONFIG_IDF_TARGET_ESP32
  98. case ESP_SLEEP_WAKEUP_ULP: {
  99. printf("Wake up from ULP\n");
  100. int16_t diff_high = (int16_t) ulp_data_read(3);
  101. int16_t diff_low = (int16_t) ulp_data_read(4);
  102. if (diff_high < 0) {
  103. printf("High temperature alarm was triggered\n");
  104. } else if (diff_low < 0) {
  105. printf("Low temperature alarm was triggered\n");
  106. } else {
  107. assert(false && "temperature has stayed within limits, but got ULP wakeup\n");
  108. }
  109. break;
  110. }
  111. #endif // CONFIG_IDF_TARGET_ESP32
  112. #endif // CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  113. case ESP_SLEEP_WAKEUP_UNDEFINED:
  114. default:
  115. printf("Not a deep sleep reset\n");
  116. }
  117. #ifdef CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  118. #if CONFIG_IDF_TARGET_ESP32
  119. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_UNDEFINED) {
  120. printf("ULP did %d temperature measurements in %d ms\n", ulp_data_read(1), sleep_time_ms);
  121. printf("Initial T=%d, latest T=%d\n", ulp_data_read(0), ulp_data_read(2));
  122. }
  123. #endif // CONFIG_IDF_TARGET_ESP32
  124. #endif // CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  125. vTaskDelay(1000 / portTICK_PERIOD_MS);
  126. const int wakeup_time_sec = 20;
  127. printf("Enabling timer wakeup, %ds\n", wakeup_time_sec);
  128. esp_sleep_enable_timer_wakeup(wakeup_time_sec * 1000000);
  129. const int ext_wakeup_pin_1 = 2;
  130. const uint64_t ext_wakeup_pin_1_mask = 1ULL << ext_wakeup_pin_1;
  131. const int ext_wakeup_pin_2 = 4;
  132. const uint64_t ext_wakeup_pin_2_mask = 1ULL << ext_wakeup_pin_2;
  133. printf("Enabling EXT1 wakeup on pins GPIO%d, GPIO%d\n", ext_wakeup_pin_1, ext_wakeup_pin_2);
  134. esp_sleep_enable_ext1_wakeup(ext_wakeup_pin_1_mask | ext_wakeup_pin_2_mask, ESP_EXT1_WAKEUP_ANY_HIGH);
  135. #ifdef CONFIG_ENABLE_TOUCH_WAKEUP
  136. #if CONFIG_IDF_TARGET_ESP32
  137. // Initialize touch pad peripheral.
  138. // The default fsm mode is software trigger mode.
  139. touch_pad_init();
  140. // If use touch pad wake up, should set touch sensor FSM mode at 'TOUCH_FSM_MODE_TIMER'.
  141. touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
  142. // Set reference voltage for charging/discharging
  143. // In this case, the high reference valtage will be 2.4V - 1V = 1.4V
  144. // The low reference voltage will be 0.5
  145. // The larger the range, the larger the pulse count value.
  146. touch_pad_set_voltage(TOUCH_HVOLT_2V4, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V);
  147. //init RTC IO and mode for touch pad.
  148. touch_pad_config(TOUCH_PAD_NUM8, TOUCH_THRESH_NO_USE);
  149. touch_pad_config(TOUCH_PAD_NUM9, TOUCH_THRESH_NO_USE);
  150. calibrate_touch_pad(TOUCH_PAD_NUM8);
  151. calibrate_touch_pad(TOUCH_PAD_NUM9);
  152. #elif CONFIG_IDF_TARGET_ESP32S2
  153. /* Initialize touch pad peripheral. */
  154. touch_pad_init();
  155. /* Only support one touch channel in sleep mode. */
  156. touch_pad_config(TOUCH_PAD_NUM9);
  157. /* Denoise setting at TouchSensor 0. */
  158. touch_pad_denoise_t denoise = {
  159. /* The bits to be cancelled are determined according to the noise level. */
  160. .grade = TOUCH_PAD_DENOISE_BIT4,
  161. .cap_level = TOUCH_PAD_DENOISE_CAP_L4,
  162. };
  163. touch_pad_denoise_set_config(&denoise);
  164. touch_pad_denoise_enable();
  165. printf("Denoise function init\n");
  166. /* Filter setting */
  167. touch_filter_config_t filter_info = {
  168. .mode = TOUCH_PAD_FILTER_IIR_16,
  169. .debounce_cnt = 1, // 1 time count.
  170. .hysteresis_thr = 3, // 3%
  171. .noise_thr = 0, // 50%
  172. .noise_neg_thr = 0, // 50%
  173. .neg_noise_limit = 10, // 10 time count.
  174. .jitter_step = 4, // use for jitter mode.
  175. .smh_lvl = TOUCH_PAD_SMOOTH_IIR_2,
  176. };
  177. touch_pad_filter_set_config(&filter_info);
  178. touch_pad_filter_enable();
  179. printf("touch pad filter init %d\n", TOUCH_PAD_FILTER_IIR_8);
  180. /* Set sleep touch pad. */
  181. touch_pad_sleep_channel_enable(TOUCH_PAD_NUM9, true);
  182. touch_pad_sleep_channel_enable_proximity(TOUCH_PAD_NUM9, false);
  183. /* Enable touch sensor clock. Work mode is "timer trigger". */
  184. touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
  185. touch_pad_fsm_start();
  186. vTaskDelay(100 / portTICK_RATE_MS);
  187. /* read sleep touch pad value */
  188. uint32_t touch_value;
  189. touch_pad_sleep_channel_read_smooth(TOUCH_PAD_NUM9, &touch_value);
  190. touch_pad_sleep_set_threshold(TOUCH_PAD_NUM9, touch_value * 0.1); //10%
  191. printf("test init: touch pad [%d] slp %d, thresh %d\n",
  192. TOUCH_PAD_NUM9, touch_value, (uint32_t)(touch_value * 0.1));
  193. #endif
  194. printf("Enabling touch pad wakeup\n");
  195. esp_sleep_enable_touchpad_wakeup();
  196. esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
  197. #endif // CONFIG_ENABLE_TOUCH_WAKEUP
  198. #ifdef CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  199. #if CONFIG_IDF_TARGET_ESP32
  200. printf("Enabling ULP wakeup\n");
  201. esp_sleep_enable_ulp_wakeup();
  202. #endif
  203. #endif
  204. #if CONFIG_IDF_TARGET_ESP32
  205. // Isolate GPIO12 pin from external circuits. This is needed for modules
  206. // which have an external pull-up resistor on GPIO12 (such as ESP32-WROVER)
  207. // to minimize current consumption.
  208. rtc_gpio_isolate(GPIO_NUM_12);
  209. #endif
  210. printf("Entering deep sleep\n");
  211. gettimeofday(&sleep_enter_time, NULL);
  212. #ifdef CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  213. #if CONFIG_IDF_TARGET_ESP32
  214. start_ulp_temperature_monitoring();
  215. #endif
  216. #endif
  217. esp_deep_sleep_start();
  218. }
  219. #ifdef CONFIG_ENABLE_TOUCH_WAKEUP
  220. #if CONFIG_IDF_TARGET_ESP32
  221. static void calibrate_touch_pad(touch_pad_t pad)
  222. {
  223. int avg = 0;
  224. const size_t calibration_count = 128;
  225. for (int i = 0; i < calibration_count; ++i) {
  226. uint16_t val;
  227. touch_pad_read(pad, &val);
  228. avg += val;
  229. }
  230. avg /= calibration_count;
  231. const int min_reading = 300;
  232. if (avg < min_reading) {
  233. printf("Touch pad #%d average reading is too low: %d (expecting at least %d). "
  234. "Not using for deep sleep wakeup.\n", pad, avg, min_reading);
  235. touch_pad_config(pad, 0);
  236. } else {
  237. int threshold = avg - 100;
  238. printf("Touch pad #%d average: %d, wakeup threshold set to %d.\n", pad, avg, threshold);
  239. touch_pad_config(pad, threshold);
  240. }
  241. }
  242. #endif
  243. #endif // CONFIG_ENABLE_TOUCH_WAKEUP
  244. #ifdef CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP
  245. #if CONFIG_IDF_TARGET_ESP32
  246. static void start_ulp_temperature_monitoring(void)
  247. {
  248. /*
  249. * This ULP program monitors the on-chip temperature sensor and wakes the chip up when
  250. * the temperature goes outside of certain window.
  251. * When the program runs for the first time, it saves the temperature measurement,
  252. * it is considered initial temperature (T0).
  253. *
  254. * On each subsequent run, temperature measured and compared to T0.
  255. * If the measured value is higher than T0 + max_temp_diff or lower than T0 - max_temp_diff,
  256. * the chip is woken up from deep sleep.
  257. */
  258. /* Temperature difference threshold which causes wakeup
  259. * With settings here (TSENS_CLK_DIV=2, 8000 cycles),
  260. * TSENS measurement is done in units of 0.73 degrees Celsius.
  261. * Therefore, max_temp_diff below is equivalent to ~2.2 degrees Celsius.
  262. */
  263. const int16_t max_temp_diff = 3;
  264. // Number of measurements ULP should do per second
  265. const uint32_t measurements_per_sec = 5;
  266. // Allow TSENS to be controlled by the ULP
  267. SET_PERI_REG_BITS(SENS_SAR_TSENS_CTRL_REG, SENS_TSENS_CLK_DIV, 2, SENS_TSENS_CLK_DIV_S);
  268. SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_SAR, 3, SENS_FORCE_XPD_SAR_S);
  269. CLEAR_PERI_REG_MASK(SENS_SAR_TSENS_CTRL_REG, SENS_TSENS_POWER_UP);
  270. CLEAR_PERI_REG_MASK(SENS_SAR_TSENS_CTRL_REG, SENS_TSENS_DUMP_OUT);
  271. CLEAR_PERI_REG_MASK(SENS_SAR_TSENS_CTRL_REG, SENS_TSENS_POWER_UP_FORCE);
  272. // Clear the part of RTC_SLOW_MEM reserved for the ULP. Makes debugging easier.
  273. memset(RTC_SLOW_MEM, 0, CONFIG_ESP32_ULP_COPROC_RESERVE_MEM);
  274. // The first word of memory (at data offset) is used to store the initial temperature (T0)
  275. // Zero it out here, then ULP will update it on the first run.
  276. ulp_data_write(0, 0);
  277. // The second word is used to store measurement count, zero it out as well.
  278. ulp_data_write(1, 0);
  279. const ulp_insn_t program[] = {
  280. // load data offset into R2
  281. I_MOVI(R2, ULP_DATA_OFFSET),
  282. // load/increment/store measurement counter using R1
  283. I_LD(R1, R2, 1),
  284. I_ADDI(R1, R1, 1),
  285. I_ST(R1, R2, 1),
  286. // enable temperature sensor
  287. I_WR_REG(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_SAR_S, SENS_FORCE_XPD_SAR_S + 1, 3),
  288. // do temperature measurement and store result in R3
  289. I_TSENS(R3, 8000),
  290. // disable temperature sensor
  291. I_WR_REG(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_SAR_S, SENS_FORCE_XPD_SAR_S + 1, 0),
  292. // Save current measurement at offset+2
  293. I_ST(R3, R2, 2),
  294. // load initial value into R0
  295. I_LD(R0, R2, 0),
  296. // if threshold value >=1 (i.e. initialized), goto 1
  297. M_BGE(1, 1),
  298. // otherwise, save the current value as initial (T0)
  299. I_MOVR(R0, R3),
  300. I_ST(R0, R2, 0),
  301. M_LABEL(1),
  302. // check if the temperature is greater or equal (T0 + max_temp_diff)
  303. // uses R1 as scratch register, difference is saved at offset + 3
  304. I_ADDI(R1, R0, max_temp_diff - 1),
  305. I_SUBR(R1, R1, R3),
  306. I_ST(R1, R2, 3),
  307. M_BXF(2),
  308. // check if the temperature is less or equal (T0 - max_temp_diff)
  309. // uses R1 as scratch register, difference is saved at offset + 4
  310. I_SUBI(R1, R0, max_temp_diff - 1),
  311. I_SUBR(R1, R3, R1),
  312. I_ST(R1, R2, 4),
  313. M_BXF(2),
  314. // temperature is within (T0 - max_temp_diff; T0 + max_temp_diff)
  315. // stop ULP until the program timer starts it again
  316. I_HALT(),
  317. M_LABEL(2),
  318. // temperature is out of bounds
  319. // disable ULP program timer
  320. I_WR_REG_BIT(RTC_CNTL_STATE0_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN_S, 0),
  321. // initiate wakeup of the SoC
  322. I_WAKE(),
  323. // stop the ULP program
  324. I_HALT()
  325. };
  326. // Load ULP program into RTC_SLOW_MEM, at offset 0
  327. size_t size = sizeof(program)/sizeof(ulp_insn_t);
  328. ESP_ERROR_CHECK( ulp_process_macros_and_load(0, program, &size) );
  329. assert(size < ULP_DATA_OFFSET && "ULP_DATA_OFFSET needs to be greater or equal to the program size");
  330. // Set ULP wakeup period
  331. const uint32_t sleep_cycles = rtc_clk_slow_freq_get_hz() / measurements_per_sec;
  332. REG_WRITE(SENS_ULP_CP_SLEEP_CYC0_REG, sleep_cycles);
  333. // Start ULP
  334. ESP_ERROR_CHECK( ulp_run(0) );
  335. }
  336. #endif // CONFIG_IDF_TARGET_ESP32
  337. #endif // CONFIG_ENABLE_ULP_TEMPERATURE_WAKEUP