@【TOC】(按键检测)
one
bsp_ked.h
#ifndef _BSP_KEY_H
#define _BSP_KEY_H
#include"stm32f10x.h"
//更换IO口,只需要更改宏定义即可
#define KEY1_G_GPIO_PIN GPIO_Pin_0 //PA0
#define KEY1_G_GPIO_PORT GPIOA //A端口
#define KEY1_G_GPIO_CLK RCC_APB2Periph_GPIOA //打开A时钟
//时钟跟硬件相关
//#define KEY2_GPIO_CLK RCC_APB2Periph_GPIOC
//#define KEY2_GPIO_PORT GPIOC
//#define KEY2_GPIO_PIN GPIO_Pin_13
#define KEY_ON 1
#define KEY_OFF 0
void KEY_GPIO_Config(void);
uint8_t KEY_Scan(GPIO_TypeDef *GPIOX,uint16_t GPIO_Pin);
//函数声明
#endif /*_BSP_KEY_H*/
two
bsp_led.h
#ifndef _BSP_LED_H
#define _BSP_LED_H
#include"stm32f10x.h"
void LED_GPIO_Config(void);
#define LED_G_GPIO_PIN GPIO_Pin_0
#define LED_G_GPIO_PORT GPIOB//端口//更换io口,只需要更改宏定义即可
#define LED_G_GPIO_CLK RCC_APB2Periph_GPIOB
#define ON 1
#define OFF 0
#define LED_G(a) if(a) GPIO_ResetBits(LED_G_GPIO_PORT, LED_G_GPIO_PIN);else GPIO_SetBits(LED_G_GPIO_PORT, LED_G_GPIO_PIN);
#define LED_G_TOGGLE {LED_G_GPIO_PORT->ODR *=LED_G_GPIO_PIN ;}
//#define LED2_TOGGLE {LED_G_GPIO_PORT->ODR *=LED_G_GPIO_PIN ;}
// *= 异或 c语言里面一个二进制的运算符
// 与1异或改变,与0异或不变
//0*=1 即1 1*=1 即0
#endif /*_BSP_LED_H*/
three
bsp_led.c
//bsp: board support package 板级支持包
#include"bsp_led.h"
void LED_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStruct;//新建一个初始化结构体,配置初始化结构体
RCC_APB2PeriphClockCmd(LED_G_GPIO_CLK , ENABLE);
GPIO_InitStruct.GPIO_Pin = LED_G_GPIO_PIN ;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; //配置速度,50兆
GPIO_Init(LED_G_GPIO_PORT, &GPIO_InitStruct);//GPIO初始化函数 端口 初始化的结构体的指针
}
four
bsp_key.c
#include"bsp_key.h"
void KEY_GPIO_Config(void) //开时钟
{
GPIO_InitTypeDef GPIO_InitStruct;//新建一个初始化结构体,配置初始化结构体
RCC_APB2PeriphClockCmd(KEY1_G_GPIO_CLK , ENABLE); //开时钟 第一个参数 使能那一个外设的时钟 ; 第二个参数 使能或者不使能
GPIO_InitStruct.GPIO_Pin = KEY1_G_GPIO_PIN ; //设置按键的引脚的开启模式为浮空输入
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING; //使用结构体初始化按键
GPIO_Init(KEY1_G_GPIO_PORT, &GPIO_InitStruct);//GPIO初始化函数 端口 初始化的结构体的指针
// GPIO_InitStruct.GPIO_Pin = KEY2_GPIO_PIN;
// GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
// GPIO_Init(KEY2_GPIO_PORT, &GPIO_InitStruct);
}//初始化GPIO
uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin)
{
if(GPIO_ReadInputDataBit(KEY1_G_GPIO_PORT, KEY1_G_GPIO_PIN) == KEY_ON)
{
//
while(GPIO_ReadInputDataBit(KEY1_G_GPIO_PORT,KEY1_G_GPIO_PIN) ==KEY_ON)
return KEY_ON;
}
else return KEY_OFF;
}
//uint8_t KEY_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin);
//{
// if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON)//io端口的电平检测一位
// {
// //松手检测
// while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON);
// return KEY_ON;
// }
// else return KEY_OFF;
//}//按键扫描,扫描哪个gpio口呢
five
main.c
#include"stm32f10x.h"
#include"bsp_key.h"
#include"bsp_led.h"
void Delay(uint32_t count)
{
for(;count!=0; count--);
}
int main(void)
{
LED_GPIO_Config();
KEY_GPIO_Config();
while(1)
{
if(Key_Scan(KEY1_G_GPIO_PORT,KEY1_G_GPIO_PIN) == KEY_ON)
LED_G_TOGGLE;
//if ( Key_Scan(KEY2_GPIO_PORT,KEY2_GPIO_PIN) == KEY_ON )
// LED2_TOGGLE;
}
}