檢測按鍵按下與否穴墅,進(jìn)而做出相應(yīng)的消息響應(yīng),
按鍵與IO口和GND相連祟霍。
<key.h>*********************************
#ifndef __KEY_H
#define __KEY_H
#define KEYPORT GPIOA //IO口的宏定義
#define KEY1 GPIO_Pin_0
#define KEY2 GPIO_Pin_1
void KEY_Init(void);
#endif
<key.c>*********************************
#include "key.h"
void KEY_Init(void){ //按鍵初始化
GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitStructure.GPIO_Pin = KEY1 | KEY2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //當(dāng)按鍵沒有按下時(shí)歪泳,IO口檢測為高電平锉屈,為上拉電阻模式苍狰,按下IO口與地連接办龄,為低電平
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //與按鍵相連的IO口為輸入,不需要設(shè)置接口速度淋昭,只有輸出才用
GPIO_Init(KEYPORT,&GPIO_InitStructure)
}
<main.c>*********************************
#include "stm32f10x.h" //STM32????
#include "delay.h"
#include "key.h"
int main (void){
u8 a;
RCC_Configuration();
KEY_Init();
while(1){
//方法1
if(GPIO_ReadInputDataBit(KEYPORT,KEY1)){ //讀取按鍵的高低電平 判斷按鍵是否按下
GPIO_ResetBits(LEDPORT,LED1); //按下后的消息響應(yīng)俐填,此處為點(diǎn)燈
}else{
GPIO_SetBits(LEDPORT,LED1); //
}
//方法2 更為常用
if(!GPIO_ReadInputDataBit(KEYPORT,KEY1)){
delay_ms(20); //延時(shí) 20ms ,硬件消抖翔忽,防止讀取錯(cuò)誤
if(!GPIO_ReadInputDataBit(KEYPORT,KEY1)){ // GPIO_WriteBit(LEDPORT,LED1,(BitAction)(1-GPIO_ReadOutputDataBit(LEDPORT,LED1)));
while(!GPIO_ReadInputDataBit(KEYPORT,KEY1)); //等待按鍵起來
}
}