<?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>Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/f/nordic-q-a/69203/setting-a-watchpoint-dynamically</link><description>Hello, 
 I am trying to spot a bug in which some memory corruption is happening. I don&amp;#39;t know in advance at which address the corruption will happen, as it happens in some circular buffer. Maybe something is wrongly reading an address referring to this</description><dc:language>en-US</dc:language><generator>Telligent Community 13</generator><lastBuildDate>Mon, 11 Jan 2021 12:47:58 GMT</lastBuildDate><atom:link rel="self" type="application/rss+xml" href="https://devzone.nordicsemi.com/f/nordic-q-a/69203/setting-a-watchpoint-dynamically" /><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/288377?ContentTypeID=1</link><pubDate>Mon, 11 Jan 2021 12:47:58 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:57d3c994-df45-4e89-9fe4-c797eeb2a896</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;Dear &lt;a href="https://devzone.nordicsemi.com/members/vibe"&gt;Vidar Berg&lt;/a&gt;,&lt;/p&gt;
&lt;p&gt;I did a&amp;nbsp;test as you recommended, with flashing a LED on a regular basis.&lt;/p&gt;
&lt;p&gt;And at some point&amp;nbsp;the program writes to the address watched out by DWT (like &lt;code&gt;*(uint32_t*)STACK_LIMIT&lt;/code&gt; in your example).&lt;/p&gt;
&lt;p&gt;So, I launched&amp;nbsp;the RTTlogger only after seeing the LED flash stopping, and it worked as expected, I got the log trace done by &lt;code&gt;DebugMon_Handler&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;What is more interesting : I exited the RTTlogger, and then connected gdb, and it also worked, I could see the stack frame with&amp;nbsp;DebugMon_Handler on the top of it.&lt;/p&gt;
&lt;p&gt;So, OK,&amp;nbsp;good to know that with the RTTlogger, your method works fine provided that some caution is taken not to connect the Jlink before the break occurs.&lt;/p&gt;
&lt;p&gt;So one needs some other signal (like a LED or some GPO to a scope) that lets you know that you are still running and the break is not yet reached.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/288330?ContentTypeID=1</link><pubDate>Mon, 11 Jan 2021 10:08:18 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:4af9b4a3-40c2-45d9-bab5-f43a003c78c5</guid><dc:creator>Vidar Berg</dc:creator><description>&lt;p&gt;I think the problem is that the JLinkRTTLogger makes the J-link connect to the 52840 and override/reset&amp;nbsp; the DWT registers settings set by your FW. Can you try to connect the&amp;nbsp; JlinkRTTViewer/client after the interrupt has been triggered?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/288143?ContentTypeID=1</link><pubDate>Fri, 08 Jan 2021 11:14:01 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:60e9b5b8-d066-4260-bbe6-a176bc08a195</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;Hello&amp;nbsp;&lt;a href="https://devzone.nordicsemi.com/members/vibe"&gt;Vidar Berg&lt;/a&gt;,&lt;/p&gt;
&lt;p&gt;Thank you for providing this code. I modified it too, in order to have some compile flags at the top of the &lt;code&gt;main.c&lt;/code&gt; file and experiment a few variants as explained below.&lt;/p&gt;
&lt;p&gt;Here is the modified&amp;nbsp;&lt;code&gt;ble_app_hrs_freertos&lt;/code&gt; &lt;code&gt;main.c&lt;/code&gt; file:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;/**
 * Copyright (c) 2014 - 2020, 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.
 *
 */
// Board/nrf6310/ble/ble_app_hrs_rtx/main.c
/**
 *
 * @brief Heart Rate Service Sample Application with RTX main file.
 *
 * This file contains the source code for a sample application using RTX and the
 * Heart Rate service (and also Battery and Device Information services).
 * This application uses the @ref srvlib_conn_params module.
 */

#define DWT_GUARD_ENABLED 0
#define NRF_LOG_BACKEND_RTT_ENABLED  0
#define NRF_LOG_BACKEND_UART_ENABLED (!NRF_LOG_BACKEND_RTT_ENABLED)

#include &amp;lt;stdint.h&amp;gt;
#include &amp;lt;string.h&amp;gt;
#include &amp;quot;nordic_common.h&amp;quot;
#include &amp;quot;nrf.h&amp;quot;
#include &amp;quot;app_error.h&amp;quot;
#include &amp;quot;ble.h&amp;quot;
#include &amp;quot;ble_hci.h&amp;quot;
#include &amp;quot;ble_srv_common.h&amp;quot;
#include &amp;quot;ble_advdata.h&amp;quot;
#include &amp;quot;ble_advertising.h&amp;quot;
#include &amp;quot;ble_bas.h&amp;quot;
#include &amp;quot;ble_hrs.h&amp;quot;
#include &amp;quot;ble_dis.h&amp;quot;
#include &amp;quot;ble_conn_params.h&amp;quot;
#include &amp;quot;sensorsim.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;nrf_sdh_freertos.h&amp;quot;
#include &amp;quot;app_timer.h&amp;quot;
#include &amp;quot;peer_manager.h&amp;quot;
#include &amp;quot;peer_manager_handler.h&amp;quot;
#include &amp;quot;bsp_btn_ble.h&amp;quot;
#include &amp;quot;FreeRTOS.h&amp;quot;
#include &amp;quot;task.h&amp;quot;
#include &amp;quot;timers.h&amp;quot;
#include &amp;quot;semphr.h&amp;quot;
#include &amp;quot;fds.h&amp;quot;
#include &amp;quot;ble_conn_state.h&amp;quot;
#include &amp;quot;nrf_drv_clock.h&amp;quot;
#include &amp;quot;nrf_ble_gatt.h&amp;quot;
#include &amp;quot;nrf_ble_qwr.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 DEVICE_NAME                         &amp;quot;Nordic_HRM&amp;quot;                            /**&amp;lt; Name of device. Will be included in the advertising data. */
#define MANUFACTURER_NAME                   &amp;quot;NordicSemiconductor&amp;quot;                   /**&amp;lt; Manufacturer. Will be passed to Device Information Service. */

#define APP_BLE_OBSERVER_PRIO               3                                       /**&amp;lt; Application&amp;#39;s BLE observer priority. You shouldn&amp;#39;t need to modify this value. */
#define APP_BLE_CONN_CFG_TAG                1                                       /**&amp;lt; A tag identifying the SoftDevice BLE configuration. */

#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_DURATION                    18000                                       /**&amp;lt; The advertising duration (180 seconds) in units of 10 milliseconds. */

#define BATTERY_LEVEL_MEAS_INTERVAL         2000                                    /**&amp;lt; Battery level measurement interval (ms). */
#define MIN_BATTERY_LEVEL                   81                                      /**&amp;lt; Minimum simulated battery level. */
#define MAX_BATTERY_LEVEL                   100                                     /**&amp;lt; Maximum simulated battery level. */
#define BATTERY_LEVEL_INCREMENT             1                                       /**&amp;lt; Increment between each simulated battery level measurement. */

#define HEART_RATE_MEAS_INTERVAL            1000                                    /**&amp;lt; Heart rate measurement interval (ms). */
#define MIN_HEART_RATE                      140                                     /**&amp;lt; Minimum heart rate as returned by the simulated measurement function. */
#define MAX_HEART_RATE                      300                                     /**&amp;lt; Maximum heart rate as returned by the simulated measurement function. */
#define HEART_RATE_INCREMENT                10                                      /**&amp;lt; Value by which the heart rate is incremented/decremented for each call to the simulated measurement function. */

#define RR_INTERVAL_INTERVAL                300                                     /**&amp;lt; RR interval interval (ms). */
#define MIN_RR_INTERVAL                     100                                     /**&amp;lt; Minimum RR interval as returned by the simulated measurement function. */
#define MAX_RR_INTERVAL                     500                                     /**&amp;lt; Maximum RR interval as returned by the simulated measurement function. */
#define RR_INTERVAL_INCREMENT               1                                       /**&amp;lt; Value by which the RR interval is incremented/decremented for each call to the simulated measurement function. */

#define SENSOR_CONTACT_DETECTED_INTERVAL    5000                                    /**&amp;lt; Sensor Contact Detected toggle interval (ms). */

#define MIN_CONN_INTERVAL                   MSEC_TO_UNITS(400, UNIT_1_25_MS)        /**&amp;lt; Minimum acceptable connection interval (0.4 seconds). */
#define MAX_CONN_INTERVAL                   MSEC_TO_UNITS(650, UNIT_1_25_MS)        /**&amp;lt; Maximum acceptable connection interval (0.65 second). */
#define SLAVE_LATENCY                       0                                       /**&amp;lt; Slave latency. */
#define CONN_SUP_TIMEOUT                    MSEC_TO_UNITS(4000, UNIT_10_MS)         /**&amp;lt; Connection supervisory time-out (4 seconds). */

#define FIRST_CONN_PARAMS_UPDATE_DELAY      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       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 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. */
#define SEC_PARAM_MAX_KEY_SIZE              16                                      /**&amp;lt; Maximum encryption key size. */

#define DEAD_BEEF                           0xDEADBEEF                              /**&amp;lt; Value used as error code on stack dump, can be used to identify stack location on stack unwind. */

#define OSTIMER_WAIT_FOR_QUEUE              2                                       /**&amp;lt; Number of ticks to wait for the timer queue to be ready */


