High power consumption in System ON sleep mode

I am working on nrf52832 based custom board which is configured to work as BLE peripheral and central. Peripherals like GPIO, SAADC, I2C, Timer and RTC are also configured. The RTC is configured to generate interrupt on a specific time interval. On that interrupt value of few sensors are read which is interfaced via SAADC and I2C. Rest of the time the device will go to system ON sleep to reduce power consumption. A GPIO based sensor is also configured to generate interrupt in both sleep and awake states. So when an RTC interrupt is occurred, SAADC, I2C and Timer peripherals are initialized and read the sensor values. Then the peripherals are de initialized and goes to sleep. I have checked the current consumption in sleep state using nRF power profiler and is about 700 micro Amps. But it's too high. I want to reduce this to below 100 micro Amps. Is it possible?

In sleep mode only GPIO and RTC are initialized and al  other peripherals are de initialized. I am attaching my main code here. 

 
/* Includes */

/* Standard includes*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>

/* SDK includes */
#include "boards.h"
#include "nordic_common.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "app_timer.h"
#include "ble.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
#include "ble_conn_state.h"
#include "nrf_fstorage.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_ble_scan.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "ble_hci.h"
#include "ble_lbs_c.h"
#include "ble_lbs.h"
#include "nrf_drv_timer.h"
#include "nrf_delay.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_drv_rtc.h"
#include "nrf_drv_clock.h"
#include "nrf_drv_gpiote.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_twi.h"


/* Macro Definitions */
#define DEVICE_NAME                     "TEST"																/**< Name of device used for advertising. */

#define APP_ADV_INTERVAL                300                               		/**< The advertising interval (in units of 0.625 ms). This value corresponds to 187.5 ms. */
#define APP_ADV_DURATION           			BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED  /**< The advertising duration set to 0 (Unlimited advertizing) */

#define APP_BLE_CONN_CFG_TAG            1                                 		/**< Tag that identifies the SoftDevice BLE configuration. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY  APP_TIMER_TICKS(5000)             		/**< Time from initiating event (connect or start of notification) to the first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(30000)            		/**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT    3                                 		/**< Number of attempts before giving up the connection parameter negotiation. */

#define APP_BLE_OBSERVER_PRIO           3																			/**< Priority of the application BLE event handler. */

#define DB_DISCOVERY_INSTANCE_CNT       2  																		/**< Number of DB Discovery instances. */

#define TWI_INSTANCE_ID     1

#define BUTTON							06
#define LED_BLUE						11
#define LED_RED							0x08
#define MPU6050_SCL         19
#define MPU6050_SDA         17
#define BAT_VOLT            NRF_SAADC_INPUT_AIN7

#define COMPARE_COUNTERTIME (15UL) 

/* Define objects */
NRF_BLE_GQ_DEF(m_ble_gatt_queue, NRF_SDH_BLE_CENTRAL_LINK_COUNT, NRF_BLE_GQ_QUEUE_SIZE);/**< BLE GATT Queue instance. */
NRF_BLE_GATT_DEF(m_gatt);                                              									/**< GATT module instance. */
NRF_BLE_QWRS_DEF(m_qwr, NRF_SDH_BLE_TOTAL_LINK_COUNT);                 									/**< Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising);                                    									/**< Advertising module instance. */
BLE_DB_DISCOVERY_DEF(m_db_disc);                                												/**< DB discovery module instance. */
NRF_BLE_SCAN_DEF(m_scan);                                           										/**< Scanning module instance. */
BLE_LBS_C_DEF(m_ble_lbs_c);                                     												/**< Main structure used by the LBS client module. */
BLE_LBS_DEF(m_lbs);                                                       							/**< LED Button Service instance. */

/* Define Variables */
static uint8_t m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET;             							/**< Advertising handle used to identify an advertising set. */
static uint8_t m_enc_advdata[BLE_GAP_ADV_SET_DATA_SIZE_MAX];              							/**< Buffer for storing an encoded advertising set. */
static uint8_t m_enc_scan_response_data[BLE_GAP_ADV_SET_DATA_SIZE_MAX];   							/**< Buffer for storing an encoded scan data. */

