This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

BLE makes CPU skip a clock cycle on nRF52-DK

Dear all,

I am expanding the eddystone example for my nRF52832 (nRF52-DK) with some extra functionality. I wanted to create a periodic impulse with a timer (timer 1), all hardware driven via PPI, toggling a GPIO, still via PPI. The timer is configured so it will clear via a short at the count of 256 (16 bit timer). Then I have a PPI channel toggling a gpio every time the timer resets. Here is my code:

	
	// initializing timer
	
	timer_ = NRF_DRV_TIMER_INSTANCE(1);
	nrf_drv_timer_config_t timer_config = NRF_DRV_TIMER_DEFAULT_CONFIG;
	timer_config.bit_width = NRF_TIMER_BIT_WIDTH_16;
	timer_config.frequency = NRF_TIMER_FREQ_16MHz;
	nrf_drv_timer_init(&timer_, &timer_config, drv_dac::timer_evt_handler);
	
	// initializing GPIOTE
	
	nrf_drv_gpiote_out_config_t ss_pin_config;
	ss_pin_config.init_state = NRF_GPIOTE_INITIAL_VALUE_HIGH;
	ss_pin_config.task_pin = true;
	ss_pin_config.action = NRF_GPIOTE_POLARITY_TOGGLE;
	
	nrf_drv_gpiote_out_init(SPI_DAC_SS_PIN, &ss_pin_config);
	
	// setting up timer compare and short
	
	unsigned int ss_period = 256;
	nrf_drv_timer_extended_compare(
		&timer_,
		NRF_TIMER_CC_CHANNEL2,
		ss_period,
		NRF_TIMER_SHORT_COMPARE2_CLEAR_MASK,
		false
	);
	
	// configuring the PPI channel for toggling the GPIO
	
	nrf_drv_ppi_channel_alloc(&ppi_channel_count_);
	nrf_drv_ppi_channel_assign(
		ppi_channel_count_,
		nrfx_timer_event_address_get(&timer_, NRF_TIMER_EVENT_COMPARE2),
		nrfx_gpiote_out_task_addr_get(SPI_DAC_SS_PIN)
	);
	nrf_drv_ppi_channel_enable(ppi_channel_count_);

	nrf_drv_gpiote_out_task_enable(SPI_DAC_SS_PIN);
	
	// clearing and starting the timer
	
	nrf_drv_timer_clear(&timer_);
	nrf_drv_timer_enable(&timer_);
	

However, when the softdevice is running and I have beacon transmission, I can see the timer occasionally "skipping a beat" meaning that the on time is 257 cycles instead of 256 as expected, I measured it quite clearly with the scope, it is exactly an extra 16MHz clock cycle, and this happens exactly in correspondence of the eddystone beacon transmission.

I could deduce that the problem is the timer "strectching its period" and not the GPIO being delayed because I can see that these delays accumulate over consecutive cycles.

EDIT:

I actually made an additional test, I wanted to see problem was happening when the timer was resetting (PPI issue) or if the whole system was actually skipping a clock cycle. So instead of toggling the gpio I set up two compares, one with counter = 2 to set the pin and the next one with counter = 253 to clear the pin, so an impulse is generated for every timer cycle.

If the problem only happens when the timer is resetting I would expect to see this clock glitch on the first rising edge after the trigger but not on the falling edge of the impulse. However I can see the glitch on the falling edge, and between rising edge and falling edge of the GPIO there is no TIMER_CLEAR. So this hints to the fact that the whole system might be skipping a cycle.

I wonder is this is due to interference of the bluetooth antenna with the clock oscillator on the nRF52-DK board. Is there any way to keep the softdevice running but disable sources of potential interference like the antenna?

