2024-08-10 07:29 AM
Hi!
I am new to Microcontrollers so the question could be not really exciting but I think it could help me to understand how clock and timers work.
I want to toggle the LD2 every 1 sec through a TIMER.
I have set up the SysClock at 2MHz and a TIMER running at 1KHz counting 1 sec, through pre-scaler(2000) and the Auto-reloded register (1000).
I have started the timer before the while(1) loop and I want to toggle the LED2 every 1 sec in the loop so I have used the following code lines. It seems to not working correctly. Why ? Maybe because the while condition is not performed at every clock tick, right ?
-------------------------- CODE------------------
HAL_TIM_Base_Start(&htim2);
while (1)
{
while(__HAL_TIM_GET_COUNTER(&htim2) == 0 ) HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
-------------------------------------------------------
Every suggestion will be appreciated!
Thank a lot.
2024-08-10 07:39 AM
> while(__HAL_TIM_GET_COUNTER(&htim2) == 0 ) HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
As TIMx_PSC is set to 2000, it takes 2000 system clocks to increment TIMx_CNT by one. One iteration of the above cycle may take say around 10-100 cycles (depending on level of optimization you are using), so the processor will "see" TIMx_CNT == 0 during several iterations of that cycle, i.e. it will very rapidly toggle the pin 200..20 times.
Instead of checking TIMx_CNT, should check the Update flag i.e. TIMx_SR.UIF, and if set, toggle the LED and clear that flag.
JW
2024-08-10 07:42 AM - edited 2024-08-10 07:44 AM
Hello @Gatsby and welcome to the ST Community :smiling_face_with_smiling_eyes:.
As a start, you may want to take a look at this example. With the details on the readme file, you will understand how it works to configure a Timer to toggle a Led each second. You can also take a look at the main.c file, the comments on the code should be really helpful.
The example is for an STM32L010RB Nucleo but you can fund it for all our board and you can migrate it to other MCUs.
Also, you can refer to this article to understand how it works.
Ciao.
STTwo-32
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.