①key.h:
#ifndef key_h
#define key_h
#include “sys.h” //位操作需要的头文件
#define key0 PEin(4)
#define key1 PEin(3) //位操作 库函数为:GPIO_ReadInputDataBit();
#define key2 PEin(2)
#define wk_up PAin(0)
#define key0_press 1
#define key1_press 2
#define key2_press 3 //数字为任意,只是为了return好返回值。
#define wk_up_press 4
void key_init(void); //按键初始化函数
u8 key_scan(u8); //按键扫描函数
#endif
② key.c:
#include “key.h”
#include “stm32f10x.h”
#include “delay.h”
#include “sys.h”
void key_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE|RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4|GPIO_Pin_3|GPIO_Pin_2;
GPIO_Init(GPIOE,&GPIO_InitStructure); //下拉
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPD;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0;
GPIO_Init(GPIOA,&GPIO_InitStructure); //上拉
}
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 key0_press;
else if(key1= =0) return key1_press;
else if(key2= =0) return key2_press;
else if (wk_up= =1) return wk_up_press;
}else if(key0= =1&&key1 = =1&&key2 = =1&&wk_up==0) key_up=1;
return 0; //无按键按下
}
③main:
#include “led.h”
#include “beep.h”
#include “key.h”
#include “delay.h”
#include “sys.h”
int main(void)
{
u8 key;
led_init();
beep_init();
key_init();
delay_init();
led0=0;
while(1){
key=key_scan(0);
switch(key)
{
case wk_up_press:
beep=!beep;
break;
case key2_press:
led0=!led0;
break;
case key1_press:
led1=!led1;
break;
case key0_press:
led0=!led0;
led1=!led1;
break;
}
}
}