cancel
Showing results for 
Search instead for 
Did you mean: 

How to change system clock during run time?

GunkutA
Senior

Hello, for decreasing the power coonsumption I want to change HSI to LSI. This is the HSI clock configurations for 72 Mhz:

void SystemClock_Config(void)
{
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
	RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
 
	/** Initializes the CPU, AHB and APB busses clocks
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
	{
		Error_Handler();
	}
	/** Initializes the CPU, AHB and APB busses clocks
	 */
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
			|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
 
	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
	{
		Error_Handler();
	}
	PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC|RCC_PERIPHCLK_USB;
	PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
	PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
	if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
	{
		Error_Handler();
	}
}

And I want to enable LSI then disable the HSI as follows:

	//Turn on the LSI
	RCC->CSR|=RCC_CSR_LSION;
	//Turn off the HSI
	RCC->CR&=~(RCC_CR_HSION);

Is it a correct way to change the system clock to 40 kHz? Or do I any others things that must be done? Any I am not sure from the order. Should I first disable HSI then turn on the LSI or should I first turn on the LSI then turn off the HSI?

4 REPLIES 4

Which STM32? Not all models allow to use LSI as system clock.

Generally, you

  • enable the new clock
  • wait until stable
  • switch the system clock source in RCC_CFGR.SW
  • wait until the switch is accomplished (by polling RCC_CFGR.SWS)
  • then you can switch off the original clock

Meantime, you might want to change settings of those peripherals which are clock-dependent, e.g. UART baudrate.

Read the RCC chapter in RM.

JW

Thank you, that is STM32F10x

Yes it does not let LSI being used as the system clock, unfortunately.

Uwe Bonnes
Principal III

You must also care for wait states and maybe other settings, like voltage regulators.