本帖最后由 e芯凌 于 2019-11-10 22:07 编辑
首先得要知道开发板的两个LED灯连接的IO口:根据原理图两个LED分别接的是PE5和PB5.
整体操作思路:
1:使能IO口时钟。调用函数RCC_APB2PeriphColckCmd();不同的IO组,调用的时钟使能函数不一样。 2:初始化IO口模式。调用函数GPIO_Init(); :3:操作IO口,输出高低电平。 GPIO_SetBits(); GPIO_ResetBits();
各个代码块详解: 1个初始化函数:
void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);
作用:初始化一个或者多个IO口(同一组)的工作方式和速度。
该函数主要是操作GPIO_CRL(CRH)寄存器,在上拉或者下拉的时候有设置BSRR或者BRR寄存器 GPIOx: GPIOA~GPIOG typedef struct { uint16_t GPIO_Pin; //指定要初始化的IO口 GPIOSpeed_TypeDef GPIO_Speed; //设置IO口输出速度 GPIOMode_TypeDef GPIO_Mode; //设置工作模式:8种中的一个 }GPIO_InitTypeDef; 注意:外设(包括GPIO)在使用之前,几乎都要先使能对应的时钟。
GPIO_Init函数初始化样例:
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;//LED0-->PB.5 端口配置
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); //根据设定参数初始化GPIOB.5
void GPIO_SetBits(GPIO_TypeDef* GPIOx,uint16_t GPIO_Pin);
作用:设置某个IO口输出为高电平(1)。实际操作BSRR寄存器
void GPIO_ResetBits(GPIO_TypeDef* GPIOx,uint16_t GPIO_Pin);
作用:设置某个IO口输出为低电平(0)。实际操作的BRR寄存器。
最后的编辑完成的代码:
led.h头文件里的代码
- #ifndef __LED_H
- #define __LED_H
- void LED_Init(void);
- #endif
复制代码 led.c源文件里的代码
- #include "led.h"
- #include "stm32f10x.h"
- void LED_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOE,ENABLE);//使能GPIOA和GPIOB
- //| 既是逻辑运算符也是位运算符;|| 只是逻辑运算符
- //| 不具有短路效果,即左边true,右边还会执行;
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
- GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
- GPIO_Init(GPIOB,&GPIO_InitStructure);
- GPIO_SetBits(GPIOB,GPIO_Pin_5);
-
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
- GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
- GPIO_Init(GPIOE,&GPIO_InitStructure);
- GPIO_SetBits(GPIOE,GPIO_Pin_5);
- }
复制代码 main.c里的代码
- #include "stm32f10x.h"
- #include "led.h"
- #include "delay.h"
- int main()
- {
- delay_init();//要先初始化,不然会出错
- LED_Init();
- while(1)
- {
- GPIO_SetBits(GPIOB,GPIO_Pin_5); //输出高电平
- GPIO_SetBits(GPIOE,GPIO_Pin_5);
- delay_ms(500);
- GPIO_ResetBits(GPIOB,GPIO_Pin_5); //输出低电平
- GPIO_ResetBits(GPIOE,GPIO_Pin_5);
- delay_ms(500);
- }
-
- }
复制代码
|