deep_sleep_example_main.c 16 KB

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