BLE_BAS_DEF(m_bas);                                                 /**&amp;lt; Battery service instance. */
BLE_HRS_DEF(m_hrs);                                                 /**&amp;lt; Heart rate service instance. */
NRF_BLE_GATT_DEF(m_gatt);                                           /**&amp;lt; GATT module instance. */
NRF_BLE_QWR_DEF(m_qwr);                                             /**&amp;lt; Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising);                                 /**&amp;lt; Advertising module instance. */

static uint16_t m_conn_handle         = BLE_CONN_HANDLE_INVALID;    /**&amp;lt; Handle of the current connection. */
static bool     m_rr_interval_enabled = true;                       /**&amp;lt; Flag for enabling and disabling the registration of new RR interval measurements (the purpose of disabling this is just to test sending HRM without RR interval data. */

static sensorsim_cfg_t   m_battery_sim_cfg;                         /**&amp;lt; Battery Level sensor simulator configuration. */
static sensorsim_state_t m_battery_sim_state;                       /**&amp;lt; Battery Level sensor simulator state. */
static sensorsim_cfg_t   m_heart_rate_sim_cfg;                      /**&amp;lt; Heart Rate sensor simulator configuration. */
static sensorsim_state_t m_heart_rate_sim_state;                    /**&amp;lt; Heart Rate sensor simulator state. */
static sensorsim_cfg_t   m_rr_interval_sim_cfg;                     /**&amp;lt; RR Interval sensor simulator configuration. */
static sensorsim_state_t m_rr_interval_sim_state;                   /**&amp;lt; RR Interval sensor simulator state. */

static ble_uuid_t m_adv_uuids[] =                                   /**&amp;lt; Universally unique service identifiers. */
{
    {BLE_UUID_HEART_RATE_SERVICE, BLE_UUID_TYPE_BLE},
    {BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
    {BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
};

static TimerHandle_t m_battery_timer;                               /**&amp;lt; Definition of battery timer. */
static TimerHandle_t m_heart_rate_timer;                            /**&amp;lt; Definition of heart rate timer. */
static TimerHandle_t m_rr_interval_timer;                           /**&amp;lt; Definition of RR interval timer. */
static TimerHandle_t m_sensor_contact_timer;                        /**&amp;lt; Definition of sensor contact detected timer. */

#if NRF_LOG_ENABLED
static TaskHandle_t m_logger_thread;                                /**&amp;lt; Definition of Logger thread. */
#endif

#define STACK_LIMIT 0x2003e000

#if DWT_GUARD_ENABLED
void DebugMon_Handler(void)
{
    NRF_LOG_INFO(&amp;quot;Debug Monitor interrupt triggered&amp;quot;);
    NRF_LOG_INFO(&amp;quot;Current SP 0x%x&amp;quot;, __get_MSP());
    NRF_LOG_FINAL_FLUSH();
}
#endif

#if DWT_GUARD_ENABLED
static void dwt_stack_guard_init()
{
    uint32_t num;

    CoreDebug-&amp;gt;DEMCR |= CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk;

    NRF_LOG_INFO(&amp;quot;CoreDebug-&amp;gt;DEMCR : 0x%x&amp;quot;, CoreDebug-&amp;gt;DEMCR);

    num = (DWT-&amp;gt;CTRL &amp;amp; DWT_CTRL_NUMCOMP_Msk) &amp;gt;&amp;gt; DWT_CTRL_NUMCOMP_Pos;
    NRF_LOG_INFO(&amp;quot;Number of DWT comparators: %d&amp;quot;, num);

    NVIC_SetPriority(DebugMonitor_IRQn, 6);

    DWT-&amp;gt;COMP0 = STACK_LIMIT;
    DWT-&amp;gt;MASK0 = 4;
    DWT-&amp;gt;FUNCTION0 = (7 &amp;lt;&amp;lt; DWT_FUNCTION_FUNCTION_Pos);

    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;COMP0 : 0x%x&amp;quot;, DWT-&amp;gt;COMP0);
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;MASK0 : 0x%x&amp;quot;, DWT-&amp;gt;MASK0);
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;FUNCTION0 : 0x%x&amp;quot;, DWT-&amp;gt;FUNCTION0);

}
#endif

static void advertising_start(void * p_erase_bonds);


/**@brief Callback function for 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]   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(DEAD_BEEF, line_num, p_file_name);
}


/**@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)
{
    bool delete_bonds = false;

    pm_handler_on_pm_evt(p_evt);
    pm_handler_flash_clean(p_evt);

    switch (p_evt-&amp;gt;evt_id)
    {
        case PM_EVT_PEERS_DELETE_SUCCEEDED:
            advertising_start(&amp;amp;delete_bonds);
            break;

        default:
            break;
    }
}


/**@brief Function for performing battery measurement and updating the Battery Level characteristic
 *        in Battery Service.
 */
static void battery_level_update(void)
{
    ret_code_t err_code;
    uint8_t  battery_level;

    battery_level = (uint8_t)sensorsim_measure(&amp;amp;m_battery_sim_state, &amp;amp;m_battery_sim_cfg);

    err_code = ble_bas_battery_level_update(&amp;amp;m_bas, battery_level, BLE_CONN_HANDLE_ALL);
    if ((err_code != NRF_SUCCESS) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_INVALID_STATE) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_RESOURCES) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_BUSY) &amp;amp;&amp;amp;
        (err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING)
       )
    {
        APP_ERROR_HANDLER(err_code);
    }
}


/**@brief Function for handling the Battery measurement timer time-out.
 *
 * @details This function will be called each time the battery level measurement timer expires.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void battery_level_meas_timeout_handler(TimerHandle_t xTimer)
{
    UNUSED_PARAMETER(xTimer);
    battery_level_update();
#if DWT_GUARD_ENABLED
    *(uint32_t *) STACK_LIMIT = 1;
#endif
}


/**@brief Function for handling the Heart rate measurement timer time-out.
 *
 * @details This function will be called each time the heart rate measurement timer expires.
 *          It will exclude RR Interval data from every third measurement.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void heart_rate_meas_timeout_handler(TimerHandle_t xTimer)
{
    static uint32_t cnt = 0;
    ret_code_t      err_code;
    uint16_t        heart_rate;

    UNUSED_PARAMETER(xTimer);

    heart_rate = (uint16_t)sensorsim_measure(&amp;amp;m_heart_rate_sim_state, &amp;amp;m_heart_rate_sim_cfg);

    cnt++;
    err_code = ble_hrs_heart_rate_measurement_send(&amp;amp;m_hrs, heart_rate);
    if ((err_code != NRF_SUCCESS) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_INVALID_STATE) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_RESOURCES) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_BUSY) &amp;amp;&amp;amp;
        (err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING)
       )
    {
        APP_ERROR_HANDLER(err_code);
    }

    // Disable RR Interval recording every third heart rate measurement.
    // NOTE: An application will normally not do this. It is done here just for testing generation
    // of messages without RR Interval measurements.
    m_rr_interval_enabled = ((cnt % 3) != 0);
}


/**@brief Function for handling the RR interval timer time-out.
 *
 * @details This function will be called each time the RR interval timer expires.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void rr_interval_timeout_handler(TimerHandle_t xTimer)
{
    UNUSED_PARAMETER(xTimer);

    if (m_rr_interval_enabled)
    {
        uint16_t rr_interval;

        rr_interval = (uint16_t)sensorsim_measure(&amp;amp;m_rr_interval_sim_state,
                                                  &amp;amp;m_rr_interval_sim_cfg);
        ble_hrs_rr_interval_add(&amp;amp;m_hrs, rr_interval);
    }
}


/**@brief Function for handling the Sensor Contact Detected timer time-out.
 *
 * @details This function will be called each time the Sensor Contact Detected timer expires.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void sensor_contact_detected_timeout_handler(TimerHandle_t xTimer)
{
    static bool sensor_contact_detected = false;

    UNUSED_PARAMETER(xTimer);

    sensor_contact_detected = !sensor_contact_detected;
    ble_hrs_sensor_contact_detected_update(&amp;amp;m_hrs, sensor_contact_detected);
}


/**@brief Function for the Timer initialization.
 *
 * @details Initializes the timer module. This creates and starts application timers.
 */
static void timers_init(void)
{
    // Initialize timer module.
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);

    // Create timers.
    m_battery_timer = xTimerCreate(&amp;quot;BATT&amp;quot;,
                                   BATTERY_LEVEL_MEAS_INTERVAL,
                                   pdTRUE,
                                   NULL,
                                   battery_level_meas_timeout_handler);
    m_heart_rate_timer = xTimerCreate(&amp;quot;HRT&amp;quot;,
                                      HEART_RATE_MEAS_INTERVAL,
                                      pdTRUE,
                                      NULL,
                                      heart_rate_meas_timeout_handler);
    m_rr_interval_timer = xTimerCreate(&amp;quot;RRT&amp;quot;,
                                       RR_INTERVAL_INTERVAL,
                                       pdTRUE,
                                       NULL,
                                       rr_interval_timeout_handler);
    m_sensor_contact_timer = xTimerCreate(&amp;quot;SCT&amp;quot;,
                                          SENSOR_CONTACT_DETECTED_INTERVAL,
                                          pdTRUE,
                                          NULL,
                                          sensor_contact_detected_timeout_handler);

    /* Error checking */
    if ( (NULL == m_battery_timer)
         || (NULL == m_heart_rate_timer)
         || (NULL == m_rr_interval_timer)
         || (NULL == m_sensor_contact_timer) )
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
}


