<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="https://devzone.nordicsemi.com/cfs-file/__key/system/syndication/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Getting error code =4 in ble_stack_init.</title><link>https://devzone.nordicsemi.com/f/nordic-q-a/45903/getting-error-code-4-in-ble_stack_init</link><description>Hi, 
 I am working on implementing concurrent BLE UART central and peripheral service. I am doing this by taking &amp;quot;ble_app_hrs_rscs_relay&amp;quot; default example as a reference. 
 I am facing a issue where in &amp;quot;ble_stack_init()&amp;quot; function &amp;quot;nrf_sdh_ble_enable(&amp;amp;ram_start</description><dc:language>en-US</dc:language><generator>Telligent Community 13</generator><lastBuildDate>Tue, 09 Apr 2019 12:58:42 GMT</lastBuildDate><atom:link rel="self" type="application/rss+xml" href="https://devzone.nordicsemi.com/f/nordic-q-a/45903/getting-error-code-4-in-ble_stack_init" /><item><title>RE: Getting error code =4 in ble_stack_init.</title><link>https://devzone.nordicsemi.com/thread/181063?ContentTypeID=1</link><pubDate>Tue, 09 Apr 2019 12:58:42 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:27395b37-437a-4788-8e1a-d197181ed599</guid><dc:creator>J&amp;#248;rgen Holmefjord</dc:creator><description>&lt;p&gt;I would recommend that you set breakpoints in your application where you call&amp;nbsp;app_uart_put()/printf(), to see if you are actually printing the same data two times. Note that you will have to restart the application after hitting a breakpoint, in order to restore the state of the softdevice.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Getting error code =4 in ble_stack_init.</title><link>https://devzone.nordicsemi.com/thread/181031?ContentTypeID=1</link><pubDate>Tue, 09 Apr 2019 11:56:28 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:72103363-6027-4075-b3e9-195c95af6945</guid><dc:creator>kishor babu</dc:creator><description>&lt;p&gt;Hi Jorgen,&lt;/p&gt;
&lt;p&gt;I made &amp;quot;&amp;nbsp;&lt;span&gt;NRF_SDH_BLE_VS_UUID_COUNT =1&amp;quot;. Now the system is not resetting and it is able to scan and advertise at a time.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;I am able to connect to the central and peripheral at a time, But the issue I am facing is when I am trying to send the data over BLE using nrfconnect the data is printing two times in UART terminal.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;/**
 * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 * 
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 * 
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 * 
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 * 
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA &amp;quot;AS IS&amp;quot; AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
/**
 * @brief BLE Heart Rate and Running speed Relay application main file.
 *
 * @detail This application demonstrates a simple &amp;quot;Relay&amp;quot;.
 * Meaning we pass on the values that we receive. By combining a collector part on
 * one end and a sensor part on the other, we show that the s130 can function
 * simultaneously as a central and a peripheral device.
 *
 * In the figure below, the sensor ble_app_hrs connects and interacts with the relay
 * in the same manner it would connect to a heart rate collector. In this case, the Relay
 * application acts as a central.
 *
 * On the other side, a collector (such as Master Control panel or ble_app_hrs_c) connects
 * and interacts with the relay the same manner it would connect to a heart rate sensor peripheral.
 *
 * Led layout:
 * LED 1: Central side is scanning       LED 2: Central side is connected to a peripheral
 * LED 3: Peripheral side is advertising LED 4: Peripheral side is connected to a central
 *
 * @note While testing, be careful that the Sensor and Collector are actually connecting to the Relay,
 *       and not directly to each other!
 *
 *    Peripheral                  Relay                    Central
 *    +--------+        +-----------|----------+        +-----------+
 *    | Heart  |        | Heart     |   Heart  |        |           |
 *    | Rate   | -----&amp;gt; | Rate     -|-&amp;gt; Rate   | -----&amp;gt; | Collector |
 *    | Sensor |        | Collector |   Sensor |        |           |
 *    +--------+        +-----------|   and    |        +-----------+
 *                      | Running   |   Running|
 *    +--------+        | Speed    -|-&amp;gt; Speed  |
 *    | Running|------&amp;gt; | Collector |   Sensor |
 *    | Speed  |        +-----------|----------+
 *    | Sensor |
 *    +--------+
 */

#include &amp;lt;stdint.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;string.h&amp;gt;
#include &amp;quot;nordic_common.h&amp;quot;
#include &amp;quot;nrf_sdh.h&amp;quot;
#include &amp;quot;nrf_sdh_soc.h&amp;quot;
#include &amp;quot;nrf_sdh_ble.h&amp;quot;
#include &amp;quot;peer_manager.h&amp;quot;
#include &amp;quot;app_timer.h&amp;quot;
#include &amp;quot;bsp_btn_ble.h&amp;quot;
#include &amp;quot;ble.h&amp;quot;
#include &amp;quot;ble_advdata.h&amp;quot;
#include &amp;quot;ble_advertising.h&amp;quot;
#include &amp;quot;ble_conn_params.h&amp;quot;
#include &amp;quot;ble_db_discovery.h&amp;quot;
#include &amp;quot;ble_hrs.h&amp;quot;
#include &amp;quot;ble_rscs.h&amp;quot;
#include &amp;quot;ble_hrs_c.h&amp;quot;
#include &amp;quot;ble_rscs_c.h&amp;quot;
#include &amp;quot;ble_conn_state.h&amp;quot;
#include &amp;quot;nrf_fstorage.h&amp;quot;
#include &amp;quot;fds.h&amp;quot;
#include &amp;quot;nrf_ble_gatt.h&amp;quot;

#include &amp;quot;ble_nus.h&amp;quot;//added
#include &amp;quot;app_uart.h&amp;quot;//added
#include &amp;quot;app_util_platform.h&amp;quot;//added
#include &amp;quot;ble_nus_c.h&amp;quot;//added
#include &amp;quot;nrf_delay.h&amp;quot;
#include &amp;quot;nrf_log.h&amp;quot;
#include &amp;quot;nrf_log_ctrl.h&amp;quot;
#include &amp;quot;nrf_log_default_backends.h&amp;quot;


#define NUS_SERVICE_UUID_TYPE           BLE_UUID_TYPE_VENDOR_BEGIN                  /**&amp;lt; UUID type for the Nordic UART Service (vendor specific). */
#define ECHOBACK_BLE_UART_DATA  0                                       /**&amp;lt; Echo the UART data that is received over the Nordic UART Service back to the sender. */
#define PERIPHERAL_ADVERTISING_LED      BSP_BOARD_LED_2
#define PERIPHERAL_CONNECTED_LED        BSP_BOARD_LED_3
#define CENTRAL_SCANNING_LED            BSP_BOARD_LED_0
#define CENTRAL_CONNECTED_LED           BSP_BOARD_LED_1

#define DEVICE_NAME                     &amp;quot;Relay&amp;quot;                                     /**&amp;lt; Name of device used for advertising. */
#define MANUFACTURER_NAME               &amp;quot;NordicSemiconductor&amp;quot;                       /**&amp;lt; Manufacturer. Will be passed to Device Information Service. */
#define APP_ADV_INTERVAL                300                                         /**&amp;lt; The advertising interval (in units of 0.625 ms). This value corresponds to 187.5 ms. */
#define APP_ADV_TIMEOUT_IN_SECONDS      180                                         /**&amp;lt; The advertising timeout in units of seconds. */

#define APP_BLE_CONN_CFG_TAG            1                                           /**&amp;lt; A tag identifying the SoftDevice BLE configuration. */

#define FIRST_CONN_PARAMS_UPDATE_DELAY  APP_TIMER_TICKS(5000)                       /**&amp;lt; Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(30000)                      /**&amp;lt; Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT    3                                           /**&amp;lt; Number of attempts before giving up the connection parameter negotiation. */

#define APP_FEATURE_NOT_SUPPORTED       BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2        /**&amp;lt; Reply when unsupported features are requested. */

#define SEC_PARAM_BOND                  1                                           /**&amp;lt; Perform bonding. */
#define SEC_PARAM_MITM                  0                                           /**&amp;lt; Man In The Middle protection not required. */
#define SEC_PARAM_LESC                  0                                           /**&amp;lt; LE Secure Connections not enabled. */
#define SEC_PARAM_KEYPRESS              0                                           /**&amp;lt; Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES       BLE_GAP_IO_CAPS_NONE                        /**&amp;lt; No I/O capabilities. */
#define SEC_PARAM_OOB                   0                                           /**&amp;lt; Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE          7                                           /**&amp;lt; Minimum encryption key size in octets. */
#define SEC_PARAM_MAX_KEY_SIZE          16                                          /**&amp;lt; Maximum encryption key size in octets. */

#define SCAN_INTERVAL                   0x00A0                                      /**&amp;lt; Determines scan interval in units of 0.625 millisecond. */
#define SCAN_WINDOW                     0x0050                                      /**&amp;lt; Determines scan window in units of 0.625 millisecond. */
#define SCAN_TIMEOUT                    0

#define MIN_CONNECTION_INTERVAL         (uint16_t) MSEC_TO_UNITS(7.5, UNIT_1_25_MS) /**&amp;lt; Determines minimum connection interval in milliseconds. */
#define MAX_CONNECTION_INTERVAL         (uint16_t) MSEC_TO_UNITS(30, UNIT_1_25_MS)  /**&amp;lt; Determines maximum connection interval in milliseconds. */
#define SLAVE_LATENCY                   0                                           /**&amp;lt; Determines slave latency in terms of connection events. */
#define SUPERVISION_TIMEOUT             (uint16_t) MSEC_TO_UNITS(4000, UNIT_10_MS)  /**&amp;lt; Determines supervision time-out in units of 10 milliseconds. */

#define UUID16_SIZE                     2                                           /**&amp;lt; Size of a UUID, in bytes. */
#define UUID32_SIZE                 4                               /**&amp;lt; Size of 32 bit UUID */
#define UUID128_SIZE                16                              /**&amp;lt; Size of 128 bit UUID */
#define UART_TX_BUF_SIZE        256                                     /**&amp;lt; UART TX buffer size. */
#define UART_RX_BUF_SIZE        256                                     /**&amp;lt; UART RX buffer size. */

#define CENTRAL_LINK_COUNT          1                                             /**&amp;lt; Number of central links used by the application. When changing this number remember to adjust the RAM settings*/
#define PERIPHERAL_LINK_COUNT       1                                             /**&amp;lt; Number of peripheral links used by the application. When changing this number remember to adjust the RAM settings*/


/**@brief   Priority of the application BLE event handler.
 * @note    You shouldn&amp;#39;t need to modify this value.
 */
#define APP_BLE_OBSERVER_PRIO           1

/**@brief Macro to unpack 16bit unsigned UUID from an octet stream.
 */
#define UUID16_EXTRACT(DST, SRC) \
    do                           \
    {                            \
        (*(DST))   = (SRC)[1];   \
        (*(DST)) &amp;lt;&amp;lt;= 8;          \
        (*(DST))  |= (SRC)[0];   \
    } while (0)


/**@brief Variable length data encapsulation in terms of length and pointer to data. */
typedef struct
{
    uint8_t  * p_data;   /**&amp;lt; Pointer to data. */
    uint16_t   data_len; /**&amp;lt; Length of data. */
} data_t;


//BLE_HRS_DEF(m_hrs);                                                 /**&amp;lt; Heart rate service instance. */
//BLE_RSCS_DEF(m_rscs);                                               /**&amp;lt; Running speed and cadence service instance. */
//BLE_HRS_C_DEF(m_hrs_c);                                             /**&amp;lt; Heart rate service client instance. */
//BLE_RSCS_C_DEF(m_rscs_c);                                           /**&amp;lt; Running speed and cadence service client instance. */

BLE_NUS_DEF(m_nus);                                                 /**&amp;lt; Heart rate service instance. */
BLE_NUS_C_DEF(m_ble_nus_c);                                             /**&amp;lt; BLE NUS service client instance. */                                              /**&amp;lt; Running speed and cadence service instance. */

NRF_BLE_GATT_DEF(m_gatt);                                           /**&amp;lt; GATT module instance. */
BLE_ADVERTISING_DEF(m_advertising);                                 /**&amp;lt; Advertising module instance. */
BLE_DB_DISCOVERY_DEF(m_db_discovery);                               /**&amp;lt; Database discovery module instances. */


static char cmd[40];//added
bool peripheral_status=0,central_status=0;
bool peripheral_event=0;

static uint16_t m_conn_handle_nus_c  = BLE_CONN_HANDLE_INVALID;     /**&amp;lt; Connection handle for the HRS central application */
//static uint16_t m_conn_handle_rscs_c = BLE_CONN_HANDLE_INVALID;     /**&amp;lt; Connection handle for the RSC central application */
static uint16_t   m_conn_handle          = BLE_CONN_HANDLE_INVALID;                 /**&amp;lt; Handle of the current connection. */
static uint16_t m_conn_handle_to_disc = BLE_CONN_HANDLE_INVALID;    /**&amp;lt; The connection handle on which to retry the DB discovery. */
static bool     m_retry_db_disc;                                    /**&amp;lt; Retry DB discovery if attempted while busy. */
static bool     m_do_retry_db_disc;
static uint16_t   m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3;            /**&amp;lt; Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
static ble_uuid_t m_adv_uuids[]          =                                          /**&amp;lt; Universally unique service identifier. */
{
    {BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}
};
/**@brief names which the central applications will scan for, and which will be advertised by the peripherals.
 *  if these are set to empty strings, the UUIDs defined below will be used
 */
static char const m_target_periph_name[] = &amp;quot;&amp;quot;;

///**@brief UUIDs which the central applications will scan for if the name above is set to an empty string,
// * and which will be advertised by the peripherals.
// */
//static ble_uuid_t m_adv_uuids[] =
//{
//    {BLE_UUID_HEART_RATE_SERVICE,        BLE_UUID_TYPE_BLE},
//    {BLE_UUID_RUNNING_SPEED_AND_CADENCE, BLE_UUID_TYPE_BLE}
//};

/**@brief Parameters used when scanning. */
static ble_gap_scan_params_t const m_scan_params =
{
    .active   = 1,
    .interval = SCAN_INTERVAL,
    .window   = SCAN_WINDOW,
    .timeout  = SCAN_TIMEOUT,
    #if (NRF_SD_BLE_API_VERSION &amp;lt;= 2)
        .selective   = 0,
        .p_whitelist = NULL,
    #endif
    #if (NRF_SD_BLE_API_VERSION &amp;gt;= 3)
        .use_whitelist = 0,
    #endif
};


/**@brief NUS uuid. */
static ble_uuid_t const m_nus_uuid =
{
    .uuid = BLE_UUID_NUS_SERVICE,
    .type = NUS_SERVICE_UUID_TYPE
};

/**@brief Connection parameters requested for connection. */
static ble_gap_conn_params_t const m_connection_param =
{
    MIN_CONNECTION_INTERVAL,
    MAX_CONNECTION_INTERVAL,
    SLAVE_LATENCY,
    SUPERVISION_TIMEOUT
};


/**@brief Function to handle asserts in the SoftDevice.
 *
 * @details This function will be called in case of an assert in the SoftDevice.
 *
 * @warning This handler is an example only and does not fit a 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 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);
}


/**@brief Parses advertisement data, providing length and location of the field in case
 *        matching data is found.
 *
 * @param[in]  Type of data to be looked for in advertisement data.
 * @param[in]  Advertisement report length and pointer to report.
 * @param[out] If data type requested is found in the data report, type data length and
 *             pointer to data will be populated here.
 *
 * @retval NRF_SUCCESS if the data type is found in the report.
 * @retval NRF_ERROR_NOT_FOUND if the data type could not be found.
 */
static uint32_t adv_report_parse(uint8_t type, data_t * p_advdata, data_t * p_typedata)
{
    uint32_t   index = 0;
    uint8_t  * p_data;

    p_data = p_advdata-&amp;gt;p_data;

    while (index &amp;lt; p_advdata-&amp;gt;data_len)
    {
        uint8_t field_length = p_data[index];
        uint8_t field_type   = p_data[index + 1];

        if (field_type == type)
        {
            p_typedata-&amp;gt;p_data   = &amp;amp;p_data[index + 2];
            p_typedata-&amp;gt;data_len = field_length - 1;
            return NRF_SUCCESS;
        }
        index += field_length + 1;
    }
    return NRF_ERROR_NOT_FOUND;
}


/**@brief Function for initiating scanning.
 */
static void scan_start(void)
{
    ret_code_t err_code;

    (void) sd_ble_gap_scan_stop();

    err_code = sd_ble_gap_scan_start(&amp;amp;m_scan_params);
    // It is okay to ignore this error since we are stopping the scan anyway.
    if (err_code != NRF_ERROR_INVALID_STATE)
    {
        APP_ERROR_CHECK(err_code);
    }
}


/**@brief Function for initiating advertising and scanning.
 */
static void adv_scan_start(void)
{
    ret_code_t err_code;

    //check if there are no flash operations in progress
    if (!nrf_fstorage_is_busy(NULL))
    {
        // Start scanning for peripherals and initiate connection to devices which
        // advertise Heart Rate or Running speed and cadence UUIDs.
        scan_start();

        // Turn on the LED to signal scanning.
        bsp_board_led_on(CENTRAL_SCANNING_LED);

        // Start advertising.
        err_code = ble_advertising_start(&amp;amp;m_advertising, BLE_ADV_MODE_FAST);
        APP_ERROR_CHECK(err_code);
    }
}


/**@brief Function for handling Peer Manager events.
 *
 * @param[in] p_evt  Peer Manager event.
 */
static void pm_evt_handler(pm_evt_t const * p_evt)
{
    ret_code_t err_code;

    switch (p_evt-&amp;gt;evt_id)
    {
        case PM_EVT_BONDED_PEER_CONNECTED:
        {
            NRF_LOG_INFO(&amp;quot;Connected to a previously bonded device.&amp;quot;);
        } break;

        case PM_EVT_CONN_SEC_SUCCEEDED:
        {
            NRF_LOG_INFO(&amp;quot;Connection secured: role: %d, conn_handle: 0x%x, procedure: %d.&amp;quot;,
                         ble_conn_state_role(p_evt-&amp;gt;conn_handle),
                         p_evt-&amp;gt;conn_handle,
                         p_evt-&amp;gt;params.conn_sec_succeeded.procedure);
        } break;

        case PM_EVT_CONN_SEC_FAILED:
        {
            /* Often, when securing fails, it shouldn&amp;#39;t be restarted, for security reasons.
             * Other times, it can be restarted directly.
             * Sometimes it can be restarted, but only after changing some Security Parameters.
             * Sometimes, it cannot be restarted until the link is disconnected and reconnected.
             * Sometimes it is impossible, to secure the link, or the peer device does not support it.
             * How to handle this error is highly application dependent. */
        } break;

        case PM_EVT_CONN_SEC_CONFIG_REQ:
        {
            // Reject pairing request from an already bonded peer.
            pm_conn_sec_config_t conn_sec_config = {.allow_repairing = false};
            pm_conn_sec_config_reply(p_evt-&amp;gt;conn_handle, &amp;amp;conn_sec_config);
        } break;

        case PM_EVT_STORAGE_FULL:
        {
            // Run garbage collection on the flash.
            err_code = fds_gc();
            if (err_code == FDS_ERR_BUSY || err_code == FDS_ERR_NO_SPACE_IN_QUEUES)
            {
                // Retry.
            }
            else
            {
                APP_ERROR_CHECK(err_code);
            }
        } break;

        case PM_EVT_PEERS_DELETE_SUCCEEDED:
        {
            adv_scan_start();
        } break;

        case PM_EVT_LOCAL_DB_CACHE_APPLY_FAILED:
        {
            // The local database has likely changed, send service changed indications.
            pm_local_database_has_changed();
        } break;

        case PM_EVT_PEER_DATA_UPDATE_FAILED:
        {
            // Assert.
            APP_ERROR_CHECK(p_evt-&amp;gt;params.peer_data_update_failed.error);
        } break;

        case PM_EVT_PEER_DELETE_FAILED:
        {
            // Assert.
            APP_ERROR_CHECK(p_evt-&amp;gt;params.peer_delete_failed.error);
        } break;

        case PM_EVT_PEERS_DELETE_FAILED:
        {
            // Assert.
            APP_ERROR_CHECK(p_evt-&amp;gt;params.peers_delete_failed_evt.error);
        } break;

        case PM_EVT_ERROR_UNEXPECTED:
        {
            // Assert.
            APP_ERROR_CHECK(p_evt-&amp;gt;params.error_unexpected.error);
        } break;

        case PM_EVT_CONN_SEC_START:
        case PM_EVT_PEER_DATA_UPDATE_SUCCEEDED:
        case PM_EVT_PEER_DELETE_SUCCEEDED:
        case PM_EVT_LOCAL_DB_CACHE_APPLIED:
        case PM_EVT_SERVICE_CHANGED_IND_SENT:
        case PM_EVT_SERVICE_CHANGED_IND_CONFIRMED:
        default:
            break;
    }
}



/**@brief Function for handling characters received by the Nordic UART Service.
 *
 * @details This function takes a list of characters of length data_len and prints the characters out on UART.
 *          If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
 */
static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len)
{
    ret_code_t ret_val;

    NRF_LOG_DEBUG(&amp;quot;Receiving data.&amp;quot;);
    NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);

    for (uint32_t i = 0; i &amp;lt; data_len; i++)
    {
        do
        {
            ret_val = app_uart_put(p_data[i]);
            if ((ret_val != NRF_SUCCESS) &amp;amp;&amp;amp; (ret_val != NRF_ERROR_BUSY))
            {
                NRF_LOG_ERROR(&amp;quot;app_uart_put failed for index 0x%04x.&amp;quot;, i);
                APP_ERROR_CHECK(ret_val);
            }
        } while (ret_val == NRF_ERROR_BUSY);
    }
    if (p_data[data_len-1] == &amp;#39;\r&amp;#39;)
    {
        while (app_uart_put(&amp;#39;\n&amp;#39;) == NRF_ERROR_BUSY);
    }
    if (ECHOBACK_BLE_UART_DATA)
    {
        // Send data back to peripheral.
        do
        {
            ret_val = ble_nus_c_string_send(&amp;amp;m_ble_nus_c, p_data, data_len);
            if ((ret_val != NRF_SUCCESS) &amp;amp;&amp;amp; (ret_val != NRF_ERROR_BUSY))
            {
                NRF_LOG_ERROR(&amp;quot;Failed sending NUS message. Error 0x%x. &amp;quot;, ret_val);
                APP_ERROR_CHECK(ret_val);
            }
        } while (ret_val == NRF_ERROR_BUSY);
    }
}


/**@brief   Function for handling app_uart events.
 *
 * @details This function will receive a single character from the app_uart module and append it to
 *          a string. The string will be be sent over BLE when the last character received was a
 *          &amp;#39;new line&amp;#39; &amp;#39;\n&amp;#39; (hex 0x0A) or if the string has reached the maximum data length.
 */
/**@snippet [Handling the data received over UART] */
void uart_event_handle(app_uart_evt_t * p_event)
{
    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
    static uint8_t index = 0;
    uint32_t       err_code;

    switch (p_event-&amp;gt;evt_type)
    {
        case APP_UART_DATA_READY:
            UNUSED_VARIABLE(app_uart_get(&amp;amp;data_array[index]));
            index++;

            if ((data_array[index - 1] == &amp;#39;\n&amp;#39;) || (index &amp;gt;= (m_ble_nus_max_data_len)))
            {
                NRF_LOG_DEBUG(&amp;quot;Ready to send data over BLE NUS&amp;quot;);
                NRF_LOG_HEXDUMP_DEBUG(data_array, index);

                do
                {
                    uint16_t length = (uint16_t)index;
                    err_code = ble_nus_string_send(&amp;amp;m_nus, data_array, &amp;amp;length);
                    if ( (err_code != NRF_ERROR_INVALID_STATE) &amp;amp;&amp;amp; (err_code != NRF_ERROR_BUSY) )
                    {
                        APP_ERROR_CHECK(err_code);
                    }
                } while (err_code == NRF_ERROR_BUSY);

                index = 0;
            }
            break;

        case APP_UART_COMMUNICATION_ERROR:
            APP_ERROR_HANDLER(p_event-&amp;gt;data.error_communication);
            break;

        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event-&amp;gt;data.error_code);
            break;

        default:
            break;
    }
}
/**@snippet [Handling the data received over UART] */



/**@brief Callback handling NUS Client events.
 *
 * @details This function is called to notify the application of NUS client events.
 *
 * @param[in]   p_ble_nus_c   NUS Client Handle. This identifies the NUS client
 * @param[in]   p_ble_nus_evt Pointer to the NUS Client event.
 */

/**@snippet [Handling events from the ble_nus_c module] */
static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
{
    uint32_t err_code;
	
    switch (p_ble_nus_evt-&amp;gt;evt_type)
    {
        case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:
            printf(&amp;quot;Discovery complete.\r\n&amp;quot;);
            err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt-&amp;gt;conn_handle, &amp;amp;p_ble_nus_evt-&amp;gt;handles);
            APP_ERROR_CHECK(err_code);

            err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
            APP_ERROR_CHECK(err_code);
            printf(&amp;quot;Connected to device with Nordic UART Service.\r\n&amp;quot;);
            break;

        case BLE_NUS_C_EVT_NUS_TX_EVT:
            ble_nus_chars_received_uart_print(p_ble_nus_evt-&amp;gt;p_data, p_ble_nus_evt-&amp;gt;data_len);
            break;

        case BLE_NUS_C_EVT_DISCONNECTED:
            printf(&amp;quot;Disconnected.\r\n&amp;quot;);
            scan_start();
            break;

			}
    
}
/**@snippet [Handling events from the ble_nus_c module] */



///**@brief Function for searching a UUID in the advertisement packets.
// *

/**@brief Reads an advertising report and checks if a UUID is present in the service list.
 *
 * @details The function is able to search for 16-bit, 32-bit and 128-bit service UUIDs.
 *          To see the format of a advertisement packet, see
 *          https://www.bluetooth.org/Technical/AssignedNumbers/generic_access_profile.htm
 *
 * @param[in]   p_target_uuid The UUID to search for.
 * @param[in]   p_adv_report  Pointer to the advertisement report.
 *
 * @retval      true if the UUID is present in the advertisement report. Otherwise false
 */
static bool is_uuid_present(ble_uuid_t               const * p_target_uuid,
                            ble_gap_evt_adv_report_t const * p_adv_report)
{
    ret_code_t   err_code;
    ble_uuid_t   extracted_uuid;
    uint16_t     index  = 0;
    uint8_t    * p_data = (uint8_t *)p_adv_report-&amp;gt;data;

    while (index &amp;lt; p_adv_report-&amp;gt;dlen)
    {
        uint8_t field_length = p_data[index];
        uint8_t field_type   = p_data[index + 1];

        if (   (field_type == BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE)
            || (field_type == BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE))
        {
            for (uint32_t i = 0; i &amp;lt; (field_length / UUID16_SIZE); i++)
            {
                err_code = sd_ble_uuid_decode(UUID16_SIZE,
                                              &amp;amp;p_data[i * UUID16_SIZE + index + 2],
                                              &amp;amp;extracted_uuid);

                if (err_code == NRF_SUCCESS)
                {
                    if (extracted_uuid.uuid == p_target_uuid-&amp;gt;uuid)
                    {
                        return true;
                    }
                }
            }
        }
        else if (   (field_type == BLE_GAP_AD_TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE)
                 || (field_type == BLE_GAP_AD_TYPE_32BIT_SERVICE_UUID_COMPLETE))
        {
            for (uint32_t i = 0; i &amp;lt; (field_length / UUID32_SIZE); i++)
            {
                err_code = sd_ble_uuid_decode(UUID32_SIZE,
                                              &amp;amp;p_data[i * UUID32_SIZE + index + 2],
                                              &amp;amp;extracted_uuid);

                if (err_code == NRF_SUCCESS)
                {
                    if (   (extracted_uuid.uuid == p_target_uuid-&amp;gt;uuid)
                        &amp;amp;&amp;amp; (extracted_uuid.type == p_target_uuid-&amp;gt;type))
                    {
                        return true;
                    }
                }
            }
        }

        else if (   (field_type == BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE)
                 || (field_type == BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE))
        {
            err_code = sd_ble_uuid_decode(UUID128_SIZE, &amp;amp;p_data[index + 2], &amp;amp;extracted_uuid);
            if (err_code == NRF_SUCCESS)
            {
                if (   (extracted_uuid.uuid == p_target_uuid-&amp;gt;uuid)
                    &amp;amp;&amp;amp; (extracted_uuid.type == p_target_uuid-&amp;gt;type))
                {
                    return true;
                }
            }
        }
        index += field_length + 1;
    }
    return false;
}


/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void  on_ble_central_evt(ble_evt_t const * p_ble_evt)
{
    ret_code_t            err_code;
    ble_gap_evt_t const * p_gap_evt = &amp;amp;p_ble_evt-&amp;gt;evt.gap_evt;

    switch (p_ble_evt-&amp;gt;header.evt_id)
    {
        case BLE_GAP_EVT_ADV_REPORT:
        {
            ble_gap_evt_adv_report_t const * p_adv_report = &amp;amp;p_gap_evt-&amp;gt;params.adv_report;

            if (is_uuid_present(&amp;amp;m_nus_uuid, p_adv_report))
            {

                err_code = sd_ble_gap_connect(&amp;amp;p_adv_report-&amp;gt;peer_addr,
                                              &amp;amp;m_scan_params,
                                              &amp;amp;m_connection_param,
                                              APP_BLE_CONN_CFG_TAG);

                if (err_code == NRF_SUCCESS)
                {
                    // scan is automatically stopped by the connect
                    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
                    APP_ERROR_CHECK(err_code);
                    NRF_LOG_INFO(&amp;quot;Connecting to target %02x%02x%02x%02x%02x%02x&amp;quot;,
                             p_adv_report-&amp;gt;peer_addr.addr[0],
                             p_adv_report-&amp;gt;peer_addr.addr[1],
                             p_adv_report-&amp;gt;peer_addr.addr[2],
                             p_adv_report-&amp;gt;peer_addr.addr[3],
                             p_adv_report-&amp;gt;peer_addr.addr[4],
                             p_adv_report-&amp;gt;peer_addr.addr[5]
                             );
                }
            }
        }break; // BLE_GAP_EVT_ADV_REPORT

        case BLE_GAP_EVT_CONNECTED:
            printf(&amp;quot;Connected to target\r\n&amp;quot;);
            err_code = ble_nus_c_handles_assign(&amp;amp;m_ble_nus_c, p_ble_evt-&amp;gt;evt.gap_evt.conn_handle, NULL);
            APP_ERROR_CHECK(err_code);

            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
            APP_ERROR_CHECK(err_code); 
            // start discovery of services. The NUS Client waits for a discovery result
            err_code = ble_db_discovery_start(&amp;amp;m_db_discovery, p_ble_evt-&amp;gt;evt.gap_evt.conn_handle);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GAP_EVT_TIMEOUT:
            if (p_gap_evt-&amp;gt;params.timeout.src == BLE_GAP_TIMEOUT_SRC_SCAN)
            {
                printf(&amp;quot;Scan timed out.\r\n&amp;quot;);
                scan_start();
            }
            else if (p_gap_evt-&amp;gt;params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
            {
                printf(&amp;quot;Connection Request timed out.\r\n&amp;quot;);
            }
            break;

        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
            // Pairing not supported
            err_code = sd_ble_gap_sec_params_reply(p_ble_evt-&amp;gt;evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
            // Accepting parameters requested by peer.
            err_code = sd_ble_gap_conn_param_update(p_gap_evt-&amp;gt;conn_handle,
                                                    &amp;amp;p_gap_evt-&amp;gt;params.conn_param_update_request.conn_params);
            APP_ERROR_CHECK(err_code);
            break;

#if defined(S132)
        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG(&amp;quot;PHY update request.&amp;quot;);
            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-&amp;gt;evt.gap_evt.conn_handle, &amp;amp;phys);
            APP_ERROR_CHECK(err_code);
        } break;
#endif

        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
          printf(&amp;quot;GATT Client Timeout.\r\n&amp;quot;);
            err_code = sd_ble_gap_disconnect(p_ble_evt-&amp;gt;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.
            printf(&amp;quot;GATT Server Timeout.\r\n&amp;quot;);
            err_code = sd_ble_gap_disconnect(p_ble_evt-&amp;gt;evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break;

        default:
            break;
    }
}




/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void on_ble_peripheral_evt(ble_evt_t const * p_ble_evt)
{
    uint32_t err_code;

    switch (p_ble_evt-&amp;gt;header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            printf(&amp;quot;peripheral Connected\r\n&amp;quot;);
            bsp_board_led_off(PERIPHERAL_ADVERTISING_LED);
            bsp_board_led_on(PERIPHERAL_CONNECTED_LED);
            m_conn_handle = p_ble_evt-&amp;gt;evt.gap_evt.conn_handle;
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            printf(&amp;quot;peripheral Disconnected\r\n&amp;quot;);
             bsp_board_led_off(PERIPHERAL_CONNECTED_LED);
				    bsp_board_led_on(PERIPHERAL_ADVERTISING_LED);
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;

#if defined(S132)
        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG(&amp;quot;PHY update request.&amp;quot;);
            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-&amp;gt;evt.gap_evt.conn_handle, &amp;amp;phys);
            APP_ERROR_CHECK(err_code);
        } break;
#endif

        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
            // Pairing not supported
            err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
            APP_ERROR_CHECK(err_code);
            break;

         case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
        {
            ble_gap_data_length_params_t dl_params;

            // Clearing the struct will effectivly set members to @ref BLE_GAP_DATA_LENGTH_AUTO
            memset(&amp;amp;dl_params, 0, sizeof(ble_gap_data_length_params_t));
            err_code = sd_ble_gap_data_length_update(p_ble_evt-&amp;gt;evt.gap_evt.conn_handle, &amp;amp;dl_params, NULL);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
            // No system attributes have been stored.
            err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
            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-&amp;gt;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-&amp;gt;evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_EVT_USER_MEM_REQUEST:
            err_code = sd_ble_user_mem_reply(p_ble_evt-&amp;gt;evt.gattc_evt.conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
        {
            ble_gatts_evt_rw_authorize_request_t  req;
            ble_gatts_rw_authorize_reply_params_t auth_reply;

            req = p_ble_evt-&amp;gt;evt.gatts_evt.params.authorize_request;

            if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
            {
                if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ)     ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
                {
                    if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
                    }
                    else
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
                    }
                    auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
                    err_code = sd_ble_gatts_rw_authorize_reply(p_ble_evt-&amp;gt;evt.gatts_evt.conn_handle,
                                                               &amp;amp;auth_reply);
                    APP_ERROR_CHECK(err_code);
                }
            }
        } break; // BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST

        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:
        {
            printf(&amp;quot;Fast advertising.\r\n&amp;quot;);
            bsp_board_led_on(PERIPHERAL_ADVERTISING_LED);
        } break;

        case BLE_ADV_EVT_IDLE:
        {
            ret_code_t err_code = ble_advertising_start(&amp;amp;m_advertising, BLE_ADV_MODE_FAST);
            APP_ERROR_CHECK(err_code);
        } break;

        default:
            // No implementation needed.
            break;
    }
}

/**@brief Function for checking if 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-&amp;gt;header.evt_id == BLE_GAP_EVT_TIMEOUT)
          &amp;amp;&amp;amp; (p_ble_evt-&amp;gt;evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_ADVERTISING));
}


static void db_discovery_retry(void)
{
    m_retry_db_disc = false;
    NRF_LOG_INFO(&amp;quot;Retrying DB discovery on handle 0x%x.&amp;quot;, m_conn_handle_to_disc);
    memset(&amp;amp;m_db_discovery, 0x00, sizeof(m_db_discovery));
    ret_code_t err_code = ble_db_discovery_start(&amp;amp;m_db_discovery, m_conn_handle_to_disc);
    APP_ERROR_CHECK(err_code);
}


/**@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-&amp;gt;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);
        ble_nus_on_ble_evt ( p_ble_evt,&amp;amp;m_nus);
 
    }
    else if ((role == BLE_GAP_ROLE_CENTRAL) || (p_ble_evt-&amp;gt;header.evt_id == BLE_GAP_EVT_ADV_REPORT))
    {
     
		  	on_ble_central_evt(p_ble_evt);
        ble_nus_c_on_ble_evt(p_ble_evt,&amp;amp;m_ble_nus_c );
			  
	}
}

/**@brief Function for initializing the NUS Client. */
static void nus_c_init(void)
{
    ret_code_t       err_code;
    ble_nus_c_init_t init;

    init.evt_handler = ble_nus_c_evt_handler;

    err_code = ble_nus_c_init(&amp;amp;m_ble_nus_c, &amp;amp;init);
	printf(&amp;quot;\r\n error code=%d&amp;quot;,err_code);
	
    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, &amp;amp;ram_start);
	   
    APP_ERROR_CHECK(err_code);

    // Enable BLE stack.
    err_code = nrf_sdh_ble_enable(&amp;amp;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 the Peer Manager initialization.
 */
static void peer_manager_init(void)
{
    ble_gap_sec_params_t sec_param;
    ret_code_t err_code;

    err_code = pm_init();
    APP_ERROR_CHECK(err_code);

    memset(&amp;amp;sec_param, 0, sizeof(ble_gap_sec_params_t));

    // Security parameters to be used for all security procedures.
    sec_param.bond           = SEC_PARAM_BOND;
    sec_param.mitm           = SEC_PARAM_MITM;
    sec_param.lesc           = SEC_PARAM_LESC;
    sec_param.keypress       = SEC_PARAM_KEYPRESS;
    sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
    sec_param.oob            = SEC_PARAM_OOB;
    sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
    sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
    sec_param.kdist_own.enc  = 1;
    sec_param.kdist_own.id   = 1;
    sec_param.kdist_peer.enc = 1;
    sec_param.kdist_peer.id  = 1;

    err_code = pm_sec_params_set(&amp;amp;sec_param);
    APP_ERROR_CHECK(err_code);

    err_code = pm_register(pm_evt_handler);
    APP_ERROR_CHECK(err_code);
}


/**@brief Clear bond information from persistent storage.
 */
static void delete_bonds(void)
{
    ret_code_t err_code;

    NRF_LOG_INFO(&amp;quot;Erase bonds!&amp;quot;);

    err_code = pm_peers_delete();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing buttons and leds.
 *
 * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to
 *                            wake the application up.
 */
static void buttons_leds_init(bool * p_erase_bonds)
{
    ret_code_t err_code;
    bsp_event_t startup_event;

    err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS, NULL);
	  
    APP_ERROR_CHECK(err_code);

    err_code = bsp_btn_ble_init(NULL, &amp;amp;startup_event);
    APP_ERROR_CHECK(err_code);

    *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
}


/**@brief Function for the GAP initialization.
 *
 * @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(&amp;amp;sec_mode);

    err_code = sd_ble_gap_device_name_set(&amp;amp;sec_mode,
                                          (const uint8_t *)DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);

    memset(&amp;amp;gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONNECTION_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONNECTION_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = SUPERVISION_TIMEOUT;

    err_code = sd_ble_gap_ppcp_set(&amp;amp;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(&amp;amp;m_gatt, NULL);
    APP_ERROR_CHECK(err_code);
}




///**@brief   Function for handling app_uart events.
// *
// * @details This function will receive a single character from the app_uart module and append it to
// *          a string. The string will be be sent over BLE when the last character received was a
// *          &amp;#39;new line&amp;#39; i.e &amp;#39;\r\n&amp;#39; (hex 0x0D) or if the string has reached a length of
// *          @ref NUS_MAX_DATA_LENGTH.
// */
///**@snippet [Handling the data received over UART] */
//void uart_event_handle(app_uart_evt_t * p_event)
//{
//	 
//	 // printf(&amp;quot;entered uart eventhandler\r\n&amp;quot;);
//    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
//    static uint8_t index = 0;
//    uint32_t       err_code;

//    switch (p_event-&amp;gt;evt_type)
//    {
//        case APP_UART_DATA_READY:
//            UNUSED_VARIABLE(app_uart_get(&amp;amp;data_array[index]));
//				    cmd[index]=data_array[index];
//            index++;

//            if ((data_array[index - 1] == &amp;#39;\n&amp;#39;) || (index &amp;gt;= (BLE_NUS_MAX_DATA_LEN)))
//            {
//							
//							  if((strncmp((char*)data_array,&amp;quot;bothon&amp;quot;,6)==0))
//								 {
//									   //bothon();
//									 //printf(&amp;quot;\r\n entered in adv_sc&amp;quot;);
//									   nrf_delay_ms(10);
//								 }
//								 
//								 
//							  else if((strncmp((char*)data_array,&amp;quot;bothoff&amp;quot;,7)==0))
//								 {
//		                     both_off();
//								 }
//								 
//								 if((strncmp((char *)data_array,&amp;quot;centralon&amp;quot;,9)==0))
//								 {
//									 
////									 nrf_delay_ms(10);
//									   adv_scan_start();
//									 
//								 }
//								 
//								 else if((strncmp((char *)data_array,&amp;quot;advon&amp;quot;,5)==0))
//								 {
//									 printf(&amp;quot;\r\n peripheral=%s&amp;quot;,data_array);
//									 nrf_delay_ms(10);
//									 adv_on();
//								 }
////                err_code = ble_nus_string_send(&amp;amp;m_nus, data_array, index);
////							  err_code=ble_nus_c_string_send(&amp;amp;m_ble_nus_c,data_array,index);//added for central
////                if (err_code != NRF_ERROR_INVALID_STATE)
////                {
////                    APP_ERROR_CHECK(err_code);
////                }
//              
//								   memset(&amp;amp;cmd, 0, sizeof(0));
////								  printf(&amp;quot;\r\n command1=%s&amp;quot;,cmd);
//                  index = 0;
//            }
//            break;

//        case APP_UART_COMMUNICATION_ERROR:
//            APP_ERROR_HANDLER(p_event-&amp;gt;data.error_communication);
//            break;

//        case APP_UART_FIFO_ERROR:
//            APP_ERROR_HANDLER(p_event-&amp;gt;data.error_code);
//            break;

//        default:
//            break;
//    }
//}
///**@snippet [Handling the data received over UART] */





/**@brief  Function for initializing the UART module.
 */
/**@snippet [UART Initialization] */
static void uart_init(void)
{
    uint32_t err_code;
    const app_uart_comm_params_t comm_params =
    {
        .rx_pin_no    = RX_PIN_NUMBER,
        .tx_pin_no    = TX_PIN_NUMBER,
        .rts_pin_no   = RTS_PIN_NUMBER,
        .cts_pin_no   = CTS_PIN_NUMBER,
        .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
        .use_parity   = false,
        .baud_rate    = UART_BAUDRATE_BAUDRATE_Baud115200
    };

    APP_UART_FIFO_INIT( &amp;amp;comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_event_handle,
                       APP_IRQ_PRIORITY_LOWEST,
                       err_code);
APP_ERROR_CHECK(err_code);
}
/**@snippet [UART Initialization] */


/**@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(&amp;amp;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(&amp;amp;cp_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling database discovery events.
 *
 * @details This function is callback function to handle events from the database discovery module.
 *          Depending on the UUIDs that are discovered, this function should forward 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_nus_c_on_db_disc_evt(&amp;amp;m_ble_nus_c, p_evt);
	
    if (   (p_evt-&amp;gt;evt_type == BLE_DB_DISCOVERY_COMPLETE)
        &amp;amp;&amp;amp; (m_retry_db_disc)
        &amp;amp;&amp;amp; (m_conn_handle_to_disc != BLE_CONN_HANDLE_INVALID))
    {
        // DB discovery cannot be restarted directly here because the
        // database discovery structure would need to be zeroed, however it is still
        // needed by the module (it might have pending events to send).
        // Let&amp;#39;s set a flag and re-run DB discovery when we receive the next BLE event.

        NRF_LOG_INFO(&amp;quot;DB discovery can be retried.&amp;quot;);
        m_do_retry_db_disc = true;
    }
}


/**
 * @brief Database discovery initialization.
 */
static void db_discovery_init(void)
{
    ret_code_t err_code = ble_db_discovery_init(db_disc_handler);
    APP_ERROR_CHECK(err_code);
}
/**@brief Function for handling the data from the Nordic UART Service.
 *
 * @details This function will process the data received from the Nordic UART BLE Service and send
 *          it to the UART module.
 *
 * @param[in] p_nus    Nordic UART Service structure.
 * @param[in] p_data   Data to be send to UART module.
 * @param[in] length   Length of the data.
 */
/**@snippet [Handling the data received over BLE] */
static void nus_data_handler(ble_nus_evt_t * p_evt)
{

    if (p_evt-&amp;gt;type == BLE_NUS_EVT_RX_DATA)
    {
        uint32_t err_code;

        NRF_LOG_DEBUG(&amp;quot;Received data from BLE NUS. Writing data on UART.&amp;quot;);
        NRF_LOG_HEXDUMP_DEBUG(p_evt-&amp;gt;params.rx_data.p_data, p_evt-&amp;gt;params.rx_data.length);

        for (uint32_t i = 0; i &amp;lt; p_evt-&amp;gt;params.rx_data.length; i++)
        {
            do
            {
                err_code = app_uart_put(p_evt-&amp;gt;params.rx_data.p_data[i]);
                if ((err_code != NRF_SUCCESS) &amp;amp;&amp;amp; (err_code != NRF_ERROR_BUSY))
                {
                    NRF_LOG_ERROR(&amp;quot;Failed receiving NUS message. Error 0x%x. &amp;quot;, err_code);
                    APP_ERROR_CHECK(err_code);
                }
            } while (err_code == NRF_ERROR_BUSY);
        }
        if (p_evt-&amp;gt;params.rx_data.p_data[p_evt-&amp;gt;params.rx_data.length-1] == &amp;#39;\r&amp;#39;)
        {
            while (app_uart_put(&amp;#39;\n&amp;#39;) == NRF_ERROR_BUSY);
        }
    }

}
/**@snippet [Handling the data received over BLE] */

/**@brief Function for initializing services that will be used by the application.
 *
 * @details Initialize the Heart Rate, Battery and Device Information services.
 */
static void services_init(void)
{
   uint32_t       err_code;
    ble_nus_init_t nus_init;

    memset(&amp;amp;nus_init, 0, sizeof(nus_init));

    nus_init.data_handler = nus_data_handler;

    err_code = ble_nus_init(&amp;amp;m_nus, &amp;amp;nus_init);
    APP_ERROR_CHECK(err_code);
}



/**@brief Function for initializing the Advertising functionality.
 */
static void advertising_init(void)
{
    ret_code_t             err_code;
    ble_advertising_init_t init;

    memset(&amp;amp;init, 0, sizeof(init));

    init.advdata.name_type               = BLE_ADVDATA_FULL_NAME;
    init.advdata.include_appearance      = true;
    init.advdata.flags                   = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
    init.advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
    init.advdata.uuids_complete.p_uuids  = m_adv_uuids;

    init.config.ble_adv_fast_enabled  = true;
    init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
    init.config.ble_adv_fast_timeout  = APP_ADV_TIMEOUT_IN_SECONDS;

    init.evt_handler = on_adv_evt;

    err_code = ble_advertising_init(&amp;amp;m_advertising, &amp;amp;init);
    APP_ERROR_CHECK(err_code);

    ble_advertising_conn_cfg_tag_set(&amp;amp;m_advertising, APP_BLE_CONN_CFG_TAG);
}


/**@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 the timer.
 */
static void timer_init(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
}


/** @brief Function to sleep until a BLE event is received by the application.
 */
static void power_manage(void)
{
    ret_code_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}


int main(void)
{
    bool erase_bonds;
     
    //log_init();
	 
    timer_init();
	  uart_init();
	 
		
	  buttons_leds_init(&amp;amp;erase_bonds);
//	  printf(&amp;quot;\r\n after leds init&amp;quot;);
//	  nrf_delay_ms(100);
    ble_stack_init();
//	  printf(&amp;quot;\r\n after stack init&amp;quot;);
//	  nrf_delay_ms(100);
    gap_params_init();
//	  printf(&amp;quot;\r\n after gap_par init&amp;quot;);
//	  nrf_delay_ms(100);
    gatt_init();
//	  printf(&amp;quot;\r\n after gatt init&amp;quot;);
//	  nrf_delay_ms(100);
    conn_params_init();
//		printf(&amp;quot;\r\n after conn_par init&amp;quot;);
//	  nrf_delay_ms(100);
    db_discovery_init();
//		printf(&amp;quot;\r\n after db_disc init&amp;quot;);
//	  nrf_delay_ms(100);
    peer_manager_init();
//		printf(&amp;quot;\r\n after peer_mng init&amp;quot;);
//	  nrf_delay_ms(100);
    nus_c_init();
//		printf(&amp;quot;\r\n after nus_c init&amp;quot;);
//	  nrf_delay_ms(100);
   // rscs_c_init();
    services_init();
//		printf(&amp;quot;\r\n after services init&amp;quot;);
//	  nrf_delay_ms(100);
    advertising_init();
//		printf(&amp;quot;\r\n after advertising init&amp;quot;);
//	  nrf_delay_ms(100);

    if (erase_bonds == true)
    {
        // Scanning and advertising is done upon PM_EVT_PEERS_DELETE_SUCCEEDED event.
        delete_bonds();
        // Scanning and advertising is done by
    }
    else
    {
        adv_scan_start();
    }

    printf(&amp;quot;Relay example started.&amp;quot;);

    for (;;)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            // Wait for BLE events.
            power_manage();
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;The above is my main code.&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Could you please help me in solve this issue?&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Thanks in advance.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Getting error code =4 in ble_stack_init.</title><link>https://devzone.nordicsemi.com/thread/181009?ContentTypeID=1</link><pubDate>Tue, 09 Apr 2019 11:19:49 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:fb04aa57-6099-481a-917f-b8a91e58bfea</guid><dc:creator>J&amp;#248;rgen Holmefjord</dc:creator><description>&lt;p&gt;Hi,&lt;/p&gt;
&lt;p&gt;Error code 0x04 means&amp;nbsp;&lt;a href="https://www.nordicsemi.com/DocLib/Content/SoftDevice_API_Doc/S132/v6-1-0/group__nrf__error#ga7ef4d466b79b31c6325f8b7af5d4f75f"&gt;NRF_ERROR_NO_MEM&lt;/a&gt;, and is returned from call to&amp;nbsp;&lt;a href="https://www.nordicsemi.com/DocLib/Content/SoftDevice_API_Doc/S132/v6-1-0/group_ble_common_functions#ga8a92420df90945526d4c89d09486508d"&gt;sd_ble_enable&lt;/a&gt;() in&amp;nbsp;nrf_sdh_ble_enable(). The API documentation for the function suggest the following problem:&lt;/p&gt;
&lt;p&gt;&lt;span&gt;One or more of the following is true:&lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The amount of memory assigned to the SoftDevice by *p_app_ram_base is not large enough to fit this configuration&amp;#39;s memory requirement. Check *p_app_ram_base and set the start address of the application RAM region accordingly.&lt;/li&gt;
&lt;li&gt;Dynamic part of the SoftDevice RAM region is larger then 64 kB which is currently not supported.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You should try to modify the RAM configuration for your application, please see &lt;a href="https://devzone.nordicsemi.com/tutorials/b/getting-started/posts/adjustment-of-ram-and-flash-memory"&gt;this tutorial&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Best regards,&lt;br /&gt;Jørgen&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item></channel></rss>