m5stack / M5Core2

M5Core2 Arduino Library
MIT License
267 stars 117 forks source link

Changing Clock Speeds #130

Closed JasonPittenger closed 1 year ago

JasonPittenger commented 1 year ago

Can you add support for changing the clock speed from the default 240Mhz?

In my use case, I have an idle state where I have very low processing requirements. Once the user interacts with the device, I need full processing power again. I would like to reduce power consumption during that idle state. I am already using light sleep, but I have to periodically wake up to check for user input. I'd like that wake up period to be run at a lower clock speed.

It would be ideal if this could be done independently on each core.

capedra commented 1 year ago

@JasonPittenger Have you tried something like this:

uint32_t currentCPUspeed = ESP.getCpuFreqMHz();
Serial.print("Current CPU speed is ");
Serial.print(currentCPUspeed);
Serial.println(" MHz");
uint32_t lowerCPUspeed = 160;
if (setCpuFrequencyMhz(lowerCPUspeed)) {
  currentCPUspeed = ESP.getCpuFreqMHz();
  Serial.print("CPU speed was changed to ");
  Serial.print(currentCPUspeed);
  Serial.println(" MHz");
} else {
  Serial.print("CPU speed could not be changed to ");
  Serial.print(lowerCPUspeed);
  Serial.println(" MHz");
}
lowerCPUspeed = 80;
if (setCpuFrequencyMhz(lowerCPUspeed)) {
  currentCPUspeed = ESP.getCpuFreqMHz();
  Serial.print("CPU speed was changed to ");
  Serial.print(currentCPUspeed);
  Serial.println(" MHz");
} else {
  Serial.print("CPU speed could not be changed to ");
  Serial.print(lowerCPUspeed);
  Serial.println(" MHz");
}
JasonPittenger commented 1 year ago

Thanks! That's what I was looking for!

It looks like the serial baud rate calculation can be incorrect below 80 MHz. There's a workaround that I found at this link. https://github.com/espressif/arduino-esp32/issues/6032

I just tried a sketch changing the clock speed from 240,160,80,40,26,24,20,13,12,10,5,4,2,1. At 40 MHz, I had to use 2 x 115200, but at 20 MHz and 10 MHz, it worked using 115200. Trying 26,24,13,12,5,4,2 or 1 MHz all resulted in a clock speed of 10MHz. Serial.begin had to be called after every change of CPU speed.

It also appears that this function changes the clock speed on both cores at the same time. I saw some information about how to change just one core, but that didn't work for me.

capedra commented 1 year ago

@JasonPittenger You're welcome! I just made some changes on the code above. You should also consider the fact that the setCpuFrequencyMhz function takes the following frequencies as valid values: 240, 160, 80 <<< For all XTAL types 40, 20, 10 <<< For 40MHz XTAL 26, 13 <<< For 26MHz XTAL 24, 12 <<< For 24MHz XTAL

JasonPittenger commented 1 year ago

The m5 support information only lists 240, 160, 80 as valid values. It does in fact support 40, 20, 10 as you pointed out!