DWT CYCCNT is not working

Hi,

I'm triying to use the DWT->CYCCNT in a low level manner. But it seems to now work and I don't really understand why. I'm using the nRF52840 DK and the program looks something like this:

#define TX_PIN NRF_GPIO_PIN_MAP(0, 6)
#define RX_PIN NRF_GPIO_PIN_MAP(0, 8)
#define RTS_PIN NRF_GPIO_PIN_MAP(0, 5)
#define CTS_PIN NRF_GPIO_PIN_MAP(0, 7)

#ifndef NRFX_DELAY_MS
    #define NRFX_DELAY_MS(_ms) NRFX_DELAY_US(_ms * 1000)
#endif

static const nrfx_uart_t UART0 = NRFX_UART_INSTANCE(0);

int _write(int handle, char *data, int size ) 
{
    (void)handle;
    nrfx_uart_tx(&UART0, data, size);
    return size;
}

static void on_clock_event(nrfx_clock_evt_type_t event)
{
    (void)event;
}

/** Read cycle counter register */
uint32_t dwt_cyccnt_get(void)
{
    return DWT->CYCCNT;
}

/** Reset cycle counter */
void dwt_reset(void) {
    DWT->CYCCNT = 0;
}

/** Enable cycle counter */
void dwt_enable(void) {
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}

/** Disable cycle counter */
void dwt_disable(void) {
    DWT->CTRL &= ~DWT_CTRL_CYCCNTENA_Msk;
}

/** TRCENA: Enable trace and debug block DEMCR (Debug Exception and Monitor Control Register */
void dwt_init(void) {
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
}

static inline void busy_loop(void) {
    volatile size_t foo = 0;
    for (size_t i = 0; i < (UINT32_MAX / 128); i++)
    {
        foo += i;
    }
}

int main()
{
    nrfx_uart_config_t uart_cfg = NRFX_UART_DEFAULT_CONFIG(TX_PIN, RX_PIN);
    uart_cfg.pselcts = CTS_PIN;
    uart_cfg.pselrts = RTS_PIN;

    if (NRFX_SUCCESS == nrfx_uart_init(&UART0, &uart_cfg, NULL)
        && NRFX_SUCCESS == nrfx_clock_init(on_clock_event))
    {
        nrfx_clock_start(NRF_CLOCK_DOMAIN_LFCLK);
        printf("enter\n");

        for (size_t i = 0; i < 3; i++)
        {
            printf("--- ---\n");
            dwt_reset();

            dwt_enable();
                busy_loop();
            dwt_disable();

            printf("%lu\n", dwt_cyccnt_get());
            dwt_reset(); // this does not work at all :(
            printf("%lu\n", dwt_cyccnt_get());
        }

        printf("exit\n");
    }

    while (true)
    {
        __WFE();
    }

    return 0;
}

Related