cancel
Showing results for 
Search instead for 
Did you mean: 

A Variable Control of Timer Period

AE104
Senior

Hello,

I want to control a timer period with a variable. The variable value is correct because I monitored it in the watch window. But the variable was not working in the timer settings. Because when I write a digit in there, it works. Is there any suggestions about this issue?

Thank you,

volatile int AmpModFreqCalculation;
 
int main(void)
{
....
 while (1)
  {
        HAL_StatusTypeDef usart2_status;
	usart2_status = HAL_UART_Receive(&huart2, Rx_dmux_mux, 98, 200000); //receive 86 bytes (0-86) of data from MATLAB, 60 sec timeout
...
ModulationFreq = (Rx_dmux_mux[65]<<8) | Rx_dmux_mux[64];
...
AmpModFreqCalculation = round((1000000 / (ModulationFreq * 128)));
}}
 
static void MX_TIM6_Init(void)
{
 
  /* USER CODE BEGIN TIM6_Init 0 */
 
  /* USER CODE END TIM6_Init 0 */
 
  TIM_MasterConfigTypeDef sMasterConfig = {0};
 
  /* USER CODE BEGIN TIM6_Init 1 */
 
  /* USER CODE END TIM6_Init 1 */
  htim6.Instance = TIM6;
  htim6.Init.Prescaler = 96-1;
  htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim6.Init.Period = AmpModFreqCalculation - 1; // (ModulationFreq * 128) = TriggerFreq; (Period) = (1.000.000 Hz / (ModulationFreq * 128)) - 1
  htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim6) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim6, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM6_Init 2 */
 
  /* USER CODE END TIM6_Init 2 */
 
}
 
 

1 ACCEPTED SOLUTION

Accepted Solutions

Do you call MX_TIM6_Init() after changing AmpModFreqCalculation in main()?

Nonetheless, this is not how are you supposed to change the timer's period. Set directly TIM6->ARR to the new value. There may be some Cube/HAL function/macro to do that - I don't know, I don't use Cube - but it will do exactly just this.

I also recommend to change this line to enable ARR preload.

htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;

JW

View solution in original post

2 REPLIES 2

Do you call MX_TIM6_Init() after changing AmpModFreqCalculation in main()?

Nonetheless, this is not how are you supposed to change the timer's period. Set directly TIM6->ARR to the new value. There may be some Cube/HAL function/macro to do that - I don't know, I don't use Cube - but it will do exactly just this.

I also recommend to change this line to enable ARR preload.

htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;

JW

Thank you very much for your quick response! When I place "MX_TIM6_Init() after changing AmpModFreqCalculation", it worked.

@Community member​