cancel
Showing results for 
Search instead for 
Did you mean: 

Problems with generating specific frequency of PWM using TIMER.

PBiał.1
Associate II

Hello,

I'm currently preparing a program for steering a telescope at my University. Everything was working fine, until I started to have a problems with generating a specific frequency for one an axis. Generally, the problem is that I cannot set a specific counter period value in the code that would be updated. Surprisingly, everything works correctly in the same code fragment, when changing this value is inside the condition with the button (for speed corrections), but in the "else" condition, which is used to return the telescope to a given specific speed, for example 1065Hz, it no longer works. The change occurs only when I press the button or when I change the counter period value to a significantly different one, for example from 1000 to 500. Then I see on the oscilloscope that the frequency has doubled. When changing from 1000 to 900, nothing changes, it is still exactly 1000Hz. Below is a piece of code that I am unable to cope with. It really seems incredibly strange to me that I can set any counter period in the part where I press the "slewing HA+" and "slewing HA-" buttons and it actually affects the frequency change very accurately, and when it is below in else it is a huge change in this frequency. variable increases the frequency. Thank you for your help, if I need any more information, I will write back as soon as possible.

Best regards,

Paweł

2 REPLIES 2
Sarra.S
ST Employee

Hello @PBiał.1

Add some debugging statements to log the values of period_RA  whenever it is set to see if the value is being set correctly.

Try to stop the timer and PWM before re-initializing it with the new period value

void RA_engine(uint32_t period_RA){
    HAL_TIM_PWM_Stop(&htim4, TIM_CHANNEL_1);  // Stop PWM
    HAL_TIM_Base_Stop(&htim4);                // Stop the timer

    __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_1, period_RA / 2);
    htim4.Init.Period = period_RA;
    HAL_TIM_Base_Init(&htim4);                // Re-initialize the timer with the new period
    HAL_TIM_Base_Start(&htim4);               // Start the timer
    HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1); // Start PWM
}

 

To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.

Thank you for your answer, I will check if it helps.