按键控制led和蜂鸣器
Goals
两个按键分别控制LED和蜂鸣器状态的翻转
Material
hardware material
software material
1、GPIO配置
2、GPIO状态读取
3、延时函数
4、按键扫描函数
Procedure
1、根据目标业务,寻找对应的原料
2、创建工程结构
3、编写key.h、key.c、main.c实现目标业务
1、将GPIO配置成 上拉输入 模式
void KEY_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
// enable the clock of ports which used as keys
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// setting the property of ports which used as keys
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
// initialize ports which used as keys
GPIO_Init(GPIOB, &GPIO_InitStructure);
// setting ports with default status
}
不需要 设置GPIO速度 和 初始值
2、读取GPIO状态的方法
#define KEY0 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12)
#define KEY1 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13)
或者使用位带操作
#include "sys.h"
#define KEY0 PBin(12)
#define KEY1 PBin(13)
3、按键扫描函数
// whethe we need to read the previous key is up
// and then to read the next key which is down
// let parament mode to be flag
u8 KEY_Scan(u8 mode) {
static u8 key_up = 1;
if (mode) {
// if we don't care the previous status of keys
// just to read and return the present status of keys
key_up = 1; // pretending as all key has been up
}
if (key_up && (KEY0==0 || KEY1==0)) {
// all previous key is up and some key is down
delay_ms(10);
key_up = 0; // marking there is some key down
if(KEY0==0)
return KEY0_PRES;
else if(KEY1==0)
return KEY1_PRES;
} else if (KEY0==1 && KEY1==1) {
// all previous key has been up
key_up = 1;
// return 0;
} else {
// means key_up=0,there are some keys is down
// return 0;
}
return 0;
}
这里按键扫描函数支持两种模式:1、所有按键弹起后才能触发下一个按键。 2、无需弹起按键,10ms后继续正常读取按键
4、main.c的编写
int main(void) {
u8 key;
delay_init();
LED_Init();
BEEP_Init();
KEY_Init();
while(1) {
key = KEY_Scan(0);
if (key) {
switch (key) {
case KEY0_PRES:
BEEP = !BEEP;
break;
case KEY1_PRES:
LED = !LED;
break;
}
} else {
// there is no key which is down
delay_ms(10);
}
}
}
4、使用keil仿真调试
5、搭建电路、下载程序、调试
Summary & Supplement
1、GPIO的输入输出的几种模式需要了解