static const nrf_drv_twi_t i2c_master = NRF_DRV_TWI_INSTANCE(TWI_INSTANCE_ID);					/* Declare I2C instance */

/**@brief Struct that contains pointers to the encoded advertising data. */
static ble_gap_adv_data_t m_adv_data =
{
    .adv_data =
    {
        .p_data = m_enc_advdata,
        .len    = BLE_GAP_ADV_SET_DATA_SIZE_MAX
    },
    .scan_rsp_data =
    {
        .p_data = m_enc_scan_response_data,
        .len    = BLE_GAP_ADV_SET_DATA_SIZE_MAX

    }
};

/**@brief Scan parameters requested for scanning and connection. */
static ble_gap_scan_params_t m_scan_param =
{
    .active        = 0x01,
    .interval      = NRF_BLE_SCAN_SCAN_INTERVAL,
    .window        = NRF_BLE_SCAN_SCAN_WINDOW,
    .filter_policy = BLE_GAP_SCAN_FP_ACCEPT_ALL,
    .timeout       = NRF_BLE_SCAN_SCAN_DURATION,
    .scan_phys     = BLE_GAP_PHY_1MBPS,
    .extended      = true,
};

uint8_t target_dev_addr[6];																															/**< Array to store target device address (Reversed) */
uint8_t conn_handle_periph;               																							/**< Handle of the current connection from BLE central. */
uint8_t conn_handle_centra;             																								/**< Handle of the current connection from BLE peripheral. */
uint8_t read_sensor_flag;

                                       							/**< Get Compare event COMPARE_TIME seconds after the counter starts from 0. */
const nrf_drv_rtc_t rtc = NRF_DRV_RTC_INSTANCE(2); 																			/**< Declaring an instance of nrf_drv_rtc for RTC0. */

/* Built-in Function definitions */

/**@brief Function for handling asserts in the SoftDevice.
 *
 * @details This function is called in case of an assert in the SoftDevice.
 *
 * @warning This handler is an example only and is not meant for the final product. You need to analyze
 *          how your product is supposed to react in case of assert.
 * @warning On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in] line_num     Line number of the failing assert call.
 * @param[in] p_file_name  File name of the failing assert call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(0xDEADBEEF, line_num, p_file_name);
}

/**@brief Function for handling the LED Button Service client errors.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void lbs_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

/**@brief Function for handling the Heart Rate Service Client
 *        Running Speed and Cadence Service Client.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void service_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


/**@brief Function for handling errors from the Connection Parameters module.
 *
 * @param[in] nrf_error  Error code containing information about what went wrong.
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{

    ret_code_t err_code;
	
	  ble_gap_evt_adv_report_t const * p_adv =  p_scan_evt->params.filter_match.p_adv_report;
    ble_gap_scan_params_t    const * p_scan_param = p_scan_evt->p_scan_params;
		
    switch(p_scan_evt->scan_evt_id)
    {
			   case NRF_BLE_SCAN_EVT_FILTER_MATCH:			// Found peripheral with mac id mathing with target_dev_addr
        {

					// Initiate connection.
					err_code = sd_ble_gap_connect(&p_adv->peer_addr,
																				p_scan_param,
																				&m_scan.conn_params,
																				APP_BLE_CONN_CFG_TAG);
					APP_ERROR_CHECK(err_code);

        } break;
        case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
				{
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
				} break;
        default:
          break;
    }
}

/**@brief Handles events coming from the LED Button service central module.
Data coming from connecetd peripheral device to this central device
 */
static void lbs_c_evt_handler(ble_lbs_c_t * p_lbs_c, ble_lbs_c_evt_t * p_lbs_c_evt)
{
    switch (p_lbs_c_evt->evt_type)
    {
        case BLE_LBS_C_EVT_DISCOVERY_COMPLETE:			// lbs service discovered on connected peripheral
        {
            ret_code_t err_code;

            err_code = ble_lbs_c_handles_assign(&m_ble_lbs_c,
                                                p_lbs_c_evt->conn_handle,
                                                &p_lbs_c_evt->params.peer_db);
					
            // LED Button service discovered. Enable notification of Button.
            err_code = ble_lbs_c_button_notif_enable(p_lbs_c);
            APP_ERROR_CHECK(err_code);
											
        } break; // BLE_LBS_C_EVT_DISCOVERY_COMPLETE
				
        case BLE_LBS_C_EVT_BUTTON_NOTIFICATION:			// Data received from connected peripheral
        {
	

        } break; // BLE_LBS_C_EVT_BUTTON_NOTIFICATION				

        default:
            // No implementation needed.
            break;
    }
}

