Section 4_点亮第一个LED灯
1.LED模块硬件电路2.GPIO库函数介绍(1)GPIO外设的库文件:(2)GPIO常用库函数<1>初始化函数<2>设置管脚输出电平函数<3>读取管脚输入电平函数<4>读取管脚输出电平函数
(3)使能GPIO时钟函数
3.GPIO初始化步骤4.创建工程1.在APP---LED---两个文件led.h头文件led.c源文件
2.main.c3.源文件添加2个位置
1.LED模块硬件电路
2.GPIO库函数介绍
(1)GPIO外设的库文件:
stm32f4xx_gpio.c、
stm32f4xx_gpio.h
(2)GPIO常用库函数
<1>初始化函数
void GPIO_Init(GPIO_TypeDef
* GPIOx
,GPIO_InitTypeDef
* GPIO_InitStruct
)
功能:初始化一个或多个IO口(同一组端口)的工作模式、输出速度、输出类型、上下拉模式,即GPIO的4个配置寄存器。 初始化范例:
GPIO_InitTypeDef GPIO_InitStructure
;
GPIO_InitStructure
.GPIO_Mode
=GPIO_Mode_OUT
;
GPIO_InitStructure
.GPIO_Pin
=GPIO_Pin_9
;
GPIO_InitStructure
.GPIO_Speed
=GPIO_Speed_100MHz
;
GPIO_InitStructure
.GPIO_OType
=GPIO_OType_PP
;
GPIO_InitStructure
.GPIO_PuPd
=GPIO_PuPd_UP
;
GPIO_Init(GPIOF
,&GPIO_InitStructure
);
可以一次对多个管脚进行初始化,前提必须是它们的配置模式需一样。 比如:
GPIO_InitStructure
.GPIO_Pin
=GPIO_Pin_9
|GPIO_Pin_10
;
<2>设置管脚输出电平函数
void GPIO_SetBits(GPIO_TypeDef
* GPIOx
, uint16_t GPIO_Pin
);
功能:设置某个IO口为高电平(可同时设置同一端口的多个IO)。底层是通过配置BSRRL寄存器。
void GPIO_ResetBits(GPIO_TypeDef
* GPIOx
, uint16_t GPIO_Pin
);
功能:设置某个IO口为低电平(可同时设置同一端口的多个IO)。底层是通过配置BSRRH寄存器。
void GPIO_WriteBit(GPIO_TypeDef
* GPIOx
, uint16_t GPIO_Pin
, BitAction BitVal
);
void GPIO_Write(GPIO_TypeDef
* GPIOx
, uint16_t PortVal
);
功能:设置端口管脚输出电平,很少使用。
<3>读取管脚输入电平函数
uint8_t
GPIO_ReadInputDataBit(GPIO_TypeDef
* GPIOx
, uint16_t GPIO_Pin
);
功能:读取端口中的某个管脚输入电平。底层是通过读取IDR寄存器。
uint16_t
GPIO_ReadInputData(GPIO_TypeDef
* GPIOx
);
功能:读取某组端口的输入电平。底层是通过读取IDR寄存器。
<4>读取管脚输出电平函数
uint8_t
GPIO_ReadOutputDataBit(GPIO_TypeDef
* GPIOx
, uint16_t GPIO_Pin
);
功能:读取端口中的某个管脚输出电平。底层是通过读取ODR寄存器。
uint16_t
GPIO_ReadOutputData(GPIO_TypeDef
* GPIOx
);
功能:读取某组端口的输出电平。底层是通过读取ODR寄存器
(3)使能GPIO时钟函数
void RCC_AHB1PeriphClockCmd(uint32_t RCC_AHB1Periph
, FunctionalState NewState
);
不同的外设调用的时钟使能函数可能不一样 使能GPIO端口时钟:
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF
,ENABLE
);
3.GPIO初始化步骤
(1)使能对应的GPIO端口时钟 (2)初始化GPIO
4.创建工程
1.在APP—LED—两个文件
led.h头文件
#ifndef _led_H
#define _led_H
#include "stm32f4xx.h"
void LED_Init(void);
#endif
led.c源文件
#include "led.h"
void LED_Init()
{
GPIO_InitTypeDef GPIO_InitStructure
;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF
,ENABLE
);
GPIO_InitStructure
.GPIO_Mode
=GPIO_Mode_OUT
;
GPIO_InitStructure
.GPIO_Pin
=GPIO_Pin_10
|GPIO_Pin_9
;
GPIO_InitStructure
.GPIO_Speed
=GPIO_Speed_100MHz
;
GPIO_InitStructure
.GPIO_OType
=GPIO_OType_PP
;
GPIO_InitStructure
.GPIO_PuPd
=GPIO_PuPd_UP
;
GPIO_Init(GPIOF
,&GPIO_InitStructure
);
}
2.main.c
#include "stm32f4xx.h"
#include "led.h"
typedef unsigned int u32
;
void delay(u32 i
)
{
while(i
--);
}
int main()
{
LED_Init();
while(1)
{
GPIO_ResetBits(GPIOF
,GPIO_Pin_10
);
GPIO_SetBits(GPIOF
, GPIO_Pin_9
);
delay(0xFFFFFF);
GPIO_ResetBits(GPIOF
,GPIO_Pin_9
);
GPIO_SetBits(GPIOF
, GPIO_Pin_10
);
delay(0xFFFFFF);
}
}
3.源文件添加2个位置
注:在创建库函数工程模板的时候,在C/C++选项中需添加如下定义,否则会出现报警。
STM32F40_41xxx
,USE_STDPERIPH_DRIVER