*通过RCC里面的APB2外设时钟控制函数打开GPIOX时钟;
*通过GPIO_Init()函数自动读取结构体的值,然后自动把外设的各个参数配置好,我们只需要提前把结构体参数配置好即可;
我比较喜欢模块化编程,这样下一次使用就不用再写了,直接复制粘贴到工程文件夹里,然后头文件声明就可以调用了。
main.c:
#include "stm32f10x.h" // Device header
#include "LED.h"
#include "Delay.h"
#include "KEY.h"
uint8_t key_value; //定义键值
int main(void)
{
/*初始化*/
LED_Init();
Key_Init();
while(1)
{
key_value=key_scan();
if(key_value == 1)
{
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_1) == 0) //用于检测输出端口电平的函数
{
GPIO_SetBits(GPIOA,GPIO_Pin_1); //置为高电平
}
else
GPIO_ResetBits(GPIOA,GPIO_Pin_1);//置为低电平
}
}
}
KEY.h:
(注意:__xxx_H 中名称是任意的,但一般与所定义的函数名一致,防止重复定义,增加CPU的负担)
#ifndef __KEY_H
#define __KEY_H
void Key_Init(void);
uint8_t key_scan(void);
#endif
key.c:
#include "stm32f10x.h" // Device header
#include "Delay.h"
void Key_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure; //定义一个结构体
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
uint8_t key_scan(void)
{
uint8_t keynum = 0;
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 0) //用于检测输入端口电平的函数
{
Delay_ms(10);//消抖
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 0);//松手检测
Delay_ms(10);
keynum = 1;
}
return keynum ;
}
LED.h:
#ifndef __LED_H
#define __LED_H
void LED_Init(void);
#endif
LDE.c:
#include "stm32f10x.h" // Device header
void LED_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出,具有输出高低电平的能力
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_1); //因为GPIOX初始化后默认低电平,此时LED 灯会点亮,所以初始化后置高电平
}
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
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);
}
}