/**@brief Function for initialization the scanning and setting the filters.
 */
static void scan_init(void)
{
	ret_code_t          err_code;
	nrf_ble_scan_init_t init_scan;

	memset(&init_scan, 0, sizeof(init_scan));

	init_scan.connect_if_match = false;
	init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;

	err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
	APP_ERROR_CHECK(err_code);

	err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ADDR_FILTER, false);
	APP_ERROR_CHECK(err_code);

	if (target_dev_addr[0] != 0)
	{
		err_code = nrf_ble_scan_all_filter_remove(&m_scan);
		APP_ERROR_CHECK(err_code);		
		err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, target_dev_addr);
		APP_ERROR_CHECK(err_code);
	}

}

/**@brief Function for assigning new connection handle to available instance of QWR module.
 *
 * @param[in] conn_handle New connection handle.
 */
static void multi_qwr_conn_handle_assign(uint16_t conn_handle)
{
    for (uint32_t i = 0; i < NRF_SDH_BLE_TOTAL_LINK_COUNT; i++)
    {
        if (m_qwr[i].conn_handle == BLE_CONN_HANDLE_INVALID)
        {
            ret_code_t err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr[i], conn_handle);
            APP_ERROR_CHECK(err_code);
            break;
        }
    }
}

/**@brief Function for initializing the scanning.
 */
static void scan_start(void)
{
    ret_code_t err_code;
	
	  if (!nrf_fstorage_is_busy(NULL))
    {

			err_code = nrf_ble_scan_start(&m_scan);
			APP_ERROR_CHECK(err_code);
		}
}

/**@brief Function for initializing the advertising.
 */
static void advertize_start(void)
{
	
	ret_code_t err_code;
	
	if (!nrf_fstorage_is_busy(NULL))
  {

		err_code = sd_ble_gap_adv_start(m_adv_handle, APP_BLE_CONN_CFG_TAG);

		APP_ERROR_CHECK(err_code);
		
	}

}

/**@brief Function for stopping the scanning.
 */
void scan_stop(void)
{
    
	nrf_ble_scan_stop();

}

/**@brief Function for stopping the advertising.
 */
void advertize_stop(void)
{
	
	ret_code_t err_code;

	err_code = sd_ble_gap_adv_stop(m_adv_handle);

	APP_ERROR_CHECK(err_code);

}


/**@brief   Function for handling BLE events from the central application.
 *
 * @details This function parses scanning reports and initiates a connection to peripherals when a
 *          target UUID is found. It updates the status of LEDs used to report the central application
 *          activity.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 */
