key.h
#ifndef __KEY_H
#define __KEY_H
#include "sys.h"
#include "delay.h"
#define Pin0 GPIO_Pin_0
#define Pin1 GPIO_Pin_1
#define Pin2 GPIO_Pin_2
#define Pin3 GPIO_Pin_3
#define Pin4 GPIO_Pin_4
#define Pin5 GPIO_Pin_5
#define Pin6 GPIO_Pin_6
#define Pin7 GPIO_Pin_7
#define GPIO_Type GPIOA
#define RCC_Periph RCC_APB2Periph_GPIOA
#define KEY0 GPIO_ReadInputDataBit(GPIO_Type,Pin0)
#define KEY1 GPIO_ReadInputDataBit(GPIO_Type,Pin1)
#define KEY2 GPIO_ReadInputDataBit(GPIO_Type,Pin2)
#define KEY3 GPIO_ReadInputDataBit(GPIO_Type,Pin3)
void key_init(void);
int key_scan( void );
#endif
key.c
#include "key.h"
static int Get_KeyValue(int LineNum);
static void Key_InitOutPin(u8 LineNum);
const int key_values[20] = {
1, 2, 3, 10, /*-- 1,2,3,A --*/
4, 5, 6, 11, /*-- 4,5,6,B --*/
7, 8, 9, 12, /*-- 7,8,9,C --*/
14,0,15, 13 /*-- *,0,#,D --*/
};
/********************
* 引脚初始化 *
*********************/
void key_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_Periph, ENABLE); //使能PA,PD端口时钟
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);//关闭jtag,使能SWD,可以用SWD模式调试
GPIO_InitStructure.GPIO_Pin = Pin0 | Pin1 | Pin2 | Pin3;//PA0~3
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //设置成上拉输入
GPIO_Init(GPIO_Type, &GPIO_InitStructure);//初始化GPIOA0~3
GPIO_InitStructure.GPIO_Pin = Pin7 | Pin6 | Pin5 | Pin4;//PA4~7
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIO_Type, &GPIO_InitStructure);//初始化GPIOA4~7
}
int key_scan( void ){
static int key_value = -1;
key_value = Get_KeyValue(0);
key_value = Get_KeyValue(1);
key_value = Get_KeyValue(2);
key_value = Get_KeyValue(3);
return key_value;
}
/*****************
* 获取对应键值 *
******************/
static int Get_KeyValue(int LineNum){
static int key_temp = -1;
Key_InitOutPin(LineNum);
if(KEY3 == 0)//确定?
{
delay_ms(10);//考虑哈(消抖)
if(KEY3 == 0)//你确定!?
key_temp = key_values[LineNum * 4];//拿去嘛
}else if(KEY2 == 0)
{
delay_ms(10);
if(KEY2 == 0)
key_temp = key_values[LineNum * 4 + 1];
}else if(KEY1 == 0)
{
delay_ms(10);
if(KEY1 == 0)
key_temp = key_values[LineNum * 4 + 2];
}else if(KEY0 == 0)
{
delay_ms(10);
if(KEY0 == 0)
key_temp = key_values[LineNum * 4 + 3];
}
return key_temp;
}
/********************
* 设置引脚输出状态 *
*********************/
static void Key_InitOutPin(u8 LineNum)
{
switch(LineNum)
{
case 0:
GPIO_SetBits(GPIO_Type, Pin6 | Pin5 | Pin4);
GPIO_ResetBits(GPIO_Type, Pin7);
break;
case 1:
GPIO_SetBits(GPIO_Type, Pin7 | Pin5 | Pin4);
GPIO_ResetBits(GPIO_Type, Pin6);
break;
case 2:
GPIO_SetBits(GPIO_Type, Pin7 | Pin6 | Pin4);
GPIO_ResetBits(GPIO_Type, Pin5);
break;
case 3:
GPIO_SetBits(GPIO_Type, Pin7 | Pin6 | Pin5);
GPIO_ResetBits(GPIO_Type, Pin4);
break;
default : break;
}
}
技术交流群:332153824。