Article Directory
Preface
In the previous chapters, we learned about the GPIO output function. In this section, we learned about the GPIO input function, key input.
1. Schematic
PA0 pin, when K1 is not pressed, PA0 is low, and when K1 is pressed, it is high.
Two, programming steps
1. Enable the GPIO port clock
2. Initialize the GPIO pins and set the input mode (floating input)
3. Check the button status and control the LED lights
GPIOB control light GPIOA control button bsp_key.h
//根据原理图找到对应的时钟
#define KEY_GPIO_PORT GPIOA
#define KEY_GPIO_CLK RCC_APB2Periph_GPIOA
#define KEY_GPIO_PIN GPIO_Pin_0
#define Toggle(p,i) {p->ODR ^=i;}
#define LED_TOGGLE Toggle(LED_GPIO_PORT,LED_GPIO_PIN)//设置ODR实现反转功能
bsp_key.c GPIO_Mode is set to float
void KEY_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd( KEY_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = KEY_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(KEY_GPIO_PORT, &GPIO_InitStructure);
}
//检测按键状态
//返回值 The input port pin value
//检测按键是否按下,GPIO_ReadInputDataBit库函数,按下为高电平
uint8_t Key_Detect(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == ON)
{
while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == ON);
return ON;
}
else
return OFF;
}
Main function main.c
#include "stm32f10x.h"
#include "bsp_led.h"
#include "bsp_key.h"
int main(void)
{
LED_GPIO_Config();
KEY_GPIO_Config();
GPIO_SetBits(LED_GPIO_PORT,LED_GPIO_PIN);// 先将灯熄灭
while(1)
{
if(Key_Detect(KEY_GPIO_PORT,KEY_GPIO_PIN) == ON)
{
digitalToggle(LED_GPIO_PORT,LED_GPIO_PIN);
}
}
}