static void on_ble_central_evt(ble_evt_t const * p_ble_evt)
{
	ret_code_t err_code;

    // For readability.
    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;

    switch (p_ble_evt->header.evt_id)
    {
        // Upon connection, check which peripheral has connected (HR or RSC), initiate DB
        // discovery, update LEDs status and resume scanning if necessary. */
        case BLE_GAP_EVT_CONNECTED:
        {					

            err_code = ble_lbs_c_handles_assign(&m_ble_lbs_c, p_gap_evt->conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
					
						conn_handle_centra = p_gap_evt->conn_handle;
					
            err_code = ble_db_discovery_start(&m_db_disc, p_gap_evt->conn_handle);
            APP_ERROR_CHECK(err_code);

        } break;

        // Upon disconnection, reset the connection handle of the peer which disconnected, update
        // the LEDs status and start scanning again.
        case BLE_GAP_EVT_DISCONNECTED:
        {

            scan_start();
					
					
        } break;

        case BLE_GAP_EVT_TIMEOUT:
        {
            // We have not specified a timeout for scanning, so only connection attemps can timeout.
            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
            {

            }
        } break;

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
        {
            // Accept parameters requested by peer.
            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                        &p_gap_evt->params.conn_param_update_request.conn_params);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {

            ble_gap_phys_t const phys =
            {
                .rx_phys = BLE_GAP_PHY_AUTO,
                .tx_phys = BLE_GAP_PHY_AUTO,
            };
            err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTC_EVT_TIMEOUT:
        {
            // Disconnect on GATT Client timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTS_EVT_TIMEOUT:
        {
            // Disconnect on GATT Server timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
        } break;

        default:
            // No implementation needed.
            break;
    }
}


/**@brief   Function for handling BLE events from peripheral applications.
 * @details Updates the status LEDs used to report the activity of the peripheral applications.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 */
static void on_ble_peripheral_evt(ble_evt_t const * p_ble_evt)
{
    ret_code_t            err_code;
    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            // Assign connection handle to the QWR module.
            multi_qwr_conn_handle_assign(p_ble_evt->evt.gap_evt.conn_handle);
						conn_handle_periph = p_ble_evt->evt.gap_evt.conn_handle;				
            break;

        case BLE_GAP_EVT_DISCONNECTED:
					
						advertize_start();

            break;

        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
            ble_gap_phys_t const phys =
            {
                .rx_phys = BLE_GAP_PHY_AUTO,
                .tx_phys = BLE_GAP_PHY_AUTO,
            };
            err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GATTS_EVT_TIMEOUT:
            // Disconnect on GATT Server timeout event.
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break;

        default:
            // No implementation needed.
            break;
    }
}


/**@brief Function for handling advertising events.
 *
 * @param[in] ble_adv_evt  Advertising event.
 */
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
        {

        } break;

        case BLE_ADV_EVT_IDLE:
        {
            ret_code_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
            APP_ERROR_CHECK(err_code);
        } break;

        default:
            // No implementation needed.
            break;
    }
}


/**@brief Function for checking whether a bluetooth stack event is an advertising timeout.
 *
 * @param[in] p_ble_evt Bluetooth stack event.
 */
static bool ble_evt_is_advertising_timeout(ble_evt_t const * p_ble_evt)
{
    return (p_ble_evt->header.evt_id == BLE_GAP_EVT_ADV_SET_TERMINATED);
}


/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
	  uint16_t conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
    uint16_t role        = ble_conn_state_role(conn_handle);

    // Based on the role this device plays in the connection, dispatch to the right handler.
    if (role == BLE_GAP_ROLE_PERIPH || ble_evt_is_advertising_timeout(p_ble_evt))
    {
        on_ble_peripheral_evt(p_ble_evt);
    }
    else if ((role == BLE_GAP_ROLE_CENTRAL) || (p_ble_evt->header.evt_id == BLE_GAP_EVT_ADV_REPORT))
    {
        on_ble_central_evt(p_ble_evt);
    }
}

/**@brief LED Button client initialization.
 */
static void lbs_c_init(void)
{
    ret_code_t       err_code;
    ble_lbs_c_init_t lbs_c_init_obj;

    lbs_c_init_obj.evt_handler   = lbs_c_evt_handler;
    lbs_c_init_obj.p_gatt_queue  = &m_ble_gatt_queue;
    lbs_c_init_obj.error_handler = lbs_error_handler;

    err_code = ble_lbs_c_init(&m_ble_lbs_c, &lbs_c_init_obj);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupts.
 */
static void ble_stack_init(void)
{
    ret_code_t err_code;

    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);

    // Configure the BLE stack using the default settings.
    // Fetch the start address of the application RAM.
    uint32_t ram_start = 0;
    err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
    APP_ERROR_CHECK(err_code);

    // Enable BLE stack.
    err_code = nrf_sdh_ble_enable(&ram_start);
    APP_ERROR_CHECK(err_code);

    // Register a handler for BLE events.
    NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}


/**@brief Function for initializing the GAP.
 *
 * @details This function sets up all the necessary GAP (Generic Access Profile) parameters of the
 *          device, including the device name, appearance, and the preferred connection parameters.
 */
