这里只介绍代码,具体的GPIO结构可学习野火的学习手册,这样就更清楚为什么是这样设置,而不是其它的。
代码点亮LED涉及的要点:
开启时钟(GPIO挂在APB2总线上)、定义结构体变量、设置工作模式
、选择端口、输出速度、初始化GPIO
led.c
#include "stm32f10x.h"
#include "led.h"
/**
led初始化:使能时钟、定义结构体变量、设置工作模式
、选择端口、输出速度、初始化GPIO
**/
void LED_Init(void)
{
//使能GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//GPIO结构体成员配置
GPIO_InitTypeDef GPIO_InitStructure;//定义结构体变量
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;//推挽输出模式
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_1;//输出端口A1
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//输出速度
GPIO_Init(GPIOA,&GPIO_InitStructure);//初始化GPIO
//端口默认电平
//GPIO_SetBits(GPIOA,GPIO_Pin_1);//A1高电平
}
led.h
其ifndef、define、endif 是为了防止重复编译。为了方便修改可将引脚、速度等进行封装在该文件中,如将led.c 中的GPIO_Pin_1
#ifndef _LED_H
#define _LED_H
void LED_Init(void);
//define GPIO_Pin_1 A1 //封装引脚,方便修改
#endif
main.c
#include "stm32f10x.h"
#include "led.h"
#include "Delay.h"//引入延时
int main(void)
{
LED_Init();//初始化LED
while(1)
{
//亮
GPIO_SetBits(GPIOA,GPIO_Pin_1);//A1高电平
Delay_ms(500);
//灭
GPIO_ResetBits(GPIOA,GPIO_Pin_1);//A1低电平
Delay_ms(500);
}
}