Thank you very much

  • HI vittopascu, 

    this is stated in PPI chapter of the nRF52832 Product Sepcification 

    On each PPI channel, the signals are synchronized to the 16 MHz clock, to avoid any internal violation of
    setup and hold timings. As a consequence, events that are synchronous to the 16 MHz clock will be delayed
    by one clock period, while other asynchronous events will be delayed by up to one 16 MHz clock period.

    So if you are seeing the GPIO being toggled exactly one 16MHz clock cycle period, then this could explain the behavior. However, it is odd that you only see this when the SD is running. However, it could be that the SD causes the TIMER_CLEAR to occur asyncronous to the 16Mhz clock.

    Best regards

    Bjørn

  • Hello Bjorn, thank you for your answer.

    I am aware that the PPI is aligned with 16mHz clock, but so is the timer as far as I understood. Also it is very strange that, when using a softdevice, one cannot set up a perfectly periodic timer...

    Anyway it looks like this clock "skipping" affects the entire SoC and all peripherals at the same time, even those that are not relying on the PPI.

    I just made three more tests:

    1) I tried to reduce the transmit power of the antenna to -12dB but that did not change anything. However while in connected mode the issue intensifies greatly.

    2) I set a timer at 16MHz (or 8MHz, same results) to a very long period like 50000. I still have my two compares to generate a GPIO pulse of some clock cycles. If the problem were exclusively the PPI, then this stretch or digital "jitter" would always be +- 1CLK @ 16MHz. However, I see that, the longer the period, the longer the stretch or "jitter", meaning that some clock cycles are skipped within the buffer period and this is not only a problem of synchronicity of the PPI.

    3) I took the untouched eddystone example from the SDK and added the code from the PWM example (via app_pwm.h), after having enabled all necessary peripherals in the configuration file. The issue presents itself exactly like in my own specific application. Below is the entire main code to use in the eddystone example necessary to reproduce the issue:

    /**
     * Copyright (c) 2016 - 2019, 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 "AS IS" 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.
     *
     */
    /** @file
     *
     * @defgroup nrf5_sdk_for_eddystone main.c
     * @{
     * @ingroup nrf5_sdk_for_eddystone
     * @brief Eddystone Beacon GATT Configuration Service + EID/eTLM sample application main file.
     *
     * This file contains the source code for an Eddystone
     * Beacon GATT Configuration Service + EID/eTLM sample application.
     */
    
    #include <stdbool.h>
    #include <stdint.h>
    #include <string.h>
    #include "bsp.h"
    #include "ble_conn_params.h"
    #include "ble_advertising.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "app_timer.h"
    #include "es_app_config.h"
    #include "app_scheduler.h"
    #include "nrf_ble_es.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_pwr_mgmt.h"
    
    #define DEAD_BEEF                       0xDEADBEEF          //!< Value used as error code on stack dump, can be used to identify stack location on stack unwind.
    #define NON_CONNECTABLE_ADV_LED_PIN     BSP_BOARD_LED_0     //!< Toggles when non-connectable advertisement is sent.
    #define CONNECTED_LED_PIN               BSP_BOARD_LED_1     //!< Is on when device has connected.
    #define CONNECTABLE_ADV_LED_PIN         BSP_BOARD_LED_2     //!< Is on when device is advertising connectable advertisements.
    
    /**@brief   Priority of the application BLE event handler.
     * @note    You shouldn't need to modify this value.
     */
    #define APP_BLE_OBSERVER_PRIO 3
    
    
    NRF_BLE_GATT_DEF(m_gatt); //!< GATT module instance.
    
    /**@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 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)
    {
        ret_code_t err_code;
    
        switch (p_ble_evt->header.evt_id)
        {
            case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
                // Pairing not supported
                err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.common_evt.conn_handle,
                                                       BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP,
                                                       NULL,
                                                       NULL);
                APP_ERROR_CHECK(err_code);
                break;
    
            case BLE_GATTS_EVT_SYS_ATTR_MISSING:
                // No system attributes have been stored.
                err_code = sd_ble_gatts_sys_attr_set(p_ble_evt->evt.common_evt.conn_handle, NULL, 0, 0);
                APP_ERROR_CHECK(err_code);
                break;
    
            case BLE_GAP_EVT_CONNECTED:
                bsp_board_led_on(CONNECTED_LED_PIN);
                bsp_board_led_off(CONNECTABLE_ADV_LED_PIN);
                break;
    
            case BLE_GAP_EVT_DISCONNECTED:
                // LED indication will be changed when advertising starts.
                break;
    
            case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
            {
                ble_gap_phys_t const phys =
                {
                    .rx_phys = BLE_GAP_PHY_AUTO,
                    .tx_phys = BLE_GAP_PHY_AUTO,
                };
                err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
                APP_ERROR_CHECK(err_code);
            } break;
    
            default:
                // No implementation needed.
                break;
        }
    }
    
    
    /**@brief Function for the GAP initialization.
    *
    * @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
    *          the device. It also sets the permissions and appearance.
    */
    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;
       uint8_t                 device_name[] = APP_DEVICE_NAME;
    
       BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
    
       err_code = sd_ble_gap_device_name_set(&sec_mode,
                                             device_name,
                                             strlen((const char *)device_name));
       APP_ERROR_CHECK(err_code);
    
       memset(&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(&gap_conn_params);
    
       APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing the GATT module.
     */
    static void gatt_init(void)
    {
        ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing the 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);
    
        uint32_t ram_start = 0;
        err_code = nrf_sdh_ble_app_ram_start_get(&ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Overwrite some of the default configurations for the BLE stack.
        ble_cfg_t ble_cfg;
    
        // Configure the maximum number of connections.
        memset(&ble_cfg, 0, sizeof(ble_cfg));
        ble_cfg.gap_cfg.role_count_cfg.periph_role_count  = 1;
    #if !defined (S112)
        ble_cfg.gap_cfg.role_count_cfg.central_role_count = 0;
        ble_cfg.gap_cfg.role_count_cfg.central_sec_count  = 0;
    #endif // !defined (S112)
        err_code = sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &ble_cfg, ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Enable BLE stack.
        err_code = nrf_sdh_ble_enable(&ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Register a handler for BLE events.
        NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
    }
    
    
    /**@brief Function for initializing the Connection Parameters module.
     */
    static void conn_params_init(void)
    {
        ret_code_t             err_code;
        ble_conn_params_init_t cp_init;
    
        memset(&cp_init, 0, sizeof(cp_init));
    
        cp_init.p_conn_params                  = NULL;
        cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
        cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
        cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
        cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
        cp_init.disconnect_on_fail             = false;
    
        err_code = ble_conn_params_init(&cp_init);
        APP_ERROR_CHECK(err_code);
    
    }
    
    
    /**@brief Function for initializing power management.
     */
    static void power_management_init(void)
    {
        ret_code_t err_code;
        err_code = nrf_pwr_mgmt_init();
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling the idle state (main loop).
     *
     * @details If there is no pending log operation, then sleep until next the next event occurs.
     */
    static void idle_state_handle(void)
    {
        app_sched_execute();
        nrf_pwr_mgmt_run();
    }
    
    
    /**@brief Function for handling Eddystone events.
     *
     * @param[in] evt Eddystone event to handle.
     */
    static void on_es_evt(nrf_ble_es_evt_t evt)
    {
        switch (evt)
        {
            case NRF_BLE_ES_EVT_ADVERTISEMENT_SENT:
                bsp_board_led_invert(NON_CONNECTABLE_ADV_LED_PIN);
                break;
    
            case NRF_BLE_ES_EVT_CONNECTABLE_ADV_STARTED:
                bsp_board_led_on(CONNECTABLE_ADV_LED_PIN);
                break;
    
            case NRF_BLE_ES_EVT_CONNECTABLE_ADV_STOPPED:
                bsp_board_led_off(CONNECTABLE_ADV_LED_PIN);
                break;
    
            default:
                break;
        }
    }
    
    
    /**@brief Function for handling button events from app_button IRQ
     *
     * @param[in] pin_no        Pin of the button for which an event has occured
     * @param[in] button_action Press or Release
     */
    static void button_evt_handler(uint8_t pin_no, uint8_t button_action)
    {
        if (button_action == APP_BUTTON_PUSH && pin_no == BUTTON_1)
        {
            nrf_ble_es_on_start_connectable_advertising();
        }
    }
    
    
    /**
     * @brief Function for initializing the registation button
     *
     * @retval Values returned by @ref app_button_init
     * @retval Values returned by @ref app_button_enable
     */
    static void button_init(void)
    {
        ret_code_t              err_code;
        const uint8_t           buttons_cnt  = 1;
        static app_button_cfg_t buttons_cfgs =
        {
            .pin_no         = BUTTON_REGISTRATION,
            .active_state   = APP_BUTTON_ACTIVE_LOW,
            .pull_cfg       = NRF_GPIO_PIN_PULLUP,
            .button_handler = button_evt_handler
        };
    
        err_code = app_button_init(&buttons_cfgs, buttons_cnt, APP_TIMER_TICKS(100));
        APP_ERROR_CHECK(err_code);
    
        err_code = app_button_enable();
        APP_ERROR_CHECK(err_code);
    }
    
    
    static void timers_init(void)
    {
        ret_code_t err_code = app_timer_init();
        APP_ERROR_CHECK(err_code);
    }
    
    
    static void leds_init(void)
    {
        ret_code_t err_code = bsp_init(BSP_INIT_LEDS, NULL);
        APP_ERROR_CHECK(err_code);
    }
    
    
    static void scheduler_init(void)
    {
        APP_SCHED_INIT(SCHED_MAX_EVENT_DATA_SIZE, SCHED_QUEUE_SIZE);
    }
    
    // added pwm stuff
    #include "app_pwm.h"
    #include "nrf_delay.h"
    APP_PWM_INSTANCE(PWM1,1);                   // Create the instance "PWM1" using TIMER1.
    static volatile bool ready_flag;            // A flag indicating PWM status.
    
    void pwm_ready_callback(uint32_t pwm_id)    // PWM callback function
    {
        ready_flag = true;
    }
    
    
    /**
     * @brief Function for application main entry.
     */
    int main(void)
    {
        // Initialize.
        timers_init();
        leds_init();
        button_init();
        scheduler_init();
        power_management_init();
        ble_stack_init();
        gap_params_init();
        gatt_init();
        conn_params_init();
        nrf_ble_es_init(on_es_evt);
    
    
        ret_code_t err_code;
    
        /* 2-channel PWM, 200Hz, output on DK LED pins. */
        app_pwm_config_t pwm1_cfg = APP_PWM_DEFAULT_CONFIG_2CH(256, 30, 31);
    
        /* Switch the polarity of the second channel. */
        pwm1_cfg.pin_polarity[1] = APP_PWM_POLARITY_ACTIVE_HIGH;
    
        /* Initialize and enable PWM. */
        err_code = app_pwm_init(&PWM1,&pwm1_cfg,pwm_ready_callback);
        APP_ERROR_CHECK(err_code);
        app_pwm_enable(&PWM1);
    
        /* Set the duty cycle - keep trying until PWM is ready... */
        while (app_pwm_channel_duty_set(&PWM1, 0, 50) == NRF_ERROR_BUSY);
    
    	uint32_t value;
        // Enter main loop.
        for (;;)
        {
            idle_state_handle();
        }
    }

    when looking at the clock edges one sees the usual jitter and then, roughly in correspondence of the beacon activity, an additional "skip" with length multiple of 1CLK @ 16MHz. the pulses are always stretched and never shortened. Once again, commenting out the instruction "nrf_ble_es_init(on_es_evt);" from the main eliminates the described "skipping"

    When I say "jitter" or "skipping" I am not talking about the normal clock jitter (which is also quite severe), I am talking about time stretches that are an integer multiple of a 16MHz clock cycle, which can be clearly seen "on top" of the usual clock jitter.

    Can anyone please try to reproduce the issue? It could be that my board is faulty...

    Thank you.

  • As a follow up, since I happened to have a spare nRF51-DK I ran test number 3 on that as well and the problem occurs there too and, I have the feeling, even more pronounced than with the nRF52. Again, commenting out the softdevice initialization eliminated the issue.

  • Hi

    it could be that you're seeing the NRF52832 switching from the internal HFCLK source to the external high frequency crystal oscillator.

    could you try to request the HFCLK by calling sd_clock_hfclk_request() in main() after you have called ble_stack_init(). The  external high frequency crystal oscillator should now be running all the time. Can you test and check if you observe the same behavior as before or if this resolves the issue?

    Best regards

    Bjørn

  • I confirm that the proposed approach solves the problem completely. A huge thank you for your swift and spot-on answer

Related