static void gap_params_init(void)
{
    ret_code_t              err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);

    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *)DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);

    memset(&gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = m_scan.conn_params.min_conn_interval;
    gap_conn_params.max_conn_interval = m_scan.conn_params.max_conn_interval;
    gap_conn_params.slave_latency     = m_scan.conn_params.slave_latency;
    gap_conn_params.conn_sup_timeout  = m_scan.conn_params.conn_sup_timeout;

    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the GATT module.
 */
static void gatt_init(void)
{
    ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the Connection Parameters module.
 */
static void conn_params_init(void)
{
    ret_code_t             err_code;
    ble_conn_params_init_t cp_init;

    memset(&cp_init, 0, sizeof(cp_init));

    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_CONN_HANDLE_INVALID; // Start upon connection.
    cp_init.disconnect_on_fail             = true;
    cp_init.evt_handler                    = NULL;  // Ignore events.
    cp_init.error_handler                  = conn_params_error_handler;

    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling database discovery events.
 *
 * @details This function is a callback function to handle events from the database discovery module.
 *          Depending on the UUIDs that are discovered, this function forwards the events
 *          to their respective services.
 *
 * @param[in] p_event  Pointer to the database discovery event.
 */
static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
{
    ble_db_discovery_t const * p_db = (ble_db_discovery_t *)p_evt->params.p_db_instance;

		ble_lbs_on_db_disc_evt(&m_ble_lbs_c, p_evt);

    if (p_evt->evt_type == BLE_DB_DISCOVERY_AVAILABLE) {

		
    }
}


/**
 * @brief Database discovery initialization.
 */
static void db_discovery_init(void)
{
    ble_db_discovery_init_t db_init;

    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));

    db_init.evt_handler  = db_disc_handler;
    db_init.p_gatt_queue = &m_ble_gatt_queue;

    ret_code_t err_code = ble_db_discovery_init(&db_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling Queued Write module errors.
 *
 * @details A pointer to this function is passed to each service that may need to inform the
 *          application about an error.
 *
 * @param[in]   nrf_error   Error code that contains information about what went wrong.
 */
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

/**@brief Function for handling write events to the LED characteristic.
						Data coming from connecetd Central device to this peripheral device
 *
 * @param[in] p_lbs     Instance of LED Button Service to which the write applies.
 * @param[in] led_state Written/desired state of the LED.
 */
static void led_write_handler(uint16_t conn_handle, ble_lbs_t * p_lbs, uint8_t led_state)
{
	

	
}

/**@brief Function for initializing services that are be used by the application.
 *
 * @details Initialize the Heart Rate, Battery and Device Information services.
 */
static void services_init(void)
{
    ret_code_t         err_code;
    ble_lbs_init_t     init;
    nrf_ble_qwr_init_t qwr_init = {0};

    // Initialize Queued Write Module instances.
    qwr_init.error_handler = nrf_qwr_error_handler;

    for (uint32_t i = 0; i < NRF_SDH_BLE_TOTAL_LINK_COUNT; i++)
    {
        err_code = nrf_ble_qwr_init(&m_qwr[i], &qwr_init);
        APP_ERROR_CHECK(err_code);
    }

    // Initialize LBS.
    init.led_write_handler = led_write_handler;
		
    err_code = ble_lbs_init(&m_lbs, &init);
    APP_ERROR_CHECK(err_code);

    ble_conn_state_init();
		

}

/**@brief Function for initializing the advertising functionality.
 */
static void advertising_init(void)
{
    ret_code_t           err_code;
    ble_advdata_t        advdata;
    ble_advdata_t        srdata;
    ble_gap_adv_params_t adv_params;


    ble_uuid_t adv_uuids[] = {{LBS_UUID_SERVICE, m_lbs.uuid_type}};

    // Build and set advertising data.
    memset(&advdata, 0, sizeof(advdata));

    advdata.name_type          = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance = true;
    advdata.flags              = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;

    memset(&srdata, 0, sizeof(srdata));
    srdata.uuids_complete.uuid_cnt = sizeof(adv_uuids) / sizeof(adv_uuids[0]);
    srdata.uuids_complete.p_uuids  = adv_uuids;
		

    err_code = ble_advdata_encode(&advdata, m_adv_data.adv_data.p_data, &m_adv_data.adv_data.len);
    APP_ERROR_CHECK(err_code);

    err_code = ble_advdata_encode(&srdata, m_adv_data.scan_rsp_data.p_data, &m_adv_data.scan_rsp_data.len);
    APP_ERROR_CHECK(err_code);

    // Start advertising.
    memset(&adv_params, 0, sizeof(adv_params));
    adv_params.p_peer_addr   = NULL;
    adv_params.filter_policy = BLE_GAP_ADV_FP_ANY;
    adv_params.interval      = APP_ADV_INTERVAL;

    adv_params.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
    adv_params.duration        = APP_ADV_DURATION;
    adv_params.primary_phy     = BLE_GAP_PHY_1MBPS;

    err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &adv_params);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing logging.
 */
static void log_init(void)
{
    ret_code_t err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    NRF_LOG_DEFAULT_BACKENDS_INIT();
}


/**@brief Function for initializing power management.
 */
static void power_management_init(void)
{
    ret_code_t err_code;
    err_code = nrf_pwr_mgmt_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling the idle state (main loop). If there is no pending log operation,
          then sleeps until the next event occurs.
 */
static void idle_state_handle(void)
{
    if (NRF_LOG_PROCESS() == false)
    {
        nrf_pwr_mgmt_run();
    }
}


/**@brief Function for initializing the timer.
 */
static void timer_init(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
}


/* User defined Static Function definitions */

/** @brief: Function for handling the RTC0 interrupts.
 * Triggered on TICK and COMPARE0 match.
 */
static void rtc_handler(nrf_drv_rtc_int_type_t int_type)
{
    if (int_type == NRF_DRV_RTC_INT_COMPARE0)
    {
			
			read_sensor_flag = 1;
			
			// Reset compare value for the next interrupt
			uint32_t cc_value = nrf_drv_rtc_counter_get(&rtc) + (COMPARE_COUNTERTIME * 8);
			nrf_drv_rtc_cc_set(&rtc, 0, cc_value, true);
			
    }
    else if (int_type == NRF_DRV_RTC_INT_TICK)
    {
	
			
    }
}

/** @brief Function initialization and configuration of RTC driver instance.
 */
static void rtc_config(void)
{
    uint32_t err_code;

    //Initialize RTC instance
    nrf_drv_rtc_config_t config = NRF_DRV_RTC_DEFAULT_CONFIG;
    config.prescaler = 4095;
    err_code = nrf_drv_rtc_init(&rtc, &config, rtc_handler);
    APP_ERROR_CHECK(err_code);

    //Enable tick event & interrupt
//    nrf_drv_rtc_tick_enable(&rtc,true);

    //Set compare channel to trigger interrupt after COMPARE_COUNTERTIME seconds
    err_code = nrf_drv_rtc_cc_set(&rtc,0,COMPARE_COUNTERTIME * 8,true);
    APP_ERROR_CHECK(err_code);

    //Power on RTC instance
    nrf_drv_rtc_enable(&rtc);
}

/** @brief Function de-initialization of RTC driver instance.
 */
static void rtc_de_init(void)
{

	nrf_drv_rtc_disable(&rtc);
	nrf_drv_rtc_uninit(&rtc);

}

/**
 *@brief function to initialize I2C peripheral in 100khz or 400khz
*/
void I2C_init()
{
	
	ret_code_t ret;
    const nrf_drv_twi_config_t config =
    {
       .scl                = MPU6050_SCL,
       .sda                = MPU6050_SDA,
       .frequency          = NRF_DRV_TWI_FREQ_100K,
       .interrupt_priority = APP_IRQ_PRIORITY_HIGH,
       .clear_bus_init     = false
    };

    ret = nrf_drv_twi_init(&i2c_master, &config, NULL, NULL);

    if (NRF_SUCCESS == ret)
    {
        nrf_drv_twi_enable(&i2c_master);
    }
	
}

/**
 *@brief function to enable I2C peripheral
*/
void I2C_enable()
{	
	nrf_drv_twi_enable(&i2c_master);
	
}

/**
 *@brief function to disable I2C peripheral
*/
void I2C_disable()
{	
	nrf_drv_twi_disable(&i2c_master);
	
}

/**
 *@brief function to disable I2C peripheral
*/
void I2C_uninit()
{	
	nrf_drv_twi_uninit(&i2c_master);
	
}


/**
 * @brief Advertize button handler
 */
static void button_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
				
	read_sensor_flag = 1;

}

static void button_init(void)
{
	
	nrf_drv_gpiote_init();
	
  nrf_drv_gpiote_in_config_t button_config = GPIOTE_RAW_CONFIG_IN_SENSE_HITOLO(true);
  button_config.pull = NRF_GPIO_PIN_NOPULL;
	
  nrf_drv_gpiote_in_init(BUTTON, &button_config, button_handler);

  nrf_drv_gpiote_in_event_enable(BUTTON, true);
	
	nrf_gpio_cfg_sense_input(BUTTON, NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_NOSENSE);
		
}

static void led_init(void)
{

	nrf_drv_gpiote_out_config_t ble_led_pin_config = GPIOTE_CONFIG_OUT_SIMPLE(true);
	ble_led_pin_config.init_state = NRF_GPIOTE_INITIAL_VALUE_HIGH;

	nrf_drv_gpiote_out_init(LED_BLUE, &ble_led_pin_config);
	nrf_drv_gpiote_out_init(LED_RED, &ble_led_pin_config);

	nrf_drv_gpiote_out_set(LED_RED);
	nrf_drv_gpiote_out_set(LED_BLUE);

}

static void batVolt_saadc_config(void){

	nrfx_saadc_config_t batVolt_config = NRFX_SAADC_DEFAULT_CONFIG;
  nrf_saadc_channel_config_t batVotl_ch_config ={
		
	  .resistor_p = NRF_SAADC_RESISTOR_DISABLED,      
    .resistor_n = NRF_SAADC_RESISTOR_DISABLED,     
    .gain       = NRF_SAADC_GAIN1_4,                
    .reference  = NRF_SAADC_REFERENCE_VDD4,     
    .acq_time   = NRF_SAADC_ACQTIME_10US,           
    .mode       = NRF_SAADC_MODE_SINGLE_ENDED,      
    .burst      = NRF_SAADC_BURST_DISABLED,         
    .pin_p      = (nrf_saadc_input_t)(BAT_VOLT),       
    .pin_n      = NRF_SAADC_INPUT_DISABLED    
	};
	
	nrf_drv_saadc_init(&batVolt_config,NULL);
	nrf_drv_saadc_channel_init(7,&batVotl_ch_config);

}

static void batVolt_saadc_de_config(void)
{
	nrf_drv_saadc_channel_uninit(7);	
	nrf_drv_saadc_uninit();
	
}	

static void led_de_init(void)
{

	nrfx_gpiote_out_task_disable(LED_BLUE);
	nrf_drv_gpiote_out_uninit(LED_BLUE);
	
	nrfx_gpiote_out_task_disable(LED_RED);
	nrf_drv_gpiote_out_uninit(LED_RED);	
}


/**@brief Function for initializing the application main entry.
 */
int main(void)
 {

  // Initialize.
	SystemInit();
	timer_init();
	rtc_config();
	power_management_init();
	ble_stack_init();
	scan_init();
	gap_params_init();
	gatt_init();
	db_discovery_init();
	services_init();
	advertising_init();
	lbs_c_init();

	button_init();
	
    // Enter main loop.
    for (;;)
    {
			
			idle_state_handle();
			
			if(read_sensor_flag == 0) {			
				
				sd_app_evt_wait();
				
			}			
			
			else if(read_sensor_flag == 1) {
				
					led_init();
					batVolt_saadc_config();
					I2C_init();
				
					/**
						Reading Sensor Values
																**/
			
					led_de_init();
					batVolt_saadc_de_config();
					I2C_disable();
					I2C_uninit();
				
					read_sensor_flag = 0;
					
					sd_app_evt_wait();	
			}		
			
    }
}

Thanks

Sachin

Related