Language: EN

esp32-cambiar-frecuencia-procesador

How to Change CPU Frequency on ESP32

It is possible to vary the operating frequency of the CPU on the ESP32 in order to reduce power 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 no longer being accurate.

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 power consumption of your project.

How to Vary the CPU Frequency of the ESP32

As 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 of this function, it can also accept 80, 160, or 240 as valid inputs.

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

uint32_t getXtalFrequencyMhz(); // In MHz

After making a change in the CPU clock frequency, you can verify the value of the CPU clock frequency 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 power optimization
  setCpuFrequencyMhz(80);

  // Print the frequency of the XTAL crystal
  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() {
  // nothing here in this example
}