Language: EN

esp32-cambiar-frecuencia-procesador

How to Change CPU Frequency on ESP32

On the ESP32, it is possible to vary the CPU operating frequency in order to reduce energy consumption.

By carefully adjusting the clock frequency according to your needs, you can achieve an optimal balance between performance and energy efficiency.

The process is quite simple and, in certain projects, it can provide better performance and energy efficiency for the ESP32.

However, changing the processor frequency is an advanced technique. You can expect all sorts of “weird things,” such as millis or delay becoming inaccurate.

So you should only use it if you are sure of what you are doing. Experiment with different frequencies and observe how it affects the performance and consumption of your project.

How to vary the CPU frequency of the ESP32

As I mentioned, it is quite simple to vary the CPU frequency of the ESP32 in the Arduino environment. The necessary code is defined in the esp32-hal-cpu.h library, which provides functions to manage the clock frequency.

// The function accepts the following frequencies as valid values:
// 240, 160, 80 <<< For all types of XTAL crystal
// 40, 20, 10 <<< For 40MHz XTAL
// 26, 13 <<< For 26MHz XTAL
// 24, 12 <<< For 24MHz XTAL
bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz);

As we can see in the documentation for this function, it can also accept 80, 160, or 240 as valid inputs.

But for the lower speeds, it depends on the crystal (XTAL) that we have. We can obtain the speed of our crystal with this function.

uint32_t getXtalFrequencyMhz(); // In MHz

After making a change to the CPU clock frequency, you can check the CPU clock frequency value by reading the return value of the following function.

uint32_t getCpuFrequencyMhz(); // In MHz

Code Example

Use the setCpuFrequencyMhz() function to set the desired clock frequency. You can use frequencies like 240, 160, 80 according to your needs. More options are possible depending on the crystal you have.

void setup() {
  Serial.begin(115200);

  // Set the CPU frequency to 80 MHz for consumption optimization
  setCpuFrequencyMhz(80);

  // Print the XTAL crystal frequency
  Serial.print("XTAL Crystal Frequency: ");
  Serial.print(getXtalFrequencyMhz());
  Serial.println(" MHz");

  // Print the CPU frequency
  Serial.print("CPU Frequency: ");
  Serial.print(getCpuFrequencyMhz());
  Serial.println(" MHz");

  // Print the APB bus frequency
  Serial.print("APB Bus Frequency: ");
  Serial.print(getApbFrequency());
  Serial.println(" Hz");
}

void loop() {
  // in this example nothing here
}