代码
void Key_Init(void) //按键初始化函数
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
//key.h 中宏定义
#include "stm32f10x.h"
#define Key1 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)
#define Key2 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_8)
#define Key3 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)
#define Key4 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)
void Key_Read(void){//按键读取函数
static u16 Key1_Sum = 0,Key2_Sum = 0,Key3_Sum = 0,Key4_Sum = 0;
//Key1,拿Key1举例
if(Key1 == 0){
Key1_Sum ++;
if(Key1_Sum == 1){//每按一次Key1取反一次
GPIOC->ODR ^= (1 << 8);
GPIOD->ODR |= (1 << 2);
GPIOD->ODR &= ~(1 << 2);
}
}
else{
Key1_Sum = 0;
}
}
//main.c文件里
u8 Key_Flag = 0;
Led_Init();
Key_Init();
while(1){
if(Key_Flag){
Key_Flag = 0;
Key_Read();
}
}
//stm32f10x_it.c文件里
extern u8 Key_Flag;//声明标志位
void SysTick_Handler(void){
static u8 Key_Sum = 0;
TimingDelay --;
if(++Key_Sum == 50){//经测试,扫描间隔只要大于 50ms,基本就已经不会受到按键抖动的影响
Key_Sum = 0;
Key_Flag = 1;
}
}
长按触发
if(Key4 == 0){
Key4_Sum ++;
if(key4_sum>1 && key4_sum<20){//短按触发
//短按功能
}
if(Key4_Sum == 40){//长按触发 2000ms
GPIOC->ODR ^= (1 << 15);
GPIOD->ODR |= (1 << 2);
GPIOD->ODR &= ~(1 << 2);
Key4_Sum = 30;//为了显示长按效果,不断触发长按
}//当我们按下按键 4 超过 2s 时候,LED8 就会以 0.5S 的间隔进行闪烁,直到按键松开后停止
}
else{
Key4_Sum = 0;
}
代码来源:@fei…—— 蓝桥杯嵌入式开发经验分享(4. 按键的配置)
(以上仅供个人学习用途)