Difference between revisions of "STM32 LED Pulse"

From Stm32World Wiki
Jump to navigation Jump to search
 
Line 1: Line 1:
 
[[Category:C]] [[Category:STM32 Development]] [[Category:STM32CubeMX]] [[Category:STM32CubeIde]] [[Category:Embedded]] [[Category:STM32]] {{metadesc|Pulse a LED using STM32}}
 
[[Category:C]] [[Category:STM32 Development]] [[Category:STM32CubeMX]] [[Category:STM32CubeIde]] [[Category:Embedded]] [[Category:STM32]] {{metadesc|Pulse a LED using STM32}}
xxx
+
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:
 +
 
 +
<pre>
 +
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
 +
 
 +
    }
 +
}
 +
</pre>
 +
 
 +
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.

Revision as of 05:07, 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.