Difference between revisions of "STM32 LED Pulse"

From Stm32World Wiki
Jump to navigation Jump to search
Line 19: Line 19:
 
It should be equally obvious why this is a really piss poor idea.  The function will block for half a second, leaving the processor unable to do anything else for that period.
 
It should be equally obvious why this is a really piss poor idea.  The function will block for half a second, leaving the processor unable to do anything else for that period.
  
A '''much''' better idea.
+
A '''much''' better idea would be to use a timer (of which most [[stm32]] processors have quite a lot) to handle the delay.
 +
 
 +
First, let us configure a timer for this use.
 +
 
 +
[[File:One shot timer.png|400px]]
 +
 
 +
In this example, the timer clock is 100 MHz.
 +
 
 +
[[File:Timer clock.png|400px]]
 +
 
 +
And the User Variables LED_PRE and LED_CNT are configured like this:
 +
 
 +
[[File:User Constants.png|400px]]

Revision as of 04:15, 23 March 2021

Imagine you had the requirement to turn on a LED for a specific length of time at the press of a button.

Obviously, responding to a button press could be easily handled by an external interrupt, so one could come up with something like:

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
    if (GPIO_Pin == BTN_Pin) // If the button
    {

        HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET); // Switch LED ON
        HAL_Delay(500); // Wait 500 ms
        HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET); // Switch LED OFF

    }
}

It should be equally obvious why this is a really piss poor idea. The function will block for half a second, leaving the processor unable to do anything else for that period.

A much better idea would be to use a timer (of which most stm32 processors have quite a lot) to handle the delay.

First, let us configure a timer for this use.

One shot timer.png

In this example, the timer clock is 100 MHz.

Timer clock.png

And the User Variables LED_PRE and LED_CNT are configured like this:

User Constants.png