How to use HAL_GPIO_Init() in modern C++ (STM32)
In modern C++, you can directly initialize structs like a GPIO_InitTypeDef
, making the code much prettier and less prone to errors. The following example configures PA8
of a STM32 in alternate function 1 mode (TIM1
output).
GPIO_InitTypeDef pinInit = {
.Pin = GPIO_PIN_8,
.Mode = GPIO_MODE_AF_PP,
.Pull = GPIO_NOPULL,
.Speed = GPIO_SPEED_FREQ_VERY_HIGH,
.Alternate = GPIO_AF1_TIM1
};
HAL_GPIO_Init(GPIOA, &pinInit);
As opposed to the old, much more verbose way of doing that:
GPIO_InitTypeDef pinInit;
pinInit.Pin = GPIO_PIN_8;
pinInit.Mode = GPIO_MODE_AF_PP;
pinInit.Pull = GPIO_NOPULL;
pinInit.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
pinInit.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init(GPIOA, &pinInit);