以下为 key.c
#include "key.h"
#include "delay.h"
//°´¼ü³õʼ»¯º¯Êý
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA|RCC_AHB1Periph_GPIOE, ENABLE);//ʹÄÜGPIOA,GPIOEʱÖÓ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4; //KEY0 KEY1 KEY2¶ÔÓ¦Òý½Å
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;//ÆÕͨÊäÈëģʽ
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100M
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;//ÉÏÀ
GPIO_Init(GPIOE, &GPIO_InitStructure);//³õʼ»¯GPIOE2,3,4
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;//WK_UP¶ÔÓ¦Òý½ÅPA0
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ;//ÏÂÀ
GPIO_Init(GPIOA, &GPIO_InitStructure);//³õʼ»¯GPIOA0
}
//°´¼ü´¦Àíº¯Êý
//·µ»Ø°´¼üÖµ
//mode:0,²»Ö§³ÖÁ¬Ðø°´;1,Ö§³ÖÁ¬Ðø°´;
//0£¬Ã»ÓÐÈκΰ´¼ü°´ÏÂ
//1£¬KEY0°´ÏÂ
//2£¬KEY1°´ÏÂ
//3£¬KEY2°´ÏÂ
//4£¬WKUP°´Ï WK_UP
//×¢Òâ´Ëº¯ÊýÓÐÏìÓ¦ÓÅÏȼ¶,KEY0>KEY1>KEY2>WK_UP!!
u8 KEY_Scan(u8 mode)
{
static u8 key_up=1;//°´¼ü°´ËÉ¿ª±êÖ¾
if(mode)key_up=1; //Ö§³ÖÁ¬°´
if(key_up&&(KEY0==0||KEY1==0||KEY2==0||WK_UP==1))
{
delay_ms(10);//È¥¶¶¶¯
key_up=0;
if(KEY0==0)return 1;
else if(KEY1==0)return 2;
else if(KEY2==0)return 3;
else if(WK_UP==1)return 4;
}else if(KEY0==1&&KEY1==1&&KEY2==1&&WK_UP==0)key_up=1;
return 0;// ÎÞ°´¼ü°´ÏÂ
}
以下为key.h
#ifndef __KEY_H
#define __KEY_H
#include "sys.h"
/*ÏÂÃæµÄ·½Ê½ÊÇͨ¹ýÖ±½Ó²Ù×÷¿âº¯Êý·½Ê½¶ÁÈ¡IO*/
#define KEY0 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4) //PE4
#define KEY1 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3) //PE3
#define KEY2 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_2) //PE2
#define WK_UP GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) //PA0
/*ÏÂÃ淽ʽÊÇͨ¹ýλ´ø²Ù×÷·½Ê½¶ÁÈ¡IO*/
/*
#define KEY0 PEin(4) //PE4
#define KEY1 PEin(3) //PE3
#define KEY2 PEin(2) //P32
#define WK_UP PAin(0) //PA0
*/
#define KEY0_PRES 1
#define KEY1_PRES 2
#define KEY2_PRES 3
#define WKUP_PRES 4
void KEY_Init(void); //IO³õʼ»¯
u8 KEY_Scan(u8); //°´¼üɨÃ躯Êý
#endif
在主函数初始化后 在while(1)进行判断
uart_init(115200);
KEY_Init();
while(1){
key=KEY_Scan(0);
if(key)
{
switch(key){
case KEY0_PRES :printf("KEY0±»°´ÏÂ\r\n"); break;
case KEY1_PRES :printf("KEY1±»°´ÏÂ\r\n"); break;
case KEY2_PRES :printf("KEY2±»°´ÏÂ\r\n"); break;
case WKUP_PRES :printf("KEYup±»°´ÏÂ\r\n");break;
}
}
}