STM32 LED Pulse
Jump to navigation
Jump to search
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.
In this example, the timer clock is 100 MHz.
And the User Variables LED_PRE and LED_CNT are configured like this: