一、总览
HAL层里的库函数和大家熟悉的stm32lib基本上是一致的。一般来说一个cpu外设的操作函数分成两部分,分别是init和operation。
来看一个cube里的例子:
static GPIO_InitTypeDef GPIO_InitStruct;
int main(void)
{
/* This sample code shows how to use GPIO HAL API to toggle LED2 IO
in an infinite loop. */
/* STM32F103xB HAL library initialization:
- Configure the Flash prefetch
- Systick timer is configured by default as source of time base, but user
can eventually implement his proper time base source (a general purpose
timer for example or other time source), keeping in mind that Time base
duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
handled in milliseconds basis.
- Set NVIC Group Priority to 4
- Low Level Initialization
*/
HAL_Init();
/* Configure the system clock to 64 MHz */
SystemClock_Config();
/* -1- Enable GPIO Clock (to be able to program the configuration registers) */
LED2_GPIO_CLK_ENABLE();
/* -2- Configure IO in output push-pull mode to drive external LEDs */
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_InitStruct.Pin = LED2_PIN;
HAL_GPIO_Init(LED2_GPIO_PORT, &GPIO_InitStruct);
/* -3- Toggle IO in an infinite loop */
while (1)
{
HAL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN);
/* Insert delay 100 ms */
HAL_Delay(100);
}
}
注释里的内容说明了之前一篇文章里的提到的HAL_INIT()函数的作用。
在使用GPIO前要先初始化GPIO的时钟,因为许多外设都被设计成时序逻辑电路,所以必须要为外设提供时钟源,否则外设的电路状态就不会改变。
GPIO时钟源设定后&