stm32按键输入实验

①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;
}

}

}

补:配置成输出模式需要speed,输入模式不需要speed。一般speed的大小为50MHZ,不需要改。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值