引言
在STC51的学习中, 程序代码往往是采用寄存器编程来编写的, 而在STM32的学习中,代码往往采用固件库编程来编写。
固件库编程是在寄存器编程的基础上升级而来的一种易于学习和开发的编程方式,是我们学习 STM32 编程的时候需要重点掌握的一种编程方法。
1. 硬件电路
打开 .\2-开发板原理图\野火_F407霸天虎 _原理图_V2.0.pdf
在第10页可以看到LED部分的原理图, 如下:
可以看到, 开发板上的小灯是由3个LED组成的。 红、绿、蓝三色小灯分别对应着STM32的PF6、PF7、PF8引脚,只要我们控制 GPIO 引脚的电平输出状态,即可控制 LED 灯的亮灭。
2. 建立工程
套用野火新建固件库的模板, 完成初始工程的建立。
之后我们在“USER”文件夹中新建“LED”文件夹, 再在“LED”文件夹下建立“bsp_led.c”及“bsp_led.h”文件, “LED”文件夹下的库不属于STM32标准库的内容, 是我们根据自己的需要自己编写的。
打开Keil, 我们将“bsp_led.c”文件添加到工程中的USER中去,再在“Options for Target”中把“bsp_led.h”的路径添加进去,这样就不用在USER中添加“bsp_led.h”了。
3. 编写代码
/*********************** bsp_led.h程序源代码 *************************/
#ifndef _BSP_LED_H
#define _BSP_LED_H
#include "stm32f4xx.h"
/* Define the Pin */
#define LED1_PIN GPIO_Pin_6
void LED_GPIO_Config(void);
#endif /* _BSP_LED_H */
/*********************** bsp_led.c程序源代码 *************************/
#include "bsp_led.h"
void LED_GPIO_Config(void)
{
/* Step 1: Enable the GPIO clock */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
/* Step 2: Define the GPIO initialization structure*/
GPIO_InitTypeDef GPIO_InitStruct;
/* Step 3: Configure the members of GPIO initialize structure */
GPIO_InitStruct.GPIO_Pin = LED1_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Low_Speed;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
/*Step 4: Invoke the GPIO initialization function to write the parameters of the structure members to the register*/
GPIO_Init(GPIOF, &GPIO_InitStruct);
}
/************************** main.c程序源代码 **************************/
#include "stm32f4xx.h"
#include "bsp_led.h"
void Delay(uint32_t cnt);
int main(void)
{
LED_GPIO_Config();
while (1)
{
GPIO_ResetBits(GPIOF, LED1_PIN); // Set the pin to zero.
Delay(0xFFFFFF);
GPIO_SetBits(GPIOF, LED1_PIN);
Delay(0xFFFFFF);
}
}
/* simple delay function */
void Delay(uint32_t cnt)
{
for(; cnt!=0; cnt--);
}
将程序下载到开发板当中, 我们可以看到小灯不断的在闪烁。
至此,我们的小灯就被点亮啦。