/**@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);

    err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_HEART_RATE_SENSOR_HEART_RATE_BELT);
    APP_ERROR_CHECK(err_code);

    memset(&amp;amp;gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_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 Queued Write Module errors.
 *
 * @details A pointer to this function will be passed to each service which may need to inform the
 *          application about an error.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


/**@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)
{
    ret_code_t         err_code;
    ble_hrs_init_t     hrs_init;
    ble_bas_init_t     bas_init;
    ble_dis_init_t     dis_init;
    nrf_ble_qwr_init_t qwr_init = {0};
    uint8_t            body_sensor_location;

    // Initialize Queued Write Module.
    qwr_init.error_handler = nrf_qwr_error_handler;

    err_code = nrf_ble_qwr_init(&amp;amp;m_qwr, &amp;amp;qwr_init);
    APP_ERROR_CHECK(err_code);

    // Initialize Heart Rate Service.
    body_sensor_location = BLE_HRS_BODY_SENSOR_LOCATION_FINGER;

    memset(&amp;amp;hrs_init, 0, sizeof(hrs_init));

    hrs_init.evt_handler                 = NULL;
    hrs_init.is_sensor_contact_supported = true;
    hrs_init.p_body_sensor_location      = &amp;amp;body_sensor_location;

    // Here the sec level for the Heart Rate Service can be changed/increased.
    hrs_init.hrm_cccd_wr_sec = SEC_OPEN;
    hrs_init.bsl_rd_sec      = SEC_OPEN;

    err_code = ble_hrs_init(&amp;amp;m_hrs, &amp;amp;hrs_init);
    APP_ERROR_CHECK(err_code);

    // Initialize Battery Service.
    memset(&amp;amp;bas_init, 0, sizeof(bas_init));

    // Here the sec level for the Battery Service can be changed/increased.
    bas_init.bl_rd_sec        = SEC_OPEN;
    bas_init.bl_cccd_wr_sec   = SEC_OPEN;
    bas_init.bl_report_rd_sec = SEC_OPEN;

    bas_init.evt_handler          = NULL;
    bas_init.support_notification = true;
    bas_init.p_report_ref         = NULL;
    bas_init.initial_batt_level   = 100;

    err_code = ble_bas_init(&amp;amp;m_bas, &amp;amp;bas_init);
    APP_ERROR_CHECK(err_code);

    // Initialize Device Information Service.
    memset(&amp;amp;dis_init, 0, sizeof(dis_init));

    ble_srv_ascii_to_utf8(&amp;amp;dis_init.manufact_name_str, (char *)MANUFACTURER_NAME);

    dis_init.dis_char_rd_sec = SEC_OPEN;

    err_code = ble_dis_init(&amp;amp;dis_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the sensor simulators. */
static void sensor_simulator_init(void)
{
    m_battery_sim_cfg.min          = MIN_BATTERY_LEVEL;
    m_battery_sim_cfg.max          = MAX_BATTERY_LEVEL;
    m_battery_sim_cfg.incr         = BATTERY_LEVEL_INCREMENT;
    m_battery_sim_cfg.start_at_max = true;

    sensorsim_init(&amp;amp;m_battery_sim_state, &amp;amp;m_battery_sim_cfg);

    m_heart_rate_sim_cfg.min          = MIN_HEART_RATE;
    m_heart_rate_sim_cfg.max          = MAX_HEART_RATE;
    m_heart_rate_sim_cfg.incr         = HEART_RATE_INCREMENT;
    m_heart_rate_sim_cfg.start_at_max = false;

    sensorsim_init(&amp;amp;m_heart_rate_sim_state, &amp;amp;m_heart_rate_sim_cfg);

    m_rr_interval_sim_cfg.min          = MIN_RR_INTERVAL;
    m_rr_interval_sim_cfg.max          = MAX_RR_INTERVAL;
    m_rr_interval_sim_cfg.incr         = RR_INTERVAL_INCREMENT;
    m_rr_interval_sim_cfg.start_at_max = false;

    sensorsim_init(&amp;amp;m_rr_interval_sim_state, &amp;amp;m_rr_interval_sim_cfg);
}


/**@brief   Function for starting application timers.
 * @details Timers are run after the scheduler has started.
 */
