]> granicus.if.org Git - esp-idf/blob - components/esp32/brownout.c
Merge branch 'feature/high_level_interrupts' into 'master'
[esp-idf] / components / esp32 / brownout.c
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
15 #include <stdint.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include "sdkconfig.h"
20 #include "soc/soc.h"
21 #include "soc/cpu.h"
22 #include "soc/rtc_cntl_reg.h"
23 #include "rom/ets_sys.h"
24 #include "esp_system.h"
25 #include "driver/rtc_cntl.h"
26 #include "freertos/FreeRTOS.h"
27
28 #ifdef CONFIG_BROWNOUT_DET_LVL
29 #define BROWNOUT_DET_LVL CONFIG_BROWNOUT_DET_LVL
30 #else
31 #define BROWNOUT_DET_LVL 0
32 #endif //CONFIG_BROWNOUT_DET_LVL
33
34 static void rtc_brownout_isr_handler()
35 {
36     /* Normally RTC ISR clears the interrupt flag after the application-supplied
37      * handler returns. Since restart is called here, the flag needs to be
38      * cleared manually.
39      */
40     REG_WRITE(RTC_CNTL_INT_CLR_REG, RTC_CNTL_BROWN_OUT_INT_CLR);
41     /* Stall the other CPU to make sure the code running there doesn't use UART
42      * at the same time as the following ets_printf.
43      */
44     esp_cpu_stall(!xPortGetCoreID());
45     ets_printf("\r\nBrownout detector was triggered\r\n\r\n");
46     esp_restart_noos();
47 }
48
49 void esp_brownout_init()
50 {
51     REG_WRITE(RTC_CNTL_BROWN_OUT_REG,
52             RTC_CNTL_BROWN_OUT_ENA /* Enable BOD */
53             | RTC_CNTL_BROWN_OUT_PD_RF_ENA /* Automatically power down RF */
54             /* Reset timeout must be set to >1 even if BOR feature is not used */
55             | (2 << RTC_CNTL_BROWN_OUT_RST_WAIT_S)
56             | (BROWNOUT_DET_LVL << RTC_CNTL_DBROWN_OUT_THRES_S));
57
58     ESP_ERROR_CHECK( rtc_isr_register(rtc_brownout_isr_handler, NULL, RTC_CNTL_BROWN_OUT_INT_ENA_M) );
59
60     REG_SET_BIT(RTC_CNTL_INT_ENA_REG, RTC_CNTL_BROWN_OUT_INT_ENA_M);
61 }