brownout.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdint.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stdbool.h>
  18. #include "sdkconfig.h"
  19. #include "soc/soc.h"
  20. #include "soc/cpu.h"
  21. #include "soc/rtc_cntl_reg.h"
  22. #include "rom/ets_sys.h"
  23. #include "esp_system_internal.h"
  24. #include "driver/rtc_cntl.h"
  25. #include "freertos/FreeRTOS.h"
  26. #ifdef CONFIG_BROWNOUT_DET_LVL
  27. #define BROWNOUT_DET_LVL CONFIG_BROWNOUT_DET_LVL
  28. #else
  29. #define BROWNOUT_DET_LVL 0
  30. #endif //CONFIG_BROWNOUT_DET_LVL
  31. static void rtc_brownout_isr_handler()
  32. {
  33. /* Normally RTC ISR clears the interrupt flag after the application-supplied
  34. * handler returns. Since restart is called here, the flag needs to be
  35. * cleared manually.
  36. */
  37. REG_WRITE(RTC_CNTL_INT_CLR_REG, RTC_CNTL_BROWN_OUT_INT_CLR);
  38. /* Stall the other CPU to make sure the code running there doesn't use UART
  39. * at the same time as the following ets_printf.
  40. */
  41. esp_cpu_stall(!xPortGetCoreID());
  42. esp_reset_reason_set_hint(ESP_RST_BROWNOUT);
  43. ets_printf("\r\nBrownout detector was triggered\r\n\r\n");
  44. esp_restart_noos();
  45. }
  46. void esp_brownout_init()
  47. {
  48. REG_WRITE(RTC_CNTL_BROWN_OUT_REG,
  49. RTC_CNTL_BROWN_OUT_ENA /* Enable BOD */
  50. | RTC_CNTL_BROWN_OUT_PD_RF_ENA /* Automatically power down RF */
  51. /* Reset timeout must be set to >1 even if BOR feature is not used */
  52. | (2 << RTC_CNTL_BROWN_OUT_RST_WAIT_S)
  53. | (BROWNOUT_DET_LVL << RTC_CNTL_DBROWN_OUT_THRES_S));
  54. ESP_ERROR_CHECK( rtc_isr_register(rtc_brownout_isr_handler, NULL, RTC_CNTL_BROWN_OUT_INT_ENA_M) );
  55. REG_SET_BIT(RTC_CNTL_INT_ENA_REG, RTC_CNTL_BROWN_OUT_INT_ENA_M);
  56. }