新建板级支持包文件夹
将.c文件加入到工程文件下的user中并在魔法棒中配置.h文件夹的路径
根据原理图编写.c文件和.h文件
关于上拉,下拉电阻的解释:https://blog.csdn.net/fymx203/article/details/89426403
根据原理图得到的信息:
GBIOA
浮空输入
第0位脚
根据以上信息编写头文件宏定义:
#ifndef __BSP_KEY_H
#define __BSP_KEY_H
#include "stm32f10x.h"
#define KEY_ON 1
#define KEY_OFF 0
#define KEY1_GPIO_PIN GPIO_Pin_0
#define KEY1_GPIO_PORT GPIOA
#define KEY1_GPIO_CLK RCC_APB2Periph_GPIOA
#define LED_TOGGLE LED_G_GPIO_PORT->ODR ^= LED_G_GPIO_PIN; // 通过异或来反转电位实现开关
void KEY_GPIO_Config(void); //初始化GPIOA的函数
uint8_t Key_Scan(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin); //输入检测函数
#endif /* __BSP_KEY_H */
编写.c文件
#include "bsp_key.h"
void KEY_GPIO_Config(void){
GPIO_InitTypeDef GPIO_InitStruct; //定义初始化结构体,初始化GPIO都要定义结构体来配合下面的GPIO_Init()函数
RCC_APB2PeriphClockCmd(KEY1_GPIO_CLK,ENABLE); //使能时钟源
GPIO_InitStruct.GPIO_Pin = KEY1_GPIO_PIN; //设置管脚位置
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING; //设置模式为浮动输入模式
GPIO_Init(KEY1_GPIO_PORT,&GPIO_InitStruct); // 初始化GPIO
}
uint8_t Key_Scan(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin){
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON){ //读取GPIOA->IDR的电位来判断开关的状态
//松手检测
while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON);
return KEY_ON;
}else{
return KEY_OFF;
}
}
写main.c函数
#include "stm32f10x.h"
#include "bsp_led.h"
#include "bsp_key.h"
#include "bsp_rccclkconfig.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_GPIO_PORT,KEY1_GPIO_PIN) ==KEY_ON ){
LED_TOGGLE;
}
}
}