Page 1 of 1

Determining the current APB_CLK frequency

Posted: Mon Apr 17, 2017 12:54 pm
by akdogan
Hi,

Timers are clocked by APB_CLK, and the technical reference manual says that APB_CLK is derived by the CPU_CLK source, and gives a table about the relation. What is the proper way of determining the APB_CLK frequency on the fly? It looks like, though I am not sure, the APB_CLK is ticking with 40 MHz after deep sleep when the deep sleep stub is running, but than it is changing to 80 MHz. I would like to determine this on the fly in order to get reliable timing counts in seconds from the timers.

Best.

Re: Determining the current APB_CLK frequency

Posted: Mon Apr 17, 2017 1:04 pm
by ESP_igrr
Whenever software changes APB frequency, it stores the new value into RTC_APB_FREQ_REG (that's one of the general purpose retention registers). There is a function which gets APB frequency value from this register in rtc_clk.c:

Code: Select all

static uint32_t reg_val_to_clk_val(uint32_t val) {
    return val & UINT16_MAX;
}

uint32_t rtc_clk_apb_freq_get()
{
    return reg_val_to_clk_val(READ_PERI_REG(RTC_APB_FREQ_REG)) << 12;
}
In the deep sleep wake stub, you can probably access RTC_APB_FREQ_REG directly or just assume the 40 MHz frequency.

Re: Determining the current APB_CLK frequency

Posted: Mon Apr 17, 2017 7:52 pm
by akdogan
Thank you. It worked. Though, I couldn't find RTC_APB_FREQ_REG definition in the SDK files, found it somewhere in a git repo which defines it as RTC_CNTL_STORE5_REG. So,

Code: Select all

uint32_t apb_freq = ((READ_PERI_REG(RTC_CNTL_STORE5_REG)) & UINT16_MAX) << 12;
yielded the answer. It turns out that the APB is ticking with 39997440 Hz in the deep sleep stub, vs 79998976 Hz in the user code. That is
64 usec and 13 usec difference every second if 40 MHz and 80 MHz is assumed. I didn't check the specs but 13-64 ppm may be important.

I assumed the correct values are 39997440 Hz and 79998976 Hz, and used the above code line directly where ever they are needed.

Kind regards.

Re: Determining the current APB_CLK frequency

Posted: Mon Apr 17, 2017 10:49 pm
by WiFive

Re: Determining the current APB_CLK frequency

Posted: Tue Apr 18, 2017 1:13 am
by ESP_igrr
The correct values are 40 (actually, the crystal frequency) and 80MHz, the values read from the store register loose precision due to rounding. I suppose that rounding to the nearest MHz is the best approach since we can't change the format used to store this value.

Re: Determining the current APB_CLK frequency

Posted: Sun Oct 15, 2023 6:35 pm
by evidals
To me worked:
  1. #include "soc/rtc.h"
  2. uint32_t this_apb_freq = rtc_clk_apb_freq_get();