STM32F103(纯代码)-按键Key控制

1.Key.h

#ifndef __Key_H
#define __Key_H

#include "stm32f10x.h"                  // Device header
#include "Delay.h"

//Key0 GPIOÅäÖÃ
#define Key0_GPIO_CLK RCC_APB2Periph_GPIOE //GPIOEʱÖÓ
#define	Key0_GPIO_PORT GPIOB //GPIOE
#define Key0_GPIO_Mode GPIO_Mode_IPU //ÉÏÀ­ÊäÈë
#define Key0_GPIO_Pin GPIO_Pin_4 //Pin_4

//Key1 GPIOÅäÖÃ
#define Key1_GPIO_CLK RCC_APB2Periph_GPIOE //GPIOEʱÖÓ
#define Key1_GPIO_PORT GPIOE //GPIOE
#define Key1_GPIO_Mode GPIO_Mode_IPU //ÉÏÀ­ÊäÈë
#define Key1_GPIO_Pin GPIO_Pin_3 //Pin_3

//Key_up GPIOÅäÖÃ
#define WK_UP_GPIO_CLK RCC_APB2Periph_GPIOA //GPIOAʱÖÓ
#define WK_UP_GPIO_PORT GPIOA //GPIOA
#define WK_UP_GPIO_Mode GPIO_Mode_IPD //ÏÂÀ­ÊäÈë
#define WK_UP_GPIO_Pin GPIO_Pin_0 //Pin_0


#define LED0 PBout(5)// PB5
#define LED1 PEout(5)// PE5	

#define KEY0  GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)//¶ÁÈ¡°´¼ü0
#define KEY1  GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3)//¶ÁÈ¡°´¼ü1
#define WK_UP   GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)//¶ÁÈ¡°´¼ü3(WK_UP) 

#define KEY0_PRES 	1	//KEY0°´ÏÂ
#define KEY1_PRES	  2	//KEY1°´ÏÂ
#define WKUP_PRES   3	//KEY_UP°´ÏÂ(¼´WK_UP/KEY_UP)

void Key_Init(void);
u8 Key_GetNum(void);

#endif

2.Key.c

#include "Key.h"

void Key_Init(void)
{
	RCC_APB2PeriphClockCmd(Key0_GPIO_CLK | Key1_GPIO_CLK | WK_UP_GPIO_CLK,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode=Key0_GPIO_Mode;
	GPIO_InitStructure.GPIO_Pin=Key0_GPIO_Pin;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(Key0_GPIO_PORT,&GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode=Key1_GPIO_Mode;
	GPIO_InitStructure.GPIO_Pin=Key1_GPIO_Pin;
	GPIO_Init(Key1_GPIO_PORT,&GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU; 
	GPIO_InitStructure.GPIO_Pin=WK_UP_GPIO_Pin;
	GPIO_Init(WK_UP_GPIO_PORT, &GPIO_InitStructure);
}

u8 Key_GetNum(void)
{
	uint8_t KeyNum=0;
	if(KEY0 == 0)
	{
		Delay_ms(20);
		while( KEY0 == 0);
		Delay_ms(20);//°´¼üÏû¶¶
		
		KeyNum = 1;
	}
	if(KEY1 == 0)
	{
		Delay_ms(20);
		while(KEY1 == 0);
		Delay_ms(20);
		KeyNum = 2;
	}
	if(WK_UP == 0)
	{
		Delay_ms(20);
		while(WK_UP == 0);
		Delay_ms(20);
		
		KeyNum = 3;
	}
	return KeyNum;
}

3.main

#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "sys.h"
#include "stdio.h"

#include "Led.h"	
#include "Key.h"

int main(void)
{
	
	Led_Init();
	Key_Init();
	
	while(1)
	{
		u8 Data = Key_GetNum();
		switch(Data)
		{
			case '1': 
								LED0 = 0;
								LED1 = 1;
								break;
			case '2': 
								LED0 = 1;
								LED1 = 0;
								break;
			case '3': 
								LED0 != LED0;
								break;
			default : LED1 = 0;
		}
		
	}	
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值