[mw_shl_code=c,true]void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB, ENABLE); //使能PA,PB端口时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_10|GPIO_Pin_11; //列 PB1 PB2 PB10 PB11
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // 推挽输出
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12; //行 PA9~PA12
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12); //行置为 1
GPIO_ResetBits(GPIOB, GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_10|GPIO_Pin_11); //列置为 0
}
u8 Read_KeyValue(u8 mode)
{
u8 KeyValue=0;
static u8 key_up=1;//按键按松开标志
if(mode)key_up=1; //支持连按
if(key_up&&(GPIO_ReadInputData(GPIOA)&0x1e00)!=0x1e00)
{
delay_ms(50);
key_up=0;
if((GPIO_ReadInputData(GPIOA)&0x1e00)!=0x1e00)
{
GPIO_SetBits(GPIOB, GPIO_Pin_2|GPIO_Pin_10); //扫描第一列 011
GPIO_ResetBits(GPIOB, GPIO_Pin_1); //
switch((GPIO_ReadInputData(GPIOA)&0x1e00))
{
case 0x1c00: KeyValue = 1; break;
case 0x1a00: KeyValue = 4; break;
case 0x1600: KeyValue = 7; break;
case 0x0e00: KeyValue = 10; break;
}
GPIO_SetBits(GPIOB, GPIO_Pin_1|GPIO_Pin_10); //扫描第二列 101
GPIO_ResetBits(GPIOB, GPIO_Pin_2); //
switch((GPIO_ReadInputData(GPIOA)&0x1e00))
{
case 0x1c00: KeyValue = 2; break;
case 0x1a00: KeyValue = 5; break;
case 0x1600: KeyValue = 8; break;
case 0xe00 : KeyValue = 11; break;
}
GPIO_SetBits(GPIOB, GPIO_Pin_1|GPIO_Pin_2); //扫描第三列 110
GPIO_ResetBits(GPIOB, GPIO_Pin_10); //
switch((GPIO_ReadInputData(GPIOA)&0x1e00))
{
case 0x1c00: KeyValue = 3; break;
case 0x1a00: KeyValue = 6; break;
case 0x1600: KeyValue = 9; break;
case 0x0e00: KeyValue = 12; break;
}
GPIO_SetBits(GPIOA, GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12); //行置为 1
GPIO_ResetBits(GPIOB, GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_10); //列置为 0
return KeyValue;
}
} //判断键值结束 有按下则返回按下的键值 如果按下的跟前面的
else //if((GPIO_ReadInputData(GPIOA)&0x1e00)==0x1e00)
key_up=1;
return 0;
}
int main()
{
delay_init(); // 延时初始化
KEY_Init();
while(1)
{
key_m=Read_KeyValue(0);
if(key_m!=0)
{
key_m=0;
test_led=~test_led; //灯。每次取反
}
}
}
[/mw_shl_code]
|