[嵌入式]按键的使用

// anjian.h
// PA0 PA8 PB1 PB2

#ifndef __ANJIAN_H
#define __ANJIAN_H

#include "main.h"

// 函数定义位置:Library->stm32f10x_gpio.c->.h->Line 353
#define Key1 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) 
#define Key2 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_8)
#define Key3 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)
#define Key4 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)


u8 Key_Scan(u8 mode);
void Key_Init(void);


#endif 
// anjian.c

#include "anjian.h"
_Bool Key_Flag = 1;
u8 Key_Scan(void)
{
	if(Key_Flag && (Key1==0||Key2==0||Key3==0||Key4==0)){
		Delay_Ms(10);
		Key_Flag = 0;
		if(Key1==0) return 1;
		else if(Key2==0) return 2;
		else if(Key3==0) return 3;
		else if(Key4==0) return 4;
	}
	else if(Key1==1&&Key2==1&&Key3==1&&Key4==1)
		Key_Flag = 1;
	return 0;
}

void Key_Init(void){
	
    // 函数位置:标准库->GPIO->main.c
	GPIO_InitTypeDef GPIO_InitStructure; // 用到A,B引脚
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB, ENABLE);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; // 最好改成floating模式
	GPIO_Init(GPIOA, &GPIO_InitStructure);	
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1|GPIO_Pin_2;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(GPIOB, &GPIO_InitStructure);	
	
}

// 使用示例
// 初始化
// 记得放进while(1)
Key_Init();

Key_num = Key_Scan();

if (Key_num == 1){
    //这里写按完按键1之后的动作
} 
else if (Key_num == 2){
    //这里写按完按键2之后的动作,下面不重复了
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值