deep_sleep_example_main.c 14 KB

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