static void application_timers_start(void)
{
    // Start application timers.
    if (pdPASS != xTimerStart(m_battery_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
    if (pdPASS != xTimerStart(m_heart_rate_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
    if (pdPASS != xTimerStart(m_rr_interval_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
    if (pdPASS != xTimerStart(m_sensor_contact_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
}


/**@brief Function for handling the Connection Parameters Module.
 *
 * @details This function will be called for all events in the Connection Parameters Module which
 *          are passed to the application.
 *          @note All this function does is to disconnect. This could have been done by simply
 *                setting the disconnect_on_fail config parameter, but instead we use the event
 *                handler mechanism to demonstrate its use.
 *
 * @param[in]   p_evt   Event received from the Connection Parameters Module.
 */
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    ret_code_t err_code;

    if (p_evt-&amp;gt;evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}


/**@brief Function for handling a Connection Parameters error.
 *
 * @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 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    = m_hrs.hrm_handles.cccd_handle;
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;
    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 putting the chip into sleep mode.
 *
 * @note This function will not return.
 */
static void sleep_mode_enter(void)
{
    ret_code_t err_code;

    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
    APP_ERROR_CHECK(err_code);

    // Prepare wakeup buttons.
    err_code = bsp_btn_ble_sleep_mode_prepare();
    APP_ERROR_CHECK(err_code);

    // Go to system-off mode (this function will not return; wakeup will cause a reset).
    err_code = sd_power_system_off();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling advertising events.
 *
 * @details This function will be called for advertising events which are passed to the application.
 *
 * @param[in] ble_adv_evt  Advertising event.
 */
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    uint32_t err_code;

    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
            NRF_LOG_INFO(&amp;quot;Fast advertising.&amp;quot;);
            err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_ADV_EVT_IDLE:
            sleep_mode_enter();
            break;

        default:
            break;
    }
}


/**@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)
{
    uint32_t err_code;

    switch (p_ble_evt-&amp;gt;header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            NRF_LOG_INFO(&amp;quot;Connected&amp;quot;);
            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
            APP_ERROR_CHECK(err_code);
            m_conn_handle = p_ble_evt-&amp;gt;evt.gap_evt.conn_handle;
            err_code = nrf_ble_qwr_conn_handle_assign(&amp;amp;m_qwr, m_conn_handle);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            NRF_LOG_INFO(&amp;quot;Disconnected&amp;quot;);
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;

        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;

        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            NRF_LOG_DEBUG(&amp;quot;GATT Client Timeout.&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.
            NRF_LOG_DEBUG(&amp;quot;GATT Server Timeout.&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:
            // No implementation needed.
            break;
    }
}


/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupt.
 */
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 handling events from the BSP module.
 *
 * @param[in]   event   Event generated by button press.
 */
static void bsp_event_handler(bsp_event_t event)
{
    ret_code_t err_code;

    switch (event)
    {
        case BSP_EVENT_SLEEP:
            sleep_mode_enter();
            break;

        case BSP_EVENT_DISCONNECT:
            err_code = sd_ble_gap_disconnect(m_conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;

        case BSP_EVENT_WHITELIST_OFF:
            if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
            {
                err_code = ble_advertising_restart_without_whitelist(&amp;amp;m_advertising);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
                }
            }
            break;

        default:
            break;
    }
}


/**@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 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_DURATION;

    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 the nrf log module.
 */
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 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_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
    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 starting advertising. */
static void advertising_start(void * p_erase_bonds)
{
    bool erase_bonds = *(bool*)p_erase_bonds;

    if (erase_bonds)
    {
        delete_bonds();
        // Advertising is started by PM_EVT_PEERS_DELETE_SUCCEEDED event.
    }
    else
    {
        ret_code_t err_code = ble_advertising_start(&amp;amp;m_advertising, BLE_ADV_MODE_FAST);
        APP_ERROR_CHECK(err_code);
    }
}


#if NRF_LOG_ENABLED
/**@brief Thread for handling the logger.
 *
 * @details This thread is responsible for processing log entries if logs are deferred.
 *          Thread flushes all log entries and suspends. It is resumed by idle task hook.
 *
 * @param[in]   arg   Pointer used for passing some arbitrary information (context) from the
 *                    osThreadCreate() call to the thread.
 */
static void logger_thread(void * arg)
{
    UNUSED_PARAMETER(arg);

    while (1)
    {
        NRF_LOG_FLUSH();

        vTaskSuspend(NULL); // Suspend myself
    }
}
#endif //NRF_LOG_ENABLED

/**@brief A function which is hooked to idle task.
 * @note Idle hook must be enabled in FreeRTOS configuration (configUSE_IDLE_HOOK).
 */
void vApplicationIdleHook( void )
{
#if NRF_LOG_ENABLED
     vTaskResume(m_logger_thread);
#endif
}


/**@brief Function for initializing the clock.
 */
static void clock_init(void)
{
    ret_code_t err_code = nrf_drv_clock_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for application main entry.
 */
int main(void)
{
    bool erase_bonds;

    // Initialize modules.
    log_init();
    clock_init();

#if DWT_GUARD_ENABLED
    dwt_stack_guard_init();
#endif


    // Do not start any interrupt that uses system functions before system initialisation.
    // The best solution is to start the OS before any other initalisation.

#if NRF_LOG_ENABLED
    // Start execution.
    if (pdPASS != xTaskCreate(logger_thread, &amp;quot;LOGGER&amp;quot;, 256, NULL, 1, &amp;amp;m_logger_thread))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
#endif

    // Activate deep sleep mode.
    SCB-&amp;gt;SCR |= SCB_SCR_SLEEPDEEP_Msk;

    // Configure and initialize the BLE stack.
    ble_stack_init();

    // Initialize modules.
    timers_init();
    buttons_leds_init(&amp;amp;erase_bonds);
    gap_params_init();
    gatt_init();
    advertising_init();
    services_init();
    sensor_simulator_init();
    conn_params_init();
    peer_manager_init();
    application_timers_start();

    // Create a FreeRTOS task for the BLE stack.
    // The task will run advertising_start() before entering its loop.
    nrf_sdh_freertos_init(advertising_start, &amp;amp;erase_bonds);

    NRF_LOG_INFO(&amp;quot;HRS FreeRTOS example started.&amp;quot;);
    // Start FreeRTOS scheduler.
    vTaskStartScheduler();

    for (;;)
    {
        APP_ERROR_HANDLER(NRF_ERROR_FORBIDDEN);
    }
}
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;With this flag settings, this is the same compiled code as the original &lt;code&gt;main.c&lt;/code&gt; file. I am using the ARM GCC compile chain and a PCA10056 DevKit, so I compile/flash it this way:&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="bat"&gt;cd pca10056/s140/armgcc
make flash_softdevice flash
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;And here is what&amp;nbsp;I get in a terminal looking at the USB port:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;.&amp;lt;info&amp;gt; app: HRS FreeRTOS example started.

&amp;lt;info&amp;gt; app: Fast advertising.

&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;So everything is wonderful like in the original example. Now let us set the first rows like this:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;#define DWT_GUARD_ENABLED 1
#define NRF_LOG_BACKEND_RTT_ENABLED  0
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;This is the same as your example, and I get this in a terminal:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;.&amp;lt;info&amp;gt; app: CoreDebug-&amp;gt;DEMCR : 0x1010000

&amp;lt;info&amp;gt; app: Number of DWT comparators: 4

&amp;lt;info&amp;gt; app: DWT-&amp;gt;COMP0 : 0x2003E000

&amp;lt;info&amp;gt; app: DWT-&amp;gt;MASK0 : 0x4

&amp;lt;info&amp;gt; app: DWT-&amp;gt;FUNCTION0 : 0x7

&amp;lt;info&amp;gt; app: HRS FreeRTOS example started.

&amp;lt;info&amp;gt; app: Fast advertising.

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&amp;lt;info&amp;gt; app: Debug Monitor interrupt triggered

&amp;lt;info&amp;gt; app: Current SP 0x2003FFD8

&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;One comment: to get it working a soft reset through SWD (like nrfjprog --reset) is not sufficient, a HW reset is needed !&lt;/p&gt;
&lt;p&gt;Now, I change again the two first lines of the main.c like this:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;#define DWT_GUARD_ENABLED 0
#define NRF_LOG_BACKEND_RTT_ENABLED  1
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;which means that I fallback to the original example, but with RTT log backend rather than UART. I compile and try it&amp;nbsp;like this:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;make flash &amp;amp;&amp;amp; JLinkRTTLogger -Device nrf52840_XXAA -If SWD -Speed 4000 -RTTCHannel 0 /dev/stdout&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;It compiles without error, but there is not output. Frankly speaking this is the first time I am trying to use the PCA10056 with RTT logging. Does&amp;nbsp;it mean&amp;nbsp;that the PCA10056 does not contain a full Jlink implementation, but only some reduced set that allows flashing, but not RTT logging ?&lt;/p&gt;
&lt;p&gt;FYI, the reason why I am trying to set a dynamic watchpoint is to find out some bug on our product custom board. On this board we use only the RTT logging. So w/o RTT logging I won&amp;#39;t be able to use your suggestion.&lt;/p&gt;
&lt;p&gt;Our using the UART backend is in principle possible, but that would require instrumenting our product board, and developing a new adaptation board for the JLink, so this is not a preferred way at this moment.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287893?ContentTypeID=1</link><pubDate>Thu, 07 Jan 2021 10:00:02 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:6c020d1d-9d9e-487c-b36b-e87f0d521d80</guid><dc:creator>Vidar Berg</dc:creator><description>&lt;p&gt;Sorry, I forgot that you can only use the &lt;span&gt;NVIC_EnableIRQ&lt;/span&gt;()/NVIC_SetPendingIRQ() CMSIS function for nRF specific interrupts (non-negative IRQ numbers), so that wasn&amp;#39;t a good test.&lt;/p&gt;
&lt;p&gt;Can you try to use my code to see if the interrupt gets triggered then? I just tested it with the ble_app_hrs_freertos example in SDK 17.0.2:&lt;/p&gt;
&lt;p&gt;&lt;img src="https://devzone.nordicsemi.com/resized-image/__size/320x240/__key/communityserver-discussions-components-files/4/5123.pastedimage1610013797931v1.png" alt=" " /&gt;&lt;/p&gt;
&lt;p&gt;Modified main.c&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;/**
 * Copyright (c) 2014 - 2020, 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.
 *
 */
// Board/nrf6310/ble/ble_app_hrs_rtx/main.c
/**
 *
 * @brief Heart Rate Service Sample Application with RTX main file.
 *
 * This file contains the source code for a sample application using RTX and the
 * Heart Rate service (and also Battery and Device Information services).
 * This application uses the @ref srvlib_conn_params module.
 */

#include &amp;lt;stdint.h&amp;gt;
#include &amp;lt;string.h&amp;gt;
#include &amp;quot;nordic_common.h&amp;quot;
#include &amp;quot;nrf.h&amp;quot;
#include &amp;quot;app_error.h&amp;quot;
#include &amp;quot;ble.h&amp;quot;
#include &amp;quot;ble_hci.h&amp;quot;
#include &amp;quot;ble_srv_common.h&amp;quot;
#include &amp;quot;ble_advdata.h&amp;quot;
#include &amp;quot;ble_advertising.h&amp;quot;
#include &amp;quot;ble_bas.h&amp;quot;
#include &amp;quot;ble_hrs.h&amp;quot;
#include &amp;quot;ble_dis.h&amp;quot;
#include &amp;quot;ble_conn_params.h&amp;quot;
#include &amp;quot;sensorsim.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;nrf_sdh_freertos.h&amp;quot;
#include &amp;quot;app_timer.h&amp;quot;
#include &amp;quot;peer_manager.h&amp;quot;
#include &amp;quot;peer_manager_handler.h&amp;quot;
#include &amp;quot;bsp_btn_ble.h&amp;quot;
#include &amp;quot;FreeRTOS.h&amp;quot;
#include &amp;quot;task.h&amp;quot;
#include &amp;quot;timers.h&amp;quot;
#include &amp;quot;semphr.h&amp;quot;
#include &amp;quot;fds.h&amp;quot;
#include &amp;quot;ble_conn_state.h&amp;quot;
#include &amp;quot;nrf_drv_clock.h&amp;quot;
#include &amp;quot;nrf_ble_gatt.h&amp;quot;
#include &amp;quot;nrf_ble_qwr.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 DEVICE_NAME                         &amp;quot;Nordic_HRM&amp;quot;                            /**&amp;lt; Name of device. Will be included in the advertising data. */
#define MANUFACTURER_NAME                   &amp;quot;NordicSemiconductor&amp;quot;                   /**&amp;lt; Manufacturer. Will be passed to Device Information Service. */

#define APP_BLE_OBSERVER_PRIO               3                                       /**&amp;lt; Application&amp;#39;s BLE observer priority. You shouldn&amp;#39;t need to modify this value. */
#define APP_BLE_CONN_CFG_TAG                1                                       /**&amp;lt; A tag identifying the SoftDevice BLE configuration. */

#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_DURATION                    18000                                       /**&amp;lt; The advertising duration (180 seconds) in units of 10 milliseconds. */

#define BATTERY_LEVEL_MEAS_INTERVAL         2000                                    /**&amp;lt; Battery level measurement interval (ms). */
#define MIN_BATTERY_LEVEL                   81                                      /**&amp;lt; Minimum simulated battery level. */
#define MAX_BATTERY_LEVEL                   100                                     /**&amp;lt; Maximum simulated battery level. */
#define BATTERY_LEVEL_INCREMENT             1                                       /**&amp;lt; Increment between each simulated battery level measurement. */

#define HEART_RATE_MEAS_INTERVAL            1000                                    /**&amp;lt; Heart rate measurement interval (ms). */
#define MIN_HEART_RATE                      140                                     /**&amp;lt; Minimum heart rate as returned by the simulated measurement function. */
#define MAX_HEART_RATE                      300                                     /**&amp;lt; Maximum heart rate as returned by the simulated measurement function. */
#define HEART_RATE_INCREMENT                10                                      /**&amp;lt; Value by which the heart rate is incremented/decremented for each call to the simulated measurement function. */

#define RR_INTERVAL_INTERVAL                300                                     /**&amp;lt; RR interval interval (ms). */
#define MIN_RR_INTERVAL                     100                                     /**&amp;lt; Minimum RR interval as returned by the simulated measurement function. */
#define MAX_RR_INTERVAL                     500                                     /**&amp;lt; Maximum RR interval as returned by the simulated measurement function. */
#define RR_INTERVAL_INCREMENT               1                                       /**&amp;lt; Value by which the RR interval is incremented/decremented for each call to the simulated measurement function. */

#define SENSOR_CONTACT_DETECTED_INTERVAL    5000                                    /**&amp;lt; Sensor Contact Detected toggle interval (ms). */

#define MIN_CONN_INTERVAL                   MSEC_TO_UNITS(400, UNIT_1_25_MS)        /**&amp;lt; Minimum acceptable connection interval (0.4 seconds). */
#define MAX_CONN_INTERVAL                   MSEC_TO_UNITS(650, UNIT_1_25_MS)        /**&amp;lt; Maximum acceptable connection interval (0.65 second). */
#define SLAVE_LATENCY                       0                                       /**&amp;lt; Slave latency. */
#define CONN_SUP_TIMEOUT                    MSEC_TO_UNITS(4000, UNIT_10_MS)         /**&amp;lt; Connection supervisory time-out (4 seconds). */

#define FIRST_CONN_PARAMS_UPDATE_DELAY      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       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 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. */
#define SEC_PARAM_MAX_KEY_SIZE              16                                      /**&amp;lt; Maximum encryption key size. */

#define DEAD_BEEF                           0xDEADBEEF                              /**&amp;lt; Value used as error code on stack dump, can be used to identify stack location on stack unwind. */

#define OSTIMER_WAIT_FOR_QUEUE              2                                       /**&amp;lt; Number of ticks to wait for the timer queue to be ready */


BLE_BAS_DEF(m_bas);                                                 /**&amp;lt; Battery service instance. */
BLE_HRS_DEF(m_hrs);                                                 /**&amp;lt; Heart rate service instance. */
NRF_BLE_GATT_DEF(m_gatt);                                           /**&amp;lt; GATT module instance. */
NRF_BLE_QWR_DEF(m_qwr);                                             /**&amp;lt; Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising);                                 /**&amp;lt; Advertising module instance. */

static uint16_t m_conn_handle         = BLE_CONN_HANDLE_INVALID;    /**&amp;lt; Handle of the current connection. */
static bool     m_rr_interval_enabled = true;                       /**&amp;lt; Flag for enabling and disabling the registration of new RR interval measurements (the purpose of disabling this is just to test sending HRM without RR interval data. */

static sensorsim_cfg_t   m_battery_sim_cfg;                         /**&amp;lt; Battery Level sensor simulator configuration. */
static sensorsim_state_t m_battery_sim_state;                       /**&amp;lt; Battery Level sensor simulator state. */
static sensorsim_cfg_t   m_heart_rate_sim_cfg;                      /**&amp;lt; Heart Rate sensor simulator configuration. */
static sensorsim_state_t m_heart_rate_sim_state;                    /**&amp;lt; Heart Rate sensor simulator state. */
static sensorsim_cfg_t   m_rr_interval_sim_cfg;                     /**&amp;lt; RR Interval sensor simulator configuration. */
static sensorsim_state_t m_rr_interval_sim_state;                   /**&amp;lt; RR Interval sensor simulator state. */

static ble_uuid_t m_adv_uuids[] =                                   /**&amp;lt; Universally unique service identifiers. */
{
    {BLE_UUID_HEART_RATE_SERVICE, BLE_UUID_TYPE_BLE},
    {BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
    {BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
};

static TimerHandle_t m_battery_timer;                               /**&amp;lt; Definition of battery timer. */
static TimerHandle_t m_heart_rate_timer;                            /**&amp;lt; Definition of heart rate timer. */
static TimerHandle_t m_rr_interval_timer;                           /**&amp;lt; Definition of RR interval timer. */
static TimerHandle_t m_sensor_contact_timer;                        /**&amp;lt; Definition of sensor contact detected timer. */

#if NRF_LOG_ENABLED
static TaskHandle_t m_logger_thread;                                /**&amp;lt; Definition of Logger thread. */
#endif

#define STACK_LIMIT 0x2003e000

void DebugMon_Handler(void)
{
    NRF_LOG_INFO(&amp;quot;Debug Monitor interrupt triggered&amp;quot;);
    NRF_LOG_INFO(&amp;quot;Current SP 0x%x&amp;quot;, __get_MSP());
    NRF_LOG_FINAL_FLUSH();
}


static void dwt_stack_guard_init()
{
    uint32_t num;

    CoreDebug-&amp;gt;DEMCR |= CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk;

    NRF_LOG_INFO(&amp;quot;CoreDebug-&amp;gt;DEMCR : 0x%x&amp;quot;, CoreDebug-&amp;gt;DEMCR);
    
    num = (DWT-&amp;gt;CTRL &amp;amp; DWT_CTRL_NUMCOMP_Msk) &amp;gt;&amp;gt; DWT_CTRL_NUMCOMP_Pos;
    NRF_LOG_INFO(&amp;quot;Number of DWT comparators: %d&amp;quot;, num);

    NVIC_SetPriority(DebugMonitor_IRQn, 6); 

    DWT-&amp;gt;COMP0 = STACK_LIMIT;
    DWT-&amp;gt;MASK0 = 4;
    DWT-&amp;gt;FUNCTION0 = (7 &amp;lt;&amp;lt; DWT_FUNCTION_FUNCTION_Pos);
     
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;COMP0 : 0x%x&amp;quot;, DWT-&amp;gt;COMP0);
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;MASK0 : 0x%x&amp;quot;, DWT-&amp;gt;MASK0);
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;FUNCTION0 : 0x%x&amp;quot;, DWT-&amp;gt;FUNCTION0);

}

static void advertising_start(void * p_erase_bonds);


/**@brief Callback function for 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]   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(DEAD_BEEF, line_num, p_file_name);
}


/**@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)
{
    bool delete_bonds = false;

    pm_handler_on_pm_evt(p_evt);
    pm_handler_flash_clean(p_evt);

    switch (p_evt-&amp;gt;evt_id)
    {
        case PM_EVT_PEERS_DELETE_SUCCEEDED:
            advertising_start(&amp;amp;delete_bonds);
            break;

        default:
            break;
    }
}


/**@brief Function for performing battery measurement and updating the Battery Level characteristic
 *        in Battery Service.
 */
static void battery_level_update(void)
{
    ret_code_t err_code;
    uint8_t  battery_level;

    battery_level = (uint8_t)sensorsim_measure(&amp;amp;m_battery_sim_state, &amp;amp;m_battery_sim_cfg);

    err_code = ble_bas_battery_level_update(&amp;amp;m_bas, battery_level, BLE_CONN_HANDLE_ALL);
    if ((err_code != NRF_SUCCESS) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_INVALID_STATE) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_RESOURCES) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_BUSY) &amp;amp;&amp;amp;
        (err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING)
       )
    {
        APP_ERROR_HANDLER(err_code);
    }
}


/**@brief Function for handling the Battery measurement timer time-out.
 *
 * @details This function will be called each time the battery level measurement timer expires.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void battery_level_meas_timeout_handler(TimerHandle_t xTimer)
{
    UNUSED_PARAMETER(xTimer);
    battery_level_update();
    *(uint32_t *) STACK_LIMIT = 1;
}


/**@brief Function for handling the Heart rate measurement timer time-out.
 *
 * @details This function will be called each time the heart rate measurement timer expires.
 *          It will exclude RR Interval data from every third measurement.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void heart_rate_meas_timeout_handler(TimerHandle_t xTimer)
{
    static uint32_t cnt = 0;
    ret_code_t      err_code;
    uint16_t        heart_rate;

    UNUSED_PARAMETER(xTimer);

    heart_rate = (uint16_t)sensorsim_measure(&amp;amp;m_heart_rate_sim_state, &amp;amp;m_heart_rate_sim_cfg);

    cnt++;
    err_code = ble_hrs_heart_rate_measurement_send(&amp;amp;m_hrs, heart_rate);
    if ((err_code != NRF_SUCCESS) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_INVALID_STATE) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_RESOURCES) &amp;amp;&amp;amp;
        (err_code != NRF_ERROR_BUSY) &amp;amp;&amp;amp;
        (err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING)
       )
    {
        APP_ERROR_HANDLER(err_code);
    }

    // Disable RR Interval recording every third heart rate measurement.
    // NOTE: An application will normally not do this. It is done here just for testing generation
    // of messages without RR Interval measurements.
    m_rr_interval_enabled = ((cnt % 3) != 0);
}


/**@brief Function for handling the RR interval timer time-out.
 *
 * @details This function will be called each time the RR interval timer expires.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void rr_interval_timeout_handler(TimerHandle_t xTimer)
{
    UNUSED_PARAMETER(xTimer);

    if (m_rr_interval_enabled)
    {
        uint16_t rr_interval;

        rr_interval = (uint16_t)sensorsim_measure(&amp;amp;m_rr_interval_sim_state,
                                                  &amp;amp;m_rr_interval_sim_cfg);
        ble_hrs_rr_interval_add(&amp;amp;m_hrs, rr_interval);
    }
}


/**@brief Function for handling the Sensor Contact Detected timer time-out.
 *
 * @details This function will be called each time the Sensor Contact Detected timer expires.
 *
 * @param[in] xTimer Handler to the timer that called this function.
 *                   You may get identifier given to the function xTimerCreate using pvTimerGetTimerID.
 */
static void sensor_contact_detected_timeout_handler(TimerHandle_t xTimer)
{
    static bool sensor_contact_detected = false;

    UNUSED_PARAMETER(xTimer);

    sensor_contact_detected = !sensor_contact_detected;
    ble_hrs_sensor_contact_detected_update(&amp;amp;m_hrs, sensor_contact_detected);
}


/**@brief Function for the Timer initialization.
 *
 * @details Initializes the timer module. This creates and starts application timers.
 */
static void timers_init(void)
{
    // Initialize timer module.
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);

    // Create timers.
    m_battery_timer = xTimerCreate(&amp;quot;BATT&amp;quot;,
                                   BATTERY_LEVEL_MEAS_INTERVAL,
                                   pdTRUE,
                                   NULL,
                                   battery_level_meas_timeout_handler);
    m_heart_rate_timer = xTimerCreate(&amp;quot;HRT&amp;quot;,
                                      HEART_RATE_MEAS_INTERVAL,
                                      pdTRUE,
                                      NULL,
                                      heart_rate_meas_timeout_handler);
    m_rr_interval_timer = xTimerCreate(&amp;quot;RRT&amp;quot;,
                                       RR_INTERVAL_INTERVAL,
                                       pdTRUE,
                                       NULL,
                                       rr_interval_timeout_handler);
    m_sensor_contact_timer = xTimerCreate(&amp;quot;SCT&amp;quot;,
                                          SENSOR_CONTACT_DETECTED_INTERVAL,
                                          pdTRUE,
                                          NULL,
                                          sensor_contact_detected_timeout_handler);

    /* Error checking */
    if ( (NULL == m_battery_timer)
         || (NULL == m_heart_rate_timer)
         || (NULL == m_rr_interval_timer)
         || (NULL == m_sensor_contact_timer) )
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
}


/**@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);

    err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_HEART_RATE_SENSOR_HEART_RATE_BELT);
    APP_ERROR_CHECK(err_code);

    memset(&amp;amp;gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_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 Queued Write Module errors.
 *
 * @details A pointer to this function will be passed to each service which may need to inform the
 *          application about an error.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}


/**@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)
{
    ret_code_t         err_code;
    ble_hrs_init_t     hrs_init;
    ble_bas_init_t     bas_init;
    ble_dis_init_t     dis_init;
    nrf_ble_qwr_init_t qwr_init = {0};
    uint8_t            body_sensor_location;

    // Initialize Queued Write Module.
    qwr_init.error_handler = nrf_qwr_error_handler;

    err_code = nrf_ble_qwr_init(&amp;amp;m_qwr, &amp;amp;qwr_init);
    APP_ERROR_CHECK(err_code);

    // Initialize Heart Rate Service.
    body_sensor_location = BLE_HRS_BODY_SENSOR_LOCATION_FINGER;

    memset(&amp;amp;hrs_init, 0, sizeof(hrs_init));

    hrs_init.evt_handler                 = NULL;
    hrs_init.is_sensor_contact_supported = true;
    hrs_init.p_body_sensor_location      = &amp;amp;body_sensor_location;

    // Here the sec level for the Heart Rate Service can be changed/increased.
    hrs_init.hrm_cccd_wr_sec = SEC_OPEN;
    hrs_init.bsl_rd_sec      = SEC_OPEN;

    err_code = ble_hrs_init(&amp;amp;m_hrs, &amp;amp;hrs_init);
    APP_ERROR_CHECK(err_code);

    // Initialize Battery Service.
    memset(&amp;amp;bas_init, 0, sizeof(bas_init));

    // Here the sec level for the Battery Service can be changed/increased.
    bas_init.bl_rd_sec        = SEC_OPEN;
    bas_init.bl_cccd_wr_sec   = SEC_OPEN;
    bas_init.bl_report_rd_sec = SEC_OPEN;

    bas_init.evt_handler          = NULL;
    bas_init.support_notification = true;
    bas_init.p_report_ref         = NULL;
    bas_init.initial_batt_level   = 100;

    err_code = ble_bas_init(&amp;amp;m_bas, &amp;amp;bas_init);
    APP_ERROR_CHECK(err_code);

    // Initialize Device Information Service.
    memset(&amp;amp;dis_init, 0, sizeof(dis_init));

    ble_srv_ascii_to_utf8(&amp;amp;dis_init.manufact_name_str, (char *)MANUFACTURER_NAME);

    dis_init.dis_char_rd_sec = SEC_OPEN;

    err_code = ble_dis_init(&amp;amp;dis_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the sensor simulators. */
static void sensor_simulator_init(void)
{
    m_battery_sim_cfg.min          = MIN_BATTERY_LEVEL;
    m_battery_sim_cfg.max          = MAX_BATTERY_LEVEL;
    m_battery_sim_cfg.incr         = BATTERY_LEVEL_INCREMENT;
    m_battery_sim_cfg.start_at_max = true;

    sensorsim_init(&amp;amp;m_battery_sim_state, &amp;amp;m_battery_sim_cfg);

    m_heart_rate_sim_cfg.min          = MIN_HEART_RATE;
    m_heart_rate_sim_cfg.max          = MAX_HEART_RATE;
    m_heart_rate_sim_cfg.incr         = HEART_RATE_INCREMENT;
    m_heart_rate_sim_cfg.start_at_max = false;

    sensorsim_init(&amp;amp;m_heart_rate_sim_state, &amp;amp;m_heart_rate_sim_cfg);

    m_rr_interval_sim_cfg.min          = MIN_RR_INTERVAL;
    m_rr_interval_sim_cfg.max          = MAX_RR_INTERVAL;
    m_rr_interval_sim_cfg.incr         = RR_INTERVAL_INCREMENT;
    m_rr_interval_sim_cfg.start_at_max = false;

    sensorsim_init(&amp;amp;m_rr_interval_sim_state, &amp;amp;m_rr_interval_sim_cfg);
}


/**@brief   Function for starting application timers.
 * @details Timers are run after the scheduler has started.
 */
static void application_timers_start(void)
{
    // Start application timers.
    if (pdPASS != xTimerStart(m_battery_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
    if (pdPASS != xTimerStart(m_heart_rate_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
    if (pdPASS != xTimerStart(m_rr_interval_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
    if (pdPASS != xTimerStart(m_sensor_contact_timer, OSTIMER_WAIT_FOR_QUEUE))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
}


/**@brief Function for handling the Connection Parameters Module.
 *
 * @details This function will be called for all events in the Connection Parameters Module which
 *          are passed to the application.
 *          @note All this function does is to disconnect. This could have been done by simply
 *                setting the disconnect_on_fail config parameter, but instead we use the event
 *                handler mechanism to demonstrate its use.
 *
 * @param[in]   p_evt   Event received from the Connection Parameters Module.
 */
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    ret_code_t err_code;

    if (p_evt-&amp;gt;evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}


/**@brief Function for handling a Connection Parameters error.
 *
 * @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 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    = m_hrs.hrm_handles.cccd_handle;
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;
    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 putting the chip into sleep mode.
 *
 * @note This function will not return.
 */
static void sleep_mode_enter(void)
{
    ret_code_t err_code;

    err_code = bsp_indication_set(BSP_INDICATE_IDLE);
    APP_ERROR_CHECK(err_code);

    // Prepare wakeup buttons.
    err_code = bsp_btn_ble_sleep_mode_prepare();
    APP_ERROR_CHECK(err_code);

    // Go to system-off mode (this function will not return; wakeup will cause a reset).
    err_code = sd_power_system_off();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling advertising events.
 *
 * @details This function will be called for advertising events which are passed to the application.
 *
 * @param[in] ble_adv_evt  Advertising event.
 */
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    uint32_t err_code;

    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
            NRF_LOG_INFO(&amp;quot;Fast advertising.&amp;quot;);
            err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_ADV_EVT_IDLE:
            sleep_mode_enter();
            break;

        default:
            break;
    }
}


/**@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)
{
    uint32_t err_code;

    switch (p_ble_evt-&amp;gt;header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            NRF_LOG_INFO(&amp;quot;Connected&amp;quot;);
            err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
            APP_ERROR_CHECK(err_code);
            m_conn_handle = p_ble_evt-&amp;gt;evt.gap_evt.conn_handle;
            err_code = nrf_ble_qwr_conn_handle_assign(&amp;amp;m_qwr, m_conn_handle);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            NRF_LOG_INFO(&amp;quot;Disconnected&amp;quot;);
            m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;

        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;

        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            NRF_LOG_DEBUG(&amp;quot;GATT Client Timeout.&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.
            NRF_LOG_DEBUG(&amp;quot;GATT Server Timeout.&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:
            // No implementation needed.
            break;
    }
}


/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupt.
 */
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 handling events from the BSP module.
 *
 * @param[in]   event   Event generated by button press.
 */
static void bsp_event_handler(bsp_event_t event)
{
    ret_code_t err_code;

    switch (event)
    {
        case BSP_EVENT_SLEEP:
            sleep_mode_enter();
            break;

        case BSP_EVENT_DISCONNECT:
            err_code = sd_ble_gap_disconnect(m_conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;

        case BSP_EVENT_WHITELIST_OFF:
            if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
            {
                err_code = ble_advertising_restart_without_whitelist(&amp;amp;m_advertising);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
                }
            }
            break;

        default:
            break;
    }
}


/**@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 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_DURATION;

    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 the nrf log module.
 */
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 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_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
    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 starting advertising. */
static void advertising_start(void * p_erase_bonds)
{
    bool erase_bonds = *(bool*)p_erase_bonds;

    if (erase_bonds)
    {
        delete_bonds();
        // Advertising is started by PM_EVT_PEERS_DELETE_SUCCEEDED event.
    }
    else
    {
        ret_code_t err_code = ble_advertising_start(&amp;amp;m_advertising, BLE_ADV_MODE_FAST);
        APP_ERROR_CHECK(err_code);
    }
}


#if NRF_LOG_ENABLED
/**@brief Thread for handling the logger.
 *
 * @details This thread is responsible for processing log entries if logs are deferred.
 *          Thread flushes all log entries and suspends. It is resumed by idle task hook.
 *
 * @param[in]   arg   Pointer used for passing some arbitrary information (context) from the
 *                    osThreadCreate() call to the thread.
 */
static void logger_thread(void * arg)
{
    UNUSED_PARAMETER(arg);

    while (1)
    {
        NRF_LOG_FLUSH();

        vTaskSuspend(NULL); // Suspend myself
    }
}
#endif //NRF_LOG_ENABLED

/**@brief A function which is hooked to idle task.
 * @note Idle hook must be enabled in FreeRTOS configuration (configUSE_IDLE_HOOK).
 */
void vApplicationIdleHook( void )
{
#if NRF_LOG_ENABLED
     vTaskResume(m_logger_thread);
#endif
}


/**@brief Function for initializing the clock.
 */
static void clock_init(void)
{
    ret_code_t err_code = nrf_drv_clock_init();
    APP_ERROR_CHECK(err_code);
}



/**@brief Function for application main entry.
 */
int main(void)
{
    bool erase_bonds;

    // Initialize modules.
    log_init();
    clock_init();

    dwt_stack_guard_init();


    // Do not start any interrupt that uses system functions before system initialisation.
    // The best solution is to start the OS before any other initalisation.

#if NRF_LOG_ENABLED
    // Start execution.
    if (pdPASS != xTaskCreate(logger_thread, &amp;quot;LOGGER&amp;quot;, 256, NULL, 1, &amp;amp;m_logger_thread))
    {
        APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
    }
#endif

    // Activate deep sleep mode.
    SCB-&amp;gt;SCR |= SCB_SCR_SLEEPDEEP_Msk;

    // Configure and initialize the BLE stack.
    ble_stack_init();

    // Initialize modules.
    timers_init();
    buttons_leds_init(&amp;amp;erase_bonds);
    gap_params_init();
    gatt_init();
    advertising_init();
    services_init();
    sensor_simulator_init();
    conn_params_init();
    peer_manager_init();
    application_timers_start();

    // Create a FreeRTOS task for the BLE stack.
    // The task will run advertising_start() before entering its loop.
    nrf_sdh_freertos_init(advertising_start, &amp;amp;erase_bonds);

    NRF_LOG_INFO(&amp;quot;HRS FreeRTOS example started.&amp;quot;);
    // Start FreeRTOS scheduler.
    vTaskStartScheduler();

    for (;;)
    {
        APP_ERROR_HANDLER(NRF_ERROR_FORBIDDEN);
    }
}


&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;The interrupt is triggered by writing to the STACK_LIMIT address from the battery timer handler.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287779?ContentTypeID=1</link><pubDate>Wed, 06 Jan 2021 15:45:59 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:13692294-7536-4a2e-837c-dadb9b259066</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;FYI, I also had a look at the &lt;code&gt;.elf.map&lt;/code&gt; file, and I can see that the&amp;nbsp;&lt;code&gt;DebugMon_Handler&lt;/code&gt; is there, and it is from the C source file where I typed it.&lt;/p&gt;
&lt;p&gt;So, the problem is not that another implementation of it is called by way of some erroneous linking.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287778?ContentTypeID=1</link><pubDate>Wed, 06 Jan 2021 15:43:03 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:c0550fcb-dd9f-4c5e-be8a-73e5e80e52fa</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;I tried to call&amp;nbsp;&lt;span&gt;&lt;code&gt;NVIC_SetPendingIRQ(DebugMonitor_IRQn)&lt;/code&gt;, both before starting FreeRTOS, and also after FreeRTOS is started, at the beginning of a thread function.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;In both cases, I cannot see the trace output of &lt;code&gt;DebugMon_Handler&lt;/code&gt; happening, and the program goes past the call of&amp;nbsp;&lt;code&gt;NVIC_SetPendingIRQ(DebugMonitor_IRQn)&lt;/code&gt; without any effect of it, and continues what is next.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Please note that in both cases, I had called&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt; NVIC_SetPriority(DebugMonitor_IRQn, _PRIO_SD_HIGH);&lt;br /&gt; NVIC_EnableIRQ(DebugMonitor_IRQn);&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;at some point of time before calling&amp;nbsp;&lt;span&gt;NVIC_SetPendingIRQ(DebugMonitor_IRQn ).&lt;/span&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287717?ContentTypeID=1</link><pubDate>Wed, 06 Jan 2021 12:53:49 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:7f3c592c-d5dd-4b3e-8fa0-ceb8022dce3b</guid><dc:creator>Vidar Berg</dc:creator><description>&lt;p&gt;Yes, I agree, it looks like maybe the DebugMonitor_IRQn is not being raised, and that the program just stays in the &amp;quot;wait for event&amp;quot; loop. Are you sure you are meeting the conditions to trigger this event? Does the ISR get invoked as expected if you call NVIC_SetPendingIRQ(DebugMonitor_IRQn )?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287704?ContentTypeID=1</link><pubDate>Wed, 06 Jan 2021 11:54:47 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:39bf7f68-0bf9-42de-95cf-9a71cd79fb45</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;Actually, it gets to the same result (everything looking like frozen) even with an empty&amp;nbsp;&lt;code&gt;DebugMon_Handler&lt;/code&gt;.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I also tried this : I carried out&amp;nbsp;the procedure to get up to the breakpoint with the RTTlogger running. When the breakpoint occurs then everything gets kind of frozen, so I exit the RTTlogger and connect to the app with gdb through the Segger gdb server. When doing this I can see this backtrace (I just replaced the full path by &amp;hellip;) :&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;(gdb) bt&lt;br /&gt;#0 vPortSuppressTicksAndSleep (xExpectedIdleTime=5120)&lt;br /&gt; at &amp;hellip;/nrf-sdk/external/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c:254&lt;br /&gt;#1 0x00002616 in prvIdleTask (pvParameters=0x0 &amp;lt;__isr_vector&amp;gt;)&lt;br /&gt; at &amp;hellip;/nrf-sdk/external/freertos/source/tasks.c:3321&lt;br /&gt;#2 0x00000548 in pxPortInitialiseStack (pxTopOfStack=0x1400 &amp;lt;xQueueSemaphoreTake+204&amp;gt;, pxCode=0xa5a5a5a5, &lt;br /&gt; pvParameters=0xa5a5a5a5)&lt;br /&gt; at &amp;hellip;/nrf-sdk/external/freertos/portable/CMSIS/nrf52/port_cmsis.c:147&lt;br /&gt;Backtrace stopped: previous frame identical to this frame (corrupt stack?)&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;I also did the experiment with having&amp;nbsp;DebugMon_Handler doing some border effect on some static flag like this :&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;uint32_t titi;&lt;br /&gt;void DebugMon_Handler(void)&lt;br /&gt;{&lt;br /&gt; titi = 1;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;and what happens is that when inspecting &lt;code&gt;titi&lt;/code&gt; with the debugger, it is equal to 0, the startup value, so it seems that either&amp;nbsp;&lt;code&gt;DebugMon_Handler&lt;/code&gt; is not entered when the interrupt occurs, or the execution goes again to the startup and gets frozen at some point.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287686?ContentTypeID=1</link><pubDate>Wed, 06 Jan 2021 11:03:41 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:187783d0-b8e7-4c8a-841e-67477a3a9365</guid><dc:creator>Vidar Berg</dc:creator><description>&lt;p&gt;Hi and happy new year!&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Yes, I only tested with the UART backend so I didn&amp;#39;t have to keep the debugger connected. Have you tried testing with and without the NRF_LOG_FINAL_FLUSH()&amp;nbsp; line in your &lt;code&gt;DebugMon_Handler&lt;/code&gt;?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/287488?ContentTypeID=1</link><pubDate>Tue, 05 Jan 2021 11:42:54 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:6f3861eb-fed2-4664-9fdd-41b8a0fcecbf</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;Dear&amp;nbsp;&lt;a href="https://devzone.nordicsemi.com/members/vibe"&gt;Vidar Berg&lt;/a&gt;,&lt;/p&gt;
&lt;p&gt;Happy new year 2021, all the best to you !&lt;/p&gt;
&lt;p&gt;One more question : can you remember which logger backend you used with the code which you provided. Was it through the UART, right ?&lt;/p&gt;
&lt;p&gt;I adapted this code to my platform and breakpoint condition, and I tried that&amp;nbsp;with the RTTlogger, and it seems that if I start to play with the&amp;nbsp;&lt;code&gt;DebugMonitor_IRQn&lt;/code&gt; and overload the&amp;nbsp;&lt;code&gt;DebugMon_Handler&lt;/code&gt;, then when the breakpoint condition occurs, the trace stops, so the final trace made by &lt;code&gt;&lt;span&gt;DebugMon_Handler&lt;/span&gt;&lt;/code&gt;&amp;nbsp;does not go to the output, the log gets kind of frozen, and nothing more seems to happen.&lt;/p&gt;
&lt;p&gt;I tried to connect the debugger in this situation, and the only thing I can see is that I am stuck in the FreeRTOS calling &lt;code&gt;vPortSuppressTicksAndSleep&lt;/code&gt; for the Idle task.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/283838?ContentTypeID=1</link><pubDate>Tue, 08 Dec 2020 14:01:09 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:b2ecd05f-f630-4a04-81a7-3039e65dd980</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;OK, here is the new&amp;nbsp;&lt;code&gt;test_dwt&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;void test_dwt(void)
{
    CoreDebug-&amp;gt;DEMCR |= CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk;

    NRF_LOG_INFO(&amp;quot;CoreDebug-&amp;gt;DEMCR : 0x%x&amp;quot;, CoreDebug-&amp;gt;DEMCR);

    NRF_LOG_WARNING(&amp;quot;DWT-&amp;gt;CTRL = 0x%08x&amp;quot;,DWT-&amp;gt;CTRL);

    uint32_t dummy;

    DWT-&amp;gt;COMP0 = &amp;amp;dummy;
    DWT-&amp;gt;MASK0 = 0;
    DWT-&amp;gt;FUNCTION0 = (6&amp;lt;&amp;lt;0) // FUNCTION0.FUNCTION = 6, generate watchpoint debug event for WO access
        | (0&amp;lt;&amp;lt;7) // FUNCTION0.CYCMATCH == 0 for address comparison
        | (0&amp;lt;&amp;lt;8) // FUNCTIONn.DATAVMATCH == 0 for address comparison
        | (0&amp;lt;&amp;lt;5) // FUNCTIONn.EMITRANGE == 0, no meaning when FUNCTION = 6
        ;

    *(uint32_t volatile*)&amp;amp;dummy = 0;

    NRF_LOG_WARNING(&amp;quot;DWT-&amp;gt;FUNCTION0 = 0x%08x&amp;quot;,DWT-&amp;gt;FUNCTION0);
    DWT-&amp;gt;FUNCTION0 = 0;

    NRF_LOG_FLUSH();
    for(;;) {}
}
&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;And here is what I get now, it looks better :&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;&amp;lt;info&amp;gt; app: CoreDebug-&amp;gt;DEMCR : 0x1010000
&amp;lt;warning&amp;gt; app: DWT-&amp;gt;CTRL = 0x40000001
&amp;lt;warning&amp;gt; app: DWT-&amp;gt;FUNCTION0 = 0x01000006
&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/283826?ContentTypeID=1</link><pubDate>Tue, 08 Dec 2020 13:39:51 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:71dcf232-c5a2-4a6c-815d-ae18250845f4</guid><dc:creator>Vidar Berg</dc:creator><description>&lt;p&gt;To ensure the device is not in debug mode, could you try to do a pin-reset or power-cycle prior to running this test? I&amp;#39;ve previously tried using DWT as a stack guard to catch stack overflows, and I think I remember some similiar problems.&lt;/p&gt;
&lt;p&gt;Here&amp;#39;s the code I used:&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;#define STACK_LIMIT 0x2003e000

void DebugMon_Handler(void)
{
    NRF_LOG_INFO(&amp;quot;Debug Monitor interrupt triggered&amp;quot;);
    NRF_LOG_INFO(&amp;quot;Current SP 0x%x&amp;quot;, __get_MSP());
    NRF_LOG_FINAL_FLUSH();
    for(;;);
}


static void dwt_stack_guard_init()
{
    uint32_t num;

    CoreDebug-&amp;gt;DEMCR |= CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk;

    NRF_LOG_INFO(&amp;quot;CoreDebug-&amp;gt;DEMCR : 0x%x&amp;quot;, CoreDebug-&amp;gt;DEMCR);
    
    /* Using the highest programmable int. priority which is reserved to the Softdevice, and
       because of that we must configure the priority after ble_stack_init(). This bypasses the
       Softdevice&amp;#39;s internal int. priority validation check. */
    NVIC_SetPriority(DebugMonitor_IRQn, _PRIO_SD_HIGH); 
    NVIC_EnableIRQ(DebugMonitor_IRQn);

    num = (DWT-&amp;gt;CTRL &amp;amp; DWT_CTRL_NUMCOMP_Msk) &amp;gt;&amp;gt; DWT_CTRL_NUMCOMP_Pos;
    NRF_LOG_INFO(&amp;quot;Number of DWT comparators: %d&amp;quot;, num);

    DWT-&amp;gt;COMP0 = STACK_LIMIT;
    DWT-&amp;gt;MASK0 = 4;
    DWT-&amp;gt;FUNCTION0 = (7 &amp;lt;&amp;lt; DWT_FUNCTION_FUNCTION_Pos);
     
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;COMP0 : 0x%x&amp;quot;, DWT-&amp;gt;COMP0);
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;MASK0 : 0x%x&amp;quot;, DWT-&amp;gt;MASK0);
    NRF_LOG_INFO(&amp;quot;DWT-&amp;gt;FUNCTION0 : 0x%x&amp;quot;, DWT-&amp;gt;FUNCTION0);

}&lt;/pre&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/283825?ContentTypeID=1</link><pubDate>Tue, 08 Dec 2020 13:34:05 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:39985a41-8a7d-4fab-8554-d400b0e1a185</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;&lt;a href="https://devzone.nordicsemi.com/members/vibe"&gt;Vidar Berg&lt;/a&gt;&amp;nbsp;Thank you for paying attention to my ticket.&lt;br /&gt;&lt;br /&gt;In the latest experiment (that in which I call some&amp;nbsp;&lt;code&gt;test_dwt&lt;/code&gt; function) there is no debugger running, just the RTTlogger through a JLink probe.&lt;/p&gt;
&lt;p&gt;BTW I did some mistake in the code comments, but I cannot re-edit my posts to fix them.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/283821?ContentTypeID=1</link><pubDate>Tue, 08 Dec 2020 13:28:37 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:b02c29bc-9a43-4b04-803d-a07b37e431ad</guid><dc:creator>Vidar Berg</dc:creator><description>&lt;p&gt;Hello,&lt;/p&gt;
&lt;p&gt;This is something I need to look more into as I don&amp;#39;t know the answer. But I suspect there is a conflict between the debugger and code as both try to access DWT.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/283819?ContentTypeID=1</link><pubDate>Tue, 08 Dec 2020 13:24:03 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:e6373f9a-60ea-4607-a045-c3d6bf07b073</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;Once again answering to myself. I did the following plain experiment, calling the &lt;code&gt;test_dwt&lt;/code&gt; &amp;nbsp;function below close to the very beginning of my application (but after logger init).&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="c_cpp"&gt;void test_dwt(void)
{
    NRF_LOG_WARNING(&amp;quot;DWT-&amp;gt;CTRL = 0x%08x&amp;quot;,DWT-&amp;gt;CTRL);

    uint32_t dummy;

    DWT-&amp;gt;COMP0 = &amp;amp;dummy;
    DWT-&amp;gt;MASK0 = 0;
    DWT-&amp;gt;FUNCTION0 = (6&amp;lt;&amp;lt;0) // generate watchpoint data trace packet for WO access
        | (0&amp;lt;&amp;lt;7) // FUNCTION0.CYCMATCH == 0 for address comparison
        | (0&amp;lt;&amp;lt;8) // FUNCTIONn.DATAVMATCH == 0 for address comparison
        | (0&amp;lt;&amp;lt;5) // FUNCTIONn.EMITRANGE == 0 for trace packet conveying PC value &amp;amp; data value
        ;

    *(uint32_t volatile*)&amp;amp;dummy = 0;

    NRF_LOG_WARNING(&amp;quot;DWT-&amp;gt;FUNCTION0 = 0x%08x&amp;quot;,DWT-&amp;gt;FUNCTION0);
    DWT-&amp;gt;FUNCTION0 = 0;

    NRF_LOG_FLUSH();
    for(;;) {}
}&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;Here is what I get in the output &lt;span class="emoticon" data-url="https://devzone.nordicsemi.com/cfs-file/__key/system/emoji/1f622.svg" title="Cry"&gt;&amp;#x1f622;&lt;/span&gt; :&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;pre class="ui-code" data-mode="text"&gt;&amp;lt;warning&amp;gt; app: DWT-&amp;gt;CTRL = 0x0000978C
&amp;lt;warning&amp;gt; app: DWT-&amp;gt;FUNCTION0 = 0x0000978C
Transfer rate: 0 KByte/s Bytes written: 105 Byte   &lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;The 3 MSBits of DWT-&amp;gt;CTRL are the &lt;code&gt;DWT_CTRL.NUMCOMP&lt;/code&gt; field which in ARM v7M reference manual are documented as giving the number of implemented comparators. According to nRF52840 data sheet there are two comparators, so this should be 2 instead of 0. Then why so ?&lt;/p&gt;
&lt;p&gt;Maybe there is some power domain setting to enable to whole debugging peripheral ?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item><item><title>RE: Setting a watchpoint dynamically</title><link>https://devzone.nordicsemi.com/thread/283699?ContentTypeID=1</link><pubDate>Tue, 08 Dec 2020 07:03:34 GMT</pubDate><guid isPermaLink="false">137ad170-7792-4731-bb38-c0d22fbe4515:2d63641b-dd2d-4aaf-a48c-b3154f45cfbf</guid><dc:creator>Vincent Bela&amp;#239;che</dc:creator><description>&lt;p&gt;Answering to myself : I did the experiment again, and actually Ozone does not get frozen --- that was probably another issue --- but the debugger does not halt and show the instruction where the watchpoint is hit, although I can see in the RTTlogging that the corruption is still happening by testing the memory in the sequel.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;</description></item></channel></rss>