一、GPIO有8种工作模式:
输入模式:
1、上拉输入(GPIO_Mode_IPU):默认读取为高电平
2、下拉输入(GPIO_Mode_IPD):默认读取为低电平
3、浮空输入(GPIO_Mode_IN_FLOATING):阻抗大,常用于I2C、USART接收端
4、模拟输入(GPIO_Mode_AIN):使用ADC外设时用
输出模式:
5、普通推挽输出(GPIO_Mode_Out_PP):用在电平为0和3.3V的场合
6、普通开漏输出(GPIO_Mode_Out_OD):用在电平不匹配场合(需要接上拉电阻)
7、复用推挽输出(GPIO_Mode_AF_PP):根据GPIO的复用功能选择
8、复用开漏输出(GPIO_Mode_AF_OD):根据GPIO的复用功能选择(需要接上拉电阻)
二、点灯流程
1、配置GPIO端口时钟
2、初始化GPIO目标引脚为推挽输出,这里控制LED的引脚为PB5,PB0,PB1分别对应RGB三原色,这里只演示了控制红色灯闪烁
3、编写测试程序,控制GPIO输出高、低电平
4、硬件方面需要将J73跳线帽连接
三、具体代码
mian.c:
#include "stm32f10x.h"
#include "led.h"
#include "Delay.h"
int main(void)
{
LED_Init();
while(1)
{
LED_R_TOGGLE();
Delay_ms(500);
}
}
led.c:
#include "led.h"
void LED_Init(void)
{
RCC_APB2PeriphClockCmd(GPIO_CLK, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_PIN;
GPIO_Init(GPIO_PORT,&GPIO_InitStructure);
GPIO_SetBits(GPIO_PORT, GPIO_PIN);//关灯
}
led.h:
#ifndef __LED_H
#define __LED_H
#include "stm32f10x.h"
//参数定义,这样使用宏定义的方法可以方便后期程序的移植,比如我换了一个开发板,我需要点灯的话就只需要改这里的宏定义
#define GPIO_CLK RCC_APB2Periph_GPIOB
#define GPIO_PIN GPIO_Pin_5
#define GPIO_PORT GPIOB
//宏函数定义
#define LED(x) GPIO_WriteBit(GPIO_PORT,GPIO_PIN,!(BitAction)x)
#define LED_R_TOGGLE() GPIO_WriteBit(GPIO_PORT,GPIO_PIN,!(BitAction)GPIO_ReadOutputDataBit(GPIO_PORT,GPIO_PIN))
//函数声明
void LED_Init(void);
#endif
Delay.c:
#include "stm32f10x.h"
/**
* @brief 微秒级延时
* @param xus 延时时长,范围:0~233015
* @retval 无
*/
void Delay_us(uint32_t xus)
{
SysTick->LOAD = 72 * xus; //设置定时器重装值
SysTick->VAL = 0x00; //清空当前计数值
SysTick->CTRL = 0x00000005; //设置时钟源为HCLK,启动定时器
while(!(SysTick->CTRL & 0x00010000)); //等待计数到0
SysTick->CTRL = 0x00000004; //关闭定时器
}
/**
* @brief 毫秒级延时
* @param xms 延时时长,范围:0~4294967295
* @retval 无
*/
void Delay_ms(uint32_t xms)
{
while(xms--)
{
Delay_us(1000);
}
}
/**
* @brief 秒级延时
* @param xs 延时时长,范围:0~4294967295
* @retval 无
*/
void Delay_s(uint32_t xs)
{
while(xs--)
{
Delay_ms(1000);
}
}
Delay.h:
#ifndef __DELAY_H
#define __DELAY_H
void Delay_us(uint32_t us);
void Delay_ms(uint32_t ms);
void Delay_s(uint32_t s);
#endif